105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/twilio/twilio-go"
|
|
api "github.com/twilio/twilio-go/rest/api/v2010"
|
|
"github.com/twilio/twilio-go/twiml"
|
|
)
|
|
|
|
// downloadFile downloads a file from the interwebz.
|
|
func downloadFile(filepath string, url string) error {
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
out, err := os.Create(filepath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer out.Close()
|
|
|
|
_, err = io.Copy(out, resp.Body)
|
|
return err
|
|
}
|
|
|
|
// pullRecordings downloads recordings from Twilio infra.
|
|
func pullRecordings() {
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
fmt.Printf("failed to get cwd: %s\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
client := twilio.NewRestClient()
|
|
for {
|
|
time.Sleep(300 * time.Second)
|
|
|
|
resp, err := client.Api.ListRecording(&api.ListRecordingParams{})
|
|
if err != nil {
|
|
fmt.Printf("failed to list recordings: %s\n", err)
|
|
continue
|
|
}
|
|
|
|
if len(resp) == 0 {
|
|
continue
|
|
}
|
|
|
|
for _, rec := range resp {
|
|
medUrl := *rec.MediaUrl
|
|
parsed, err := url.Parse(medUrl)
|
|
if err != nil {
|
|
fmt.Printf("failed to parse %s: %s\n", medUrl, err)
|
|
continue
|
|
}
|
|
|
|
split := strings.Split(parsed.Path, "/")
|
|
fname := fmt.Sprintf("%s.wav", split[len(split)-1])
|
|
absFname := fmt.Sprintf("%s/%s", cwd, fname)
|
|
|
|
if err := downloadFile(absFname, medUrl); err != nil {
|
|
fmt.Printf("failed to download %s: %s\n", medUrl, err)
|
|
continue
|
|
}
|
|
|
|
err = client.Api.DeleteRecording(*rec.Sid, &api.DeleteRecordingParams{})
|
|
if err != nil {
|
|
fmt.Printf("failed to delete %s: %s\n", medUrl, err)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
|
|
router := gin.Default()
|
|
router.POST("/", func(context *gin.Context) {
|
|
say := &twiml.VoiceSay{Message: "Thanks for calling Varia. Please leave a message after the beep."}
|
|
record := &twiml.VoiceRecord{PlayBeep: "true"}
|
|
|
|
twimlResult, err := twiml.Voice([]twiml.Element{say, record})
|
|
if err != nil {
|
|
context.String(http.StatusInternalServerError, err.Error())
|
|
} else {
|
|
context.Header("Content-Type", "text/xml")
|
|
context.String(http.StatusOK, twimlResult)
|
|
}
|
|
})
|
|
|
|
go pullRecordings()
|
|
|
|
router.Run(":1312")
|
|
}
|