Permalink
Browse files

Add bin/sourceserver.

  • Loading branch information...
nornagon committed Aug 4, 2012
1 parent 53bc389 commit 0b7c4196b7bcbcf538cd1bba8c52ccf75445436b
Showing with 81 additions and 0 deletions.
  1. +81 −0 bin/sourceserver
View
@@ -0,0 +1,81 @@
+#!/usr/bin/env coffee
+
+connect = require 'connect'
+sharejs = require '../src/server'
+fs = require 'fs'
+path = require 'path'
+
+argv = require('optimist').
+ usage("Usage: $0 [-p portnum]").
+ default('p', 8000).
+ alias('p', 'port').
+ argv
+
+fileVersions = {}
+
+atomicallyWriteFile = (file, snapshot) ->
+ return if snapshot.v < fileVersions[file]
+ tmpfile = '/tmp/sharesource-'+file.replace(/\//g,'_')
+ fs.writeFile tmpfile, snapshot.snapshot, (err) ->
+ throw err if err
+ fs.rename tmpfile, file, (err) ->
+ throw err if err
+ fileVersions[file] = snapshot.v
+ console.log "wrote #{file} v#{snapshot.v}"
+
+
+
+
+server = connect(
+ connect.favicon(),
+ connect.static(__dirname + '/../examples'),
+ connect.router (app) ->
+
+ app.get '/pad/*', (req, res, next) ->
+ file = req.params[0]
+ docName = 'pad:'+file
+ contents = fs.readFileSync(file, 'utf8')
+ console.log docName
+ timer = null
+ share.model.create docName, 'text', ->
+ share.model.applyOp docName, {
+ v:0, op:[{i:contents,p:0}]
+ }, ->
+ fileVersions[file] = 0
+ res.writeHead 303, {location: '/pad/pad.html#' + file}
+ res.write ''
+ res.end()
+ share.model.listen docName, (op, appliedAt) ->
+ clearTimeout timer if timer?
+ timer = setTimeout ->
+ timer = null
+ share.model.getSnapshot docName, (error, s) ->
+ throw error if error
+ atomicallyWriteFile file, s
+ , 200
+ , (startingVersion) ->
+ console.log 'start:',startingVersion
+
+ app.get '/?', (req, res, next) ->
+ res.writeHead 302, {location: '/index.html'}
+ res.end()
+
+)
+
+# Change to this to enable persistance
+options = {db: {type:'memory'}}
+
+# Lets try and enable redis persistance if redis is installed...
+#try
+# require 'redis'
+# options = {db: {type:'redis'}}
+
+console.log "Options: ", options
+
+port = argv.p
+
+# Attach the sharejs REST and Socket.io interfaces to the server
+share = sharejs.attach server, options
+
+server.listen port
+console.log "Demos running at http://localhost:#{port}/"

0 comments on commit 0b7c419

Please sign in to comment.