Skip to content

Instantly share code, notes, and snippets.

@nanki
Last active December 22, 2015 00:29
Show Gist options
  • Save nanki/6390079 to your computer and use it in GitHub Desktop.
Save nanki/6390079 to your computer and use it in GitHub Desktop.
request = require 'request'
http = require 'http'
url = require 'url'
cp = require 'child_process'
command = (command, args, callback) ->
cmd = cp.spawn command, args
if callback
result = new Buffer(0)
cmd.stdout.on "data", (chunk) ->
result = Buffer.concat [result, chunk]
cmd.stdout.on "end", ->
callback result.toString()
cmd
entries = []
command "man", ["-k", "."], (result) ->
for line in result.split("\n")
entries = entries.concat Entry.parse(line)
class Entry
@names = {}
@parse: (line) ->
names = line.split(" - ")[0].trim()
description = line.split(" - ")[1]
new Entry(name, description) for name in names.split(", ")
constructor: (@name, @description) ->
Entry.names[@name] = true
search = (keyword) ->
keyword = keyword.replace(/^man:\s*/, "")
if keyword.length > 0
entry.name for entry in entries when entry.name.lastIndexOf(keyword, 0) == 0
else
[]
escape_html = (html) ->
html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
link = (html) ->
html.replace /<b>([^<]*\))<\/b>/gi, (_, word) ->
if Entry.names[word]
"<a href=\"x-dictionary:d:#{word}\">#{word}</a>"
else
word
htmlman = (section, name, callback) ->
man = command "man", [section, name]
man2html = command "man2html", ["-bare"], (result) ->
callback result.toString()
man.stdout.pipe(man2html.stdin)
proxy = http.createServer()
proxy.on 'request', (req, client) ->
if req.url.lastIndexOf("/man.wikipedia", 0) is 0
query = url.parse(req.url, true).query
body = new Buffer(0)
req.on 'data', (chunk) ->
body = Buffer.concat [body, chunk]
req.on 'end', =>
switch query.action
when "opensearch"
client.writeHead 200
client.end JSON.stringify [query.search, search(query.search)]
when "parse"
r = query.page.match(/(.*)\(([^)]+)\)$/)
client.writeHead 200, 'content-type': 'application/xml'
if r
htmlman r[1], r[0], (body) ->
client.end "<?xml version=\"1.0\"?><api><parse displaytitle=\"#{r[0]}\"><redirects/><text xml:space=\"preserve\">#{escape_html link body}</text></parse></api>"
else
client.end ""
else
console.log req.url
else
target = request "http://210.149.135.52#{req.url}"
target.setHeader "host", "lookup-api.apple.com"
req.pipe(target)
target.pipe(client)
proxy.listen 80, '0.0.0.0'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment