diff options
-rw-r--r-- | .editorconfig | 3 | ||||
-rw-r--r-- | .gitlab-ci.yml | 82 | ||||
-rw-r--r-- | config/config.go | 19 | ||||
-rw-r--r-- | go.mod | 18 | ||||
-rw-r--r-- | go.sum | 50 | ||||
-rw-r--r-- | gomuks.go | 4 | ||||
-rw-r--r-- | interface/matrix.go | 5 | ||||
-rw-r--r-- | main.go | 86 | ||||
-rw-r--r-- | matrix/crypto.go | 62 | ||||
-rw-r--r-- | matrix/matrix.go | 148 | ||||
-rw-r--r-- | matrix/nocrypto.go | 13 | ||||
-rw-r--r-- | matrix/rooms/room.go | 13 | ||||
-rw-r--r-- | matrix/rooms/roomcache.go | 24 | ||||
-rw-r--r-- | matrix/sync.go | 46 | ||||
-rw-r--r-- | ui/messages/filemessage.go | 59 | ||||
-rw-r--r-- | ui/messages/parser.go | 6 | ||||
-rw-r--r-- | ui/room-view.go | 11 |
17 files changed, 467 insertions, 182 deletions
diff --git a/.editorconfig b/.editorconfig index 1b83267..9fa8d76 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,3 +7,6 @@ end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true + +[.gitlab-ci.yml] +indent_size = 2 diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b52047e..05097b8 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,65 +1,41 @@ -image: golang:alpine - -variables: - CGO_ENABLED: "0" - -stages: -- modules -- build - -cache: - paths: - - .cache - -default: +build: + stage: build + image: debian:bullseye + cache: + paths: + - .cache before_script: - - apk add git + - apt-get update + - apt-get install -y git libolm-dev golang-go - mkdir -p .cache - export GOPATH="$CI_PROJECT_DIR/.cache" - -modules: - stage: modules script: - - go get + - go build -o gomuks_linux_amd64 + artifacts: + paths: + - gomuks_linux_amd64 -.build: &build +build_static: stage: build + image: golang:alpine cache: paths: - .cache + before_script: + - mkdir -p .cache + - export GOPATH="$CI_PROJECT_DIR/.cache" + variables: + CGO_ENABLED: "0" script: - - echo "Building... $GOPATH $CGO_ENABLED $GOOS $GOARCH" - - go build -o gomuks + - GOOS=linux GOARCH=amd64 go build -o gomuks_linux_amd64 + - GOOS=linux GOARCH=386 go build -o gomuks_linux_386 + - GOOS=linux GOARCH=arm go build -o gomuks_linux_arm + - GOOS=linux GOARCH=arm64 go build -o gomuks_linux_arm64 + - GOOS=darwin GOARCH=amd64 go build -o gomuks_darwin_amd64 artifacts: paths: - - gomuks - -build_linux_amd64: - <<: *build - variables: - GOOS: linux - GOARCH: amd64 - -build_linux_386: - <<: *build - variables: - GOOS: linux - GOARCH: "386" - -build_linux_arm: - <<: *build - variables: - GOOS: linux - GOARCH: arm - -build_linux_arm64: - <<: *build - variables: - GOOS: linux - GOARCH: arm64 - -build_darwin_amd64: - <<: *build - variables: - GOOS: darwin - GOARCH: amd64 + - gomuks_linux_amd64 + - gomuks_linux_386 + - gomuks_linux_arm + - gomuks_linux_arm64 + - gomuks_darwin_amd64 diff --git a/config/config.go b/config/config.go index 3fe961e..a958b1c 100644 --- a/config/config.go +++ b/config/config.go @@ -54,9 +54,10 @@ type UserPreferences struct { // Config contains the main config of gomuks. type Config struct { - UserID id.UserID `yaml:"mxid"` - AccessToken string `yaml:"access_token"` - HS string `yaml:"homeserver"` + UserID id.UserID `yaml:"mxid"` + DeviceID id.DeviceID `yaml:"device_id"` + AccessToken string `yaml:"access_token"` + HS string `yaml:"homeserver"` RoomCacheSize int `yaml:"room_cache_size"` RoomCacheAge int64 `yaml:"room_cache_age"` @@ -64,6 +65,7 @@ type Config struct { NotifySound bool `yaml:"notify_sound"` Dir string `yaml:"-"` + DataDir string `yaml:"data_dir"` CacheDir string `yaml:"cache_dir"` HistoryPath string `yaml:"history_path"` RoomListPath string `yaml:"room_list_path"` @@ -80,9 +82,10 @@ type Config struct { } // NewConfig creates a config that loads data from the given directory. -func NewConfig(configDir, cacheDir, downloadDir string) *Config { +func NewConfig(configDir, dataDir, cacheDir, downloadDir string) *Config { return &Config{ Dir: configDir, + DataDir: dataDir, CacheDir: cacheDir, DownloadDir: downloadDir, HistoryPath: filepath.Join(cacheDir, "history.db"), @@ -107,8 +110,14 @@ func (config *Config) Clear() { config.nosave = true } +// ClearData clears non-temporary session data. +func (config *Config) ClearData() { + _ = os.RemoveAll(config.DataDir) +} + func (config *Config) CreateCacheDirs() { _ = os.MkdirAll(config.CacheDir, 0700) + _ = os.MkdirAll(config.DataDir, 0700) _ = os.MkdirAll(config.StateDir, 0700) _ = os.MkdirAll(config.MediaDir, 0700) } @@ -117,9 +126,11 @@ func (config *Config) DeleteSession() { config.AuthCache.NextBatch = "" config.AuthCache.InitialSyncDone = false config.AccessToken = "" + config.DeviceID = "" config.Rooms = rooms.NewRoomCache(config.RoomListPath, config.StateDir, config.RoomCacheSize, config.RoomCacheAge, config.GetUserID) config.PushRules = nil + config.ClearData() config.Clear() config.nosave = false config.CreateCacheDirs() @@ -3,12 +3,12 @@ module maunium.net/go/gomuks go 1.14 require ( - github.com/alecthomas/chroma v0.7.1 + github.com/alecthomas/chroma v0.7.2 github.com/disintegration/imaging v1.6.2 - github.com/kyokomi/emoji v2.1.0+incompatible + github.com/kyokomi/emoji v2.2.2+incompatible github.com/lithammer/fuzzysearch v1.1.0 github.com/lucasb-eyer/go-colorful v1.0.3 - github.com/mattn/go-runewidth v0.0.8 + github.com/mattn/go-runewidth v0.0.9 github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect github.com/pkg/errors v0.9.1 github.com/rivo/uniseg v0.1.0 @@ -16,12 +16,12 @@ require ( github.com/sasha-s/go-deadlock v0.2.0 github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/stretchr/testify v1.5.1 - go.etcd.io/bbolt v1.3.3 - golang.org/x/image v0.0.0-20200119044424-58c23975cae1 - golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e + go.etcd.io/bbolt v1.3.4 + golang.org/x/image v0.0.0-20200430140353-33d19683fad8 + golang.org/x/net v0.0.0-20200505041828-1ed23360d12c gopkg.in/toast.v1 v1.0.0-20180812000517-0a84660828b2 gopkg.in/yaml.v2 v2.2.8 - maunium.net/go/mautrix v0.2.0-beta.4 - maunium.net/go/mauview v0.1.0 - maunium.net/go/tcell v0.1.0 + maunium.net/go/mautrix v0.3.1 + maunium.net/go/mauview v0.1.1 + maunium.net/go/tcell v0.2.0 ) @@ -1,6 +1,6 @@ github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= -github.com/alecthomas/chroma v0.7.1 h1:G1i02OhUbRi2nJxcNkwJaY/J1gHXj9tt72qN6ZouLFQ= -github.com/alecthomas/chroma v0.7.1/go.mod h1:gHw09mkX1Qp80JlYbmN9L3+4R5o6DJJ3GRShh+AICNc= +github.com/alecthomas/chroma v0.7.2 h1:B76NU/zbQYIUhUowbi4fmvREmDUJLsUzKWTZmQd3ABY= +github.com/alecthomas/chroma v0.7.2/go.mod h1:fv5SzZPFJbwp2NXJWpFIX7DZS4HgV1K4ew4Pc2OZD9s= github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= github.com/alecthomas/kong v0.2.1-0.20190708041108-0548c6b1afae/go.mod h1:+inYUSluD+p4L8KdviBSgzcqEjUQOfC5fQDRFuc36lI= github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= @@ -16,8 +16,9 @@ github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= -github.com/kyokomi/emoji v2.1.0+incompatible h1:+DYU2RgpI6OHG4oQkM5KlqD3Wd3UPEsX8jamTo1Mp6o= -github.com/kyokomi/emoji v2.1.0+incompatible/go.mod h1:mZ6aGCD7yk8j6QY6KICwnZ2pxoszVseX1DNoGtU2tBA= +github.com/kyokomi/emoji v1.5.1 h1:qp9dub1mW7C4MlvoRENH6EAENb9skEFOvIEbp1Waj38= +github.com/kyokomi/emoji v2.2.2+incompatible h1:gaQFbK2+uSxOR4iGZprJAbpmtqTrHhSdgOyIMD6Oidc= +github.com/kyokomi/emoji v2.2.2+incompatible/go.mod h1:mZ6aGCD7yk8j6QY6KICwnZ2pxoszVseX1DNoGtU2tBA= github.com/lithammer/fuzzysearch v1.1.0 h1:go9v8tLCrNTTlH42OAaq4eHFe81TDHEnlrMEb6R4f+A= github.com/lithammer/fuzzysearch v1.1.0/go.mod h1:Bqx4wo8lTOFcJr3ckpY6HA9lEIOO0H5HrkJ5CsN56HQ= github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac= @@ -25,8 +26,9 @@ github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.8 h1:3tS41NlGYSmhhe/8fhGRzc+z3AYCw1Fe1WAyLuujKs0= github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= @@ -47,23 +49,37 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/tidwall/gjson v1.6.0 h1:9VEQWz6LLMUsUl6PueE49ir4Ka6CzLymOAZDxpFsTDc= +github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls= +github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc= +github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tidwall/pretty v1.0.1 h1:WE4RBSZ1x6McVVC8S/Md+Qse8YUv6HRObAx6ke00NY8= +github.com/tidwall/pretty v1.0.1/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tidwall/sjson v1.1.1 h1:7h1vk049Jnd5EH9NyzNiEuwYW4b5qgreBbqRC19AS3U= +github.com/tidwall/sjson v1.1.1/go.mod h1:yvVuSnpEQv5cYIrO+AT6kw4QVfd5SDZoGIS7/5+fZFs= github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197 h1:gYTNnAW6azuB3BbA6QYWO/H4F2ABSOjjw3Z03tlXd2c= github.com/zyedidia/clipboard v0.0.0-20190823154308-241f98e9b197/go.mod h1:WDk3p8GiZV9+xFWlSo8qreeoLhW6Ik692rqXk+cNeRY= +github.com/zyedidia/clipboard v0.0.0-20200421031010-7c45b8673834 h1:0nOfq3JwYRiY3+nwfWVQYEaXDmGCQgj3RKoqTifLzP4= +github.com/zyedidia/clipboard v0.0.0-20200421031010-7c45b8673834/go.mod h1:zykFnZUXX0ErxqvYLUFEq7QDJKId8rmh2FgD0/Y8cjA= github.com/zyedidia/poller v1.0.1/go.mod h1:vZXJOHGDcuK08GXhF6IAY0ZFd2WcgOR5DOTp84Uk5eE= -go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= -go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.4 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg= +go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/image v0.0.0-20200119044424-58c23975cae1 h1:5h3ngYt7+vXCDZCup/HkCQgW5XwmSvR/nA2JmJ0RErg= -golang.org/x/image v0.0.0-20200119044424-58c23975cae1/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200430140353-33d19683fad8 h1:6WW6V3x1P/jokJBpRQYUJnMHRP6isStQwCozxnU7XQw= +golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200505041828-1ed23360d12c h1:zJ0mtu4jCalhKg6Oaukv6iIkb+cOvDrajDH9DH46Q4M= +golang.org/x/net v0.0.0-20200505041828-1ed23360d12c/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/sys v0.0.0-20181128092732-4ed8d59d0b35/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 h1:5B6i6EAiSYyejWfvc5Rc9BbI3rzIsrrXfAQBWnYfn+w= +golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -73,11 +89,15 @@ gopkg.in/toast.v1 v1.0.0-20180812000517-0a84660828b2/go.mod h1:s1Sn2yZos05Qfs7NK gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -maunium.net/go/mautrix v0.2.0-beta.3 h1:pm5MQszvzYaLyCEGjyUau4DvzrOw5dT45UAvDLz5zBo= -maunium.net/go/mautrix v0.2.0-beta.3/go.mod h1:WeTUYKrM3/4LZK2bXQ9NRIXnRWKsa+6+OA1gw0nf5G8= -maunium.net/go/mautrix v0.2.0-beta.4 h1:L7Jpc+8GGc+Qo0DdamACEeU1Ci9G1mergJpsTTgDOUA= -maunium.net/go/mautrix v0.2.0-beta.4/go.mod h1:WeTUYKrM3/4LZK2bXQ9NRIXnRWKsa+6+OA1gw0nf5G8= +maunium.net/go/mautrix v0.3.0 h1:Ij8O3JY5zL/8TqXYSYm0YGe2RFO3HgG/BAfdy9CFFo8= +maunium.net/go/mautrix v0.3.0/go.mod h1:SkGZzch8CvU2qKtNpYxtzZ0sQxfVEJ3IsVVLSUBUx9Y= +maunium.net/go/mautrix v0.3.1 h1:zDhN4PYdWavbssA+9JVoCsUmu/u0LtdHeE647oh3W8c= +maunium.net/go/mautrix v0.3.1/go.mod h1:SkGZzch8CvU2qKtNpYxtzZ0sQxfVEJ3IsVVLSUBUx9Y= maunium.net/go/mauview v0.1.0 h1:x2WdkKI2zdriJuPAB0CKlwmnHGE7W9xfM5z6RgG+IIg= maunium.net/go/mauview v0.1.0/go.mod h1:og9WbzmWe9SNYNyOFlCv8qa9zMcOvG2nzRJ5vYyud9U= +maunium.net/go/mauview v0.1.1 h1:wfTXyPx3LGAGpTskh+UbBv/QItUWnEpaneHmywoYnfY= +maunium.net/go/mauview v0.1.1/go.mod h1:3QBUiuLct9moP1LgDhCGIg0Ovxn38Bd2sGndnUOuj4o= maunium.net/go/tcell v0.1.0 h1:XzsEoGCvOw5nac+tlkSLzQcliLYTN4PrtA7ar2ptjSM= maunium.net/go/tcell v0.1.0/go.mod h1:Ru7KmI5AU7xHUx6hGltgJvknrS+8jlGGMKK15pZuc9k= +maunium.net/go/tcell v0.2.0 h1:1Q0kN3wCOGAIGu1r3QHADsjSUOPDylKREvCv3EzJpVg= +maunium.net/go/tcell v0.2.0/go.mod h1:9Apcb3lNNS6C6lCqKT9UFp7BTRzHXfWE+/tgufsAMho= @@ -38,12 +38,12 @@ type Gomuks struct { // NewGomuks creates a new Gomuks instance with everything initialized, // but does not start it. -func NewGomuks(uiProvider ifc.UIProvider, configDir, cacheDir, downloadDir string) *Gomuks { +func NewGomuks(uiProvider ifc.UIProvider, configDir, dataDir, cacheDir, downloadDir string) *Gomuks { gmx := &Gomuks{ stop: make(chan bool, 1), } - gmx.config = config.NewConfig(configDir, cacheDir, downloadDir) + gmx.config = config.NewConfig(configDir, dataDir, cacheDir, downloadDir) gmx.ui = uiProvider(gmx) gmx.matrix = matrix.NewContainer(gmx) diff --git a/interface/matrix.go b/interface/matrix.go index 7895957..f4f46ef 100644 --- a/interface/matrix.go +++ b/interface/matrix.go @@ -18,6 +18,7 @@ package ifc import ( "maunium.net/go/mautrix" + "maunium.net/go/mautrix/crypto/attachment" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" @@ -59,8 +60,8 @@ type MatrixContainer interface { GetRoom(roomID id.RoomID) *rooms.Room GetOrCreateRoom(roomID id.RoomID) *rooms.Room - Download(uri id.ContentURI) ([]byte, error) - DownloadToDisk(uri id.ContentURI, target string) (string, error) + Download(uri id.ContentURI, file *attachment.EncryptedFile) ([]byte, error) + DownloadToDisk(uri id.ContentURI, file *attachment.EncryptedFile, target string) (string, error) GetDownloadURL(uri id.ContentURI) string GetCachePath(uri id.ContentURI) string } @@ -48,24 +48,32 @@ func main() { debug.Initialize() defer debug.Recover() - configDir, err := UserConfigDir() + var configDir, dataDir, cacheDir, downloadDir string + var err error + + configDir, err = UserConfigDir() if err != nil { - fmt.Fprintln(os.Stderr, "Failed to get config directory:", err) + _, _ = fmt.Fprintln(os.Stderr, "Failed to get config directory:", err) os.Exit(3) } - cacheDir, err := UserCacheDir() + dataDir, err = UserDataDir() if err != nil { - fmt.Fprintln(os.Stderr, "Failed to get cache directory:", err) + _, _ = fmt.Fprintln(os.Stderr, "Failed to get data directory:", err) os.Exit(3) } - downloadDir, err := UserDownloadDir() + cacheDir, err = UserCacheDir() if err != nil { - fmt.Fprintln(os.Stderr, "Failed to get download directory:", err) + _, _ = fmt.Fprintln(os.Stderr, "Failed to get cache directory:", err) + os.Exit(3) + } + downloadDir, err = UserDownloadDir() + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, "Failed to get download directory:", err) os.Exit(3) } - gmx := NewGomuks(MainUIProvider, configDir, cacheDir, downloadDir) + gmx := NewGomuks(MainUIProvider, configDir, dataDir, cacheDir, downloadDir) gmx.Start() // We use os.Exit() everywhere, so exiting by returning from Start() shouldn't happen. @@ -74,43 +82,63 @@ func main() { os.Exit(2) } +func getRootDir(subdir string) string { + rootDir := os.Getenv("GOMUKS_ROOT") + if rootDir == "" { + return "" + } + return filepath.Join(rootDir, subdir) +} + func UserCacheDir() (dir string, err error) { dir = os.Getenv("GOMUKS_CACHE_HOME") if dir == "" { + dir = getRootDir("cache") + } + if dir == "" { dir, err = os.UserCacheDir() dir = filepath.Join(dir, "gomuks") } return } -func UserDownloadDir() (dir string, err error) { - dir = os.Getenv("HOME") - return filepath.Join(dir, "Downloads"), nil -} - -func UserConfigDir() (dir string, err error) { - dir = os.Getenv("GOMUKS_CONFIG_HOME") +func UserDataDir() (dir string, err error) { + dir = os.Getenv("GOMUKS_DATA_HOME") if dir != "" { return } - if runtime.GOOS == "windows" { - dir = os.Getenv("AppData") - if dir == "" { - err = errors.New("%AppData% is not defined") - } - } else { - dir = os.Getenv("XDG_CONFIG_HOME") + if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { + return UserConfigDir() + } + dir = os.Getenv("XDG_DATA_HOME") + if dir == "" { + dir = getRootDir("data") + } + if dir == "" { + dir = os.Getenv("HOME") if dir == "" { - dir = os.Getenv("HOME") - if dir == "" { - err = errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined") - } else if runtime.GOOS == "darwin" { - dir = filepath.Join(dir, "Library", "Application Support") - } else { - dir = filepath.Join(dir, ".config") - } + return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined") } + dir = filepath.Join(dir, ".local", "share") } dir = filepath.Join(dir, "gomuks") return } + +func UserDownloadDir() (dir string, err error) { + dir, err = os.UserHomeDir() + dir = filepath.Join(dir, "Downloads") + return +} + +func UserConfigDir() (dir string, err error) { + dir = os.Getenv("GOMUKS_CONFIG_HOME") + if dir == "" { + dir = getRootDir("cache") + } + if dir == "" { + dir, err = os.UserConfigDir() + dir = filepath.Join(dir, "gomuks") + } + return +} diff --git a/matrix/crypto.go b/matrix/crypto.go new file mode 100644 index 0000000..8eab355 --- /dev/null +++ b/matrix/crypto.go @@ -0,0 +1,62 @@ +// gomuks - A terminal Matrix client written in Go. +// Copyright (C) 2020 Tulir Asokan +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +// +build cgo + +package matrix + +import ( + "path/filepath" + + "maunium.net/go/mautrix/crypto" + + "maunium.net/go/gomuks/debug" +) + +type cryptoLogger struct{} + +func (c cryptoLogger) Error(message string, args ...interface{}) { + debug.Printf("[Crypto/Error] "+message, args...) +} + +func (c cryptoLogger) Warn(message string, args ...interface{}) { + debug.Printf("[Crypto/Warn] "+message, args...) +} + +func (c cryptoLogger) Debug(message string, args ...interface{}) { + debug.Printf("[Crypto/Debug] "+message, args...) +} + +func (c cryptoLogger) Trace(message string, args ...interface{}) { + debug.Printf("[Crypto/Trace] "+message, args...) +} + +func isBadEncryptError(err error) bool { + return err != crypto.SessionExpired && err != crypto.SessionNotShared && err != crypto.NoGroupSession +} + +func (c *Container) initCrypto() error { + cryptoStore, err := crypto.NewGobStore(filepath.Join(c.config.DataDir, "crypto.gob")) + if err != nil { + return err + } + c.crypto = crypto.NewOlmMachine(c.client, cryptoLogger{}, cryptoStore, c.config.Rooms) + err = c.crypto.Load() + if err != nil { + return err + } + return nil +} diff --git a/matrix/matrix.go b/matrix/matrix.go index d0fd2f4..30e28fb 100644 --- a/matrix/matrix.go +++ b/matrix/matrix.go @@ -17,7 +17,6 @@ package matrix import ( - "bytes" "context" "crypto/tls" "encoding/gob" @@ -37,6 +36,7 @@ import ( "github.com/pkg/errors" "maunium.net/go/mautrix" + "maunium.net/go/mautrix/crypto/attachment" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/format" "maunium.net/go/mautrix/id" @@ -55,6 +55,7 @@ import ( // It is used for all Matrix calls from the UI and Matrix event handlers. type Container struct { client *mautrix.Client + crypto CryptoInterface syncer *GomuksSyncer gmx ifc.Gomuks ui ifc.GomuksUI @@ -88,6 +89,16 @@ func (log mxLogger) Debugfln(message string, args ...interface{}) { debug.Printf("[Matrix] "+message, args...) } +type CryptoInterface interface { + Load() error + FlushStore() error + ProcessSyncResponse(resp *mautrix.RespSync, since string) + HandleMemberEvent(*event.Event) + DecryptMegolmEvent(*event.Event) (*event.Event, error) + EncryptMegolmEvent(id.RoomID, event.Type, event.Content) (*event.EncryptedEventContent, error) + ShareGroupSession(id.RoomID, []id.UserID) error +} + // InitClient initializes the mautrix client and connects to the homeserver specified in the config. func (c *Container) InitClient() error { if len(c.config.HS) == 0 { @@ -97,6 +108,7 @@ func (c *Container) InitClient() error { if c.client != nil { c.Stop() c.client = nil + c.crypto = nil } var mxid id.UserID @@ -112,6 +124,12 @@ func (c *Container) InitClient() error { return err } c.client.Logger = mxLogger{} + c.client.DeviceID = c.config.DeviceID + + err = c.initCrypto() + if err != nil { + return err + } if c.history == nil { c.history, err = NewHistoryManager(c.config.HistoryPath) @@ -159,7 +177,9 @@ func (c *Container) PasswordLogin(user, password string) error { func (c *Container) finishLogin(resp *mautrix.RespLogin) { c.client.SetCredentials(resp.UserID, resp.AccessToken) + c.client.DeviceID = resp.DeviceID c.config.UserID = resp.UserID + c.config.DeviceID = resp.DeviceID c.config.AccessToken = resp.AccessToken c.config.Save() @@ -247,9 +267,10 @@ func (c *Container) Login(user, password string) error { // Logout revokes the access token, stops the syncer and calls the OnLogout() method of the UI. func (c *Container) Logout() { c.client.Logout() - c.config.DeleteSession() c.Stop() + c.config.DeleteSession() c.client = nil + c.crypto = nil c.ui.OnLogout() } @@ -265,6 +286,13 @@ func (c *Container) Stop() { debug.Print("Error closing history manager:", err) } c.history = nil + if c.crypto != nil { + debug.Print("Flushing crypto store") + err = c.crypto.FlushStore() + if err != nil { + debug.Print("Error flushing crypto store:", err) + } + } } } @@ -315,8 +343,20 @@ func (c *Container) OnLogin() { debug.Print("Initializing syncer") c.syncer = NewGomuksSyncer(c.config.Rooms) + if c.crypto != nil { + c.syncer.OnSync(c.crypto.ProcessSyncResponse) + c.syncer.OnEventType(event.StateMember, func(source EventSource, evt *event.Event) { + // Don't spam the crypto module with member events of an initial sync + // TODO invalidate all group sessions when clearing cache? + if c.config.AuthCache.InitialSyncDone { + c.crypto.HandleMemberEvent(evt) + } + }) + c.syncer.OnEventType(event.EventEncrypted, c.HandleEncrypted) + } else { + c.syncer.OnEventType(event.EventEncrypted, c.HandleMessage) + } c.syncer.OnEventType(event.EventMessage, c.HandleMessage) - c.syncer.OnEventType(event.EventEncrypted, c.HandleMessage) c.syncer.OnEventType(event.EventSticker, c.HandleMessage) c.syncer.OnEventType(event.EventReaction, c.HandleMessage) c.syncer.OnEventType(event.EventRedaction, c.HandleRedaction) @@ -516,6 +556,17 @@ func (c *Container) HandleReaction(room *rooms.Room, reactsTo id.EventID, reactE } } +func (c *Container) HandleEncrypted(source EventSource, mxEvent *event.Event) { + evt, err := c.crypto.DecryptMegolmEvent(mxEvent) + if err != nil { + debug.Print("Failed to decrypt event:", err) + // TODO add decryption failed message instead of passing through directly + c.HandleMessage(source, mxEvent) + return + } + c.HandleMessage(source, evt) +} + // HandleMessage is the event handler for the m.room.message timeline event. func (c *Container) HandleMessage(source EventSource, mxEvent *event.Event) { room := c.GetOrCreateRoom(mxEvent.RoomID) @@ -526,13 +577,16 @@ func (c *Container) HandleMessage(source EventSource, mxEvent *event.Event) { return } - rel := mxEvent.Content.AsMessage().GetRelatesTo() - if editID := rel.GetReplaceID(); len(editID) > 0 { - c.HandleEdit(room, editID, muksevt.Wrap(mxEvent)) - return - } else if reactionID := rel.GetAnnotationID(); mxEvent.Type == event.EventReaction && len(reactionID) > 0 { - c.HandleReaction(room, reactionID, muksevt.Wrap(mxEvent)) - return + relatable, ok := mxEvent.Content.Parsed.(event.Relatable) + if ok { + rel := relatable.GetRelatesTo() + if editID := rel.GetReplaceID(); len(editID) > 0 { + c.HandleEdit(room, editID, muksevt.Wrap(mxEvent)) + return + } else if reactionID := rel.GetAnnotationID(); mxEvent.Type == event.EventReaction && len(reactionID) > 0 { + c.HandleReaction(room, reactionID, muksevt.Wrap(mxEvent)) + return + } } events, err := c.history.Append(room, []*event.Event{mxEvent}) @@ -824,8 +878,28 @@ func (c *Container) Redact(roomID id.RoomID, eventID id.EventID, reason string) func (c *Container) SendEvent(evt *muksevt.Event) (id.EventID, error) { defer debug.Recover() - c.client.UserTyping(evt.RoomID, false, 0) + _, _ = c.client.UserTyping(evt.RoomID, false, 0) c.typing = 0 + room := c.GetRoom(evt.RoomID) + if room != nil && room.Encrypted && c.crypto != nil && evt.Type != event.EventReaction { + encrypted, err := c.crypto.EncryptMegolmEvent(evt.RoomID, evt.Type, evt.Content) + if err != nil { + if isBadEncryptError(err) { + return "", err + } + debug.Print("Got", err, "while trying to encrypt message, sharing group session and trying again...") + err = c.crypto.ShareGroupSession(room.ID, room.GetMemberList()) + if err != nil { + return "", err + } + encrypted, err = c.crypto.EncryptMegolmEvent(evt.RoomID, evt.Type, evt.Content) + if err != nil { + return "", err + } + } + evt.Type = event.EventEncrypted + evt.Content = event.Content{Parsed: encrypted} + } resp, err := c.client.SendMessageEvent(evt.RoomID, evt.Type, &evt.Content, mautrix.ReqSendEvent{TransactionID: evt.Unsigned.TransactionID}) if err != nil { return "", err @@ -923,11 +997,21 @@ func (c *Container) GetHistory(room *rooms.Room, limit int) ([]*muksevt.Event, e return nil, err } debug.Printf("Loaded %d events for %s from server from %s to %s", len(resp.Chunk), room.ID, resp.Start, resp.End) - for _, evt := range resp.Chunk { + for i, evt := range resp.Chunk { err := evt.Content.ParseRaw(evt.Type) if err != nil { debug.Printf("Failed to unmarshal content of event %s (type %s) by %s in %s: %v\n%s", evt.ID, evt.Type.Repr(), evt.Sender, evt.RoomID, err, string(evt.Content.VeryRaw)) } + + if c.crypto != nil && evt.Type == event.EventEncrypted { + decrypted, err := c.crypto.DecryptMegolmEvent(evt) + if err != nil { + debug.Print("Failed to decrypt event:", err) + // TODO add decryption failed message instead of passing through directly + } else { + resp.Chunk[i] = decrypted + } + } } for _, evt := range resp.State { room.UpdateState(evt) @@ -991,7 +1075,7 @@ func cp(src, dst string) error { return out.Close() } -func (c *Container) DownloadToDisk(uri id.ContentURI, target string) (fullPath string, err error) { +func (c *Container) DownloadToDisk(uri id.ContentURI, file *attachment.EncryptedFile, target string) (fullPath string, err error) { cachePath := c.GetCachePath(uri) if target == "" { fullPath = cachePath @@ -1002,21 +1086,27 @@ func (c *Container) DownloadToDisk(uri id.ContentURI, target string) (fullPath s } if _, statErr := os.Stat(cachePath); os.IsNotExist(statErr) { - var file *os.File - file, err = os.OpenFile(cachePath, os.O_CREATE|os.O_WRONLY, 0600) + var body io.ReadCloser + body, err = c.client.Download(uri) if err != nil { return } - defer file.Close() - var body io.ReadCloser - body, err = c.client.Download(uri) + var data []byte + data, err = ioutil.ReadAll(body) + _ = body.Close() if err != nil { return } - defer body.Close() - _, err = io.Copy(file, body) + if file != nil { + data, err = file.Decrypt(data) + if err != nil { + return + } + } + + err = ioutil.WriteFile(cachePath, data, 0600) if err != nil { return } @@ -1036,7 +1126,7 @@ func (c *Container) DownloadToDisk(uri id.ContentURI, target string) (fullPath s // Download fetches the given Matrix content (mxc) URL and returns the data, homeserver, file ID and potential errors. // // The file will be either read from the media cache (if found) or downloaded from the server. -func (c *Container) Download(uri id.ContentURI) (data []byte, err error) { +func (c *Container) Download(uri id.ContentURI, file *attachment.EncryptedFile) (data []byte, err error) { cacheFile := c.GetCachePath(uri) var info os.FileInfo if info, err = os.Stat(cacheFile); err == nil && !info.IsDir() { @@ -1046,7 +1136,7 @@ func (c *Container) Download(uri id.ContentURI) (data []byte, err error) { } } - data, err = c.download(uri, cacheFile) + data, err = c.download(uri, file, cacheFile) return } @@ -1054,21 +1144,25 @@ func (c *Container) GetDownloadURL(uri id.ContentURI) string { return c.client.GetDownloadURL(uri) } -func (c *Container) download(uri id.ContentURI, cacheFile string) (data []byte, err error) { +func (c *Container) download(uri id.ContentURI, file *attachment.EncryptedFile, cacheFile string) (data []byte, err error) { var body io.ReadCloser body, err = c.client.Download(uri) if err != nil { return } - defer body.Close() - var buf bytes.Buffer - _, err = io.Copy(&buf, body) + data, err = ioutil.ReadAll(body) + _ = body.Close() if err != nil { return } - data = buf.Bytes() + if file != nil { + data, err = file.Decrypt(data) + if err != nil { + return + } + } err = ioutil.WriteFile(cacheFile, data, 0600) return diff --git a/matrix/nocrypto.go b/matrix/nocrypto.go new file mode 100644 index 0000000..979afda --- /dev/null +++ b/matrix/nocrypto.go @@ -0,0 +1,13 @@ +// This contains no-op stubs of the methods in crypto.go for non-cgo builds with crypto disabled. + +// +build !cgo + +package matrix + +func isBadEncryptError(err error) bool { + return false +} + +func (c *Container) initCrypto() error { + return nil +} diff --git a/matrix/rooms/room.go b/matrix/rooms/room.go index 0238cfb..d5d1d8f 100644 --- a/matrix/rooms/room.go +++ b/matrix/rooms/room.go @@ -412,7 +412,7 @@ func (room *Room) UpdateState(evt *event.Event) { case *event.TopicEventContent: room.topicCache = content.Topic case *event.EncryptionEventContent: - if content.Algorithm == event.AlgorithmMegolmV1 { + if content.Algorithm == id.AlgorithmMegolmV1 { room.Encrypted = true } } @@ -650,6 +650,17 @@ func (room *Room) GetMembers() map[id.UserID]*Member { return room.memberCache } +func (room *Room) GetMemberList() []id.UserID { + members := room.GetMembers() + memberList := make([]id.UserID, len(members)) + index := 0 + for userID, _ := range members { + memberList[index] = userID + index++ + } + return memberList +} + // GetMember returns the member with the given MXID. // If the member doesn't exist, nil is returned. func (room *Room) GetMember(userID id.UserID) *Member { diff --git a/matrix/rooms/roomcache.go b/matrix/rooms/roomcache.go index ffdcad1..067cbb6 100644 --- a/matrix/rooms/roomcache.go +++ b/matrix/rooms/roomcache.go @@ -27,6 +27,7 @@ import ( sync "github.com/sasha-s/go-deadlock" "maunium.net/go/gomuks/debug" + "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) @@ -67,6 +68,29 @@ func (cache *RoomCache) EnableUnloading() { cache.noUnload = false } +func (cache *RoomCache) IsEncrypted(roomID id.RoomID) bool { + room := cache.Get(roomID) + return room != nil && room.Encrypted +} + +func (cache *RoomCache) FindSharedRooms(userID id.UserID) (shared []id.RoomID) { + // FIXME this disables unloading so TouchNode wouldn't try to double-lock + cache.DisableUnloading() + cache.Lock() + for _, room := range cache.Map { + if !room.Encrypted { + continue + } + member, ok := room.GetMembers()[userID] + if ok && member.Membership == event.MembershipJoin { + shared = append(shared, room.ID) + } + } + cache.Unlock() + cache.EnableUnloading() + return +} + func (cache *RoomCache) LoadList() error { cache.Lock() defer cache.Unlock() diff --git a/matrix/sync.go b/matrix/sync.go index 85de68c..2136088 100644 --- a/matrix/sync.go +++ b/matrix/sync.go @@ -83,9 +83,11 @@ func (es EventSource) String() string { } type EventHandler func(source EventSource, event *event.Event) +type SyncHandler func(resp *mautrix.RespSync, since string) type GomuksSyncer struct { rooms *rooms.RoomCache + globalListeners []SyncHandler listeners map[event.Type][]EventHandler // event type to listeners array FirstSyncDone bool InitDoneCallback func() @@ -96,10 +98,11 @@ type GomuksSyncer struct { // NewGomuksSyncer returns an instantiated GomuksSyncer func NewGomuksSyncer(rooms *rooms.RoomCache) *GomuksSyncer { return &GomuksSyncer{ - rooms: rooms, - listeners: make(map[event.Type][]EventHandler), - FirstSyncDone: false, - Progress: StubSyncingModal{}, + rooms: rooms, + globalListeners: []SyncHandler{}, + listeners: make(map[event.Type][]EventHandler), + FirstSyncDone: false, + Progress: StubSyncingModal{}, } } @@ -109,23 +112,26 @@ func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err s.rooms.DisableUnloading() } debug.Print("Received sync response") + s.Progress.SetMessage("Processing sync response") steps := len(res.Rooms.Join) + len(res.Rooms.Invite) + len(res.Rooms.Leave) - s.Progress.SetSteps(steps + 2) - s.Progress.SetMessage("Processing global events") - s.processSyncEvents(nil, res.Presence.Events, EventSourcePresence) - s.Progress.Step() - s.processSyncEvents(nil, res.AccountData.Events, EventSourceAccountData) - s.Progress.Step() + s.Progress.SetSteps(steps + 2 + len(s.globalListeners)) wait := &sync.WaitGroup{} - - wait.Add(steps) callback := func() { wait.Done() s.Progress.Step() } + wait.Add(len(s.globalListeners)) + s.notifyGlobalListeners(res, since, callback) + wait.Wait() + + s.processSyncEvents(nil, res.Presence.Events, EventSourcePresence) + s.Progress.Step() + s.processSyncEvents(nil, res.AccountData.Events, EventSourceAccountData) + s.Progress.Step() + + wait.Add(steps) - s.Progress.SetMessage("Processing room events") for roomID, roomData := range res.Rooms.Join { go s.processJoinedRoom(roomID, roomData, callback) } @@ -152,6 +158,15 @@ func (s *GomuksSyncer) ProcessResponse(res *mautrix.RespSync, since string) (err return } +func (s *GomuksSyncer) notifyGlobalListeners(res *mautrix.RespSync, since string, callback func()) { + for _, listener := range s.globalListeners { + go func(listener SyncHandler) { + listener(res, since) + callback() + }(listener) + } +} + func (s *GomuksSyncer) processJoinedRoom(roomID id.RoomID, roomData mautrix.SyncJoinedRoom, callback func()) { defer debug.Recover() room := s.rooms.GetOrCreate(roomID) @@ -239,6 +254,10 @@ func (s *GomuksSyncer) OnEventType(eventType event.Type, callback EventHandler) s.listeners[eventType] = append(s.listeners[eventType], callback) } +func (s *GomuksSyncer) OnSync(callback SyncHandler) { + s.globalListeners = append(s.globalListeners, callback) +} + func (s *GomuksSyncer) notifyListeners(source EventSource, evt *event.Event) { listeners, exists := s.listeners[evt.Type] if !exists { @@ -269,6 +288,7 @@ func (s *GomuksSyncer) GetFilterJSON(_ id.UserID) *mautrix.Filter { event.StateCanonicalAlias, event.StatePowerLevels, event.StateTombstone, + event.StateEncryption, }, }, Timeline: mautrix.FilterPart{ diff --git a/ui/messages/filemessage.go b/ui/messages/filemessage.go index 7422146..3d5e554 100644 --- a/ui/messages/filemessage.go +++ b/ui/messages/filemessage.go @@ -22,7 +22,7 @@ import ( "image" "image/color" - "maunium.net/go/gomuks/matrix/muksevt" + "maunium.net/go/mautrix/crypto/attachment" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" "maunium.net/go/mauview" @@ -32,14 +32,19 @@ import ( "maunium.net/go/gomuks/debug" "maunium.net/go/gomuks/interface" "maunium.net/go/gomuks/lib/ansimage" + "maunium.net/go/gomuks/matrix/muksevt" "maunium.net/go/gomuks/ui/messages/tstring" ) type FileMessage struct { - Type event.MessageType - Body string - URL id.ContentURI - Thumbnail id.ContentURI + Type event.MessageType + Body string + + URL id.ContentURI + File *attachment.EncryptedFile + Thumbnail id.ContentURI + ThumbnailFile *attachment.EncryptedFile + imageData []byte buffer []tstring.TString @@ -49,14 +54,23 @@ type FileMessage struct { // NewFileMessage creates a new FileMessage object with the provided values and the default state. func NewFileMessage(matrix ifc.MatrixContainer, evt *muksevt.Event, displayname string) *UIMessage { content := evt.Content.AsMessage() - url, _ := content.URL.Parse() - thumbnail, _ := content.GetInfo().ThumbnailURL.Parse() + var file, thumbnailFile *attachment.EncryptedFile + if content.File != nil { + file = &content.File.EncryptedFile + content.URL = content.File.URL + } + if content.GetInfo().ThumbnailFile != nil { + thumbnailFile = &content.Info.ThumbnailFile.EncryptedFile + content.Info.ThumbnailURL = content.Info.ThumbnailFile.URL + } return newUIMessage(evt, displayname, &FileMessage{ - Type: content.MsgType, - Body: content.Body, - URL: url, - Thumbnail: thumbnail, - matrix: matrix, + Type: content.MsgType, + Body: content.Body, + URL: content.URL.ParseOrIgnore(), + File: file, + Thumbnail: content.GetInfo().ThumbnailURL.ParseOrIgnore(), + ThumbnailFile: thumbnailFile, + matrix: matrix, }) } @@ -96,17 +110,20 @@ func (msg *FileMessage) String() string { } func (msg *FileMessage) DownloadPreview() { - url := msg.Thumbnail - if url.IsEmpty() { - if msg.Type == event.MsgImage && !msg.URL.IsEmpty() { - msg.Thumbnail = msg.URL - url = msg.Thumbnail - } else { - return - } + var url id.ContentURI + var file *attachment.EncryptedFile + if !msg.Thumbnail.IsEmpty() { + url = msg.Thumbnail + file = msg.ThumbnailFile + } else if msg.Type == event.MsgImage && !msg.URL.IsEmpty() { + msg.Thumbnail = msg.URL + url = msg.URL + file = msg.File + } else { + return } debug.Print("Loading file:", url) - data, err := msg.matrix.Download(url) + data, err := msg.matrix.Download(url, file) if err != nil { debug.Printf("Failed to download file %s: %v", url, err) return diff --git a/ui/messages/parser.go b/ui/messages/parser.go index 9e44647..4a214f1 100644 --- a/ui/messages/parser.go +++ b/ui/messages/parser.go @@ -20,13 +20,13 @@ import ( "fmt" "strings" - "maunium.net/go/gomuks/debug" - "maunium.net/go/gomuks/matrix/muksevt" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" "maunium.net/go/tcell" + "maunium.net/go/gomuks/debug" "maunium.net/go/gomuks/interface" + "maunium.net/go/gomuks/matrix/muksevt" "maunium.net/go/gomuks/matrix/rooms" "maunium.net/go/gomuks/ui/messages/html" "maunium.net/go/gomuks/ui/messages/tstring" @@ -82,7 +82,7 @@ func directParseEvent(matrix ifc.MatrixContainer, room *rooms.Room, evt *muksevt } return ParseMessage(matrix, room, evt, displayname) case *event.EncryptedEventContent: - return NewExpandedTextMessage(evt, displayname, tstring.NewStyleTString("Encrypted messages are not yet supported", tcell.StyleDefault.Italic(true))) + return NewExpandedTextMessage(evt, displayname, tstring.NewStyleTString("Decryption failed or gomuks not built with encryption support", tcell.StyleDefault.Italic(true))) case *event.TopicEventContent, *event.RoomNameEventContent, *event.CanonicalAliasEventContent: return ParseStateEvent(evt, displayname) case *event.MemberEventContent: diff --git a/ui/room-view.go b/ui/room-view.go index 5792626..09e1965 100644 --- a/ui/room-view.go +++ b/ui/room-view.go @@ -26,6 +26,7 @@ import ( "github.com/kyokomi/emoji" "github.com/mattn/go-runewidth" + "maunium.net/go/mautrix/crypto/attachment" "maunium.net/go/mauview" "maunium.net/go/tcell" @@ -122,6 +123,10 @@ func NewRoomView(parent *MainView, room *rooms.Room) *RoomView { SetPressKeyUpAtStartFunc(view.EditPrevious). SetPressKeyDownAtEndFunc(view.EditNext) + if room.Encrypted { + view.input.SetPlaceholder("Send an encrypted message...") + } + view.topic. SetTextColor(tcell.ColorWhite). SetBackgroundColor(tcell.ColorDarkGreen) @@ -202,7 +207,7 @@ func (view *RoomView) OnSelect(message *messages.UIMessage) { } else if view.selectReason == SelectDownload { path = msg.Body } - go view.Download(msg.URL, path, view.selectReason == SelectOpen) + go view.Download(msg.URL, msg.File, path, view.selectReason == SelectOpen) } } view.selecting = false @@ -624,8 +629,8 @@ func (view *RoomView) InputSubmit(text string) { view.SetInputText("") } -func (view *RoomView) Download(url id.ContentURI, filename string, openFile bool) { - path, err := view.parent.matrix.DownloadToDisk(url, filename) +func (view *RoomView) Download(url id.ContentURI, file *attachment.EncryptedFile, filename string, openFile bool) { + path, err := view.parent.matrix.DownloadToDisk(url, file, filename) if err != nil { view.AddServiceMessage(fmt.Sprintf("Failed to download media: %v", err)) view.parent.parent.Render() |