This repository was archived by the owner on Jun 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathsonos.coffee
75 lines (65 loc) · 2.41 KB
/
sonos.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
# Description:
# None
#
# Dependencies:
# "xml2js": "0.1.14"
#
# Configuration:
# HUBOT_SONOS_HOST
#
# Commands:
# hubot what's playing - show what's playing on the office Sonos
#
# Author:
# berg
xml2js = require 'xml2js'
util = require 'util'
wrapInEnvelope = (body) ->
"""
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>#{body}</s:Body>
</s:Envelope>
"""
getURL = (path) ->
host = process.env.HUBOT_SONOS_HOST
"http://#{host}:1400#{path}"
makeRequest = (msg, path, action, body, response, cb) ->
wrappedBody = wrapInEnvelope body
msg.http(getURL path).header('SOAPAction', action).header('Content-type', 'text/xml; charset=utf8')
.post(wrappedBody) (err, resp, body) ->
unless err?
(new xml2js.Parser()).parseString body, (err, json) ->
unless err?
body = json['s:Body']
if body?
response_body = body[response]
if response_body?
cb response_body
whatsPlaying = (msg) ->
body = """
<u:GetPositionInfo xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">
<InstanceID>0</InstanceID>
<Channel>Master</Channel>
</u:GetPositionInfo>
"""
action = 'urn:schemas-upnp-org:service:AVTransport:1#GetPositionInfo'
path = '/MediaRenderer/AVTransport/Control'
makeRequest msg, path, action, body, 'u:GetPositionInfoResponse', (obj) ->
metadata = obj.TrackMetaData
if metadata?
(new xml2js.Parser()).parseString metadata, (err, obj) ->
unless err?
item = obj?.item
if item?
title = item['dc:title'] ? "(no title)"
artist = item['dc:creator'] ? "(no artist)"
album = item['upnp:album'] ? "(no album)"
artURI = item['upnp:albumArtURI']
if artURI?
artURI = getURL artURI + "#.png"
reply = "Now playing: \"#{title}\" by #{artist} (off of \"#{album}\") #{artURI}"
msg.reply reply
module.exports = (robot) ->
robot.respond /what'?s playing\??/i, (msg) ->
whatsPlaying msg