main.go 8.8 KB

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