~singpolyma/jmp-dialplan

ref: 23a079eca933def7b4086799c3ebec5dc4829e06 jmp-dialplan/extensions.lua -rw-r--r-- 2.1 KiB
23a079ecStephen Paul Weber Read out TTS 4 months ago
                                                                                
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
local http_request = require "http.request"
local cjson = require "cjson"

function hex_to_char(x)
	return string.char(tonumber(x, 16))
end

function uri_decode(uri)
	return uri:gsub("%%(%x%x)", hex_to_char)
end

function prepare_tts(text)
	local sha = channel.SHA1(text):get()
	local handle = assert(io.popen("flite -voice /etc/asterisk/voice.flitevox -o /tmp/" .. sha .. ".wav16", "w"))
	handle:write(text)
	assert(handle:close())
	return "/tmp/" .. sha
end

function call_sgx_jmp(from_jid, to)
	local req = http_request.new_from_uri(
		"https://bandwidth-voice.jmp.chat/outbound/calls"
	)
	req.headers:upsert(":method", "POST")
	req.headers:upsert("Content-Type", "application/json")
	req.headers:upsert("Accept", "application/json")
	req:set_body(cjson.encode({
		from = "xmpp:" .. from_jid,
		to = to
	}))
	local headers, stream = assert(req:go())
	return cjson.decode(stream:get_body_as_string())
end

extensions = {
	jmp = {
		["_+X!"] = function(context, extension)
			local from_cheogram = channel.CHEOGRAM:get() == "yes"
			if from_cheogram then
				channel.CDR("context"):set("jmp")
				local from_header = channel.SIP_HEADER("From"):get()
				local from = from_header:gsub("^[^<]*<sip:", ""):gsub(">.*$", "")
				local from_jid = uri_decode(from:sub(0, from:find("@sip.cheogram.com") - 1))

				local result = call_sgx_jmp(from_jid, extension)
				channel.CDR("customer_id"):set(result.customer_id)

				if result.tts then
					local wav = prepare_tts(result.tts)

					if result.from and result.to then
						app.read("digits", wav, 1, nil, 3)
					else
						app.playback(wav)
					end

					os.remove(wav .. ".wav16")

					if channel.digits:get() ~= "1" then
						app.hangup()
						return
					end
				end

				if result.from and result.to then
					channel.CALLERID("all"):set(result.from .. " <" .. result.from .. ">")
					app.dial("SIP/bandwidth/" .. result.to)
				else
					app.log("NOTICE", "JMP rejected call from " .. from .. " (" .. from_jid .. "): no caller id found")
				end
			else
				app.log("NOTICE", "Call from '' (" .. channel.CHANNEL("peerip"):get() .. ":0) to extension '" .. extension .. "' rejected in context 'jmp'.")
			end
		end;
	};
}