Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: d23a01a980
Fetching contributors…

Cannot retrieve contributors at this time

file 84 lines (69 sloc) 2.057 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
http = require 'http'
url = require 'url'
querystring = require 'querystring'
u_ = require 'underscore'


exports.connect = (options={}) ->
  return unless 'apikey' of options

  api = {}
  api.options = u_.extend {}, options

  api.options.host ||= 'localhost'
  api.options.port ||= 9001


  api.call = (functionName, functionArgs, callback) ->
    rootPath = '/api/1/'
    apiOptions = u_.extend { 'apikey': @options.apikey }, functionArgs
    httpOptions =
      host: @options.host
      port: @options.port
      path: rootPath + functionName + '?' + querystring.stringify apiOptions

    chunks = []
    req = http.get httpOptions, (res) ->
      res.on 'data', (data) ->
        chunks.push(data)
      res.on 'end', () ->
        try
          response = JSON.parse chunks.join('')
        catch error
          callback { code: -1, message: 'cannot parse the API response' }, null
          return

        if response.code is 0 and response.message is 'ok'
          callback null, response.data
        else
          callback { code: response.code, message: response.message}, null

    req.on 'error', (error) ->
      callback { code: -1, message: (error.message or error) }, null


  apiFunctions = [
    'createGroup',
    'createGroupIfNotExistsFor',
    'deleteGroup',
    'listPads',
    'createGroupPad',
    'createAuthor',
    'createAuthorIfNotExistsFor',
    'createSession',
    'deleteSession',
    'getSessionInfo',
    'listSessionsOfGroup',
    'listSessionsOfAuthor',
    'getText',
    'setText',
    'getHTML',
    'createPad',
    'getRevisionsCount',
    'deletePad',
    'getReadOnlyID',
    'setPublicStatus',
    'getPublicStatus',
    'setPassword',
    'isPasswordProtected',
  ]
  for functionName in apiFunctions
    do (functionName) ->
      api[functionName] = (args, callback) ->
        if arguments.length is 1 and u_.isFunction(args)
          callback = args
          args = {}

        callback ||= () ->
          # pass

        api.call(functionName, args, callback)
        return null


  return api
Something went wrong with that request. Please try again.