started working on DBUS implementation

This commit is contained in:
Bernhard B 2020-09-30 11:15:12 +02:00
parent 524939dd0a
commit 2557214bd4
10 changed files with 766 additions and 409 deletions

View File

@ -1,6 +1,6 @@
FROM golang:1.13-buster AS buildcontainer
ARG SIGNAL_CLI_VERSION=0.6.8
ARG SIGNAL_CLI_VERSION=0.6.10
ARG SWAG_VERSION=1.6.7
ENV GIN_MODE=release
@ -33,17 +33,36 @@ RUN cd /tmp/ \
COPY src/api /tmp/signal-cli-rest-api-src/api
COPY src/main.go /tmp/signal-cli-rest-api-src/
COPY src/system /tmp/signal-cli-rest-api-src/system
COPY src/datastructures /tmp/signal-cli-rest-api-src/datastructures
COPY src/commands /tmp/signal-cli-rest-api-src/commands
COPY src/go.mod /tmp/signal-cli-rest-api-src/
COPY src/go.sum /tmp/signal-cli-rest-api-src/
COPY src/go.sum /tmp/signal-cli-rest-api-src/
RUN cd /tmp/signal-cli-rest-api-src && swag init && go build
# Start a fresh container for release container
FROM adoptopenjdk:11-jre-hotspot
RUN apt-get update\
&& apt-get install -y --no-install-recommends dbus supervisor \
&& rm -rf /var/lib/apt/lists/*
COPY --from=buildcontainer /tmp/signal-cli-rest-api-src/signal-cli-rest-api /usr/bin/signal-cli-rest-api
COPY --from=buildcontainer /tmp/signal-cli /opt/signal-cli
# DBUS
# Create own signal-cli user for DBUS communication
RUN useradd -ms /bin/bash signal-cli
COPY data/org.asamk.Signal.conf /etc/dbus-1/system.d/
#COPY data/org.asamk.Signal.service /usr/share/dbus-1/system-services/
#COPY data/signal.service /etc/systemd/system/
COPY conf/supervisor/signal-cli.conf /etc/supervisor/conf.d/signal-cli.conf
RUN mkdir -p /var/log/signal-cli
RUN mkdir -p /var/run/dbus
RUN ln -s /opt/signal-cli/bin/signal-cli /usr/bin/signal-cli
RUN mkdir -p /signal-cli-config/
RUN mkdir -p /home/.local/share/signal-cli

View File

@ -0,0 +1,14 @@
[program:signal-cli]
process_name=signal-cli-%(process_num)s
environment=JAVA_HOME=/opt/java/openjdk/
command=/usr/bin/signal-cli -u !#MY_NUMBER#! --config /home/.local/share/signal-cli daemon --system
autostart=true
autorestart=true
startretries=10
user=signal-cli
redirect_stderr=true
stdout_logfile=/var/log/signal-cli/out-%(process_num)s.log
stderr_logfile=/var/log/signal-cli/err-%(process_num)s.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=10
numprocs=1

View File

@ -1,279 +1,16 @@
package api
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
uuid "github.com/gofrs/uuid"
"github.com/h2non/filetype"
log "github.com/sirupsen/logrus"
qrcode "github.com/skip2/go-qrcode"
"os"
"os/exec"
commands "github.com/bbernhard/signal-cli-rest-api/commands"
datastructures "github.com/bbernhard/signal-cli-rest-api/datastructures"
"strings"
"time"
)
const groupPrefix = "group."
type GroupEntry struct {
Name string `json:"name"`
Id string `json:"id"`
InternalId string `json:"internal_id"`
Members []string `json:"members"`
Active bool `json:"active"`
Blocked bool `json:"blocked"`
}
type RegisterNumberRequest struct {
UseVoice bool `json:"use_voice"`
}
type VerifyNumberSettings struct {
Pin string `json:"pin"`
}
type SendMessageV1 struct {
Number string `json:"number"`
Recipients []string `json:"recipients"`
Message string `json:"message"`
Base64Attachment string `json:"base64_attachment"`
IsGroup bool `json:"is_group"`
}
type SendMessageV2 struct {
Number string `json:"number"`
Recipients []string `json:"recipients"`
Message string `json:"message"`
Base64Attachments []string `json:"base64_attachments"`
}
type Error struct {
Msg string `json:"error"`
}
type About struct {
SupportedApiVersions []string `json:"versions"`
BuildNr int `json:"build"`
}
type CreateGroup struct {
Id string `json:"id"`
}
func convertInternalGroupIdToGroupId(internalId string) string {
return groupPrefix + base64.StdEncoding.EncodeToString([]byte(internalId))
}
func getStringInBetween(str string, start string, end string) (result string) {
i := strings.Index(str, start)
if i == -1 {
return
}
i += len(start)
j := strings.Index(str[i:], end)
if j == -1 {
return
}
return str[i : i+j]
}
func cleanupTmpFiles(paths []string) {
for _, path := range paths {
os.Remove(path)
}
}
func send(c *gin.Context, attachmentTmpDir string, signalCliConfig string, number string, message string,
recipients []string, base64Attachments []string, isGroup bool) {
cmd := []string{"--config", signalCliConfig, "-u", number, "send", "-m", message}
if len(recipients) == 0 {
c.JSON(400, gin.H{"error": "Please specify at least one recipient"})
return
}
if !isGroup {
cmd = append(cmd, recipients...)
} else {
if len(recipients) > 1 {
c.JSON(400, gin.H{"error": "More than one recipient is currently not allowed"})
return
}
groupId, err := base64.StdEncoding.DecodeString(recipients[0])
if err != nil {
c.JSON(400, gin.H{"error": "Invalid group id"})
return
}
cmd = append(cmd, []string{"-g", string(groupId)}...)
}
attachmentTmpPaths := []string{}
for _, base64Attachment := range base64Attachments {
u, err := uuid.NewV4()
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
dec, err := base64.StdEncoding.DecodeString(base64Attachment)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
fType, err := filetype.Get(dec)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
attachmentTmpPath := attachmentTmpDir + u.String() + "." + fType.Extension
attachmentTmpPaths = append(attachmentTmpPaths, attachmentTmpPath)
f, err := os.Create(attachmentTmpPath)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
defer f.Close()
if _, err := f.Write(dec); err != nil {
cleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := f.Sync(); err != nil {
cleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
f.Close()
}
if len(attachmentTmpPaths) > 0 {
cmd = append(cmd, "-a")
cmd = append(cmd, attachmentTmpPaths...)
}
_, err := runSignalCli(true, cmd)
if err != nil {
cleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
cleanupTmpFiles(attachmentTmpPaths)
c.JSON(201, nil)
}
func getGroups(number string, signalCliConfig string) ([]GroupEntry, error) {
groupEntries := []GroupEntry{}
out, err := runSignalCli(true, []string{"--config", signalCliConfig, "-u", number, "listGroups", "-d"})
if err != nil {
return groupEntries, err
}
lines := strings.Split(out, "\n")
for _, line := range lines {
var groupEntry GroupEntry
if line == "" {
continue
}
idIdx := strings.Index(line, " Name: ")
idPair := line[:idIdx]
groupEntry.InternalId = strings.TrimPrefix(idPair, "Id: ")
groupEntry.Id = convertInternalGroupIdToGroupId(groupEntry.InternalId)
lineWithoutId := strings.TrimLeft(line[idIdx:], " ")
nameIdx := strings.Index(lineWithoutId, " Active: ")
namePair := lineWithoutId[:nameIdx]
groupEntry.Name = strings.TrimRight(strings.TrimPrefix(namePair, "Name: "), " ")
lineWithoutName := strings.TrimLeft(lineWithoutId[nameIdx:], " ")
activeIdx := strings.Index(lineWithoutName, " Blocked: ")
activePair := lineWithoutName[:activeIdx]
active := strings.TrimPrefix(activePair, "Active: ")
if active == "true" {
groupEntry.Active = true
} else {
groupEntry.Active = false
}
lineWithoutActive := strings.TrimLeft(lineWithoutName[activeIdx:], " ")
blockedIdx := strings.Index(lineWithoutActive, " Members: ")
blockedPair := lineWithoutActive[:blockedIdx]
blocked := strings.TrimPrefix(blockedPair, "Blocked: ")
if blocked == "true" {
groupEntry.Blocked = true
} else {
groupEntry.Blocked = false
}
lineWithoutBlocked := strings.TrimLeft(lineWithoutActive[blockedIdx:], " ")
membersPair := lineWithoutBlocked
members := strings.TrimPrefix(membersPair, "Members: ")
trimmedMembers := strings.TrimRight(strings.TrimLeft(members, "["), "]")
trimmedMembersList := strings.Split(trimmedMembers, ",")
for _, member := range trimmedMembersList {
groupEntry.Members = append(groupEntry.Members, strings.Trim(member, " "))
}
groupEntries = append(groupEntries, groupEntry)
}
return groupEntries, nil
}
func runSignalCli(wait bool, args []string) (string, error) {
cmd := exec.Command("signal-cli", args...)
if wait {
var errBuffer bytes.Buffer
var outBuffer bytes.Buffer
cmd.Stderr = &errBuffer
cmd.Stdout = &outBuffer
err := cmd.Start()
if err != nil {
return "", err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(60 * time.Second):
err := cmd.Process.Kill()
if err != nil {
return "", err
}
return "", errors.New("process killed as timeout reached")
case err := <-done:
if err != nil {
return "", errors.New(errBuffer.String())
}
}
return outBuffer.String(), nil
} else {
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
cmd.Start()
buf := bufio.NewReader(stdout) // Notice that this is not in a loop
line, _, _ := buf.ReadLine()
return string(line), nil
}
}
type Api struct {
signalCliConfig string
@ -291,11 +28,11 @@ func NewApi(signalCliConfig string, attachmentTmpDir string) *Api {
// @Tags General
// @Description Returns the supported API versions and the internal build nr
// @Produce json
// @Success 200 {object} About
// @Success 200 {object} datastructures.About
// @Router /v1/about [get]
func (a *Api) About(c *gin.Context) {
about := About{SupportedApiVersions: []string{"v1", "v2"}, BuildNr: 2}
about := datastructures.About{SupportedApiVersions: []string{"v1", "v2"}, BuildNr: 2}
c.JSON(200, about)
}
@ -305,13 +42,13 @@ func (a *Api) About(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 201
// @Failure 400 {object} Error
// @Failure 400 {object} datastructures.Error
// @Param number path string true "Registered Phone Number"
// @Router /v1/register/{number} [post]
func (a *Api) RegisterNumber(c *gin.Context) {
number := c.Param("number")
var req RegisterNumberRequest
var req datastructures.RegisterNumberRequest
buf := new(bytes.Buffer)
buf.ReadFrom(c.Request.Body)
@ -319,7 +56,7 @@ func (a *Api) RegisterNumber(c *gin.Context) {
err := json.Unmarshal(buf.Bytes(), &req)
if err != nil {
log.Error("Couldn't register number: ", err.Error())
c.JSON(400, Error{Msg: "Couldn't process request - invalid request."})
c.JSON(400, datastructures.Error{Msg: "Couldn't process request - invalid request."})
return
}
} else {
@ -331,13 +68,7 @@ func (a *Api) RegisterNumber(c *gin.Context) {
return
}
command := []string{"--config", a.signalCliConfig, "-u", number, "register"}
if req.UseVoice == true {
command = append(command, "--voice")
}
_, err := runSignalCli(true, command)
err := commands.RegisterNumber(a.signalCliConfig, number, req.UseVoice)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
@ -351,9 +82,9 @@ func (a *Api) RegisterNumber(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 201 {string} string "OK"
// @Failure 400 {object} Error
// @Failure 400 {object} datastructures.Error
// @Param number path string true "Registered Phone Number"
// @Param data body VerifyNumberSettings true "Additional Settings"
// @Param data body datastructures.VerifyNumberSettings true "Additional Settings"
// @Param token path string true "Verification Code"
// @Router /v1/register/{number}/verify/{token} [post]
func (a *Api) VerifyRegisteredNumber(c *gin.Context) {
@ -361,14 +92,14 @@ func (a *Api) VerifyRegisteredNumber(c *gin.Context) {
token := c.Param("token")
pin := ""
var req VerifyNumberSettings
var req datastructures.VerifyNumberSettings
buf := new(bytes.Buffer)
buf.ReadFrom(c.Request.Body)
if buf.String() != "" {
err := json.Unmarshal(buf.Bytes(), &req)
if err != nil {
log.Error("Couldn't verify number: ", err.Error())
c.JSON(400, Error{Msg: "Couldn't process request - invalid request."})
c.JSON(400, datastructures.Error{Msg: "Couldn't process request - invalid request."})
return
}
pin = req.Pin
@ -384,13 +115,7 @@ func (a *Api) VerifyRegisteredNumber(c *gin.Context) {
return
}
cmd := []string{"--config", a.signalCliConfig, "-u", number, "verify", token}
if pin != "" {
cmd = append(cmd, "--pin")
cmd = append(cmd, pin)
}
_, err := runSignalCli(true, cmd)
err := commands.VerifyRegisteredNumber(a.signalCliConfig, number, token, pin)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
@ -404,13 +129,13 @@ func (a *Api) VerifyRegisteredNumber(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 201 {string} string "OK"
// @Failure 400 {object} Error
// @Param data body SendMessageV1 true "Input Data"
// @Failure 400 {object} datastructures.Error
// @Param data body datastructures.SendMessageV1 true "Input Data"
// @Router /v1/send [post]
// @Deprecated
func (a *Api) Send(c *gin.Context) {
var req SendMessageV1
var req datastructures.SendMessageV1
err := c.BindJSON(&req)
if err != nil {
c.JSON(400, gin.H{"error": "Couldn't process request - invalid request"})
@ -422,7 +147,7 @@ func (a *Api) Send(c *gin.Context) {
base64Attachments = append(base64Attachments, req.Base64Attachment)
}
send(c, a.signalCliConfig, a.signalCliConfig, req.Number, req.Message, req.Recipients, base64Attachments, req.IsGroup)
commands.SendMessage(c, a.signalCliConfig, a.signalCliConfig, req.Number, req.Message, req.Recipients, base64Attachments, req.IsGroup)
}
// @Summary Send a signal message.
@ -431,11 +156,11 @@ func (a *Api) Send(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 201 {string} string "OK"
// @Failure 400 {object} Error
// @Param data body SendMessageV2 true "Input Data"
// @Failure 400 {object} datastructures.Error
// @Param data body datastructures.SendMessageV2 true "Input Data"
// @Router /v2/send [post]
func (a *Api) SendV2(c *gin.Context) {
var req SendMessageV2
var req datastructures.SendMessageV2
err := c.BindJSON(&req)
if err != nil {
c.JSON(400, gin.H{"error": "Couldn't process request - invalid request"})
@ -452,8 +177,8 @@ func (a *Api) SendV2(c *gin.Context) {
recipients := []string{}
for _, recipient := range req.Recipients {
if strings.HasPrefix(recipient, groupPrefix) {
groups = append(groups, strings.TrimPrefix(recipient, groupPrefix))
if strings.HasPrefix(recipient, datastructures.GroupPrefix) {
groups = append(groups, strings.TrimPrefix(recipient, datastructures.GroupPrefix))
} else {
recipients = append(recipients, recipient)
}
@ -470,11 +195,11 @@ func (a *Api) SendV2(c *gin.Context) {
}
for _, group := range groups {
send(c, a.attachmentTmpDir, a.signalCliConfig, req.Number, req.Message, []string{group}, req.Base64Attachments, true)
commands.SendMessage(c, a.attachmentTmpDir, a.signalCliConfig, req.Number, req.Message, []string{group}, req.Base64Attachments, true)
}
if len(recipients) > 0 {
send(c, a.attachmentTmpDir, a.signalCliConfig, req.Number, req.Message, recipients, req.Base64Attachments, false)
commands.SendMessage(c, a.attachmentTmpDir, a.signalCliConfig, req.Number, req.Message, recipients, req.Base64Attachments, false)
}
}
@ -484,32 +209,19 @@ func (a *Api) SendV2(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 200 {object} []string
// @Failure 400 {object} Error
// @Failure 400 {object} datastructures.Error
// @Param number path string true "Registered Phone Number"
// @Router /v1/receive/{number} [get]
func (a *Api) Receive(c *gin.Context) {
number := c.Param("number")
command := []string{"--config", a.signalCliConfig, "-u", number, "receive", "-t", "1", "--json"}
out, err := runSignalCli(true, command)
res, err := commands.Receive(a.signalCliConfig, number)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
out = strings.Trim(out, "\n")
lines := strings.Split(out, "\n")
jsonStr := "["
for i, line := range lines {
jsonStr += line
if i != (len(lines) - 1) {
jsonStr += ","
}
}
jsonStr += "]"
c.String(200, jsonStr)
c.String(200, res)
}
// @Summary Create a new Signal Group.
@ -517,8 +229,8 @@ func (a *Api) Receive(c *gin.Context) {
// @Description Create a new Signal Group with the specified members.
// @Accept json
// @Produce json
// @Success 201 {object} CreateGroup
// @Failure 400 {object} Error
// @Success 201 {object} datastructures.CreateGroup
// @Failure 400 {object} datastructures.Error
// @Param number path string true "Registered Phone Number"
// @Router /v1/groups/{number} [post]
func (a *Api) CreateGroup(c *gin.Context) {
@ -537,17 +249,13 @@ func (a *Api) CreateGroup(c *gin.Context) {
return
}
cmd := []string{"--config", a.signalCliConfig, "-u", number, "updateGroup", "-n", req.Name, "-m"}
cmd = append(cmd, req.Members...)
out, err := runSignalCli(true, cmd)
internalGroupId, err := commands.CreateGroup(a.signalCliConfig, number, req.Name, req.Members)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
internalGroupId := getStringInBetween(out, `"`, `"`)
c.JSON(201, CreateGroup{Id: convertInternalGroupIdToGroupId(internalGroupId)})
c.JSON(201, datastructures.CreateGroup{Id: commands.ConvertInternalGroupIdToGroupId(internalGroupId)})
}
// @Summary List all Signal Groups.
@ -555,14 +263,14 @@ func (a *Api) CreateGroup(c *gin.Context) {
// @Description List all Signal Groups.
// @Accept json
// @Produce json
// @Success 200 {object} []GroupEntry
// @Failure 400 {object} Error
// @Success 200 {object} []datastructures.GroupEntry
// @Failure 400 {object} datastructures.Error
// @Param number path string true "Registered Phone Number"
// @Router /v1/groups/{number} [get]
func (a *Api) GetGroups(c *gin.Context) {
number := c.Param("number")
groups, err := getGroups(number, a.signalCliConfig)
groups, err := commands.GetGroups(a.signalCliConfig, number)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
@ -577,7 +285,7 @@ func (a *Api) GetGroups(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 200 {string} string "OK"
// @Failure 400 {object} Error
// @Failure 400 {object} datastructures.Error
// @Param number path string true "Registered Phone Number"
// @Param groupid path string true "Group Id"
// @Router /v1/groups/{number}/{groupid} [delete]
@ -590,17 +298,19 @@ func (a *Api) DeleteGroup(c *gin.Context) {
return
}
groupId, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(base64EncodedGroupId, groupPrefix))
groupId, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(base64EncodedGroupId, datastructures.GroupPrefix))
if err != nil {
c.JSON(400, gin.H{"error": "Invalid group id"})
return
}
_, err = runSignalCli(true, []string{"--config", a.signalCliConfig, "-u", number, "quitGroup", "-g", string(groupId)})
err = commands.DeleteGroup(a.signalCliConfig, number, string(groupId))
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
c.JSON(204, nil)
}
// @Summary Link device and generate QR code.
@ -617,25 +327,11 @@ func (a *Api) GetQrCodeLink(c *gin.Context) {
return
}
command := []string{"--config", a.signalCliConfig, "link", "-n", deviceName}
tsdeviceLink, err := runSignalCli(false, command)
png, err := commands.GetQrCodeLink(a.signalCliConfig, deviceName)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
q, err := qrcode.New(string(tsdeviceLink), qrcode.Medium)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
}
q.DisableBorder = true
var png []byte
png, err = q.PNG(256)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
}
c.Data(200, "image/png", png)
}

396
src/commands/commands.go Normal file
View File

@ -0,0 +1,396 @@
package commands
import (
datastructures "github.com/bbernhard/signal-cli-rest-api/datastructures"
system "github.com/bbernhard/signal-cli-rest-api/system"
"strings"
"encoding/base64"
"github.com/h2non/filetype"
"github.com/gin-gonic/gin"
uuid "github.com/gofrs/uuid"
"os"
log "github.com/sirupsen/logrus"
qrcode "github.com/skip2/go-qrcode"
)
func getStringInBetween(str string, start string, end string) (result string) {
i := strings.Index(str, start)
if i == -1 {
return
}
i += len(start)
j := strings.Index(str[i:], end)
if j == -1 {
return
}
return str[i : i+j]
}
func ConvertInternalGroupIdToGroupId(internalId string) string {
return datastructures.GroupPrefix + base64.StdEncoding.EncodeToString([]byte(internalId))
}
func GetGroups(signalCliConfig string, number string) ([]datastructures.GroupEntry, error) {
groupEntries := []datastructures.GroupEntry{}
out, err := system.RunSignalCli(true, []string{"--config", signalCliConfig, "-u", number, "listGroups", "-d"})
if err != nil {
return groupEntries, err
}
lines := strings.Split(out, "\n")
for _, line := range lines {
var groupEntry datastructures.GroupEntry
if line == "" {
continue
}
idIdx := strings.Index(line, " Name: ")
idPair := line[:idIdx]
groupEntry.InternalId = strings.TrimPrefix(idPair, "Id: ")
groupEntry.Id = ConvertInternalGroupIdToGroupId(groupEntry.InternalId)
lineWithoutId := strings.TrimLeft(line[idIdx:], " ")
nameIdx := strings.Index(lineWithoutId, " Active: ")
namePair := lineWithoutId[:nameIdx]
groupEntry.Name = strings.TrimRight(strings.TrimPrefix(namePair, "Name: "), " ")
lineWithoutName := strings.TrimLeft(lineWithoutId[nameIdx:], " ")
activeIdx := strings.Index(lineWithoutName, " Blocked: ")
activePair := lineWithoutName[:activeIdx]
active := strings.TrimPrefix(activePair, "Active: ")
if active == "true" {
groupEntry.Active = true
} else {
groupEntry.Active = false
}
lineWithoutActive := strings.TrimLeft(lineWithoutName[activeIdx:], " ")
blockedIdx := strings.Index(lineWithoutActive, " Members: ")
blockedPair := lineWithoutActive[:blockedIdx]
blocked := strings.TrimPrefix(blockedPair, "Blocked: ")
if blocked == "true" {
groupEntry.Blocked = true
} else {
groupEntry.Blocked = false
}
lineWithoutBlocked := strings.TrimLeft(lineWithoutActive[blockedIdx:], " ")
membersPair := lineWithoutBlocked
members := strings.TrimPrefix(membersPair, "Members: ")
trimmedMembers := strings.TrimRight(strings.TrimLeft(members, "["), "]")
trimmedMembersList := strings.Split(trimmedMembers, ",")
for _, member := range trimmedMembersList {
groupEntry.Members = append(groupEntry.Members, strings.Trim(member, " "))
}
groupEntries = append(groupEntries, groupEntry)
}
return groupEntries, nil
}
func sendMessageViaDbus(c *gin.Context, attachmentTmpDir string, signalCliConfig string, number string, message string,
recipients []string, base64Attachments []string, isGroup bool) {
messageType := "org.asamk.Signal.sendMessage"
if isGroup {
messageType = "org.asamk.Signal.sendGroupMessage"
}
cmd := []string{"--system", "--type=method_call", "--print-reply", "--dest=org.asamk.Signal",
"/org/asamk/Signal", messageType, "string:" + message }
if len(recipients) == 0 {
c.JSON(400, gin.H{"error": "Please specify at least one recipient"})
return
}
attachmentTmpPaths := []string{}
for _, base64Attachment := range base64Attachments {
u, err := uuid.NewV4()
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
dec, err := base64.StdEncoding.DecodeString(base64Attachment)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
fType, err := filetype.Get(dec)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
attachmentTmpPath := attachmentTmpDir + u.String() + "." + fType.Extension
attachmentTmpPaths = append(attachmentTmpPaths, attachmentTmpPath)
f, err := os.Create(attachmentTmpPath)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
defer f.Close()
if _, err := f.Write(dec); err != nil {
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := f.Sync(); err != nil {
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
f.Close()
}
delimitedAttachmentPaths := "array:string:"
if len(attachmentTmpPaths) > 0 {
joinedAttachmentTmpPaths := strings.Join(attachmentTmpPaths, ",")
delimitedAttachmentPaths += joinedAttachmentTmpPaths
}
cmd = append(cmd, delimitedAttachmentPaths)
delimitedRecipients := "array:string:"
if !isGroup {
joinedRecipients := strings.Join(recipients, ",")
delimitedRecipients += joinedRecipients
cmd = append(cmd, delimitedRecipients)
} else {
if len(recipients) > 1 {
c.JSON(400, gin.H{"error": "More than one recipient is currently not allowed"})
return
}
groupId, err := base64.StdEncoding.DecodeString(recipients[0])
if err != nil {
c.JSON(400, gin.H{"error": "Invalid group id"})
return
}
groupIdByteArray := "array:byte:"
groupIdArray := []string{}
for _, c := range groupId {
groupIdArray = append(groupIdArray, string(c))
}
groupIdByteArray += strings.Join(groupIdArray, ",")
cmd = append(cmd, groupIdByteArray)
}
log.Info(cmd)
_, err := system.RunCommand("dbus-send", cmd)
if err != nil {
//system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(201, nil)
}
func sendMessage(c *gin.Context, attachmentTmpDir string, signalCliConfig string, number string, message string,
recipients []string, base64Attachments []string, isGroup bool) {
cmd := []string{"--config", signalCliConfig, "-u", number, "send", "-m", message}
if len(recipients) == 0 {
c.JSON(400, gin.H{"error": "Please specify at least one recipient"})
return
}
if !isGroup {
cmd = append(cmd, recipients...)
} else {
if len(recipients) > 1 {
c.JSON(400, gin.H{"error": "More than one recipient is currently not allowed"})
return
}
groupId, err := base64.StdEncoding.DecodeString(recipients[0])
if err != nil {
c.JSON(400, gin.H{"error": "Invalid group id"})
return
}
cmd = append(cmd, []string{"-g", string(groupId)}...)
}
attachmentTmpPaths := []string{}
for _, base64Attachment := range base64Attachments {
u, err := uuid.NewV4()
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
dec, err := base64.StdEncoding.DecodeString(base64Attachment)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
fType, err := filetype.Get(dec)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
attachmentTmpPath := attachmentTmpDir + u.String() + "." + fType.Extension
attachmentTmpPaths = append(attachmentTmpPaths, attachmentTmpPath)
f, err := os.Create(attachmentTmpPath)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
defer f.Close()
if _, err := f.Write(dec); err != nil {
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := f.Sync(); err != nil {
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
f.Close()
}
if len(attachmentTmpPaths) > 0 {
cmd = append(cmd, "-a")
cmd = append(cmd, attachmentTmpPaths...)
}
_, err := system.RunSignalCli(true, cmd)
if err != nil {
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(400, gin.H{"error": err.Error()})
return
}
system.CleanupTmpFiles(attachmentTmpPaths)
c.JSON(201, nil)
}
func SendMessage(c *gin.Context, attachmentTmpDir string, signalCliConfig string, number string, message string,
recipients []string, base64Attachments []string, isGroup bool) {
if system.UseDbus() {
sendMessageViaDbus(c, attachmentTmpDir, signalCliConfig, number, message, recipients, base64Attachments, isGroup)
return
}
sendMessage(c, attachmentTmpDir, signalCliConfig, number, message, recipients, base64Attachments, isGroup)
}
func RegisterNumber(signalCliConfig string, number string, useVoice bool) error {
command := []string{"--config", signalCliConfig, "-u", number, "register"}
if useVoice == true {
command = append(command, "--voice")
}
_, err := system.RunSignalCli(true, command)
if err != nil {
return err
}
return nil
}
func VerifyRegisteredNumber(signalCliConfig string, number string, token string, pin string) error {
cmd := []string{"--config", signalCliConfig, "-u", number, "verify", token}
if pin != "" {
cmd = append(cmd, "--pin")
cmd = append(cmd, pin)
}
_, err := system.RunSignalCli(true, cmd)
if err != nil {
return err
}
return nil
}
func CreateGroup(signalCliConfig string, number string, groupName string, groupMembers []string) (string, error) {
cmd := []string{"--config", signalCliConfig, "-u", number, "updateGroup", "-n", groupName, "-m"}
cmd = append(cmd, groupMembers...)
out, err := system.RunSignalCli(true, cmd)
if err != nil {
return "", err
}
internalGroupId := getStringInBetween(out, `"`, `"`)
return internalGroupId, nil
}
func Receive(signalCliConfig string, number string,) (string, error) {
command := []string{"--config", signalCliConfig, "-u", number, "receive", "-t", "1", "--json"}
out, err := system.RunSignalCli(true, command)
if err != nil {
return "", err
}
out = strings.Trim(out, "\n")
lines := strings.Split(out, "\n")
jsonStr := "["
for i, line := range lines {
jsonStr += line
if i != (len(lines) - 1) {
jsonStr += ","
}
}
jsonStr += "]"
return jsonStr, nil
}
func DeleteGroup(signalCliConfig string, number string, groupId string) error {
_, err := system.RunSignalCli(true, []string{"--config", signalCliConfig, "-u", number, "quitGroup", "-g", groupId})
if err != nil {
return err
}
return nil
}
func GetQrCodeLink(signalCliConfig string, deviceName string) ([]byte, error) {
command := []string{"--config", signalCliConfig, "link", "-n", deviceName}
var png []byte
tsdeviceLink, err := system.RunSignalCli(false, command)
if err != nil {
return png, err
}
q, err := qrcode.New(string(tsdeviceLink), qrcode.Medium)
if err != nil {
return png, err
}
q.DisableBorder = true
png, err = q.PNG(256)
if err != nil {
return png, err
}
return png, nil
}

View File

@ -0,0 +1,49 @@
package datastructures
const GroupPrefix = "group."
type GroupEntry struct {
Name string `json:"name"`
Id string `json:"id"`
InternalId string `json:"internal_id"`
Members []string `json:"members"`
Active bool `json:"active"`
Blocked bool `json:"blocked"`
}
type RegisterNumberRequest struct {
UseVoice bool `json:"use_voice"`
}
type VerifyNumberSettings struct {
Pin string `json:"pin"`
}
type SendMessageV1 struct {
Number string `json:"number"`
Recipients []string `json:"recipients"`
Message string `json:"message"`
Base64Attachment string `json:"base64_attachment"`
IsGroup bool `json:"is_group"`
}
type SendMessageV2 struct {
Number string `json:"number"`
Recipients []string `json:"recipients"`
Message string `json:"message"`
Base64Attachments []string `json:"base64_attachments"`
}
type Error struct {
Msg string `json:"error"`
}
type About struct {
SupportedApiVersions []string `json:"versions"`
BuildNr int `json:"build"`
}
type CreateGroup struct {
Id string `json:"id"`
}

View File

@ -39,7 +39,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api.About"
"$ref": "#/definitions/datastructures.About"
}
}
}
@ -73,14 +73,14 @@ var doc = `{
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/api.GroupEntry"
"$ref": "#/definitions/datastructures.GroupEntry"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -110,13 +110,13 @@ var doc = `{
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/api.CreateGroup"
"$ref": "#/definitions/datastructures.CreateGroup"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -161,7 +161,7 @@ var doc = `{
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -222,7 +222,7 @@ var doc = `{
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -255,7 +255,7 @@ var doc = `{
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -288,7 +288,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api.VerifyNumberSettings"
"$ref": "#/definitions/datastructures.VerifyNumberSettings"
}
},
{
@ -309,7 +309,7 @@ var doc = `{
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -336,7 +336,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api.SendMessageV1"
"$ref": "#/definitions/datastructures.SendMessageV1"
}
}
],
@ -350,7 +350,7 @@ var doc = `{
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -376,7 +376,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api.SendMessageV2"
"$ref": "#/definitions/datastructures.SendMessageV2"
}
}
],
@ -390,7 +390,7 @@ var doc = `{
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -398,7 +398,7 @@ var doc = `{
}
},
"definitions": {
"api.About": {
"datastructures.About": {
"type": "object",
"properties": {
"build": {
@ -412,7 +412,7 @@ var doc = `{
}
}
},
"api.CreateGroup": {
"datastructures.CreateGroup": {
"type": "object",
"properties": {
"id": {
@ -420,7 +420,7 @@ var doc = `{
}
}
},
"api.Error": {
"datastructures.Error": {
"type": "object",
"properties": {
"error": {
@ -428,7 +428,7 @@ var doc = `{
}
}
},
"api.GroupEntry": {
"datastructures.GroupEntry": {
"type": "object",
"properties": {
"active": {
@ -454,7 +454,7 @@ var doc = `{
}
}
},
"api.SendMessageV1": {
"datastructures.SendMessageV1": {
"type": "object",
"properties": {
"base64_attachment": {
@ -477,7 +477,7 @@ var doc = `{
}
}
},
"api.SendMessageV2": {
"datastructures.SendMessageV2": {
"type": "object",
"properties": {
"base64_attachments": {
@ -500,7 +500,7 @@ var doc = `{
}
}
},
"api.VerifyNumberSettings": {
"datastructures.VerifyNumberSettings": {
"type": "object",
"properties": {
"pin": {

View File

@ -24,7 +24,7 @@
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api.About"
"$ref": "#/definitions/datastructures.About"
}
}
}
@ -58,14 +58,14 @@
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/api.GroupEntry"
"$ref": "#/definitions/datastructures.GroupEntry"
}
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -95,13 +95,13 @@
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/api.CreateGroup"
"$ref": "#/definitions/datastructures.CreateGroup"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -146,7 +146,7 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -207,7 +207,7 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -240,7 +240,7 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -273,7 +273,7 @@
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api.VerifyNumberSettings"
"$ref": "#/definitions/datastructures.VerifyNumberSettings"
}
},
{
@ -294,7 +294,7 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -321,7 +321,7 @@
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api.SendMessageV1"
"$ref": "#/definitions/datastructures.SendMessageV1"
}
}
],
@ -335,7 +335,7 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -361,7 +361,7 @@
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api.SendMessageV2"
"$ref": "#/definitions/datastructures.SendMessageV2"
}
}
],
@ -375,7 +375,7 @@
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api.Error"
"$ref": "#/definitions/datastructures.Error"
}
}
}
@ -383,7 +383,7 @@
}
},
"definitions": {
"api.About": {
"datastructures.About": {
"type": "object",
"properties": {
"build": {
@ -397,7 +397,7 @@
}
}
},
"api.CreateGroup": {
"datastructures.CreateGroup": {
"type": "object",
"properties": {
"id": {
@ -405,7 +405,7 @@
}
}
},
"api.Error": {
"datastructures.Error": {
"type": "object",
"properties": {
"error": {
@ -413,7 +413,7 @@
}
}
},
"api.GroupEntry": {
"datastructures.GroupEntry": {
"type": "object",
"properties": {
"active": {
@ -439,7 +439,7 @@
}
}
},
"api.SendMessageV1": {
"datastructures.SendMessageV1": {
"type": "object",
"properties": {
"base64_attachment": {
@ -462,7 +462,7 @@
}
}
},
"api.SendMessageV2": {
"datastructures.SendMessageV2": {
"type": "object",
"properties": {
"base64_attachments": {
@ -485,7 +485,7 @@
}
}
},
"api.VerifyNumberSettings": {
"datastructures.VerifyNumberSettings": {
"type": "object",
"properties": {
"pin": {

View File

@ -1,6 +1,6 @@
basePath: /
definitions:
api.About:
datastructures.About:
properties:
build:
type: integer
@ -9,17 +9,17 @@ definitions:
type: string
type: array
type: object
api.CreateGroup:
datastructures.CreateGroup:
properties:
id:
type: string
type: object
api.Error:
datastructures.Error:
properties:
error:
type: string
type: object
api.GroupEntry:
datastructures.GroupEntry:
properties:
active:
type: boolean
@ -36,7 +36,7 @@ definitions:
name:
type: string
type: object
api.SendMessageV1:
datastructures.SendMessageV1:
properties:
base64_attachment:
type: string
@ -51,7 +51,7 @@ definitions:
type: string
type: array
type: object
api.SendMessageV2:
datastructures.SendMessageV2:
properties:
base64_attachments:
items:
@ -66,7 +66,7 @@ definitions:
type: string
type: array
type: object
api.VerifyNumberSettings:
datastructures.VerifyNumberSettings:
properties:
pin:
type: string
@ -88,7 +88,7 @@ paths:
"200":
description: OK
schema:
$ref: '#/definitions/api.About'
$ref: '#/definitions/datastructures.About'
summary: Lists general information about the API
tags:
- General
@ -110,12 +110,12 @@ paths:
description: OK
schema:
items:
$ref: '#/definitions/api.GroupEntry'
$ref: '#/definitions/datastructures.GroupEntry'
type: array
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: List all Signal Groups.
tags:
- Groups
@ -135,11 +135,11 @@ paths:
"201":
description: Created
schema:
$ref: '#/definitions/api.CreateGroup'
$ref: '#/definitions/datastructures.CreateGroup'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Create a new Signal Group.
tags:
- Groups
@ -169,7 +169,7 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Delete a Signal Group.
tags:
- Groups
@ -209,7 +209,7 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Receive Signal Messages.
tags:
- Messages
@ -231,7 +231,7 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Register a phone number.
tags:
- Devices
@ -251,7 +251,7 @@ paths:
name: data
required: true
schema:
$ref: '#/definitions/api.VerifyNumberSettings'
$ref: '#/definitions/datastructures.VerifyNumberSettings'
- description: Verification Code
in: path
name: token
@ -267,7 +267,7 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Verify a registered phone number.
tags:
- Devices
@ -283,7 +283,7 @@ paths:
name: data
required: true
schema:
$ref: '#/definitions/api.SendMessageV1'
$ref: '#/definitions/datastructures.SendMessageV1'
produces:
- application/json
responses:
@ -294,7 +294,7 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Send a signal message.
tags:
- Messages
@ -309,7 +309,7 @@ paths:
name: data
required: true
schema:
$ref: '#/definitions/api.SendMessageV2'
$ref: '#/definitions/datastructures.SendMessageV2'
produces:
- application/json
responses:
@ -320,7 +320,7 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api.Error'
$ref: '#/definitions/datastructures.Error'
summary: Send a signal message.
tags:
- Messages

View File

@ -8,6 +8,7 @@ import (
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/bbernhard/signal-cli-rest-api/api"
system "github.com/bbernhard/signal-cli-rest-api/system"
_ "github.com/bbernhard/signal-cli-rest-api/docs"
)
@ -37,6 +38,18 @@ func main() {
attachmentTmpDir := flag.String("attachment-tmp-dir", "/tmp/", "Attachment tmp directory")
flag.Parse()
if system.UseDbus() {
err := system.StartSystemDbus()
if err != nil {
log.Fatal("Couldn't start system DBUS: ", err.Error())
}
err = system.StartSignalCliDbusDaemon(*signalCliConfig)
if err != nil {
log.Fatal("Couldn't start supervisor: ", err.Error())
}
}
router := gin.Default()
log.Info("Started Signal Messenger REST API")

170
src/system/system.go Normal file
View File

@ -0,0 +1,170 @@
package system
import (
"os/exec"
"errors"
"bytes"
"time"
"io/ioutil"
"strings"
"bufio"
"os"
)
func UseDbus() bool {
useDbus := os.Getenv("USE_DBUS")
if useDbus == "true" {
return true
}
return false
}
func CleanupTmpFiles(paths []string) {
for _, path := range paths {
os.Remove(path)
}
}
func RunCommand(command string, args []string) (string, error) {
cmd := exec.Command(command, args...)
var errBuffer bytes.Buffer
var outBuffer bytes.Buffer
cmd.Stderr = &errBuffer
cmd.Stdout = &outBuffer
err := cmd.Start()
if err != nil {
return "", err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(60 * time.Second):
err := cmd.Process.Kill()
if err != nil {
return "", err
}
return "", errors.New("process killed as timeout reached")
case err := <-done:
if err != nil {
return "", errors.New(errBuffer.String())
}
}
return outBuffer.String(), nil
}
func RunSignalCli(wait bool, args []string) (string, error) {
cmd := exec.Command("signal-cli", args...)
if wait {
var errBuffer bytes.Buffer
var outBuffer bytes.Buffer
cmd.Stderr = &errBuffer
cmd.Stdout = &outBuffer
err := cmd.Start()
if err != nil {
return "", err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(60 * time.Second):
err := cmd.Process.Kill()
if err != nil {
return "", err
}
return "", errors.New("process killed as timeout reached")
case err := <-done:
if err != nil {
return "", errors.New(errBuffer.String())
}
}
return outBuffer.String(), nil
} else {
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
cmd.Start()
buf := bufio.NewReader(stdout) // Notice that this is not in a loop
line, _, _ := buf.ReadLine()
return string(line), nil
}
}
func getRegisteredNumbers(path string) ([]string, error) {
registeredNumbers := []string{}
files, err := ioutil.ReadDir(path)
if err != nil {
return registeredNumbers, err
}
for _, f := range files {
if !f.IsDir() {
registeredNumbers = append(registeredNumbers, f.Name())
}
}
return registeredNumbers, nil
}
func StartSystemDbus() error {
_, err := RunCommand("dbus-daemon", []string{"--system"})
return err
}
func StartSignalCliDbusDaemon(signalCliConfig string) error {
registeredNumbers, err := getRegisteredNumbers(signalCliConfig+"/data/")
if err != nil {
return err
}
if len(registeredNumbers) > 1 {
return errors.New("DBUS only supports max. one number!")
}
if len(registeredNumbers) != 1 {
return errors.New("No registered number found!")
}
supervisorConfPath := "/etc/supervisor/conf.d/signal-cli.conf"
data, err := ioutil.ReadFile(supervisorConfPath)
if err != nil {
return err
}
out := strings.Replace(string(data), "!#MY_NUMBER#!", registeredNumbers[0], -1)
err = ioutil.WriteFile(supervisorConfPath, []byte(out), 0644)
if err != nil {
return err
}
_, err = RunCommand("service", []string{"supervisor", "start"})
return err
}
/*func SendMessage() error {
conn, err := dbus.ConnectSystemBus()
if err != nil {
return err
}
defer conn.Close()
var s string
err = conn.Object("org.asamk.Signal", "/").Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&s)
if err != nil {
return err
}
}*/