]> git.r.bdr.sh - rbdr/dotfiles/blob - vim/.backup/server.jz~
Add gitignore
[rbdr/dotfiles] / vim / .backup / server.jz~
1 #!/usr/bin/env node
2
3 require('colors');
4 var Ne = require('neon');
5
6 Nitrogen = {
7 Manifest : require('./lib/manifest.js'),
8 Server : {}
9 };
10
11 Ne.Class(Nitrogen.Server, 'Editor')({
12 prototype : {
13 fs : require('fs'),
14 express : require('express'),
15 httpProxy : require('http-proxy'),
16 io : require('socket.io'),
17 http : require('http'),
18 app : null,
19 server : null,
20 socket : null,
21 port : 4000,
22 occipitalOptions : {},
23
24 init : function init(config) {
25 Object.keys(config).forEach(function (property) {
26 this[property] = config[property];
27 }, this);
28
29 console.log('Nitrogen Session Server starting ');
30 this.app = this.express();
31 this.proxy = new this.httpProxy.RoutingProxy();
32 this.server = this.http.createServer(this.app);
33 this.initRack();
34 this.initDb();
35 this.initRoutes();
36 this.server.listen(this.port);
37 this.socket = this.io.listen(this.server);
38 this.socket.set('transports', ['websocket'])
39 this.socket.disable('heartbeats');
40 this.initSyncEvents();
41 console.log('Nitrogen Session Server listening on port ' + this.port);
42 },
43
44 initRack : function initRack() {
45 var nitrogen = this;
46 this.app.use(this.express.logger());
47 this.app.use(this.express.compress());
48 this.app.use(function (request, response, next) {
49 response.header("Access-Control-Allow-Origin", "*");
50 response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
51 response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
52 if ('OPTIONS' == request.method) {
53 response.send(200);
54 }
55 else {
56 next();
57 }
58 });
59 // This has to be here in order for a proxied post to work.
60 // See https://github.com/nodejitsu/node-http-proxy/issues/180
61 // for more information.
62 this.app.use(function (request, response, next) {
63 if (request.url.match(/\/attachments\/.*/) && request.method === "POST" ){
64 var options = nitrogen.occipitalOptions;
65 nitrogen.proxy.proxyRequest( request, response, options );
66 } else {
67 return next();
68 }
69 });
70 this.app.use(this.express.bodyParser());
71 this.app.use('/', this.express.static('public'));
72 },
73
74 initDb : function initDb() {
75 var fileNames = this.fs.readdirSync(__dirname + '/../').filter(function(fn){ return fn.match(/.*\.json$/); });
76 var i, filePath, collectionName;
77 data = Nitrogen.data = {};
78
79 for( i=0; i < fileNames.length; i+=1 ){
80 filePath = __dirname + '/../' + fileNames[i];
81 collectionName = fileNames[i].replace(/.json/, '');
82 data[collectionName] = this.fs.readFileSync(filePath).toString().replace(/\n$/, "").split(/\n/).map(function(r){
83 return JSON.parse(r);
84 });
85 }
86 },
87
88 initRoutes : function initRoutes() {
89 var nitrogen = this,
90 path = require('path');
91
92 this.app.get('/', function (request, response) {
93 var file = path.resolve('./public/app.html');
94 response.sendfile(file);
95 });
96
97 this.app.get('/api/all', function (req, res) {
98 res.set('Content-Type', 'application/json');
99 res.send(JSON.stringify(data));
100 });
101
102 this.app.get('/api/:model', function (req, res) {
103 var records = data[req.params.model]
104 res.set('Content-Type', 'application/json');
105 res.send(JSON.stringify(records));
106 });
107
108 this.app.get('/api/:model/:id', function (req, res){
109 var model = req.params.model;
110 var record = data[model].filter(function (record) {
111 return record.id == req.params.id;
112 })[0];
113
114 if (record) {
115 res.set('Content-Type', 'application/json');
116 res.send(JSON.stringify(record));
117 }
118 else {
119 res.set('Content-Type', 'application/json');
120 res.send(404, 'record not found');
121 }
122 });
123
124 this.app.get('/api/:model/:id/delete', function (req, res){
125 var model = req.params.model;
126 var record = data[model].filter(function (record) {
127 return record.id == req.params.id;
128 })[0];
129
130 data[model].splice(data[model].indexOf(record), 1);
131
132 res.set('Content-Type', 'application/json');
133 res.send('{}');
134 });
135
136 this.app.post('/api/:model/create', function (req, res){
137 var model = req.params.model;
138 var record = req.body;
139 record.id = util.generateUid(24);
140
141 data[model].push(record);
142
143 res.set('Content-Type', 'application/json');
144 res.send(JSON.stringify(record));
145 });
146
147 this.app.post('/api/:model/:id/update', function (req, res){
148 var model = req.params.model;
149
150 var record = data[model].filter(function (record) {
151 return record.id == req.params.id;
152 })[0];
153
154 var position = data[model].indexOf(record);
155 console.log(req);
156 data[model].splice(position, 1, req.body);
157
158 var record = data[model].filter(function (record) {
159 return record.id == req.params.id;
160 })[0];
161 res.set('Content-Type', 'application/json');
162 res.send(JSON.stringify(record));
163 });
164
165 this.app.get('/manifest_doc.js', function (req, res) {
166 res.set('Content-Type', 'application/json');
167
168 // Generate the package every time for development
169 Manifest.generatePackage(function () {
170 res.sendfile(path.resolve('./public/manifest_doc.js'));
171 });
172 /* TODO: Uncomment when file detection is done
173 nitrogen.fs.exists('./public/manifest_doc.js', function (exists) {
174 if (exists) {
175 res.sendfile(path.resolve('./public/manifest_doc.js'));
176 } else {
177 // create package
178 Manifest.generatePackage(function () {
179 res.sendfile(path.resolve('./public/manifest_doc.js'));
180 });
181 }
182 }); */
183 });
184
185 this.app.get('/get_assets', function (req, res) {
186 res.set('Content-Type', 'text/plain');
187
188 // Generate the package everytime for development
189 Manifest.generatePackage(function () {
190 res.sendfile(path.resolve('../app_assets/package.dat'));
191 });
192 /* TODO: Uncomment when file detection is ready
193 nitrogen.fs.exists('../app_assets/package.dat', function (exists) {
194 if (exists) {
195 res.sendfile(path.resolve('../app_assets/package.dat'));
196 } else {
197 // create package
198 Manifest.generatePackage(function () {
199 res.sendfile(path.resolve('../app_assets/package.dat'));
200 });
201 }
202 }); */
203 });
204
205 this.app.get('/attachments/*', function (req, res) {
206 var options = nitrogen.occipitalOptions;
207
208 nitrogen.proxy.proxyRequest( req, res, options );
209 });
210 },
211
212 initSyncEvents : function () {
213 this.socket.sockets.on('connection', function (socket) {
214 socket.emit('connected', {message : "Connection established"});
215
216 socket.on('sync', function (sync_data) {
217 console.log(">> Incoming LSD DATA".blue);
218
219 sync_data = JSON.parse(sync_data);
220
221 // Let's handle each guy
222 switch(sync_data.action) {
223 case "create":
224 data["tasks"].push(sync_data.data);
225 break;
226 case "update":
227 var record = data["tasks"].filter(function (record) {
228 return record.id == sync_data.data.id;
229 })[0];
230 var position = data["tasks"].indexOf(record);
231 data["tasks"].splice(position, 1, sync_data.data);
232 break;
233 case "remove":
234 var record = data["tasks"].filter(function (record) {
235 return record.id == sync_data.data.id;
236 })[0];
237 var position = data["tasks"].indexOf(record);
238 data["tasks"].splice(position, 1);
239 break;
240 }
241
242 socket.emit('sync_ok', {message : "Sync Received: OK"});
243 });
244 });
245
246 this.socket.sockets.on('disconnect', function (socket) {
247 socket.emit('disconnected', {message : "Connection lost"});
248 });
249 }
250 }
251 });
252
253 new Nitrogen.Server.Editor({
254 port : process.argv[2] || 4000,
255 occipitalOptions : {
256 host : (process.argv[3]) ? process.argv[3].replace(/:.*/, '') : '127.0.0.1',
257 port : (process.argv[3]) ? process.argv[3].replace(/.*:/, '') : '3001'
258 }
259 });
260