main.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. _ "embed"
  19. "net/http"
  20. "os"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "google.golang.org/protobuf/proto"
  26. "go.mau.fi/whatsmeow"
  27. waProto "go.mau.fi/whatsmeow/binary/proto"
  28. "go.mau.fi/whatsmeow/store"
  29. "go.mau.fi/whatsmeow/store/sqlstore"
  30. "go.mau.fi/whatsmeow/types"
  31. "maunium.net/go/mautrix"
  32. "maunium.net/go/mautrix/bridge"
  33. "maunium.net/go/mautrix/bridge/commands"
  34. "maunium.net/go/mautrix/bridge/status"
  35. "maunium.net/go/mautrix/event"
  36. "maunium.net/go/mautrix/id"
  37. "maunium.net/go/mautrix/util/configupgrade"
  38. "maunium.net/go/mautrix-whatsapp/config"
  39. "maunium.net/go/mautrix-whatsapp/database"
  40. )
  41. // Information to find out exactly which commit the bridge was built from.
  42. // These are filled at build time with the -X linker flag.
  43. var (
  44. Tag = "unknown"
  45. Commit = "unknown"
  46. BuildTime = "unknown"
  47. )
  48. //go:embed example-config.yaml
  49. var ExampleConfig string
  50. type WABridge struct {
  51. bridge.Bridge
  52. Config *config.Config
  53. DB *database.Database
  54. Provisioning *ProvisioningAPI
  55. Formatter *Formatter
  56. Metrics *MetricsHandler
  57. WAContainer *sqlstore.Container
  58. WAVersion string
  59. usersByMXID map[id.UserID]*User
  60. usersByUsername map[string]*User
  61. usersLock sync.Mutex
  62. spaceRooms map[id.RoomID]*User
  63. spaceRoomsLock sync.Mutex
  64. managementRooms map[id.RoomID]*User
  65. managementRoomsLock sync.Mutex
  66. portalsByMXID map[id.RoomID]*Portal
  67. portalsByJID map[database.PortalKey]*Portal
  68. portalsLock sync.Mutex
  69. puppets map[types.JID]*Puppet
  70. puppetsByCustomMXID map[id.UserID]*Puppet
  71. puppetsLock sync.Mutex
  72. }
  73. func (br *WABridge) Init() {
  74. br.CommandProcessor = commands.NewProcessor(&br.Bridge)
  75. br.RegisterCommands()
  76. // TODO this is a weird place for this
  77. br.EventProcessor.On(event.EphemeralEventPresence, br.HandlePresence)
  78. br.EventProcessor.On(TypeMSC3381PollStart, br.MatrixHandler.HandleMessage)
  79. br.EventProcessor.On(TypeMSC3381PollResponse, br.MatrixHandler.HandleMessage)
  80. br.EventProcessor.On(TypeMSC3381V2PollResponse, br.MatrixHandler.HandleMessage)
  81. Segment.log = br.Log.Sub("Segment")
  82. Segment.key = br.Config.SegmentKey
  83. if Segment.IsEnabled() {
  84. Segment.log.Infoln("Segment metrics are enabled")
  85. }
  86. br.DB = database.New(br.Bridge.DB, br.Log.Sub("Database"))
  87. br.WAContainer = sqlstore.NewWithDB(br.DB.RawDB, br.DB.Dialect.String(), &waLogger{br.Log.Sub("Database").Sub("WhatsApp")})
  88. br.WAContainer.DatabaseErrorHandler = br.DB.HandleSignalStoreError
  89. ss := br.Config.Bridge.Provisioning.SharedSecret
  90. if len(ss) > 0 && ss != "disable" {
  91. br.Provisioning = &ProvisioningAPI{bridge: br}
  92. }
  93. br.Formatter = NewFormatter(br)
  94. br.Metrics = NewMetricsHandler(br.Config.Metrics.Listen, br.Log.Sub("Metrics"), br.DB)
  95. br.MatrixHandler.TrackEventDuration = br.Metrics.TrackMatrixEvent
  96. store.BaseClientPayload.UserAgent.OsVersion = proto.String(br.WAVersion)
  97. store.BaseClientPayload.UserAgent.OsBuildNumber = proto.String(br.WAVersion)
  98. store.DeviceProps.Os = proto.String(br.Config.WhatsApp.OSName)
  99. store.DeviceProps.RequireFullSync = proto.Bool(br.Config.Bridge.HistorySync.RequestFullSync)
  100. if fsc := br.Config.Bridge.HistorySync.FullSyncConfig; fsc.DaysLimit > 0 && fsc.SizeLimit > 0 && fsc.StorageQuota > 0 {
  101. store.DeviceProps.HistorySyncConfig = &waProto.DeviceProps_HistorySyncConfig{
  102. FullSyncDaysLimit: proto.Uint32(fsc.DaysLimit),
  103. FullSyncSizeMbLimit: proto.Uint32(fsc.SizeLimit),
  104. StorageQuotaMb: proto.Uint32(fsc.StorageQuota),
  105. }
  106. }
  107. versionParts := strings.Split(br.WAVersion, ".")
  108. if len(versionParts) > 2 {
  109. primary, _ := strconv.Atoi(versionParts[0])
  110. secondary, _ := strconv.Atoi(versionParts[1])
  111. tertiary, _ := strconv.Atoi(versionParts[2])
  112. store.DeviceProps.Version.Primary = proto.Uint32(uint32(primary))
  113. store.DeviceProps.Version.Secondary = proto.Uint32(uint32(secondary))
  114. store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(tertiary))
  115. }
  116. platformID, ok := waProto.DeviceProps_PlatformType_value[strings.ToUpper(br.Config.WhatsApp.BrowserName)]
  117. if ok {
  118. store.DeviceProps.PlatformType = waProto.DeviceProps_PlatformType(platformID).Enum()
  119. }
  120. }
  121. func (br *WABridge) Start() {
  122. err := br.WAContainer.Upgrade()
  123. if err != nil {
  124. br.Log.Fatalln("Failed to upgrade whatsmeow database: %v", err)
  125. os.Exit(15)
  126. }
  127. if br.Provisioning != nil {
  128. br.Log.Debugln("Initializing provisioning API")
  129. br.Provisioning.Init()
  130. }
  131. go br.CheckWhatsAppUpdate()
  132. go br.StartUsers()
  133. if br.Config.Metrics.Enabled {
  134. go br.Metrics.Start()
  135. }
  136. go br.Loop()
  137. }
  138. func (br *WABridge) CheckWhatsAppUpdate() {
  139. br.Log.Debugfln("Checking for WhatsApp web update")
  140. resp, err := whatsmeow.CheckUpdate(http.DefaultClient)
  141. if err != nil {
  142. br.Log.Warnfln("Failed to check for WhatsApp web update: %v", err)
  143. return
  144. }
  145. if store.GetWAVersion() == resp.ParsedVersion {
  146. br.Log.Debugfln("Bridge is using latest WhatsApp web protocol")
  147. } else if store.GetWAVersion().LessThan(resp.ParsedVersion) {
  148. if resp.IsBelowHard || resp.IsBroken {
  149. br.Log.Warnfln("Bridge is using outdated WhatsApp web protocol and probably doesn't work anymore (%s, latest is %s)", store.GetWAVersion(), resp.ParsedVersion)
  150. } else if resp.IsBelowSoft {
  151. br.Log.Infofln("Bridge is using outdated WhatsApp web protocol (%s, latest is %s)", store.GetWAVersion(), resp.ParsedVersion)
  152. } else {
  153. br.Log.Debugfln("Bridge is using outdated WhatsApp web protocol (%s, latest is %s)", store.GetWAVersion(), resp.ParsedVersion)
  154. }
  155. } else {
  156. br.Log.Debugfln("Bridge is using newer than latest WhatsApp web protocol")
  157. }
  158. }
  159. func (br *WABridge) Loop() {
  160. for {
  161. br.SleepAndDeleteUpcoming()
  162. time.Sleep(1 * time.Hour)
  163. br.WarnUsersAboutDisconnection()
  164. }
  165. }
  166. func (br *WABridge) WarnUsersAboutDisconnection() {
  167. br.usersLock.Lock()
  168. for _, user := range br.usersByUsername {
  169. if user.IsConnected() && !user.PhoneRecentlySeen(true) {
  170. go user.sendPhoneOfflineWarning()
  171. }
  172. }
  173. br.usersLock.Unlock()
  174. }
  175. func (br *WABridge) StartUsers() {
  176. br.Log.Debugln("Starting users")
  177. foundAnySessions := false
  178. for _, user := range br.GetAllUsers() {
  179. if !user.JID.IsEmpty() {
  180. foundAnySessions = true
  181. }
  182. go user.Connect()
  183. }
  184. if !foundAnySessions {
  185. br.SendGlobalBridgeState(status.BridgeState{StateEvent: status.StateUnconfigured}.Fill(nil))
  186. }
  187. br.Log.Debugln("Starting custom puppets")
  188. for _, loopuppet := range br.GetAllPuppetsWithCustomMXID() {
  189. go func(puppet *Puppet) {
  190. puppet.log.Debugln("Starting custom puppet", puppet.CustomMXID)
  191. err := puppet.StartCustomMXID(true)
  192. if err != nil {
  193. puppet.log.Errorln("Failed to start custom puppet:", err)
  194. }
  195. }(loopuppet)
  196. }
  197. }
  198. func (br *WABridge) Stop() {
  199. br.Metrics.Stop()
  200. for _, user := range br.usersByUsername {
  201. if user.Client == nil {
  202. continue
  203. }
  204. br.Log.Debugln("Disconnecting", user.MXID)
  205. user.Client.Disconnect()
  206. close(user.historySyncs)
  207. }
  208. }
  209. func (br *WABridge) GetExampleConfig() string {
  210. return ExampleConfig
  211. }
  212. func (br *WABridge) GetConfigPtr() interface{} {
  213. br.Config = &config.Config{
  214. BaseConfig: &br.Bridge.Config,
  215. }
  216. br.Config.BaseConfig.Bridge = &br.Config.Bridge
  217. return br.Config
  218. }
  219. const unstableFeatureBatchSending = "org.matrix.msc2716"
  220. func (br *WABridge) CheckFeatures(versions *mautrix.RespVersions) (string, bool) {
  221. if br.Config.Bridge.HistorySync.Backfill {
  222. supported, known := versions.UnstableFeatures[unstableFeatureBatchSending]
  223. if !known {
  224. return "Backfilling is enabled in bridge config, but homeserver does not support MSC2716 batch sending", false
  225. } else if !supported {
  226. return "Backfilling is enabled in bridge config, but MSC2716 batch sending is not enabled on homeserver", false
  227. }
  228. }
  229. return "", true
  230. }
  231. func main() {
  232. br := &WABridge{
  233. usersByMXID: make(map[id.UserID]*User),
  234. usersByUsername: make(map[string]*User),
  235. spaceRooms: make(map[id.RoomID]*User),
  236. managementRooms: make(map[id.RoomID]*User),
  237. portalsByMXID: make(map[id.RoomID]*Portal),
  238. portalsByJID: make(map[database.PortalKey]*Portal),
  239. puppets: make(map[types.JID]*Puppet),
  240. puppetsByCustomMXID: make(map[id.UserID]*Puppet),
  241. }
  242. br.Bridge = bridge.Bridge{
  243. Name: "mautrix-whatsapp",
  244. URL: "https://github.com/mautrix/whatsapp",
  245. Description: "A Matrix-WhatsApp puppeting bridge.",
  246. Version: "0.8.0",
  247. ProtocolName: "WhatsApp",
  248. CryptoPickleKey: "maunium.net/go/mautrix-whatsapp",
  249. ConfigUpgrader: &configupgrade.StructUpgrader{
  250. SimpleUpgrader: configupgrade.SimpleUpgrader(config.DoUpgrade),
  251. Blocks: config.SpacedBlocks,
  252. Base: ExampleConfig,
  253. },
  254. Child: br,
  255. }
  256. br.InitVersion(Tag, Commit, BuildTime)
  257. br.WAVersion = strings.FieldsFunc(br.Version, func(r rune) bool { return r == '-' || r == '+' })[0]
  258. br.Main()
  259. }