-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsonglocator-api.coffee
76 lines (52 loc) · 1.87 KB
/
songlocator-api.coffee
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
{Server} = require 'ws'
{v4} = require 'node-uuid'
{ResolverSet} = require 'songlocator-base'
{readConfigSync, parseArguments} = require 'songlocator-cli'
class exports.SongLocatorServer
constructor: (config) ->
this.config = config
this.server = undefined
log: (args...) ->
console.log(args...)
debug: (args...) ->
this.log(args...) if this.config.debug?
serve: ->
this.server = new Server(port: this.config.port or 3000)
this.server.on 'connection', (sock) =>
this.debug('got new connection')
send = (msg) =>
try
this.debug('response', {qid: msg.qid, length: msg.results.length})
sock.send JSON.stringify msg
catch e
this.debug("error while sending message: #{e}")
resolvers = for name, cfg of this.config.resolvers
resolverCls = (require("songlocator-#{name}")).Resolver
new resolverCls(cfg)
this.debug("initialized resolvers: #{(r.name for r in resolvers).join(', ')}")
resolver = new ResolverSet(resolvers)
resolver.on 'results', send
sock.on 'message', (message) =>
req = try
JSON.parse(message)
catch e
undefined
return unless req
# generate qid if no qid was supplied
qid = req.qid or v4()
this.debug('request', req)
if req.method == 'search' and req.query
resolver.search(qid, req.query)
else if req.method == 'resolve' and req.title
resolver.resolve(qid, req.title, req.artist, req.album)
this.log "start listening on localhost:#{this.config.port}"
exports.main = (port = 3000) ->
{opts} = parseArguments()
config = readConfigSync(opts.config) or {}
for resolverName in opts.resolvers
config[resolverName] = {}
server = new exports.SongLocatorServer
debug: opts.debug
port: port
resolvers: config
server.serve()