Commits

firefly  committed be16f88 Merge

Merge.

  • Participants
  • Parent commits b30b41a, db871b9

Comments (0)

Files changed (4)

File backends/node-bindings.js

-var events = require('events'),
-	util   = require('util'),
-	sys    = util,
-	net    = require('net'),
-	http   = require('http'),
-	https  = require('https'),
-	fs     = require('fs'),
-	qs     = require('querystring')
+var events = require('events')
+  , util   = require('util')
+  , net    = require('net')
+  , http   = require('http')
+  , https  = require('https')
+  , fs     = require('fs')
+  , qs     = require('querystring')
 
-	// BufferedSocket
+// BufferedSocket
 function BufferedSocket(options) {
-	if (!options.hostname || !options.port) {
-		throw new TypeError("Missing required option property: hostname or port.")
-	}
-	
-	options.separator || (options.separator = "\r")
-	
-	this.options = options
+  if (!options.hostname || !options.port) {
+    throw new TypeError("Missing required option property: hostname or port.")
+  }
+
+  options.separator || (options.separator = "\r")
+
+  this.options = options
 }
 exports.BufferedSocket = BufferedSocket
 util.inherits(BufferedSocket, events.EventEmitter)
 
 BufferedSocket.prototype.connect = function () {
-	var conn = this
-	var socket = this.socket = net.createConnection(this.options.port,
-			this.options.hostname)
-	var cache = ""
-	
-	socket.on('data', function (chunk) {
-		var linesRaw = "" + cache + chunk.toString()
-		
-		var lines = linesRaw.split('\r').slice(0)
-		cache = lines.pop()
-		
-		for (var i=0; i<lines.length; i++) {
-			conn.emit('data', lines[i])
-		}
-	})
-	socket.on('connect', function () {
-		conn.emit('connect')
-	})
-	socket.on('end', function () {
-		conn.emit('end')
-	})
+  var conn = this
+  var socket = this.socket = net.createConnection(this.options.port,
+      this.options.hostname)
+  var cache = ""
+
+  socket.on('data', function (chunk) {
+    var linesRaw = "" + cache + chunk.toString()
+
+    var lines = linesRaw.split('\r').slice(0)
+    cache = lines.pop()
+
+    for (var i=0; i<lines.length; i++) {
+      conn.emit('data', lines[i])
+    }
+  })
+  socket.on('connect', function () {
+    conn.emit('connect')
+  })
+  socket.on('end', function () {
+    conn.emit('end')
+  })
 }
 
 BufferedSocket.prototype.write = function (str) {
-	this.socket.write(str)
+  this.socket.write(str)
 }
 
-	// Data saving
+// Data saving
 var functionExpression = /^function\s*\w*\(([^)]*)\)\s*{([\W\S]*)}/
 
 function jsonReplacer(name, value) {
-	if (typeof value == 'function') {
-		var matches = value.toString().match(functionExpression)
-		if (!matches || !(2 in matches)) {
-			sys.error("Erroring function was: " + value)
-			throw new Error("Couldn't stringify function -- check your environment!")
-		}
-		
-		return {
-			$type: "function",
-			args: matches[1],
-			body: matches[2]
-		}
-	}
-	
-	return value
+  if (typeof value == 'function') {
+    var matches = value.toString().match(functionExpression)
+    if (!matches || !(2 in matches)) {
+      util.error("Erroring function was: " + value)
+      throw new Error("Couldn't stringify function -- check your environment!")
+    }
+
+    return {
+      $type: "function",
+      args: matches[1],
+      body: matches[2]
+    }
+  }
+
+  return value
 }
 
 function jsonReviver(name, value) {
-	if (typeof value == 'object' && value !== null && value.$type == 'function') {
-		try {
+  if (typeof value == 'object' && value !== null && value.$type == 'function') {
+    try {
           return Function(value.args, value.body)
 
-		} catch (err) {
+    } catch (err) {
           if (value.body.match(/\[native code\]/)) {
             console.warn("Function with body: '%s'.", value.body)
 
             throw err
           }
         }
-	}
-	
-	return value
+  }
+
+  return value
 }
 
 exports.storage = {
-	load: function (name) {
-		var fullname = 'data/' + name + '.json'
-		
-		try {
-			fs.statSync(fullname)	// TODO: Better way of checking if file exists
-			
-			return JSON.parse(fs.readFileSync(fullname).toString(), jsonReviver)
-		} catch (err) {
-			if (err.message.match(/^ENOENT/)) {
-				return {}
-			} else {
-				throw err
-			}
-		}
-	},
-	save: function (name, data) {
-		fs.writeFile('data/' + name + '.json', JSON.stringify(data, jsonReplacer, "\t"))
-	}
+  load: function (name) {
+    var fullname = 'data/' + name + '.json'
+
+    try {
+      fs.statSync(fullname)  // TODO: Better way of checking if file exists
+
+      return JSON.parse(fs.readFileSync(fullname).toString(), jsonReviver)
+    } catch (err) {
+      if (err.message.match(/^ENOENT/)) {
+        return {}
+      } else {
+        throw err
+      }
+    }
+  },
+  save: function (name, data) {
+    fs.writeFile('data/' + name + '.json', JSON.stringify(data, jsonReplacer, "\t"))
+  }
 }
 
-	// readFile
+// readFile
 exports.readFile = fs.readFile
 
-	// net
+// net
 exports.net = {
-	get: function (url, getData, useSsl, callback) {
-		var matches = url.match(/(?:[^:]+:\/\/)?([^\/]+)(?:\/([^#]+)(.*)|()())/)	// host, path + get, hash
-		
-		if (!callback) {
-			callback = useSsl
-			useSsl = false
-		}
-		
-		if (!callback) {
-			callback = getData
-			getData = {}
-		}
-		
-		if (!matches) {
-			throw new Error("URL not correctly formatted: '" + url + "'")
-		}
-		
-		var that = this
-		var firstSep = (url.match(/\?/) ? '&' : '?')
-		var extraGets = []
-		
-		for (var key in getData) {
-			extraGets.push(key + "=" + getData[key])
-		}
-		
-		allChunks = []
+  get: function (url, getData, useSsl, callback) {
+    var matches = url.match(/(?:[^:]+:\/\/)?([^\/]+)(?:\/([^#]+)(.*)|()())/)  // host, path + get, hash
 
-		var userAgent = 'Mozilla/4.0 (compatible; node.js; ' +
-				'see <http://bitbucket.org/firefly/eldis4>) Eldis/4.0'
-	//	'User-Agent': 'Eldis/4.0 (node.js; see <http://bitbucket.org/firefly/eldis4>)'
+    if (!callback) {
+      callback = useSsl
+      useSsl = false
+    }
 
-		;(useSsl ? https : http).get({
-			host: matches[1],
-			port: (useSsl ? 443 : 80),
-			path: '/' + matches[2] + firstSep + extraGets.join("&"),
-			headers: { 'User-Agent':userAgent }
-		}, function handleResult(res) {
-			if (res.statusCode == 301 || res.statusCode == 302) { // Moved permanently
-				var matches = (res.headers["location"] || "").match(/^\w+:\/\/([^\/]+)\/(.*)/)
+    if (!callback) {
+      callback = getData
+      getData = {}
+    }
 
-				if (!matches) {
-					callback(new Error("Invalid 'location' header."))
-					return
-				}
+    if (!matches) {
+      throw new Error("URL not correctly formatted: '" + url + "'")
+    }
 
- //res.headers["location"].replace(/^\w+:\/\/[^\/]+/, ''),
-				(useSsl ? https : http).get({
-					host: matches[1],
-					port: (useSsl ? 443 : 80),
-					path: res.headers["location"].replace(/^\w+:\/\/[^\/]+/, ''),
-					headers: { 'User-Agent':userAgent }
-				}, handleResult)
-				return
-			}
+    var that = this
+    var firstSep = (url.match(/\?/) ? '&' : '?')
+    var extraGets = []
 
-			res.on('data', function (chunk) {
-				allChunks.push(chunk.toString())
-				var doContinue = callback.call(that, null, chunk.toString(), false)
-				
-				if (doContinue === false) {
-					res.removeAllListeners('data')
-					res.removeAllListeners('end')
-				}
-			})
-			
-			res.on('end', function () {
-				callback.call(that, null, allChunks.join(""), true)
-			})
-		})
-	}
+    for (var key in getData) {
+      extraGets.push(key + "=" + getData[key])
+    }
+
+    allChunks = []
+
+    var userAgent = 'Mozilla/4.0 (compatible; node.js; ' +
+        'see <http://bitbucket.org/firefly/eldis4>) Eldis/4'
+  //  'User-Agent': 'Eldis/4 (node.js; see <http://bitbucket.org/firefly/eldis4>)'
+
+    ;(useSsl ? https : http).get({
+      host: matches[1],
+      port: (useSsl ? 443 : 80),
+      path: '/' + matches[2] + firstSep + extraGets.join("&"),
+      headers: { 'User-Agent':userAgent }
+    }, function handleResult(res) {
+      if (res.statusCode == 301 || res.statusCode == 302) { // Moved permanently
+        var matches = (res.headers["location"] || "").match(/^\w+:\/\/([^\/]+)\/(.*)/)
+
+        if (!matches) {
+          callback(new Error("Invalid 'location' header."))
+          return
+        }
+
+        (useSsl ? https : http).get({
+          host: matches[1],
+          port: (useSsl ? 443 : 80),
+          path: res.headers["location"].replace(/^\w+:\/\/[^\/]+/, ''),
+          headers: { 'User-Agent':userAgent }
+        }, handleResult)
+        return
+      }
+
+      res.on('data', function (chunk) {
+        allChunks.push(chunk.toString())
+        var doContinue = callback.call(that, null, chunk.toString(), false)
+
+        if (doContinue === false) {
+          res.removeAllListeners('data')
+          res.removeAllListeners('end')
+        }
+      })
+
+      res.on('end', function () {
+        callback.call(that, null, allChunks.join(""), true)
+      })
+    })
+  }
 }

File modules/05-wikipedia/parser.js

   return str.replace(/[\[\]\+\*]/g, '\\$&')
 }
 
+// Since wikilinks and templates are so similar, we unify their implementation
+// with this helper function.
 function getWikilinkTemplateFunc(delimTokens, allowNamedArgs) {
   var beginPattern = new RegExp("^" + regexEscape(delimTokens[0]))
     , endPattern   = new RegExp("^" + regexEscape(delimTokens[1]))
         last = i+1
       }
     }
+
     pushArg(str.slice(last, i-2))
 
     var target = args.shift()
 var backend
 try {
   backend = require('../backends/node-bindings')
+
 } catch (err) {
   console.warn("Couldn't load node backend.")
   console.warn(err.message, err.stack)
     throw new Error("No suitable backend found!")
   }
 
-  /* Minimal connector:
-    setup: ->
-    createConnection: ->
-      on: ->
-      connect: ->
-      disconnect: ->
-  */
-
   function nop() {}
 
   this.connectors =
     }
 
   this.connections = {}
-
-  /*
-  @connectors =
-    'irc': ircConnector
-    'www':
-      setup: ->
-      createConnection: ->
-        on: ->
-        connect: ->
-        disconnect: ->
-
-  @connections = {}
-  */
 }
 
 exports.Bot = Bot

File src/eldis4.js

     })
 
     // Creates a function that modules can use to log stuff.
-    moduleObj["log"] = function() {
-      Array.prototype.forEach.call(arguments, function(line) {
-        console.log("[%s]: %s", name, line)
-      })
+    moduleObj["log"] = function (/*...*/) {
+      process.stdout.write(util.format("[%s]: ", name))
+      console.log.apply(this, arguments)
     }
 
     // The actual context that the module will be run in.