Soundcloud SDK - load track from url - javascript

So I did a tutorial on Soundcloud SDK through CodeAcademy here and wanted to take the knowledge I learned from that and put it on Codepen. But I want to use a different track than the one they use in this tutorial - specifically this song https://soundcloud.com/hardwell/coldplay-sky-full-of-stars-hardwell-remix-download.
I read that /resolve was a good approach to get the trackid but it's not working. I get 403 Forbidden in the console.
SC.get('/resolve/?url=https://soundcloud.com/hardwell/coldplay-sky-full-of-stars-hardwell-remix-download&client_id=3596a42d6242b9c1ee76740a7771d33a', function(track) {
console.log(track); // returns null
});
Here is my codepen. Please help me load this track for my basic SoundCloud SDK audio player. Thanks

Your code is correct and even works with some tracks, for example the ones from the documentation.
You're encountering a problem that I found personally should be emphasized in their documentation. The API access for this track has been disabled (even if the widget is enabled), therefore your have not right to query this track using the API and it returns a 403 Forbidden HTTP status code.
This is described in the Linked Services part of the SoundCloud terms of use:
You can limit and restrict the availability of certain of Your Content to other users of the Platform, and to users of Linked Services, at any time using the permissions tab in the track edit section for each sound you upload, subject to the provisions of the Disclaimer section below.
You can check in your code if any error like this one was encountered while fetching the track informations and depending on the success or failure, continue with the correct action:
var clientId = 'CLIENT_ID';
SC.initialize({
client_id: clientId
});
var songUrl = 'https://soundcloud.com/hardwell/coldplay-sky-full-of-stars-hardwell-remix-download';
SC.get('/resolve?url=' + songUrl + '&client_id=' + clientId, function(data, error) {
if (error === null) {
console.log('Do something like playing the song.');
} else {
console.log('Print an error message?');
}
});

Related

WP REST API ERROR 401 While trying to fetch image from wp:featuredmedia

I'm trying to fetch featured image from my published post but it seems impossible! I get
an error :( that's the code:
function fetchSlideShow(){
let endpoint = "http://loreleiheckmann.com/wordpress/wordpress/wp-json/wp/v2/Vinyls?_embed";
fetch(endpoint)
.then(e => e.json())
.then(showSlideShow);
}
function showSlideShow(data){
console.log(data);
data.forEach(showSingleSlide);
showSlides();
}
function showSingleSlide(aSlide) {
let template = document.querySelector(".slide_template").content;
let clone = template.cloneNode(true);
console.log(aSlide);
clone.querySelector("img").setAttribute("src", aSlide._embedded["wp:featuredmedia"]
[0].media_details.source_url);
let SlideList = document.querySelector("#SlideList");
SlideList.appendChild(clone);
}
While going to the array I see error 401 :( and moreover: Cannot read property 'source_url' of undefined" I don't know what I'm doing wrong .. any insights?
HERE ARE THE ERRORS -> 401 ON CONSOLE + PROBLEM WITH URL.:
Please try changing your url in the endpoint variable:
let endpoint = "http://loreleiheckmann.com/wordpress/wordpress/wp-json/wp/v2/posts?per_page=20&_embed=wp:featuredmedia
If you need more data you can add them with a comma:
wp-json/wp/v2/posts?per_page=20&_embed=wp:term,wp:featuredmedia
Post per page is optional, but I would prefer having that set.
And you should write what image size you need. That way rest api will give you the right source url:
_embedded['wp:featuredmedia']['0'].media_details.sizes.medium_large.source_url
I think it would also be better practice if you use an ssl certificate, there are free by "Let's encrypt".
EDIT:
Your screenshot shows the rest api message:
wp:featuredmedia: Array(1)
0:
code: "rest_forbidden"
data: {status: 401}
message: "Sorry, you are not allowed to do that."
So the 401 status code means: unauthorised
Seems like you are not allowed to access the data via rest api.
There could be multiple reasons for that:
The image is attached to an unpublished post. The post may have the status "private" or "draft", and therefore is not public available.
Your post (and attached image) is not available for not logged in users. If there is a restriction to view your code, this also applies to rest api.
Maybe you are using some kind of membership plugin that restricts the wp rest-api. Try deactivating all plugins if one of them affects the behaviour.
You have added some custom code to restrict access rest api access.
If nothing works for you, you should look into your database and check the medias post_status.
I think it is working fine, but you do not have access to view the posts data. This is what the 401 error indicates.
To whom it may concern - In the end, I added image in WP by custom post type ( I gave up wp:featured media - I wasn't able to fetch it.) Afterward I added a code to JS -> b.querySelector(".img").setAttribute("src", a.acf.image.url); so it works:)

Facebook: How to get any pages total likes, ratings?

I would like to get any facebook page's total likes, ratings, etc...
I have created a developer account
What I tried:
- Created an app for this.
- Tried to fetch this information using AppID & AppSecret
- Tried Using access token
I have also done R&D on google and tried many examples but not getting a correct solution which I want.
Pls help me to solve this.
Thanks.
Edit (taken from comment by author):
I tried this example but for every page it requires pageaccesstoken
FB.api('/{pagename}?fields=ratings', function (response) {
Data = response.name; //alert(Data);
if (response.error) {
alert(response.error.message);
}
}, { access_token: "xxxx|yyyy" });
You can get the current likes of a Page with a simple App Access Token:
/[page-id]?fields=fan_count&access_token=[App-Token]
For the ratings of a Page, you need to use a Page Token instead:
/[page-id]/ratings&access_token=[Page-Token]
More information about Tokens and how to get them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

Having an hard issues with google and his API or login buttons

I followed the documentation from them and i don't see what is my error from my part !
I'm trying to get the information from the profile of the user (which could be the name gender etc etc...)
And i followed all the steps from google website (in my case, the javascript code)
Everything works, less that request which i want to do to the user profile!
This example is the callback function after logging to the google account which is automatically executed:
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
//document.getElementById('signinButton').setAttribute('style', 'display: none');
console.log(authResult);
gapi.client.setApiKey('API_KEY'); //(That function gaves me an error which is invalid credentials, i did put my API_KEY (from the google console ))
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log(resp);
//console.log('Retrieved profile for:' + resp.displayName);
});
});
gapi.auth.signOut(); // logging out !
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
Everything works less than setAPIkeys and everything below !
If i don't put the set function and the code below, i receive an 400 error ("message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.").
So i'm losing hope in doing that sincerely ... i think that google's documentation is awful !
What's wrong with that?
Merry christmas to everyone !
P.S. : yeah i know that the API key musn't be hard coded, but i'm so lost with the documentation from google sincerely ...
Possible solutions:
Try removing
gapi.client.setApiKey('API_KEY');
and
gapi.auth.signOut(); // logging out !
signOut works very fast, while gapi.client.load is asynchronous function which loads js code. User is probably signed out before gapi.client.load callback is executed.
I'm not sure if that's required:
Go to the Google Developers Console.
Select your project.
In the sidebar on the left, select APIs & auth.
In the displayed list of APIs, find the Google+ API and set its status to ON.
Make sure you're requesting scope https://www.googleapis.com/auth/plus.login or https://www.googleapis.com/auth/plus.me while signing in.

Facebook API - access token for web application

I am making a web app that pulls the latest posts from our Facebook page and processes them.
This is all working fine with a hard-coded access token generated from this page.
The problem is that this token expires, so i am looking for a solution to generate a new token every time the page loads or a non-expiring token - (i have read somewhere that non expiring tokens don't exist anymore).
So of course i did some research, here, here and here.
But non of these examples seem to be working.
Before any complaints of some code that i have tried so far, this is my working example - with an expiring access token:
var Facebook = function () {
this.token = 'MYTOKEN';
this.lastPost = parseInt((new Date().getTime()) / 1000);
this.posts = [];
};
Facebook.prototype.GetPosts = function () {
var self = this;
var deffered = $q.defer();
var url = 'https://graph.facebook.com/fql?q=SELECT created_time, message, attachment FROM stream WHERE created_time < ' + self.lastPost + ' AND source_id = 437526302958567 ORDER BY created_time desc LIMIT 5&?access_token=' + this.token + '';
$http.get(url)
.success(function (response) {
angular.forEach(response.data, function (post) {
self.posts.push(new Post(post.message, post.attachment.media, post.attachment.media[0].src, post.created_time, 'facebook'));
});
self.lastPost = response.data[response.data.length -1].created_time;
deffered.resolve(self.posts);
self.posts = [];
});
return deffered.promise;
};
return Facebook;
Any help / suggestion will be greatly appreciated.
First off, it is important to remember that Facebook has just launched the Version 2 of the Graph API. From April 2014 on, if you have issues with your app, you need to tell us when you created it on Facebook Developers (new apps use the Version 2 by default).
In order manage pages, your app needs to have manage_pages permission. Make sure that the user you want to manage fan pages for has authorized you. If your app uses the Version 2, make sure that Facebook (the Facebook staff) has authorized you to ask users that kind of permission, otherwise your app won't work.
Once you get your token, exchange it for a permanent token (or a token with long expiry date). Make sure you use the token of the fan page, not the token of the user.
If instead you want to read the stream of public fan pages, you need an access token with read_stream permissions. This permission needs to be approved by Facebook (see above) and this specific type of permission takes time to approve, if you're using the Version 2 of the Graph API. If you're using the old API (Version 1), you can still do that without pre-approval on Facebook's side.
The URL to ask for the permission to read the stream is as follows: https://www.facebook.com/dialog/oauth?client_id=$YOUR_APP_ID&redirect_uri=$YOUR_URL&scope=read_stream,manage_pages (i've added manage_pages in this case, you may not need it).
That url will prompt for authorization. Once the user has authorized the app, you'll be recirected to the URL you chose, with a code= variable.
At that point, call this other url:
https://graph.facebook.com/oauth/access_token?client_id={$app_id}&redirect_uri=$someurl&client_secret={$app_secret}&code={$code}
You'll get a response that has the access_token=variable in it. Grab that access token, exchange it for a long one, with the following URL:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={$app_id}&client_secret={$app_secret}&fb_exchange_token={$token_you_have_just_grabbed}
The response will give you a token that lasts for some time. Previously, Facebook had decided to have these "long duration tokens" expire after one month. I have found out, though, that they may have changed their mind: if you put a user token in the debugger, you'll see it never expires.
This is the authorization flow for users who visit with a browser. There's the app authorization flow too. If all you need is a stream from your own Fan page, you want to do the following (with Graph API V.1):
make an HTTP GET request using the following URL:
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}
Use the resulting token to make another HTTP GET call, like so:
https://graph.facebook.com/{$your_page_id}/feed?{$authToken}&limit=10
//ten posts
Decode the json object
You're done.

How to get Facebook user's friends' profile picture using Javascript SDK V2.0

I am creating a website using Facebook API V2.0 JavaScript SDK and I would like to display the profile pictures of the user's friends.
I have managed to display my profile picture using the graph API but I can't manage to get the ID of all my friends if I am logged in my app (I am an admin). If I have the ID, I'll be able to show their profile picture.
In the graph explorer, I have checked all permissions (User Data Permissions + Extended Permissions). I have noticed if I switch to API V1.0, I get friends permission which is exactly what I'd like.
Also, I have added a couple of permission to my app in Facebook developers > App details > App Center Listed Platforms > Configure app center permissions. (user_friends + friends_birthday + friends_religion_politics + friends_relationships + friends_relationship_details + friends_location + friends_photos + friends_about_me)
So far, my html looks like this :
<fb:login-button scope="public_profile,email,user_friends,read_friendlists" onlogin="checkLoginState();">
After loading the Facebook SDK, I have :
function getUserFriends() {
FB.api('me/friends?fields=first_name,gender,location,last_name', function (response) {
console.log('Got friends: ', response);
$("#friendslist").html('<img src="https://graph.facebook.com/'+ response.id+'/picture?type=large"/>');
});
}
However, the array which is suppose to contain all my friends info is empty (see image : http://www.screencast.com/t/W02GaOm3h)
If all you need is their image, this can be found in the "taggable_friends" scope. However, do note that this field is very limited (by design) and that you require additional review by Facebook in order to present it to the average user.
It contains:
A taggable id. This is an id with the express purpose of tagging; it cannot be used to identify the user or otherwise gather information from their profile.
A name. The user's first and last name.
A picture, with common related fields. Url, is_silhouette, height and width.
function getUserFriends() {
FB.api('me/taggable_friends', function (response) {
console.log('Got friends: ', response.data);
$("#friendslist").html('<img src="'+response.data[0].picture.data.url+'"/>');
// maybe an $.each as well
// var friendMarkup = '';
// $.each(response.data, function(e, v) {
// friendMarkup += '<img src="' + v.picture.data.url +'" alt="'+ v.name +' picture"/>';
// }
// $("#friendlist").html(friendMarkup);
});
}
Related reading:
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends
https://developers.facebook.com/docs/opengraph/using-actions/v2.0 - Tagging friends and Mentioning friends sections
A disclaimer: I've been battling with this issue for several days without really being able to mention-tag. My submission to use taggable_friends as a comprehensive, navigatable list for the user was rejected and I speculate (speculation ho!) it was because I did no actual tagging. I'll get back to this in a few days when I've clarified and re-submitted my request for a review on Facebook.
-- Edit --
It would seem the reason my initial submission was rejected was because I was using a special development url and did not point out clearly enough why it was not enough to use the url set under settings. This time I clearly pointed out and explained this reasoning in both the general description of my submission and in the step-by-step notes. In summary, be exceptionally clear in your submission about everything; your reasoning as to why you need this permission, how they can access it, etc. Just to make sure it isn't missed if skim-read.
It seems like in V2.0, Friends permission have dissapeared :
Facebook graph api explorer doesn't show 'Friends Data Permission' tab
https://developers.facebook.com/docs/facebook-login/permissions/v2.0

Categories