Skip to content

Instantly share code, notes, and snippets.

@kruppel
Created May 18, 2011 16:24
Show Gist options
  • Save kruppel/978926 to your computer and use it in GitHub Desktop.
Save kruppel/978926 to your computer and use it in GitHub Desktop.
chattradio diff
diff --git a/app.js b/app.js
index cd2fd3c..89fa861 100644
--- a/app.js
+++ b/app.js
@@ -1,8 +1,12 @@
-
var express = require('express'),
jade = require('jade'),
app = module.exports = express.createServer();
+// Models
+var room = require('./lib/room.js'),
+ user = require('./lib/user.js'),
+ song = require('./lib/song.js');
+
var DOTCLOUD_APP_PORT = 8080;
app.API_KEYS = require('./config/api_keys');
@@ -88,112 +92,103 @@ STATUS = {
everyone.now.STATUS = STATUS;
everyone.connected(function(){
- console.log("Joined: " + this.now.name);
+ //console.log("Joined: " + this.now.name);
});
everyone.disconnected(function(){
- console.log("Left: " + this.now.name);
+ //console.log("Left: " + this.now.name);
});
var check = require('validator').check,
sanitize = require('validator').sanitize
-everyone.now.distributeMessage = function(message){
- var user = Users[this.user.clientId];
-
- message = sanitize(message).trim();
- message = sanitize(message).xss();
- console.log(message);
- console.log((user));
- // make sure we have an internal user and room
- if (!user || !user.room) return;
- user.room.roomGroup.now.receiveMessage(user.username, message);
-};
-// Get the models we'll need
-require('./lib/room.js');
-require('./lib/user.js');
-require('./lib/song.js');
+everyone.now.distributeMessage = function(roomName, message) {
+ user.getUser(this.user.clientId, function(err, currUser) {
+ room.getRoom(roomName, function(err, currRoom) {
+ if (!currRoom) { return; }
-// Maps of all Rooms and Users
-app.Rooms = Rooms = {};
-app.Users = Users = {};
-app.Room = Room;
+ message = sanitize(message).trim();
+ message = sanitize(message).xss();
+ console.log(message);
+ console.log(currUser.username + ' - ' + message);
+
+ currRoom.roomGroup.now.receiveMessage(currUser.username, message);
+ });
+ });
+};
/* A join method for every client */
everyone.now.join = function(roomName) {
+ /**
+ * SIMPLE
+ * ======
+ * // Get room
+ * // this.now.room = roomName;
+ * // nowjs.getGroup(this.now.room)
+ * currRoom = room.getRoom(roomName);
+ * // Create/get user
+ * currUser = user.getUser(this.user.clientId);
+ * // Add user to room
+ * currRoom.addUser(currUser);
+ */
+ var self = this;
+
// See if the room already exists, if not create it
- var room = null;
- if (roomName in Rooms) {
- room = Rooms[roomName];
- }
- else {
- room = new Room(roomName);
- Rooms[roomName] = room;
- }
-
- // Find our internal User object for the user
- var user = null;
- if (!(this.user.clientId in Users)) {
- // If this user wasn't registered, register now
- this.now.registerUser();
- }
- user = Users[this.user.clientId];
- if (user.room) user.room.removeUser(user);
-
- // Add the user to our room and nowjs group
- room.addUser(user);
- this.now.broadcastJoin();
-
- // Start the user at the correct position in the playing song.
- // xxx slloyd Song position needs a magic number to incorporate delays:
- // - client -> server transit for last reported pos
- // - server -> client transit for playAt call
- // - rdio flash player buffer/seek time
- this.now.playAt(room.station.song.id, room.station.song.pos + 3);
+ room.getRoom(roomName, function(err, currRoom) {
+ user.getUser(self.user.clientId, function(err, currUser) {
+ currUser.username = self.now.name;
+
+ // Add the user to our room and nowjs group
+ currRoom.addUser(currUser);
+
+ // Broadcast join to the room
+ self.now.broadcastJoin(currRoom);
+
+ // Start the user at the correct position in the playing song.
+ // xxx slloyd Song position needs a magic number to incorporate delays:
+ // - client -> server transit for last reported pos
+ // - server -> client transit for playAt call
+ // - rdio flash player buffer/seek time
+ self.now.playAt(currRoom.station.song.id, currRoom.station.song.pos + 3);
+ });
+ });
}
/**
* \brief Broadcast user has joined room
*/
-everyone.now.broadcastJoin = function() {
- everyone.now.receiveJoin(this.now.name);
-}
+everyone.now.broadcastJoin = function(userroom) {
+ var self = this;
-everyone.now.updateUsers = function() {
- Users.forEach(function(user) {
- console.log(user);
- });
-}
-
-everyone.now.registerUser = function() {
- user = new User(this.now.name, this.user.clientId);
- Users[this.user.clientId] = user;
+ userroom.roomGroup.now.receiveJoin(userroom.name, self.now.name);
}
// A method for all users to report back where they are in a song
-everyone.now.updatePosition = function(pos){
-
- // get the internal User object
- var user = Users[this.user.clientId];
-
- // if this user is further along than our last position, update
- // that position
- if (user && pos > user.room.station.song.pos) {
- user.room.station.song.pos = pos;
- }
+everyone.now.updatePosition = function(roomName, pos) {
+ user.getUser(this.user.clientId, function(err, currUser) {
+ room.getRoom(roomName, function(err, currRoom) {
+ // if this user is further along than our last position, update
+ // that position
+ if (currUser && pos > currRoom.station.song.pos) {
+ currRoom.station.song.pos = pos;
+ }
+ });
+ });
};
// Clients report when they complete track playback
-everyone.now.trackFinished = function(trackId) {
-
- var user = Users[this.user.clientId],
- station = user.room.station;
-
- // Ensure that we only call station.next() once
- if (trackId == station.song.id) {
- station.next(function (err, song) {
- everyone.now.playAt(song.id, 0);
+everyone.now.trackFinished = function(roomName, trackId) {
+ user.getUser(this.user.clientId, function(err, currUser) {
+ room.getRoom(roomName, function(err, currRoom) {
+ var currStation = currRoom.station;
+
+ // Ensure that we only call station.next() once
+ if (trackId == currStation.song.id) {
+ currStation.next(function (err, song) {
+ everyone.now.playAt(song.id, 0);
+ });
+ }
});
- }
+ });
}
diff --git a/lib/room.js b/lib/room.js
index 7a9c951..10be787 100644
--- a/lib/room.js
+++ b/lib/room.js
@@ -1,21 +1,37 @@
-var nowjs = require("now");
+var rooms = {},
+ app = require('./../app.js'),
+ nowjs = require('now');
-Room = function (aName) {
+module.exports = {
+ getRoom: function(username, callback) {
+ var room;
+
+ if (!(username in rooms)) {
+ room = new Room(username);
+ rooms[username] = room;
+ }
+
+ callback(null, rooms[username]);
+ }
+};
+
+function Room(aName) {
this.name = aName;
this.roomGroup = nowjs.getGroup(this.name);
+ this.station = null;
this.song = null;
+
+ this.users = {};
}
Room.prototype = {
-
addUser: function(user) {
this.roomGroup.addUser(user.clientId);
- user.room = this;
+ console.log(this.users);
+ this.users[user.clientId] = user;
},
removeUser: function(user) {
this.roomGroup.removeUser(user.clientId);
- user.room = null;
}
-
-}
+};
diff --git a/lib/station.js b/lib/station.js
index fea1648..cfcc2b5 100644
--- a/lib/station.js
+++ b/lib/station.js
@@ -1,4 +1,3 @@
-
var stations = {},
app = require('./../app.js'),
lastfm = app.lastfm,
diff --git a/lib/user.js b/lib/user.js
index 1e44d43..bbbd9c2 100644
--- a/lib/user.js
+++ b/lib/user.js
@@ -3,18 +3,24 @@ var users = {},
rdio = app.Rdio;
module.exports = {
- getCurrentUser: function(callback) {
- rdio.request(function(err) {
- console.log('rdio api call done bad. ' + err);
- callback(null);
- }, {}, callback(data));
+ getUser: function(clientId, callback) {
+ var user;
+
+ if (!(clientId in users)) {
+ user = new User(clientId);
+ users[clientId] = user;
+ } else {
+ user = users[clientId];
+ }
+
+ callback(null, user);
}
};
-User = function(username, clientId) {
- this.username = username;
+function User(clientId) {
+ this.username = null;
this.clientId = clientId;
- this.room = null;
+ this.rooms = [];
this._token = null;
this._tokensecret = null;
}
diff --git a/package.json b/package.json
index be5e353..00aac2e 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"lastfm": "=0.6.0",
"less": ">=1.0.41",
"jade": ">=0.10.1",
- "now": ">=0.5.3",
+ "now": "0.5.3",
"request": ">=0.10.0",
"validator": ">=0.2.0"
}
diff --git a/public/javascripts/client.js b/public/javascripts/client.js
index d31d0ce..8eaa22c 100644
--- a/public/javascripts/client.js
+++ b/public/javascripts/client.js
@@ -1,4 +1,5 @@
$(document).ready(function(){
+ var roomName = "";
/* Rdio Flash player setup */
$.getJSON('/flashvars', function (data) {
@@ -18,8 +19,9 @@ $(document).ready(function(){
/* Join a room */
$("#join-channel").keydown(function(e){
now.registerUser();
- var code = (e.keyCode) ? e.keyCode : e.which,
- roomName = $("#join-channel").val();
+ var code = (e.keyCode) ? e.keyCode : e.which;
+
+ roomName = $("#join-channel").val();
if (!roomName || roomName.length < 1 || code !== 13) {
return;
@@ -40,7 +42,7 @@ $(document).ready(function(){
}
e.preventDefault();
- now.distributeMessage(msg);
+ now.distributeMessage(Chattradio.roomName, msg);
$("#message").val("");
});
@@ -50,11 +52,12 @@ $(document).ready(function(){
return ++counter;
}
- now.receiveJoin = function(name) {
+ now.receiveJoin = function(roomName, username) {
var chatlog = $('#chat-log'),
scrollHeight;
- chatlog.append('<br>' + name + ' joined.');
+ Chattradio.roomName = roomName;
+ chatlog.append('<br>' + username + ' joined.');
scrollHeight = chatlog.attr("scrollHeight");
chatlog.attr("scrollTop", scrollHeight);
}
@@ -69,16 +72,20 @@ $(document).ready(function(){
chatlog.attr("scrollTop", scrollHeight);
}
+ now.updateUsers = function(users) {
+ users.forEach(function(user) {
+ $("#users").append('<br>' + user.username);
+ });
+ }
+
/* Play a song at a position */
- now.playAt = function(id, pos){
+ now.playAt = function(id, pos) {
function waitForReady() {
if (Chattradio.RdioListener.isReady) {
var volume = sessionStorage.getItem('volume');
if (volume) {
- volume = volume.replace(/%/g, '');
-
// Init swf player volume
Chattradio.rdioswf.rdio_setMute(Boolean(sessionStorage.getItem('mute')));
Chattradio.rdioswf.rdio_setVolume(parseInt(volume) / 100);
@@ -101,7 +108,6 @@ $(document).ready(function(){
}
waitForReady();
-
}
now.pause = function() {
@@ -159,7 +165,7 @@ Chattradio.RdioListener = {
var percent = position / Math.floor(Chattradio.track.duration) * 100;
$('#seek').css('width', percent + '%');
- now.updatePosition(position);
+ now.updatePosition(Chattradio.roomName, position);
},
shuffleChanged: function (shuffle) {
diff --git a/routes/all.js b/routes/all.js
index c399b1b..9ec7939 100644
--- a/routes/all.js
+++ b/routes/all.js
@@ -1,4 +1,5 @@
var user = require('./../lib/user'),
+ room = require('./../lib/room'),
station = require('./../lib/station');
module.exports = function(app) {
@@ -21,24 +22,24 @@ module.exports = function(app) {
});
app.get('/rooms/:id', function (req, res) {
- var room = req.params.id;
-
- if (app.Rooms[room]) {
- app.Rdio.request(function (err) {
- res.send(JSON.stringify({ 'oops, room-fail': err.data }));
- }, {
- method: 'currentUser',
- token: req.session.oauth_access_token,
- token_secret: req.session.oauth_access_token_secret ,
- }, function (data) {
- var userUrl = data.result.url.split('/');
- res.render('room', {username: userUrl[userUrl.length -2],
- roomName: room});
- });
- } else {
- // create a room?
- res.send('YOU BROKE IT');
- }
+ room.getRoom(req.params.id, function(err, uroom) {
+ if (uroom) {
+ app.Rdio.request(function(err) {
+ res.send(JSON.stringify({ 'oops, room-fail': err.data }));
+ }, {
+ method: 'currentUser',
+ token: req.session.oauth_access_token,
+ token_secret: req.session.oauth_access_token_secret ,
+ }, function (data) {
+ var userUrl = data.result.url.split('/');
+ res.render('room', {username: userUrl[userUrl.length -2],
+ roomName: uroom.name });
+ });
+ } else {
+ // create a room?
+ res.send('YOU BROKE IT');
+ }
+ });
});
// temporary test route
@@ -57,25 +58,22 @@ module.exports = function(app) {
app.post('/rooms', function (req, res) {
var username = req.param('lastfm');
console.log('posting username:' + username);
- station.getStationForUser(username, function(err, station) {
-
+ station.getStationForUser(username, function(err, currStation) {
if (err) {
return res.send(err.message);
}
- var room;
- if (username in app.Rooms) {
- room = app.Rooms[username];
- res.redirect('/rooms/' + username);
- } else {
- room = new app.Room(username);
- app.Rooms[username] = room;
- room.station = station;
- station.next(function (err, id) {
- if (err) return res.send(err.message);
+ room.getRoom(username, function(err, currRoom) {
+ currRoom.station = currStation;
+
+ currStation.next(function (err, id) {
+ if (err) {
+ return res.send(err.message)
+ }
+
res.redirect('/rooms/' + username);
});
- }
+ });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment