Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

[dist] Added nowjs support, for realtime, also you can post new comme…

…nts based on the url and more
  • Loading branch information...
commit e1fe93bea9c634c6cd7ded2b90ba7aa1bd8dca21 1 parent e907b3b
@alejandro authored
View
130 app.js
@@ -1,24 +1,25 @@
+var express = require('express'),
+ crypto = require('crypto'),
+ url = require('url'),
+ sys = require('util'),
+ util = require('./lib/utils').util,
+ app = module.exports = express.createServer( express.cookieParser(),
+ express.session({ secret: 'keyboard cat' })),
+ nowjs = require('now'),
+ groups =[],
+ ID=require('./lib/ObjectID').ObjectId;
-/**
- * Module dependencies.
- */
-
-var express = require('express')
- , routes = require('./routes')
-
-var app = module.exports = express.createServer();
-
-// Configuration
-
+var comments = require('./lib/comments');
+/* A little hack for correct handle of session */
+
app.configure(function(){
- app.set('views', __dirname + '/views');
- app.set('view engine', 'jade');
- app.use(express.bodyParser());
- app.use(express.methodOverride());
+ app.set('views',__dirname+ '/views');
+ app.set('view engine','jade');
app.use(app.router);
- app.use(express.static(__dirname + '/public'));
+ app.use(express.static(__dirname+'/public'));
+ app.use(express.methodOverride());
+ app.use(express.bodyParser());
});
-
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
@@ -26,10 +27,97 @@ app.configure('development', function(){
app.configure('production', function(){
app.use(express.errorHandler());
});
+app.dynamicHelpers({
+ message: function(req){
+ var err = req.session.error
+ , msg = req.session.success;
+ delete req.session.error;
+ delete req.session.success;
+ if (err) return '<p class="msg error">' + err + '</p>';
+ if (msg) return '<p class="msg success">' + msg + '</p>';
+ }
+});
-// Routes
+app.get('/', function(req, res){
+ var n = new ID().toString()
+ res.render("form",{user: { id: n},title:"HOME"})
+});
-app.get('/', routes.index);
+app.get('/otraURL',function(req,res){
+ console.log(req.url);
+ var n = new ID().toString();
+ res.render("form",{user: { id: n},title:"otraURL"})
+});
+app.get('/login', function(req, res){
+ res.render('login',{title:'Hol'});
+});
+
+app.post('/login', function(req, res){
+});
+// Regresa el index num de un valor en una array como el de un
+// objeto objeto["VALOR"] -> array[indexOf(array,VALOR)]
+function indexOf(array, value){
+ var i = 0, f=-1;
+ array.forEach(function(v) {
+ if (v.member.groupName === value) {
+ f = i;
+ } else if (array.length=== i){
+ return false;
+ } else {
+ i++;
+ }
+ });
+ return f;
+}
+// Una array es miembro
+function isMember(array,path){
+ var i = 0,f=-1;
+ array.forEach(function(v){
+ if (v.member.groupName === path) {
+ f = 0;
+ } else {
+ i++
+ }
+ });
+ return f;
+}
+app.listen(process.env.PORT || 8080);
+console.log('Server on port: %s \non: %s ',app.address().port,app.settings.env);
-app.listen(3000);
-console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
+var everyone = nowjs.initialize(app);
+everyone.now.joinRoom = function(req){
+ nowjs.getGroup(req.url).addUser(this.user.clientId);
+}
+everyone.now.sendComment = function(req) {
+ /* { url:'http://numbus.co:8080/f/prueba/h',
+ comment: { authorId: "4ebef2c27f21bd298a000000", comment: "YOUR COMMENT",time: Date.now(),
+ parent: "URL parent or comment parent as reply" } } */
+ comments.newComment(req, function(e,d){
+ nowjs.getGroup(req.url).now.receiveMessage(req.data.authorId,util.toStaticHTML(req.data.comment));
+ });
+}
+everyone.now.fetchBySite = function(req,res){
+ comments.fetchBySite(req.url,function(e,r){
+ res(e,r);
+ });
+}
+everyone.now.fetchByThread = function(req,res){
+ comments.fetchByThread(req,function(e,r){
+ res(e,r);
+ });
+}
+everyone.now.send = function(req){
+ if (req.data) {
+ nowjs.getGroup(req.url).now.receiveMessage(req.data.id, req.data.msg)
+ }
+}
+everyone.now.delete = function(req){
+ comments.deleteComment(req,function(e,d){
+ nowjs.getGroup(req.url).now.onEditMessage(req.data.authorId,util.toStaticHTML(req.data.comment));
+ });
+}
+everyone.now.edit = function(req){
+ comments.edit(req,function(e,d){
+ nowjs.getGroup(req.url).now.onEditMessage(req.data.authorId,util.toStaticHTML(req.data.comment));
+ });
+}
View
46 lib/ObjectID.js
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2011 Justin Dearing (zippy1981@gmail.com)
+* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+* and GPL (http://www.opensource.org/licenses/gpl-license.php) version 2 licenses.
+* This software is not distributed under version 3 or later of the GPL.
+*
+* Version 2.0.0
+* Implemented for server-side by Alejandro Morales (vamg008[at]gmail[dot]com)
+* Date: Nov 11 2011
+* https://github.com/numbus-org/ObjectId
+*/
+
+/**
+ * Javascript class that mimics how WCF serializes a object of type MongoDB.Bson.ObjectId
+ * and converts between that format and the standard 24 character representation.
+*/
+var ObjectId = exports.ObjectId = function () {
+ var increment = 0;
+ var pid = Math.floor(Math.random() * (32767));
+ var machine = Math.floor(Math.random() * (16777216));
+ this.timestamp = Math.floor(new Date().valueOf() / 1000);
+ this.machine = machine;
+ this.pid = pid;
+ if (increment > 0xffffff) {
+ increment = 0;
+ }
+ this.increment = increment++;
+ return this;
+};
+
+ObjectId.prototype.getDate = function () {
+ return new Date(this.timestamp * 1000);
+}
+/**
+* Turns a WCF representation of a BSON ObjectId into a 24 character string representation.
+*/
+ObjectId.prototype.toString = function () {
+ var timestamp = this.timestamp.toString(16);
+ var machine = this.machine.toString(16);
+ var pid = this.pid.toString(16);
+ var increment = this.increment.toString(16);
+ return '00000000'.substr(0, 6 - timestamp.length) + timestamp +
+ '000000'.substr(0, 6 - machine.length) + machine +
+ '0000'.substr(0, 4 - pid.length) + pid +
+ '000000'.substr(0, 6 - increment.length) + increment;
+}
View
52 lib/comments.js
@@ -68,22 +68,23 @@ Array.prototype.unique = function () {
comment: { authorId: "4ebef2c27f21bd298a000000", comment: "YOUR COMMENT",time: Date.now(),
parent: "URL parent or comment parent as reply" } }
*/
-var newComment = module.exports.newComment = function(Object,res) {
- var O = Object;
+var newComment = module.exports.newComment = function(req,res) {
+ var O = req;
/* the RegExp was a const but everytwo presented a bug */
if (/^(http:\/\/)([\w]+\.){1,}[A-Z]{2,}\b/gi.test(O.url)) {
- var threadId = convertURL(O.url).slug,
+ var threadId = convertURL(O.url).slug || 'home',
parent = convertURL(O.url).host;
thread = threadKey(threadId,parent),
toJSONString = function(val){val.comment = util.toStaticHTML(val.comment);return JSON.stringify(val)};
redis.exists(thread, function(e,d){
if (e) res('No ok: ' + e,null);
redis.hincrby(thread,'id',1,function(e4,d4){
- redis.hincrby('u:' + O.comment.authorId, 'id',1, function(error, data){
- O.comment.lid = data, O.comment.id = d4; /* Setting up floating points */
+ redis.hincrby('u:' + O.data.authorId, 'id',1, function(error, data){
+ /* Setting up floating points */
+ O.data.lid = data, O.data.id = d4;O.data.url = url(O.url).pathname;
redis.multi()
- .HSET('u:' + O.comment.authorId, data, toJSONString(O.comment))
- .HSET(thread,d4, toJSONString(O.comment))
+ .HSET('u:' + O.data.authorId, data, toJSONString(O.data))
+ .HSET(thread,d4, toJSONString(O.data))
.lpush(shortTKeys(parent),url(O.url).pathname)
.exec(function(e2,d2){
if (e2) res('No ok: ' + err, null)
@@ -96,13 +97,13 @@ var newComment = module.exports.newComment = function(Object,res) {
res('I need an url', null)
}
}
-var deleteComment = exports.deleteComment = function(Object,res){
- var nO = Object;
+var deleteComment = exports.deleteComment = function(req,res){
+ var nO = req;
if (/^(http:\/\/)([\w]+\.){1,}[A-Z]{2,}\b/gi.test(nO.url)) {
- var threadId = convertURL(nO.url).slug,
+ var threadId = convertURL(nO.url).slug || 'home',
parent = convertURL(nO.url).host;
thread = threadKey(threadId,parent),
- comment = nO.comment;
+ comment = nO.data;
redis.multi()
.HDEL(thread, comment.id)
.HDEL('u:'+ comment.authorId, comment.lid)
@@ -118,9 +119,9 @@ var deleteComment = exports.deleteComment = function(Object,res){
}
}
-var fetchByThread = module.exports.fetch = function(Object,res){
- var nO = Object,
- threadId = convertURL(nO.url).slug,
+var fetchByThread = module.exports.fetchByThread = function(req,res){
+ var nO = req,
+ threadId = convertURL(nO.url).slug || 'home',
parent = convertURL(nO.url).host,
thread = threadKey(threadId,parent);
redis.hgetall(thread, function(e,d){
@@ -131,8 +132,8 @@ var fetchByThread = module.exports.fetch = function(Object,res){
}
});
}
-var fetchByUser = module.exports.fetchByUser = function(Object, res) {
- redis.hgetall('u:' + Object.comment.authorId, function(e,d){
+var fetchByUser = module.exports.fetchByUser = function(req, res) {
+ redis.hgetall('u:' + req.data.authorId, function(e,d){
if (!e) {
res(null, d);
} else {
@@ -141,7 +142,7 @@ var fetchByUser = module.exports.fetchByUser = function(Object, res) {
});
}
var fetchBySite = module.exports.fetchBySite = function(site,res){
- redis.lrange(shortTKeys(site), 0, -1, function(e,d){
+ redis.lrange(shortTKeys(convertURL(site).host), 0, -1, function(e,d){
if (e) {
res(e, null);
} else {
@@ -159,19 +160,22 @@ var fetchBySite = module.exports.fetchBySite = function(site,res){
res(null, JSON.stringify(r));
}
});
-
});
-
}
});
}
+
+/*
+* TODO: Optional
+* Implement edit comments via merge
+*/
var merge = module.exports.merge = function (obj1, obj2) {
for (var p in obj2) {
try {
if ( obj2[p].constructor===Object ) {
obj1[p] = merge(obj2[p], obj1[p]);
} else {
- if (typeof parseFloat(p) != 'number') {
+ if (typeof parseFloat(p) != 'number') /* WTF¡ lol */{
obj1[p] = obj2[p];
}
}
@@ -183,15 +187,15 @@ var merge = module.exports.merge = function (obj1, obj2) {
}
var edit = module.exports.edit = function(obj, res){
var nO = obj,
- threadId = convertURL(nO.url).slug,
+ threadId = convertURL(nO.url).slug || 'home',
parent = convertURL(nO.url).host,
thread = threadKey(threadId,parent);
- redis.hget(thread, nO.comment.id, function(e,d){
+ redis.hget(thread, nO.data.id, function(e,d){
if (d) {
d = JSON.parse(d);
- d.comment = nO.comment.comment;
+ d.comment = nO.data.comment;
d.time = Date.now();
- redis.hset(thread, nO.comment.id, JSON.stringify(d), function(e,d){
+ redis.hset(thread, nO.data.id, JSON.stringify(d), function(e,d){
if (d===0) d ='ok';
res(e,d);
});
View
9 lib/redis.js
@@ -1,9 +1,9 @@
var options = require('./options');
var redis = require('redis');
if (options.env == 'production') {
- var createRedisClient = function() {
- var db = redis.createClient(9034, 'carp.redistogo.com');
- var dbAuth=function() { db.auth('2ac23e223b531f90263935c0f6ff4a1e');};
+ var createRedisClient = function(port, host, auth) {
+ var db = redis.createClient(port, host);
+ var dbAuth=function() { db.auth(auth);};
db.addListener('connected',dbAuth);
db.addListener('reconnected',dbAuth);
db.on("error", function (err) {
@@ -12,7 +12,8 @@ if (options.env == 'production') {
dbAuth();
return db;
};
- exports.redis = createRedisClient();
+
+ exports.redis = createRedisClient(3187,HOST);
} else {
exports.redis = redis.createClient();
}
View
2  routes/index.js
@@ -3,5 +3,5 @@
*/
exports.index = function(req, res){
- res.render('index', { title: 'Express' })
+ res.render('index', { title: 'Node-comm' ,locals: {flash: ''}})
};
View
59 views/form.jade
@@ -0,0 +1,59 @@
+form(action="javascript:alert('success!');",id="form")
+ input(type="hidden",id="reply",name="reply")
+ input(type="hidden",id="userId",name="userId",value= user.id || "")
+ input(type="hidden",id="url")
+ label Comment:
+ textarea(name="comment",id="comment")
+ input(type="submit",value="submit")
+script
+ var p = document.getElementById('url');
+ p.value = window.location.href;
+script
+ $(document).ready(function(){
+ now.ready(function(){
+ now.fetchByThread({url: window.location.href},function(e,r){
+ if (e === null) {
+ window.r = r; // I like this objects
+ i = 0;
+ for(var m in r){
+ if(m ==='id') {
+ }else {
+ var comment = JSON.parse(r[m]);
+ var NODE ='';
+ if ( (comment.authorName || comment.authorId) === "#{user.id}") {
+ NODE = '> <a href="#" id="edit">Edit </a> | <a href="#" id="delete">Delete</a></div>'
+ }
+ $('body').append("<br><div id='comment" + i +"'><label>"+ (comment.authorName || comment.authorId) + ":</label><p> " + comment.comment + "</p><input type='hidden' id='commentId"+ i+"' value='"+JSON.stringify(r[m])+"'>" + (NODE || '</div>') );
+ }
+ i++;
+ }
+ } else {
+ console.log(e)
+ }
+ });
+ now.receiveMessage = function(name, message){
+ if (name === "#{user.id}") {
+ $('body').append("<br>" + name + ": " + message + ' <a href="#" id="edit">Edit </a> | <a href="#" id="delete">Delete</a>');
+ } else {
+ $('body').append("<br>" + name + ": " + message);
+ }
+ }
+ now.joinRoom({url: document.getElementById('url').value,id:document.getElementById('userId').value});
+
+ })
+ //setInterval(function(){this.now.hear(Date.now())},1000)
+ /* { url:'http://numbus.co:8080/f/prueba/h',
+ comment: { authorId: "4ebef2c27f21bd298a000000", comment: "YOUR COMMENT",time: Date.now(),
+ parent: "URL parent or comment parent as reply" } } */
+ $('#form').submit(function(){
+ now.sendComment({url: window.location.href,
+ data: {
+ authorId:"#{user.id}",
+ comment: $('#comment').val() || 'Null',
+ time: new Date(Date.now()),
+ parent:$('#reply').val() || window.location.href
+ }
+ });
+ return false;
+ });
+ });
View
14 views/index.jade
@@ -1,2 +1,14 @@
h1= title
-p Welcome to #{title}
+p Login
+
+p Try accessing
+ a(href="/restricted") /restricted.
+form(method="post", action="/login")
+ p
+ label Username:
+ input( type="text", name="username")
+ p
+ label Password:
+ input(type="text", name="password")
+ p
+ input(type="submit",value="Login")
View
2  views/layout.jade
@@ -3,4 +3,6 @@ html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
+ script(type="text/javascript" ,src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js")
+ script(src="/nowjs/now.js")
body!= body
View
16 views/login.ejs
@@ -0,0 +1,16 @@
+<h1>Login</h1>
+<%- message %>
+Try accessing <a href="/restricted">/restricted</a>.
+<form method="post" action="/login">
+ <p>
+ <label>Username:</label>
+ <input type="text" name="username">
+ </p>
+ <p>
+ <label>Password:</label>
+ <input type="text" name="password">
+ </p>
+ <p>
+ <input type="submit" value="Login">
+ </p>
+</form>
View
11 views/login.jade
@@ -0,0 +1,11 @@
+h1 Login
+- if (message)
+ div= message
+p Try accessing
+ a(href="/restricted") /restricted
+form(method="post", action="/login")
+ label Username:
+ input(type="text", name="username")
+ label Pass:
+ input(type="password", name="password")
+ input(type="submit", value="Login")
Please sign in to comment.
Something went wrong with that request. Please try again.