How to fix SoundCloud player since API updates? - javascript

I've been working with this code that builds a custom SoundCloud player from hrefs to the tracks via their API:
https://codepen.io/nicholaspetersen/pen/yyVYMY
It was working fine until SoundCloud changed the way their API authorises as described here:
https://developers.soundcloud.com/blog/security-updates-api
They said in that post:
Currently, to access the public resources of the platform, server-side integrations with our API only require a client_id in the URL’s query parameter. We’ll be strengthening our authorization here by making all public resources on the API only accessible to apps that have been authorized with the client_credentials grant. This will enable the app to capture both the access_token and the refresh_token to then fetch the resources from the API. Please note that the use of client_id will be deprecated and deleted soon (from July 2021). Developers should provide the Authentication header for all their requests to the SoundCloud API going forward.*
So, my understanding from the above is that I need to update the Authentication header as currently the code above is authenticating using this code:
// convert a SoundCloud resource URL to an API URL
scApiUrl = function(url, apiKey) {
var resolver = ( secureDocument || (/^https/i).test(url) ? 'https' : 'http') + '://api.' + domain + '/resolve?url=',
params = 'format=json&consumer_key=' + apiKey +'&callback=?';
However, I'm completely stuck as to how to do that... can anyone take a look at the JS in that codepen and let me know what I should be doing to fix the issue? I thought it might involve updating the code above to include a callback URL, but then that blog post says the use of client_id is now deprecated.
Any help / pointers hugely welcome.

After the SoundCloud security updates, the playlist on my website also stopped working. It wouldn't load any of the tracks in my playlist. I did a lot of research, finally realizing that I would need to register an app on SoundCloud to get access to the API. This was not possible due to the app registration page being down since early this year and with no promises of it ever going back up. So, I needed to find an alternative. Which brought me to the Widget API page.
https://developers.soundcloud.com/docs/api/html5-widget
The Widget API allows you to externally control the widget that is embedded on your website through javascript. You set the width and height of the widget to 0 and it hides the widget. I tinkered with this on codepen this week and I am pleased that I now have a working playlist ready to be utilized on my website. See the link below.
https://codepen.io/mdcrowcodes/pen/eYEMyzY
enter code here

Related

Trying to find video ID of starting YouTube Streaming Broadcast

I am trying to retrieve the video ID (eventually in JavaScript) of the YouTube video that just started streaming from our church. In testing to see what works and what doesn't, when I try calling
curl 'https://www.googleapis.com/youtube/v3/search?eventType=live&part=snippet&channelId={CHANNEL_ID}&type=video&key={API_KEY}'
I get back an empty list until I go into Studio for the channel and change the setting on the now live video (which is already Public) to something else and then Public again and click Publish. It is worth noting that in the Live Streaming portion of Studio where the video is set up that it is also marked Public. This is not something that we could have church volunteers running the broadcast on Sunday do. Is there either some way to either get the video ID (for certain reasons I don't want to use the https://www.youtube.com/embed/live_stream?channel={CHANNEL_ID} option) or to publish the new live video either automatically or without requiring an OAuth token?
I am looking to do this so that from our web page, which is on a hosted site that doesn't allow programmatic updates, we would dynamically be able to look up the video ID of the pending (or now actively streaming) live stream being broadcast from the church. OAuth access to the YouTube APIs isn't a good option, as there are security issues, so that rules out certain options. Some API key searches let you see the ID, but only after the video is published from YouTube Studio, but depending on church volunteers to go into the YouTube channel and make updates there as the video is starting is also not a valid option in this case.
We could do the video ID lookup and update the web page manually if that is the only option, but my hope was that there would be some way that this could be done from JavaScript so that we could always know that the web page was pointing to the right video so that we don't have to rely on someone remembering to (or being able to) update the web page or do some similar update each week.
According to the official documentation, the LiveBroadcasts.list API endpoint has a request parameter that allows you to retrieve a set of LiveBroadcast resource objects pertaining to the live broadcasts that belong to the authenticated user (which objects contain, among other info, the IDs of your interest):
mine (boolean)
The mine parameter can be used to instruct the API to only return broadcasts owned by the authenticated user. Set the parameter value to true to only retrieve your own broadcasts.
Note that to invoke this endpoint, you have to have proper authorization; that is to say that you have to have obtained valid credentials upon running to successful completion an OAuth 2 authentication/authorization flow. Hence you have to pass on to the endpoint a valid access token that has among its scopes at least one of those specified by the official documentation.
The curl call to LiveBroadcast.list at a bash command line prompt would look like:
$ curl \
--header "Authorization: Bearer $ACCESS_TOKEN" \
'https://www.googleapis.com/youtube/v3/liveBroadcasts?part=id&fields=items/id&maxResults=50&mine=true'
where $ACCESS_TOKEN is an environment variable that is set to a valid access token (as mentioned above).
For what concerns a JavaScript implementation of this endpoint call, there are several possible solutions, mainly depending on the type of your app: a desktop app or a web app.
If using the Fetch API, you'll have to mimic closely the curl call above:
fetch('https://www.googleapis.com/youtube/v3/liveBroadcasts?part=id&fields=items/id&maxResults=50&mine=true', {
headers: {
'Authorization': 'Bearer ' + access_token
}
})
where the variable access_token contains your valid access token.
For what concerns a Javascript GAPI (i.e. Google’s Client Library for Browser-side JavaScript) implementation, the code would look like shown below (for a broader context look into this sample source file from Google: analytics_codelab.js):
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
getMyLiveBroadcasts();
});
}
function getMyLiveBroadcasts() {
var request = gapi.client.youtube.liveBroadcasts.list({
part: 'id',
fields: 'items/id',
mine: true,
maxResults: 50
});
request.execute(function(response) {
if ('error' in response) {
displayMessage(response.error.message);
} else {
// process each response.items[k].id
...
}
});
}
Note that each piece of code above uses the fields request parameter for to obtain from LiveBroadcasts.list only the broadcast's ID info (it is always good to ask from the API only the info that is of actual use).

How to use GTMetrix Api using Javascript?

I am new to API usage. I have properly managed to utilize Google Page Insights V.5 API through javascript code, but I cannot for the life of me succeed in doing so for GTMetrix. It seems the only information relating to GTMetrix API & Javascript is a link to the RapidApi website. I simply wish to achieve the same simple retrieval of data from GTMetrix as I have from Google. Is this possible?
Am I simply structuring my request incorrectly when I set it as:
https://gtmetrix.com/api/0.1/?login-user=myemail#email.com&login-pass=MyRanDomApIKeY&location=2&url=https://sitetotest.com
Because when I set my Google Page Insights Request URL as the following it works.
https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://websitetotest.com&category=performance&strategy=desktop&key=MyRanDomApIKeY
The below code works for Google Page Insights and I am even able to retrieve JSON data in a browser window with a URL such as:
<div id="firstmetric"></div>
<br>
<div id="domSize"></div>
<button>Click Me</button>
<script>
$('button').click(function(){
var baseUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=";
var fieldUrl = "https://websitetotest.com";
var trailing = "&category=performance&strategy=desktop&key=MyRanDomApIKeY";
$.getJSON(baseUrl + fieldUrl + trailing, function(data){
console.log(data);
var item = data.lighthouseResult.categories.performance.auditRefs[0].weight;
var domSize = data.lighthouseResult.audits['dom-size'].displayValue;
$("#firstmetric").html( item );
$("#domSize").html( domSize );
});
});
I truly need it spelled out for me because anything less is going to lead me to ask follow up questions and put us in a tail spin. :/
As a newbie, JSFiddle has been a life saving resource for testing and trying, breaking, and building in my learning process. If it wouldn't be too much to ask for, a fiddle would help me get my brain around things.
The parameters that you are using: login-user and login-pass refer to HTTP authentication on the page you are analyzing (as in, GTmetrix will pass these parameters on your analysis) not your GTmetrix API credentials.
The authentication used for the GTmetrix API is your e-mail for the username and your API key as the password, as pointed out by the API docs.
Another thing to keep in mind is that GTmetrix will not allow you to do API calls through your web application frontend, since they disallow CORS requests. If you do it through your Web application on a normal website, you would be exposing your GTmetrix API key, which is probably not a good idea.
So, you would then do it through your backend code. For example if done through Node JavaScript:
fetch("https://gtmetrix.com/api/0.1/locations", {
headers: new Headers({
"Authorization": 'Basic ' + btoa("[YOUR E-MAIL]" + ":" +"[YOUR API KEY]"),
}),
}).then(res => res.json())
.then(response => console.log(response));
would print me the array of locations.
Note that whichever backend code you choose, you need to add the basic authorization header request for you API call and encode it properly (that is what the btoa function call does).

Can't Post to Facebook Page using JS

Okay what I want is to post to the Facebook Page as an Page(This is developing mode application only viewable to ne).
I have done with Facebook login.
So basically I ask for 2 permissions and they are
Manage Pages
Publish Pages
I can post to the page using the Facebook graph explorer tool but can't via my Javascript code.
Here is the code that I write using JS. This code is written inside a function.
FB.api('me/accounts', function(response){
token = response.data[0].access_token;
post_with_token(token);
});
function post_with_token(token){
var message = $('#post_body').html();
var page_id = 'page_id';
FB.api('page_id/feed', 'post',
{ message : message,
access_token : token},
function (response){
console.log(response);
});
The error object in the console says this
message: "(#200) The user hasn't authorized the application to perform this action"
Both the apps My and Graph explorer have the same permissions granted.Is any new permission to be asked. I am unable to figure out what exactly the problem is.Correct me if I am wrong anywhere.
I got the answer that I posted below but didn't got why I need additional permission.?
publish_pages has only been introduced with Graph API version 2.3.
Before that, publish_actions was used to allow posts on pages by the page as well – now with v2.3, they have made that into two separate permissions. publish_actions is for everything you publish as/in the name of a user, and publish_pages is for publishing as a page.
Graph API Explorer has API version 2.3 selected by default – that is why your call was successful there. Most likely, with your own API call from your JS code, you did not use v2.3, but specified a lower API version when initializing the JS SDK.
So just specify version: 'v2.3' in your FB.init parameters (see Basic Setup section in JS SDK docs), and it should work fine with publish_pages.
Okay I solved the problem . I have to ask for publish_actions permission also. So I asked through the Login Dialog and used the same code as above to post to the page!
The error implies exactly what it says. They've designer their API so it's not going to let you post without proper authorization first.
Facebook provides a guide on how to give proper authorization to your registered app

Twitter OAuth Pin based authorization 'oob' in Google Apps Script

I am trying to use Twitter Pin-based authorization in my Google Apps Script to eventually send tweets on behalf of other uses.
I freely admit that I don't relay know what I'm doing but I have read a lot of info on the internet and feel I have tried everything.
My current Google Apps Script JavaScript code:
var method = 'post';
var url = 'https://api.twitter.com/oauth/request_token';
var consumerKey = '[my consumer key]';
var ticks = '1422745454';
var nonce = '6826266';
var options = {
'method': method,
'oauth_callback': 'oob',
'oauth_consumer_key': consumerKey,
'oauth_nonce': nonce,
'oauth_signature': 'cIFeptE5HjHp7xrp%2BZt9xFhHox4%3D',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': ticks,
'oauth_version': '1.0'
};
var response = UrlFetchApp.fetch(url, options);
For testing I set the ticks just before each test run to the value here
The nonce is a random number between 111111 and 9999999 which is regenerated before each test run.
The oauth signature I have been generating with some c# code lifted from the linq2twitter project
I suspect the problem is the signature. I have read the twitter documentation on creating a signature and I think the C# code is doing it correctly but I am not sure.
The problem is that whatever I try I always get this error:
"Request failed for https://api.twitter.com/oauth/request_token returned code 401. Truncated server response: Failed to validate oauth signature and token (use muteHttpExceptions option to examine full response)"
I have been trying to find an example of Twitter Pin-based authorization in a Google Apps Script but have so far not found anything.
My attempts to translate examples in C#, PHP, etc. have also failed.
Please help.
Apps Script provides an Oauth API that works with UrlFetchApp, they even use twitter in their examples. Work with those if at all possible, troubleshooting signature generation is a real hassle.
https://developers.google.com/apps-script/reference/url-fetch/o-auth-config
https://developers.google.com/apps-script/articles/twitter_tutorial
If you absolutely must do it from scratch, the best approach is to get requests working with an existing library (like the c# one you mention), then work on getting your apps script to generate the exact same request.
I get the sense that is what you are doing now, so it may just be a matter of base64 encoding your Signature in the outgoing request:
https://developers.google.com/apps-script/reference/utilities/utilities#base64Encode(String)
Ultimately, it's very difficult to do the whole Oauth process manually in Apps Script. When I tried something like this from scratch about a year ago I ultimately gave up and used a Python application deployed to Google App Engine instead. I submit requests from Apps Script to the App Engine application, and the App Engine application handles Oauth and relays my requests on to the external service, before returning requests to my Apps Script. This approach comes with complications of it's own.

Display Google Analytics data on my web site?

I'm trying to figure out a way to display data collected from Google Analytics on my web site. I'm using NopCommerce, and I want to display this information/statistics in a view in the Admin Section.
There might be many ways to achieve this, and after searching the web I found some examples using JavaScript, but I couldn't find a good tutorial for this.
I have also looked into integrating Google Analytics with C#, and I found this example: http://biasecurities.com/2012/02/using-the-google-analytics-api-with-asp-net-mvc/#comment-1310
A demo project can be downloaded from GitHub here: https://github.com/jgeurts/Analytics-Example
However the demo project doesn't seem to work as the google URL (https://www.google.com/analytics/feeds/accounts/default) is no longer in use.
As I'm using a MVC application it would be preferable to make this happen by applying the Google Analytics logic within a Controller and displaying it in a view. Or something like that.
Google provides a query tool to experiment with here, so it shouldn't be to hard extracting data from Google Analytics and display the data on the website: https://ga-dev-tools.appspot.com/explorer/
Has anyone been able to successfully display Google Analytics data on their website?
In case some one else is having the same problem here's what I did and it pretty much answers the question.
1.
Here is the basic code for a API client that access data from Google Analytics via your Google Service Account. https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account
In order to make this application work you need to have several things ready before you start coding.
*Google Analytics Account - once registered a "tracker" code is generated for you to put on each webpage you want to track. You may not see any statistics right away and it can take up to 24h before any statistics are shown in the Google Analytics Dashboard.
An OAuth Authorisation (API-Key) with CLIENT_ID, CLIENT SECRET and EMAIL ADRESS (This is not your normal email but a service account email that is created for you when you make an OAuth Authorisation).
console.developers.google.com/
A serverkey, can also be created here: console.developers.google.com/.
You can also create a browser key, haven't bothered with that though and don't know what it does.
Finally you need a certificate key. Your application will only be able to access your Google Analytics account by using the key and credentials. The key is an encrypted p.12 file. You can find the key in https://code.google.com/apis/console/.
Here is a guide for the key: http://www.pimcore.org/wiki/display/PIMCORE/Setup+Google+Analytics+Reporting+with+OAuth2+Service+Accounts+(since+1.4.6)
2.
Now that you have all keys and credentials you need it is time to start looking at the code I linked in "1". Here is the basic for it again: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account
Create a console application and implement the code above.
Note: your not making a "Google Plus service" so you have to change those parts for "AnalyticsService". Go to manage nuget and install packages:
Google Apis Core Library
Google Apis Client Library
Google Apis Auth Client Library
Google Apis Analytics.v3 Library
Google GData Client (This provides properties used to query data, metrics, demensions etc)
Google GData Extensions Library
Analytics
Might forgot something but here are the namespaces I use:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Analytics.v3;
3
Finally, here's is some of my code. Note I'm creating a new Analytics as supposed to "new ServiceAccountCredentials" as in the code from Google. That's the main difference:
Retrieve data from Google Analytics API with .NET, multiple metrics?
With this I'm able to access and query data from Google Analytics account. The best part is that you don't have to log in to Google for this as the key and credentials gives you access to the account data directly.
I will migrate this code to MVC now I might make an update later on for how to implement this Analytics client in Mvc.
This document explains how to get Google Access tokens and use them to get Google Analytics data to be displayed in our websites.
Example: A live example is available in
https://newtonjoshua.com
Note: Use the same Gmail account for all the below steps.
STEP 1: Set Up Google Analytics
Follow the below steps to set up Google Analytics on your website
Sign in to your Analytics account.
Select the Admin tab.
Select an account from the drop-down menu in the ACCOUNT column.
Select a property from the drop-down menu in the PROPERTY column.
Under PROPERTY, click Tracking Info -> Tracking Code.
To collect data, you must copy and paste the Analytics tracking code
into the source code on every web page you wish to track.
Once you have the JavaScript tracking code snippet for your
property, copy the snippet exactly without editing it.
Paste your tracking code snippet (unaltered, in its entirety) before
the closing </head> tag on every web page on your site you wish to
track.
Once you have successfully installed Analytics tracking, it may take
up to 24 hours for data such as traffic referral information, user
characteristics, and browsing information to appear in your reports
Refer to:
https://support.google.com/analytics/answer/1008080?hl=en
https://analytics.google.com
STEP 2: Get Tokens
Google Project:
To create a Google Cloud Platform project, open the Google Developers Console (https://console.developers.google.com) and click Create Project.
Enable OAuth 2.0 API access:
Your application will need to access user data and contact other Google services on your behalf. Use OAuth 2.0 to grant your app API access.
To enable that, you need a client ID:
Open the Google API Console Credentials page (https://console.developers.google.com/apis/credentials).
From the project, drop-down and select your project.
Select Create credentials and choose OAuth client ID.
Under Application type, select Web application, enter a Name and
set the Restrictions by entering JavaScript origins, Redirect URIs to point the website where you are planning to display the data, and then click Create.
Make note of the OAuth 2.0 client_id and client_secret. You will need them to configure the UI.
Get Authorization code:
Enter in browser:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&client_id={{
client_id}}&redirect_uri={{redirect_uri }}
&approval_prompt=force&access_type=offline
You will get redirected to
{{redirect_uri }}?code=={{authorization_code}}#
Get Refresh Token:
Send a POST request, possibly via a REST console to
https://www.googleapis.com/oauth2/v3/token?code={{authorization_code}}
&client_id={{client_id}}&client_secret={{client_secret}}
&redirect_uri={{redirect_uri }}&grant_type=authorization_code
You will get a JSON response with
{"refresh_token": refresh_token}
You can use the refresh token to get access token to access to Google APIs.
Get the Access Token:
Send a POST request to,
https://www.googleapis.com/oauth2/v3/token?client_id={{client_id}}
&client_secret={{client_id}}
&grant_type=refresh_token&refresh_token={{refresh_token}}
You will get a JSON with access_token in the response.
{access_token: {{access_token}}}
Example:
var access_token = '';
function getAccessToken(){
$.post('https://www.googleapis.com/oauth2/v3/token', {
client_id: {{client_id}},
client_secret: {{client_secret}},
grant_type: 'refresh_token',
refresh_token: {{refresh_token}}
}, function (data, status) {
if (status === 'success') {
access_token = data.access_token;
// Do something eith the access_token
}
else {
console.error(status);
}
});
}
Check Token validity:
Send a POST request to,
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={{access_token}}
Example:
function checkValidity() {
$.post('https://www.googleapis.com/oauth2/v1/tokeninfo', {
access_token:{{access_token}}
}).done(function (data, status) {
if (status === 'success') {
console.debug(data.expires_in);
var check = false;
check = data.hasOwnProperty('expires_in');
if (check) {
// Token is valid
}
if (!check) {
getAccessToken();
}
}
else {
console.debug(status);
}
})
.fail(function (data) {
console.error(data);
getAccessToken();
});
}
Step 3: Fetch Data
Embed API:
The GA Embed API is a JavaScript library that allows you to easily create and embed your GA dashboard on your website in a matter of minutes.
Refer to https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started.
Query Explorer:
Visit Embed API Query Explorer and authorize
https://ga-dev-tools.appspot.com/query-explorer/
Select the view for which you want to fetch the data.
Select the required metrics and dimensions.
Example:
Get Country Data (I want to know the number of users accessing my website from each country).
To get that data, select the metrics as 'users' and the dimensions as 'country'.
Click on Run Query.
You will find the analytics data for the query displayed in a table.
Copy the API Query URI. And add access_token={{access_token}} to the URI.
Example:
https://www.googleapis.com/analytics/v3/data/ga?ids={{ids}}&start-date=2015-07-01&end-date=today&metrics=ga%3Ausers&dimensions=ga%3Acountry&access_token={{access_token}}
Send POST request to the URIs to get the data in your browser.
Example:
function gaGetCountry() {
$.get('https://www.googleapis.com/analytics/v3/data/ga?' +
'ids={{ids}}' +
'start-date=2015-07-01&' +
'end-date=today&' +
'metrics=ga%3Ausers&' +
'dimensions=ga%3Acountry&' +
'sort=ga%3Ausers&' +
'filters=ga%3Ausers%3E10&' +
'max-results=50' +
'&access_token=' + {{access_token}},
function (data, status) {
if (status === 'success') {
// Display the Data
drawRegionsMap(data.rows);
} else {
console.debug(status);
}
});
}
Step 4: Display Data
Now we have gathered the data. Finally we have to display them on our website.
"Display live data on your site" is the title of Google Charts. And that is what we are going to do.
Refer to https://developers.google.com/chart/.
The following example will draw a GeoChart in the div with id='countryChart'.
// Draw country chart
function drawRegionsMap(data) {
var head = data[0];
head[0] = 'Country';
head[1] = 'Users';
for (var i = 1; i < data.length; i++) {
var d = data[i];
d[1] = Number(d[1]);
}
var chartData = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Website is viewed from,',
domain: '{{Country Code eg: IN for India}}',
tooltip: {
textStyle: {
color: 'navy'
},
showColorCode: true
},
legend: {
textStyle: {
color: 'navy',
fontSize: 12
}
},
colorAxis: {
colors: ['#00FFFF', '#0000FF']
}
};
var chart = new google.visualization.GeoChart(document.getElementById('countryChart'));
chart.draw(chartData, options);
}
Refer to https://newtonjoshua.com to view the above example in action.
I'd recommend to use the new Google APIs Client Library for .NET (currently in beta). Information about the Analytics API can be found here. Note that the Client Library for .NET (google-api-dotnet-client) supersedes the .NET library for the Google Data API (google-gdata).
Unfortunately, there is no sample code available yet from Google (see this issue) but this question on SO should help.
If you don't want to login every time you access Analytics data, you can use OAuth 2.0 authorization with offline access. You have to grant initial access to your web application, though. This requires you to login once but you can use a refresh token later on.
To date, the easiest solution is to create a report of your Google Analytics data in Google Data Studio (free, native connector to GA), and share that report to embed in an <iframe>
See details on https://support.google.com/datastudio/answer/7450249?hl=en
You get
flexible vizualisation
security and control on the data being shared
0 code nor maintenance
result is being cached for better performance
I spent a couple of days trawling the Internet to get some sample ASP.NET code with no luck. I used Koffe14's method for authentication, and also Linda Lawton's excellent ASP.NET analytics example.
I've posted the code on my website. It's not MVC, but it might help other people who need to get data from Google analytics into an ASP.NET web page using the v3 Google API.
Check out embeddedanalytics.com (disclaimer - I work with them).
This is a simple yet powerful solution geared for people that don't want deal with learning the GA API and then having to link it to visualization (e.g. charts/graphs).
Basically define your charts and embed a snippet of code where you want the chart to show. We also support mechanisms so that it is easy to integrate into a custom built CMS or other web portal.

Categories