OmnomIRC.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!node
  2. var fs = require('fs'),
  3. url = require('url'),
  4. path = require('path'),
  5. vm = require('vm'),
  6. toobusy = function(){return false;},//require('toobusy'),
  7. cluster = require('cluster'),
  8. options = (function(){
  9. var defaults = {
  10. port: 80,
  11. loglevel: 3,
  12. redis: {
  13. port: 6379,
  14. host: 'localhost'
  15. }
  16. },
  17. options;
  18. try{
  19. options = JSON.parse(fs.readFileSync('./options.json'));
  20. for(var i in options){
  21. defaults[i] = options[i];
  22. }
  23. }catch(e){
  24. console.warn('Using default settings. Please create options.json');
  25. }
  26. return defaults;
  27. })();
  28. if(typeof fs.existsSync == 'undefined') fs.existsSync = path.existsSync; // legacy support
  29. if(cluster.isMaster){
  30. for(var i=0;i<require('os').cpus().length;i++){
  31. cluster.fork();
  32. }
  33. cluster.on('exit', function(worker, code, signal) {
  34. console.log('worker ' + worker.process.pid + ' died');
  35. });
  36. }else{
  37. var RedisStore = require('socket.io/lib/stores/redis'),
  38. redis = require('socket.io/node_modules/redis'),
  39. pub = redis.createClient(options.redis.port,options.redis.host),
  40. sub = redis.createClient(options.redis.port,options.redis.host),
  41. client = redis.createClient(options.redis.port,options.redis.host),
  42. mimeTypes = {
  43. 'html': 'text/html',
  44. 'js': 'text/javascript',
  45. 'css': 'text/css',
  46. 'png': 'image/png',
  47. 'jpg': 'image/jpeg'
  48. },
  49. app = require('http').createServer(function(req,res){
  50. if(toobusy()){
  51. res.writeHead(503,{
  52. 'Content-type': 'text/plain'
  53. });
  54. res.write('503 Server busy.\n');
  55. res.end();
  56. return;
  57. }
  58. req.addListener('end',function(){
  59. logger.debug('served static content for '+req.url);
  60. var uri = url.parse(req.url).pathname,
  61. serveFile = function(filename,req,res){
  62. try{
  63. stats = fs.lstatSync(filename);
  64. }catch(e){
  65. res.writeHead(404,{
  66. 'Content-type': 'text/plain'
  67. });
  68. res.write('404 Not Found.\n');
  69. res.end();
  70. return;
  71. }
  72. if(stats.isFile()){
  73. var fileStream,
  74. mimetype = mimeTypes[path.extname(filename).split('.')[1]];
  75. res.writeHead(200,{
  76. 'Content-Type': mimetype
  77. });
  78. fileStream = fs.createReadStream(filename);
  79. fileStream.pipe(res);
  80. }else if(stats.isDirectory()){
  81. if(fs.existsSync(path.join(filename,'index.html'))){
  82. serveFile(path.join(filename,'index.html'),req,res);
  83. }else if(fs.existsSync(path.join(filename,'index.htm'))){
  84. serveFile(path.join(filename,'index.htm'),req,res);
  85. }else if(fs.existsSync(path.join(filename,'index.txt'))){
  86. serveFile(path.join(filename,'index.txt'),req,res);
  87. }else{
  88. res.writeHead(200,{
  89. 'Content-Type': 'text/plain'
  90. });
  91. res.write('Index of '+url+'\n');
  92. res.write('TODO, show index');
  93. res.end();
  94. }
  95. }else{
  96. res.writeHead(500,{
  97. 'Content-Type': 'text/plain'
  98. });
  99. res.write('500 Internal server error\n');
  100. res.end();
  101. }
  102. },
  103. filepath = unescape(uri);
  104. if(filepath.substr(0,5) == '/api/'){
  105. filepath = path.join('./api/',filepath.substr(5));
  106. logger.debug('Attempting to run api script '+filepath);
  107. if(fs.existsSync(filepath)){
  108. fs.readFile(filepath,function(e,data){
  109. if(e){
  110. logger.error(e);
  111. res.end('null;');
  112. }else{
  113. var output = '',
  114. sandbox = {
  115. log: function(text){
  116. output += text;
  117. },
  118. error: function(msg){
  119. logger.error(msg);
  120. },
  121. info: function(msg){
  122. logger.info(msg);
  123. },
  124. debug: function(msg){
  125. logger.debug(msg);
  126. },
  127. head: {
  128. 'Content-Type': 'text/javascript'
  129. },
  130. returnCode: 200,
  131. vm: vm,
  132. fs: fs
  133. };
  134. vm.runInNewContext(data,sandbox,filepath);
  135. res.writeHead(sandbox.returnCode,sandbox.head);
  136. res.end(output);
  137. }
  138. });
  139. }else{
  140. res.writeHead(404,{
  141. 'Content-Type': 'text/javascript'
  142. });
  143. res.end('null;');
  144. }
  145. }else{
  146. serveFile(path.join('./www/',filepath),req,res);
  147. }
  148. }).resume();
  149. }).listen(options.port),
  150. io = require('socket.io').listen(app)
  151. logger = io.log;
  152. io.set('log level',options.loglevel);
  153. if(typeof options.redis.password != 'undefined'){
  154. var eh = function(e){
  155. throw e;
  156. };
  157. pub.auth(options.redis.ppassword,eh);
  158. sub.auth(options.redis.ppassword,eh);
  159. client.auth(options.redis.ppassword,eh);
  160. }
  161. io.set('store', new RedisStore({
  162. redisPub : pub,
  163. redisSub : sub,
  164. redisClient : client
  165. }));
  166. io.sockets.on('connection',function(socket){
  167. socket.on('join',function(data){
  168. socket.join(data.name);
  169. data.title = data.name;
  170. socket.emit('join',{
  171. name: data.name,
  172. title: data.title
  173. });
  174. sendUserList(data.name);
  175. socket.get('nick',function(e,nick){
  176. logger.debug(nick+' joined '+data.name);
  177. io.sockets.in(data.name).emit('message',{
  178. message: nick+' joined the channel',
  179. room: data.name,
  180. from: 0
  181. });
  182. });
  183. });
  184. socket.on('part',function(data){
  185. socket.leave(data.name);
  186. socket.get('nick',function(e,nick){
  187. logger.debug(nick+' left '+data.name);
  188. sendUserList(data.name);
  189. });
  190. });
  191. socket.on('disconnect',function(data){
  192. var rooms = io.sockets.manager.rooms,
  193. i,
  194. room;
  195. for(i in rooms){
  196. if(rooms[i] != '' && typeof rooms[i] == 'string'){
  197. try{
  198. room = rooms[i].substr(1);
  199. }catch(e){}
  200. sendUserList(room);
  201. }
  202. }
  203. });
  204. socket.on('message',function(data){
  205. logger.debug('message sent to '+data.room);
  206. io.sockets.in(data.room).emit('message',data);
  207. });
  208. socket.on('echo',function(data){
  209. logger.debug('echoing to '+data.room);
  210. socket.emit('message',data);
  211. });
  212. socket.on('names',function(data){
  213. var sockets = io.sockets.clients(data.name),
  214. i;
  215. runWithUserList(data.name,function(users){
  216. var temp = [],i;
  217. for(i in users) i && temp.push(users[i]);
  218. users = temp;
  219. socket.emit('message',{
  220. message: data.name+" users:\n\t\t"+users.join("\n\t\t"),
  221. room: data.name,
  222. from: 0
  223. });
  224. sendUserList(data.name);
  225. });
  226. });
  227. socket.on('auth',function(data){
  228. logger.info(data.nick+' registered');
  229. // TODO - authorize
  230. socket.set('nick',data.nick.substr(0,12));
  231. socket.emit('authorized',{
  232. nick: data.nick.substr(0,12)
  233. });
  234. });
  235. var runWithUserList = function(room,callback){
  236. var sockets = io.sockets.clients(room),
  237. i = 0,
  238. ret = [],
  239. getNext = function(){
  240. if(i < sockets.length){
  241. sockets[i].get('nick',function(e,nick){
  242. if(e){
  243. logger.error(e);
  244. ret.push('');
  245. }else{
  246. logger.debug(room+' '+nick);
  247. ret.push(nick);
  248. }
  249. i++;
  250. getNext();
  251. });
  252. }else{
  253. callback(ret);
  254. }
  255. };
  256. getNext();
  257. },
  258. sendUserList = function(room){
  259. if(typeof room != 'undefined'){
  260. runWithUserList(room,function(users){
  261. io.sockets.in(room).emit('names',{
  262. room: room,
  263. names: users
  264. });
  265. });
  266. }
  267. };
  268. });
  269. }
  270. process.on('uncaughtException',function(e){
  271. if(typeof logger != 'undefined'){
  272. logger.error(e);
  273. }else{
  274. console.error(e);
  275. }
  276. });