Unable to create Spotify app playlist view - spotify

I'm trying to display a simple playlist view in my Spotify app with the following code:
sp = getSpotifyApi(1);
var m = sp.require("sp://import/scripts/api/models");
var v = sp.require("sp://import/scripts/api/views");
var jq = sp.require('sp://XXX/jquery/jquery-1.7.1.min');
var pl = m.Playlist.fromURI('spotify:user:d3marcus:playlist:4zPZzImEYkUOVBvxIo42im');
var player = new v.Player();
player.track = pl.get(0);
player.context = pl;
var list = new v.List(pl);
$('XXX').append(list.node);
This will result in an empty list view and an error caught in sp://import/scripts/language.js:44: "Uncaught TypeError: Cannot read property 'length' of undefined"
Any suggestions?

I would say you are getting this error because the playlist has not yet loaded when you do pl.get(0). To make sure the playlist model has loaded you could either do
pl = m.Playlist.fromURI('spotify:user:d3marcus:playlist:4zPZzImEYkUOVBvxIo42im');
pl.observe(models.EVENT.LOAD, function() {
player.track = pl.get(0);
...
});
or
m.Playlist.fromURI("spotify:user:d3marcus:playlist:4zPZzImEYkUOVBvxIo42im", function(pl) {
player.track = pl.get(0);
...
});

I'm not sure, but could you try this :
$('YYY').append($(player.node));
$('XXX').append($(list.node));
instead of
$('XXX').append(list.node);
let us know...

For the 1.0 API:
require([
'$api/models',
'$views/list#List'
], function (models,List) {
var addList = function(list) {
list.load('tracks').done(function(list) {
list.tracks.snapshot().done(function(trackSnapshot){
// Make the playlist view
var multiple_tracks_player = document.getElementById('addedTracksList');
var playableList = List.forPlaylist(list);
multiple_tracks_player.appendChild(playableList.node);
playableList.init();
});
});
}
exports.addList = addList;
}
// Example of use:
addList(models.Playlist.fromURI(...))
I've tested it as used above, so it should work.
I found this in the tutorial-app available on github under "Playing music"-section -> "Play a list of tracks"
I hope this is helpfull.

Related

Extending element methods in JSDOM

How can we to extend element methods in JSDOM to all opened pages?
// load the module and few pages
const JSDOM = require("jsdom").JSDOM;
var dom1 = new JSDOM("<p>1st</p><p>2nd</p>");
var dom2 = new JSDOM("<p>1st</p><p>2nd</p>");
...
// add methods such as: map, filter, searchText...
var window = dom1.window;
window.NodeList.prototype.map =
function (cb) { return Array.from(this).map(cb) };
...
// Execution:
dom1.window.document.querySelectorAll('p').map(p=> p.textContent);
// returns: [ '1st', '2nd' ]
dom2.window.document.querySelectorAll('p').map(p=> p.textContent);
// throws an error
Is it possible to extend NodeList ones, without loading it for every new document?
Something more like:
JSDOM.installedInterfaces.NodeList.prototype.map = ...

How do I search an object full of strings in node js?

I'm new to node js programming and I have the following :
var myObj = {
AD: '{+376}',
AF: '{+93}',
AG: '{+1268}'
};
NOTE: I cannot modify this object data, as it comes from a third party component. I have only put an example of what data is returned to me in a local object for debugging purposes.
I'd like to be able to search this object for "AD" and pull out just the +376 from this line
"AD": "{+376}"
this does not seem to work:
var i = myObj.indexOf("AD");
console.log(i);
UPDATE
Sorry... I was using stringify on the object and the output I was seeing in the terminal window was wrong... I have corrected the question
UPDATE again
OK... running it using myObj works in a local sandbox... but using it on the actual data that comes back from the NPM object does not. Here is a RunKit:
https://npm.runkit.com/country-codes-list
This code does returns the number...
var ccl = require("country-codes-list")
var l = ccl.customList('countryCode', '+{countryCallingCode}');
console.log(l.AD);
BUT I need a variable instead of .AD like this:
var ad = 'AD'
var ccl = require("country-codes-list")
var l = ccl.customList('countryCode', '+{countryCallingCode}');
console.log(l.ad); // doesn't work !
This should work.
var ad = 'AD'
var ccl = require("country-codes-list")
var l = ccl.customList('countryCode', '+{countryCallingCode}');
console.log(l[ad]);
You can use the key to reach for the value.
var string = '{"AD":"{+376}","AF":"{+93}","AG":"{+1268}"}';
var object = JSON.parse(string);
function search(id) {
return object[id];
}
console.log(search('AD')) //--> {+376}

Getting Data from a Weather API to a Twitter Bot

I'm setting up a Twitter bot to tweet out a city's temperature, I got the API but I can't seem to hook it on my bot.js file
I tried changing the variables but nothing seems to work.
var Twit = require('twit');
var config = require('./config');
var T = new Twit(config);
gotData();
function setup() {
loadJSON("http://api.apixu.com/v1/current.json?key=7165704df08340e9b00213540192507&q=Colombo", gotData);
}
function gotData(data) {
console.log('Weather Data Retrieved...')
var r = data.current[2];
var tweet = {
status: 'here is ' + r + ' temperature test '
}
T.post('statuses/update', tweet);
}
TypeError: Cannot read property 'current' of undefined
Your call to gotData() does not pass a data argument so when the gotData function attempts to access data.current[2] data is undefined. By the looks of your code you just need to change the line gotData(); to setup();

How to unpack an google.protobuf.Any type in gRPC nodejs client?

My protobuf file is like this:
syntax = "proto3"; import "google/protobuf/any.proto";
service RoomService {
getTestAny (Hotelid) returns (google.protobuf.Any); }
message Hotelid {
string hotelid = 1;
}
message HtlInDate {
Hotelid hotelid = 1;
string date = 2;
}
My java-gRPC-server code is like that:
#Override
public void getTestAny(Roomservice.Hotelid request, StreamObserver<Any> responseObserver) {
Roomservice.Hotelid hotelid = Roomservice.Hotelid.newBuilder()
.setHotelid("This is Hotelid")
.build();
Roomservice.HtlInDate htlDate = Roomservice.HtlInDate.newBuilder()
.setHotelid(hotelid)
.setDate("This is Data")
.build();
responseObserver.onNext(Any.pack(htlDate));
responseObserver.onCompleted();
}
And I make a request from a nodejs-gRPC-client, which code is like that:
function () {
var client = new services.RoomServiceClient('localhost:6565',
grpc.credentials.createInsecure());
var request = new messages.Hotelid();
var hotelid = "ignore";
request.setHotelid(hotelid);
var call = client.getTestAny(request, function (err, response) {
var obj = response.toObject();
console.log(obj);
});
}
The response in nodejs-gRPC-client is a type of Any. And it contains a data array:
array:["type.googleapis.com/HtlInDate", Uint8Array[10,17,10...]]
I try to use response.toObject() to get HtlInDate instance but I just get like this:
obj:{
typeUrl:"type.googleapis.com/HtlInDate",
value:"ChEKD1RoaXMgaXMgSG90ZWxpZBIMVGhpcyBpcyBEYXRh"
}
So how can I unpack the Any type response and get the HtlInDate instance exactly? Thanks a lot if you have any idea about this!
Currently, the google.protobuf.Any type is not supported in Node.js, either in Protobuf.js, which gRPC uses by default, or by google-protobuf, which is the official first party protobuf implementation.
From documentation:
https://developers.google.com/protocol-buffers/docs/reference/javascript-generated#message
// Storing an arbitrary message type in Any.
const status = new proto.foo.ErrorStatus();
const any = new Any();
const binarySerialized = ...;
any.pack(binarySerialized, 'foo.Bar');
console.log(any.getTypeName()); // foo.Bar
// Reading an arbitrary message from Any.
const bar = any.unpack(proto.foo.Bar.deserializeBinary, 'foo.Bar');
Please take a note that for browser support you need to use webpack(probably with babel loader) or browserify
As found in google-protobuf tests Any is bundled with pack and unpack functions.
Your code could be unpacked like this:
function () {
var client = new services.RoomServiceClient('localhost:6565',
grpc.credentials.createInsecure());
var request = new messages.Hotelid();
var hotelid = "ignore";
request.setHotelid(hotelid);
var call = client.getTestAny(request, function (err, response) {
var obj = response.toObject();
console.log('Any content', obj);
var date = response.unpack(messages.HtlInDate.deserializeBinary, response.getTypeName());
console.log('HtlInDate', date.toObject());
});
}
This will deserialize the bytes received in the Any object.
You could also build some Any using pack function for wrapping TypeUrl and Value:
var someAny = new Any();
someAny.pack(date.serializeBinary(), 'HtlInDate')

Get new object from another class nodejs

Ok so I have a class that contains
Object JS
var GameServer = require("./GameServer");
var gameServer = new GameServer();
GameServer() contains
GameServer JS
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
}
Now, what im trying to acheive is getting gameServer from ObjectClass
In my class i've tried
new JS
var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
But from this way, I won't be able to grab the class GameServer() properties. I'm new to node and im sorry I have to ask this question. I'm currently stuck right now
When I try to grab clients from GameServer
var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
gameServer.clients.length;
I get error, clients is undefined. Any way around this?.
I cannot modify GameServer nor Object js.. Basicly im making a script attacthed to a script for extra functionalities.
You are missing the exports of your files so when doing require(file) you're getting and empty object {}..
For gameServer you should be doing something like:
'use strict';
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
}
module.exports = exports = GameServer;
ObjectClass
'use strict';
var GameServer = require("./GameServer");
var gameServer = new GameServer();
exports.gameServer = gameServer;
You need to understand that require cache the value returned by the file, so you would be using a singleton of gameServer.

Resources