main.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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/event"
  35. "maunium.net/go/mautrix/id"
  36. "maunium.net/go/mautrix/util/configupgrade"
  37. "maunium.net/go/mautrix-whatsapp/config"
  38. "maunium.net/go/mautrix-whatsapp/database"
  39. )
  40. // Information to find out exactly which commit the bridge was built from.
  41. // These are filled at build time with the -X linker flag.
  42. var (
  43. Tag = "unknown"
  44. Commit = "unknown"
  45. BuildTime = "unknown"
  46. )
  47. //go:embed example-config.yaml
  48. var ExampleConfig string
  49. type WABridge struct {
  50. bridge.Bridge
  51. Config *config.Config
  52. DB *database.Database
  53. Provisioning *ProvisioningAPI
  54. Formatter *Formatter
  55. Metrics *MetricsHandler
  56. WAContainer *sqlstore.Container
  57. WAVersion string
  58. usersByMXID map[id.UserID]*User
  59. usersByUsername map[string]*User
  60. usersLock sync.Mutex
  61. spaceRooms map[id.RoomID]*User
  62. spaceRoomsLock sync.Mutex
  63. managementRooms map[id.RoomID]*User
  64. managementRoomsLock sync.Mutex
  65. portalsByMXID map[id.RoomID]*Portal
  66. portalsByJID map[database.PortalKey]*Portal
  67. portalsLock sync.Mutex
  68. puppets map[types.JID]*Puppet
  69. puppetsByCustomMXID map[id.UserID]*Puppet
  70. puppetsLock sync.Mutex
  71. }
  72. func (br *WABridge) Init() {
  73. br.CommandProcessor = commands.NewProcessor(&br.Bridge)
  74. br.RegisterCommands()
  75. // TODO this is a weird place for this
  76. br.EventProcessor.On(event.EphemeralEventPresence, br.HandlePresence)
  77. Segment.log = br.Log.Sub("Segment")
  78. Segment.key = br.Config.SegmentKey
  79. if Segment.IsEnabled() {
  80. Segment.log.Infoln("Segment metrics are enabled")
  81. }
  82. br.DB = database.New(br.Bridge.DB)
  83. br.WAContainer = sqlstore.NewWithDB(br.DB.DB, br.DB.Dialect.String(), &waLogger{br.DB.Log.Sub("WhatsApp")})
  84. br.WAContainer.DatabaseErrorHandler = br.DB.HandleSignalStoreError
  85. ss := br.Config.Bridge.Provisioning.SharedSecret
  86. if len(ss) > 0 && ss != "disable" {
  87. br.Provisioning = &ProvisioningAPI{bridge: br}
  88. }
  89. br.Formatter = NewFormatter(br)
  90. br.Metrics = NewMetricsHandler(br.Config.Metrics.Listen, br.Log.Sub("Metrics"), br.DB)
  91. br.MatrixHandler.TrackEventDuration = br.Metrics.TrackMatrixEvent
  92. store.BaseClientPayload.UserAgent.OsVersion = proto.String(br.WAVersion)
  93. store.BaseClientPayload.UserAgent.OsBuildNumber = proto.String(br.WAVersion)
  94. store.DeviceProps.Os = proto.String(br.Config.WhatsApp.OSName)
  95. store.DeviceProps.RequireFullSync = proto.Bool(br.Config.Bridge.HistorySync.RequestFullSync)
  96. versionParts := strings.Split(br.WAVersion, ".")
  97. if len(versionParts) > 2 {
  98. primary, _ := strconv.Atoi(versionParts[0])
  99. secondary, _ := strconv.Atoi(versionParts[1])
  100. tertiary, _ := strconv.Atoi(versionParts[2])
  101. store.DeviceProps.Version.Primary = proto.Uint32(uint32(primary))
  102. store.DeviceProps.Version.Secondary = proto.Uint32(uint32(secondary))
  103. store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(tertiary))
  104. }
  105. platformID, ok := waProto.DeviceProps_DevicePropsPlatformType_value[strings.ToUpper(br.Config.WhatsApp.BrowserName)]
  106. if ok {
  107. store.DeviceProps.PlatformType = waProto.DeviceProps_DevicePropsPlatformType(platformID).Enum()
  108. }
  109. }
  110. func (br *WABridge) Start() {
  111. err := br.WAContainer.Upgrade()
  112. if err != nil {
  113. br.Log.Fatalln("Failed to upgrade whatsmeow database: %v", err)
  114. os.Exit(15)
  115. }
  116. if br.Provisioning != nil {
  117. br.Log.Debugln("Initializing provisioning API")
  118. br.Provisioning.Init()
  119. }
  120. go br.CheckWhatsAppUpdate()
  121. go br.StartUsers()
  122. if br.Config.Metrics.Enabled {
  123. go br.Metrics.Start()
  124. }
  125. if br.Config.Bridge.ResendBridgeInfo {
  126. go br.ResendBridgeInfo()
  127. }
  128. go br.Loop()
  129. }
  130. func (br *WABridge) CheckWhatsAppUpdate() {
  131. br.Log.Debugfln("Checking for WhatsApp web update")
  132. resp, err := whatsmeow.CheckUpdate(http.DefaultClient)
  133. if err != nil {
  134. br.Log.Warnfln("Failed to check for WhatsApp web update: %v", err)
  135. return
  136. }
  137. if store.GetWAVersion() == resp.ParsedVersion {
  138. br.Log.Debugfln("Bridge is using latest WhatsApp web protocol")
  139. } else if store.GetWAVersion().LessThan(resp.ParsedVersion) {
  140. if resp.IsBelowHard || resp.IsBroken {
  141. br.Log.Warnfln("Bridge is using outdated WhatsApp web protocol and probably doesn't work anymore (%s, latest is %s)", store.GetWAVersion(), resp.ParsedVersion)
  142. } else if resp.IsBelowSoft {
  143. br.Log.Infofln("Bridge is using outdated WhatsApp web protocol (%s, latest is %s)", store.GetWAVersion(), resp.ParsedVersion)
  144. } else {
  145. br.Log.Debugfln("Bridge is using outdated WhatsApp web protocol (%s, latest is %s)", store.GetWAVersion(), resp.ParsedVersion)
  146. }
  147. } else {
  148. br.Log.Debugfln("Bridge is using newer than latest WhatsApp web protocol")
  149. }
  150. }
  151. func (br *WABridge) Loop() {
  152. for {
  153. br.SleepAndDeleteUpcoming()
  154. time.Sleep(1 * time.Hour)
  155. br.WarnUsersAboutDisconnection()
  156. }
  157. }
  158. func (br *WABridge) WarnUsersAboutDisconnection() {
  159. br.usersLock.Lock()
  160. for _, user := range br.usersByUsername {
  161. if user.IsConnected() && !user.PhoneRecentlySeen(true) {
  162. go user.sendPhoneOfflineWarning()
  163. }
  164. }
  165. br.usersLock.Unlock()
  166. }
  167. func (br *WABridge) ResendBridgeInfo() {
  168. // FIXME
  169. //if *dontSaveConfig {
  170. // br.Log.Warnln("Not setting resend_bridge_info to false in config due to --no-update flag")
  171. //} else {
  172. // err := config.Mutate(*configPath, func(helper *configupgrade.Helper) {
  173. // helper.Set(configupgrade.Bool, "false", "bridge", "resend_bridge_info")
  174. // })
  175. // if err != nil {
  176. // br.Log.Errorln("Failed to save config after setting resend_bridge_info to false:", err)
  177. // }
  178. //}
  179. //br.Log.Infoln("Re-sending bridge info state event to all portals")
  180. //for _, portal := range br.GetAllPortals() {
  181. // portal.UpdateBridgeInfo()
  182. //}
  183. //br.Log.Infoln("Finished re-sending bridge info state events")
  184. }
  185. func (br *WABridge) StartUsers() {
  186. br.Log.Debugln("Starting users")
  187. foundAnySessions := false
  188. for _, user := range br.GetAllUsers() {
  189. if !user.JID.IsEmpty() {
  190. foundAnySessions = true
  191. }
  192. go user.Connect()
  193. }
  194. if !foundAnySessions {
  195. br.SendGlobalBridgeState(bridge.State{StateEvent: bridge.StateUnconfigured}.Fill(nil))
  196. }
  197. br.Log.Debugln("Starting custom puppets")
  198. for _, loopuppet := range br.GetAllPuppetsWithCustomMXID() {
  199. go func(puppet *Puppet) {
  200. puppet.log.Debugln("Starting custom puppet", puppet.CustomMXID)
  201. err := puppet.StartCustomMXID(true)
  202. if err != nil {
  203. puppet.log.Errorln("Failed to start custom puppet:", err)
  204. }
  205. }(loopuppet)
  206. }
  207. }
  208. func (br *WABridge) Stop() {
  209. br.Metrics.Stop()
  210. for _, user := range br.usersByUsername {
  211. if user.Client == nil {
  212. continue
  213. }
  214. br.Log.Debugln("Disconnecting", user.MXID)
  215. user.Client.Disconnect()
  216. close(user.historySyncs)
  217. }
  218. }
  219. func (br *WABridge) GetExampleConfig() string {
  220. return ExampleConfig
  221. }
  222. func (br *WABridge) GetConfigPtr() interface{} {
  223. br.Config = &config.Config{
  224. BaseConfig: &br.Bridge.Config,
  225. }
  226. br.Config.BaseConfig.Bridge = &br.Config.Bridge
  227. return br.Config
  228. }
  229. const unstableFeatureBatchSending = "org.matrix.msc2716"
  230. func (br *WABridge) CheckFeatures(versions *mautrix.RespVersions) (string, bool) {
  231. if br.Config.Bridge.HistorySync.Backfill {
  232. supported, known := versions.UnstableFeatures[unstableFeatureBatchSending]
  233. if !known {
  234. return "Backfilling is enabled in bridge config, but server does not support MSC2716 batch sending", false
  235. } else if !supported {
  236. return "Backfilling is enabled in bridge config, but MSC2716 batch sending is not enabled on server", false
  237. }
  238. }
  239. return "", true
  240. }
  241. func main() {
  242. br := &WABridge{
  243. usersByMXID: make(map[id.UserID]*User),
  244. usersByUsername: make(map[string]*User),
  245. spaceRooms: make(map[id.RoomID]*User),
  246. managementRooms: make(map[id.RoomID]*User),
  247. portalsByMXID: make(map[id.RoomID]*Portal),
  248. portalsByJID: make(map[database.PortalKey]*Portal),
  249. puppets: make(map[types.JID]*Puppet),
  250. puppetsByCustomMXID: make(map[id.UserID]*Puppet),
  251. }
  252. br.Bridge = bridge.Bridge{
  253. Name: "mautrix-whatsapp",
  254. URL: "https://github.com/mautrix/whatsapp",
  255. Description: "A Matrix-WhatsApp puppeting bridge.",
  256. Version: "0.5.0",
  257. ProtocolName: "WhatsApp",
  258. CryptoPickleKey: "maunium.net/go/mautrix-whatsapp",
  259. ConfigUpgrader: &configupgrade.StructUpgrader{
  260. SimpleUpgrader: configupgrade.SimpleUpgrader(config.DoUpgrade),
  261. Blocks: config.SpacedBlocks,
  262. Base: ExampleConfig,
  263. },
  264. Child: br,
  265. }
  266. br.InitVersion(Tag, Commit, BuildTime)
  267. br.WAVersion = strings.FieldsFunc(br.Version, func(r rune) bool { return r == '-' || r == '+' })[0]
  268. br.Main()
  269. }