portal.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2018 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. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "html"
  22. "image"
  23. "io"
  24. "math/rand"
  25. "mime"
  26. "net/http"
  27. "regexp"
  28. "strings"
  29. "sync"
  30. "github.com/Rhymen/go-whatsapp"
  31. "maunium.net/go/gomatrix"
  32. "maunium.net/go/gomatrix/format"
  33. log "maunium.net/go/maulogger"
  34. "maunium.net/go/mautrix-appservice"
  35. "maunium.net/go/mautrix-whatsapp/database"
  36. "maunium.net/go/mautrix-whatsapp/types"
  37. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  38. )
  39. func (user *User) GetPortalByMXID(mxid types.MatrixRoomID) *Portal {
  40. user.portalsLock.Lock()
  41. defer user.portalsLock.Unlock()
  42. portal, ok := user.portalsByMXID[mxid]
  43. if !ok {
  44. dbPortal := user.bridge.DB.Portal.GetByMXID(mxid)
  45. if dbPortal == nil || dbPortal.Owner != user.ID {
  46. return nil
  47. }
  48. portal = user.NewPortal(dbPortal)
  49. user.portalsByJID[portal.JID] = portal
  50. if len(portal.MXID) > 0 {
  51. user.portalsByMXID[portal.MXID] = portal
  52. }
  53. }
  54. return portal
  55. }
  56. func (user *User) GetPortalByJID(jid types.WhatsAppID) *Portal {
  57. user.portalsLock.Lock()
  58. defer user.portalsLock.Unlock()
  59. portal, ok := user.portalsByJID[jid]
  60. if !ok {
  61. dbPortal := user.bridge.DB.Portal.GetByJID(user.ID, jid)
  62. if dbPortal == nil {
  63. dbPortal = user.bridge.DB.Portal.New()
  64. dbPortal.JID = jid
  65. dbPortal.Owner = user.ID
  66. dbPortal.Insert()
  67. }
  68. portal = user.NewPortal(dbPortal)
  69. user.portalsByJID[portal.JID] = portal
  70. if len(portal.MXID) > 0 {
  71. user.portalsByMXID[portal.MXID] = portal
  72. }
  73. }
  74. return portal
  75. }
  76. func (user *User) GetAllPortals() []*Portal {
  77. user.portalsLock.Lock()
  78. defer user.portalsLock.Unlock()
  79. dbPortals := user.bridge.DB.Portal.GetAll(user.ID)
  80. output := make([]*Portal, len(dbPortals))
  81. for index, dbPortal := range dbPortals {
  82. portal, ok := user.portalsByJID[dbPortal.JID]
  83. if !ok {
  84. portal = user.NewPortal(dbPortal)
  85. user.portalsByJID[dbPortal.JID] = portal
  86. if len(dbPortal.MXID) > 0 {
  87. user.portalsByMXID[dbPortal.MXID] = portal
  88. }
  89. }
  90. output[index] = portal
  91. }
  92. return output
  93. }
  94. func (user *User) NewPortal(dbPortal *database.Portal) *Portal {
  95. return &Portal{
  96. Portal: dbPortal,
  97. user: user,
  98. bridge: user.bridge,
  99. log: user.log.Sub(fmt.Sprintf("Portal/%s", dbPortal.JID)),
  100. }
  101. }
  102. type Portal struct {
  103. *database.Portal
  104. user *User
  105. bridge *Bridge
  106. log log.Logger
  107. roomCreateLock sync.Mutex
  108. }
  109. func (portal *Portal) SyncParticipants(metadata *whatsapp_ext.GroupInfo) {
  110. for _, participant := range metadata.Participants {
  111. intent := portal.user.GetPuppetByJID(participant.JID).Intent()
  112. intent.EnsureJoined(portal.MXID)
  113. }
  114. }
  115. func (portal *Portal) UpdateAvatar() bool {
  116. avatar, err := portal.user.Conn.GetProfilePicThumb(portal.JID)
  117. if err != nil {
  118. portal.log.Errorln(err)
  119. return false
  120. }
  121. if portal.Avatar == avatar.Tag {
  122. return false
  123. }
  124. data, err := avatar.DownloadBytes()
  125. if err != nil {
  126. portal.log.Errorln("Failed to download avatar:", err)
  127. return false
  128. }
  129. mimeType := http.DetectContentType(data)
  130. resp, err := portal.MainIntent().UploadBytes(data, mimeType)
  131. if err != nil {
  132. portal.log.Errorln("Failed to upload avatar:", err)
  133. return false
  134. }
  135. _, err = portal.MainIntent().SetRoomAvatar(portal.MXID, resp.ContentURI)
  136. if err != nil {
  137. portal.log.Warnln("Failed to set room topic:", err)
  138. return false
  139. }
  140. portal.Avatar = avatar.Tag
  141. return true
  142. }
  143. func (portal *Portal) UpdateName(metadata *whatsapp_ext.GroupInfo) bool {
  144. if portal.Name != metadata.Name {
  145. _, err := portal.MainIntent().SetRoomName(portal.MXID, metadata.Name)
  146. if err == nil {
  147. portal.Name = metadata.Name
  148. return true
  149. }
  150. portal.log.Warnln("Failed to set room name:", err)
  151. }
  152. return false
  153. }
  154. func (portal *Portal) UpdateTopic(metadata *whatsapp_ext.GroupInfo) bool {
  155. if portal.Topic != metadata.Topic {
  156. _, err := portal.MainIntent().SetRoomTopic(portal.MXID, metadata.Topic)
  157. if err == nil {
  158. portal.Topic = metadata.Topic
  159. return true
  160. }
  161. portal.log.Warnln("Failed to set room topic:", err)
  162. }
  163. return false
  164. }
  165. func (portal *Portal) UpdateMetadata() bool {
  166. metadata, err := portal.user.Conn.GetGroupMetaData(portal.JID)
  167. if err != nil {
  168. portal.log.Errorln(err)
  169. return false
  170. }
  171. portal.SyncParticipants(metadata)
  172. update := false
  173. update = portal.UpdateName(metadata) || update
  174. update = portal.UpdateTopic(metadata) || update
  175. return update
  176. }
  177. func (portal *Portal) Sync(contact whatsapp.Contact) {
  178. if len(portal.MXID) == 0 {
  179. if !portal.IsPrivateChat() {
  180. portal.Name = contact.Name
  181. }
  182. err := portal.CreateMatrixRoom()
  183. if err != nil {
  184. portal.log.Errorln("Failed to create portal room:", err)
  185. return
  186. }
  187. }
  188. if portal.IsPrivateChat() {
  189. return
  190. }
  191. update := false
  192. update = portal.UpdateMetadata() || update
  193. update = portal.UpdateAvatar() || update
  194. if update {
  195. portal.Update()
  196. }
  197. }
  198. func (portal *Portal) CreateMatrixRoom() error {
  199. portal.roomCreateLock.Lock()
  200. defer portal.roomCreateLock.Unlock()
  201. if len(portal.MXID) > 0 {
  202. return nil
  203. }
  204. name := portal.Name
  205. topic := portal.Topic
  206. isPrivateChat := false
  207. invite := []string{portal.user.ID}
  208. if portal.IsPrivateChat() {
  209. name = ""
  210. topic = "WhatsApp private chat"
  211. isPrivateChat = true
  212. }
  213. resp, err := portal.MainIntent().CreateRoom(&gomatrix.ReqCreateRoom{
  214. Visibility: "private",
  215. Name: name,
  216. Topic: topic,
  217. Invite: invite,
  218. Preset: "private_chat",
  219. IsDirect: isPrivateChat,
  220. })
  221. if err != nil {
  222. return err
  223. }
  224. portal.MXID = resp.RoomID
  225. portal.Update()
  226. return nil
  227. }
  228. func (portal *Portal) IsPrivateChat() bool {
  229. return strings.HasSuffix(portal.JID, whatsapp_ext.NewUserSuffix)
  230. }
  231. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  232. if portal.IsPrivateChat() {
  233. return portal.user.GetPuppetByJID(portal.JID).Intent()
  234. }
  235. return portal.bridge.AppService.BotIntent()
  236. }
  237. func (portal *Portal) IsDuplicate(id types.WhatsAppMessageID) bool {
  238. msg := portal.bridge.DB.Message.GetByJID(portal.Owner, id)
  239. if msg != nil {
  240. return true
  241. }
  242. return false
  243. }
  244. func (portal *Portal) MarkHandled(jid types.WhatsAppMessageID, mxid types.MatrixEventID) {
  245. msg := portal.bridge.DB.Message.New()
  246. msg.Owner = portal.Owner
  247. msg.JID = jid
  248. msg.MXID = mxid
  249. msg.Insert()
  250. }
  251. func (portal *Portal) GetMessageIntent(info whatsapp.MessageInfo) *appservice.IntentAPI {
  252. if info.FromMe {
  253. portal.log.Debugln("Unhandled message from me:", info.Id)
  254. return nil
  255. } else if portal.IsPrivateChat() {
  256. return portal.MainIntent()
  257. }
  258. puppet := portal.user.GetPuppetByJID(info.SenderJid)
  259. return puppet.Intent()
  260. }
  261. func (portal *Portal) SetReply(content *gomatrix.Content, info whatsapp.MessageInfo) {
  262. if len(info.QuotedMessageID) == 0 {
  263. return
  264. }
  265. message := portal.bridge.DB.Message.GetByJID(portal.Owner, info.QuotedMessageID)
  266. if message != nil {
  267. event, err := portal.MainIntent().GetEvent(portal.MXID, message.MXID)
  268. if err != nil {
  269. portal.log.Warnln("Failed to get reply target:", err)
  270. return
  271. }
  272. content.SetReply(event)
  273. }
  274. return
  275. }
  276. var codeBlockRegex = regexp.MustCompile("```((?:.|\n)+?)```")
  277. var italicRegex = regexp.MustCompile("([\\s>~*]|^)_(.+?)_([^a-zA-Z\\d]|$)")
  278. var boldRegex = regexp.MustCompile("([\\s>_~]|^)\\*(.+?)\\*([^a-zA-Z\\d]|$)")
  279. var strikethroughRegex = regexp.MustCompile("([\\s>_*]|^)~(.+?)~([^a-zA-Z\\d]|$)")
  280. var whatsAppFormat = map[*regexp.Regexp]string{
  281. italicRegex: "$1<em>$2</em>$3",
  282. boldRegex: "$1<strong>$2</strong>$3",
  283. strikethroughRegex: "$1<del>$2</del>$3",
  284. }
  285. func (portal *Portal) ParseWhatsAppFormat(input string) string {
  286. output := html.EscapeString(input)
  287. for regex, replacement := range whatsAppFormat {
  288. output = regex.ReplaceAllString(output, replacement)
  289. }
  290. output = codeBlockRegex.ReplaceAllStringFunc(output, func(str string) string {
  291. str = str[3 : len(str)-3]
  292. if strings.ContainsRune(str, '\n') {
  293. return fmt.Sprintf("<pre><code>%s</code></pre>", str)
  294. }
  295. return fmt.Sprintf("<code>%s</code>", str)
  296. })
  297. return output
  298. }
  299. func (portal *Portal) HandleTextMessage(message whatsapp.TextMessage) {
  300. if portal.IsDuplicate(message.Info.Id) {
  301. return
  302. }
  303. err := portal.CreateMatrixRoom()
  304. if err != nil {
  305. portal.log.Errorln("Failed to create portal room:", err)
  306. return
  307. }
  308. intent := portal.GetMessageIntent(message.Info)
  309. if intent == nil {
  310. return
  311. }
  312. content := gomatrix.Content{
  313. Body: message.Text,
  314. MsgType: gomatrix.MsgText,
  315. }
  316. htmlBody := portal.ParseWhatsAppFormat(message.Text)
  317. if htmlBody != message.Text {
  318. content.FormattedBody = htmlBody
  319. content.Format = gomatrix.FormatHTML
  320. }
  321. portal.SetReply(&content, message.Info)
  322. intent.UserTyping(portal.MXID, false, 0)
  323. resp, err := intent.SendMassagedMessageEvent(portal.MXID, gomatrix.EventMessage, content, int64(message.Info.Timestamp*1000))
  324. if err != nil {
  325. portal.log.Errorfln("Failed to handle message %s: %v", message.Info.Id, err)
  326. return
  327. }
  328. portal.MarkHandled(message.Info.Id, resp.EventID)
  329. portal.log.Debugln("Handled message", message.Info.Id, "->", resp.EventID)
  330. }
  331. func (portal *Portal) HandleMediaMessage(download func() ([]byte, error), thumbnail []byte, info whatsapp.MessageInfo, mimeType, caption string) {
  332. if portal.IsDuplicate(info.Id) {
  333. return
  334. }
  335. err := portal.CreateMatrixRoom()
  336. if err != nil {
  337. portal.log.Errorln("Failed to create portal room:", err)
  338. return
  339. }
  340. intent := portal.GetMessageIntent(info)
  341. if intent == nil {
  342. return
  343. }
  344. data, err := download()
  345. if err != nil {
  346. portal.log.Errorln("Failed to download media:", err)
  347. return
  348. }
  349. uploaded, err := intent.UploadBytes(data, mimeType)
  350. if err != nil {
  351. portal.log.Errorln("Failed to upload media:", err)
  352. return
  353. }
  354. if len(caption) == 0 {
  355. caption = info.Id
  356. exts, _ := mime.ExtensionsByType(mimeType)
  357. if exts != nil && len(exts) > 0 {
  358. caption += exts[0]
  359. }
  360. }
  361. content := gomatrix.Content{
  362. Body: caption,
  363. URL: uploaded.ContentURI,
  364. Info: &gomatrix.FileInfo{
  365. Size: len(data),
  366. MimeType: mimeType,
  367. },
  368. }
  369. portal.SetReply(&content, info)
  370. if thumbnail != nil {
  371. thumbnailMime := http.DetectContentType(thumbnail)
  372. uploadedThumbnail, _ := intent.UploadBytes(thumbnail, thumbnailMime)
  373. if uploadedThumbnail != nil {
  374. content.Info.ThumbnailURL = uploadedThumbnail.ContentURI
  375. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  376. content.Info.ThumbnailInfo = &gomatrix.FileInfo{
  377. Size: len(thumbnail),
  378. Width: cfg.Width,
  379. Height: cfg.Height,
  380. MimeType: thumbnailMime,
  381. }
  382. }
  383. }
  384. switch strings.ToLower(strings.Split(mimeType, "/")[0]) {
  385. case "image":
  386. content.MsgType = gomatrix.MsgImage
  387. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  388. content.Info.Width = cfg.Width
  389. content.Info.Height = cfg.Height
  390. case "video":
  391. content.MsgType = gomatrix.MsgVideo
  392. case "audio":
  393. content.MsgType = gomatrix.MsgAudio
  394. default:
  395. content.MsgType = gomatrix.MsgFile
  396. }
  397. intent.UserTyping(portal.MXID, false, 0)
  398. resp, err := intent.SendMassagedMessageEvent(portal.MXID, gomatrix.EventMessage, content, int64(info.Timestamp*1000))
  399. if err != nil {
  400. portal.log.Errorfln("Failed to handle message %s: %v", info.Id, err)
  401. return
  402. }
  403. portal.MarkHandled(info.Id, resp.EventID)
  404. portal.log.Debugln("Handled message", info.Id, "->", resp.EventID)
  405. }
  406. var htmlParser = format.HTMLParser{
  407. TabsToSpaces: 4,
  408. Newline: "\n",
  409. PillConverter: func(mxid, eventID string) string {
  410. return mxid
  411. },
  412. BoldConverter: func(text string) string {
  413. return fmt.Sprintf("*%s*", text)
  414. },
  415. ItalicConverter: func(text string) string {
  416. return fmt.Sprintf("_%s_", text)
  417. },
  418. StrikethroughConverter: func(text string) string {
  419. return fmt.Sprintf("~%s~", text)
  420. },
  421. MonospaceConverter: func(text string) string {
  422. return fmt.Sprintf("```%s```", text)
  423. },
  424. MonospaceBlockConverter: func(text string) string {
  425. return fmt.Sprintf("```%s```", text)
  426. },
  427. }
  428. func makeMessageID() string {
  429. b := make([]byte, 10)
  430. rand.Read(b)
  431. return strings.ToUpper(hex.EncodeToString(b))
  432. }
  433. func (portal *Portal) PreprocessMatrixMedia(evt *gomatrix.Event) (string, io.ReadCloser, []byte) {
  434. if evt.Content.Info == nil {
  435. evt.Content.Info = &gomatrix.FileInfo{}
  436. }
  437. caption := evt.Content.Body
  438. exts, err := mime.ExtensionsByType(evt.Content.Info.MimeType)
  439. for _, ext := range exts {
  440. if strings.HasSuffix(caption, ext) {
  441. caption = ""
  442. break
  443. }
  444. }
  445. content, err := portal.MainIntent().Download(evt.Content.URL)
  446. if err != nil {
  447. portal.log.Errorln("Failed to download media in %s: %v", evt.ID, err)
  448. return "", nil, nil
  449. }
  450. thumbnail, err := portal.MainIntent().DownloadBytes(evt.Content.Info.ThumbnailURL)
  451. return caption, content, thumbnail
  452. }
  453. func (portal *Portal) HandleMatrixMessage(evt *gomatrix.Event) {
  454. info := whatsapp.MessageInfo{
  455. Id: makeMessageID(),
  456. RemoteJid: portal.JID,
  457. }
  458. var err error
  459. switch evt.Content.MsgType {
  460. case gomatrix.MsgText, gomatrix.MsgEmote:
  461. text := evt.Content.Body
  462. if evt.Content.Format == gomatrix.FormatHTML {
  463. text = htmlParser.Parse(evt.Content.FormattedBody)
  464. }
  465. if evt.Content.MsgType == gomatrix.MsgEmote {
  466. text = "/me " + text
  467. }
  468. err = portal.user.Conn.Send(whatsapp.TextMessage{
  469. Text: text,
  470. Info: info,
  471. })
  472. case gomatrix.MsgImage:
  473. caption, content, thumbnail := portal.PreprocessMatrixMedia(evt)
  474. if content == nil {
  475. return
  476. }
  477. err = portal.user.Conn.Send(whatsapp.ImageMessage{
  478. Caption: caption,
  479. Content: content,
  480. Thumbnail: thumbnail,
  481. Type: evt.Content.Info.MimeType,
  482. Info: info,
  483. })
  484. case gomatrix.MsgVideo:
  485. caption, content, thumbnail := portal.PreprocessMatrixMedia(evt)
  486. if content == nil {
  487. return
  488. }
  489. err = portal.user.Conn.Send(whatsapp.VideoMessage{
  490. Caption: caption,
  491. Content: content,
  492. Thumbnail: thumbnail,
  493. Type: evt.Content.Info.MimeType,
  494. Info: info,
  495. })
  496. case gomatrix.MsgAudio:
  497. _, content, _ := portal.PreprocessMatrixMedia(evt)
  498. if content == nil {
  499. return
  500. }
  501. err = portal.user.Conn.Send(whatsapp.AudioMessage{
  502. Content: content,
  503. Type: evt.Content.Info.MimeType,
  504. Info: info,
  505. })
  506. case gomatrix.MsgFile:
  507. _, content, thumbnail := portal.PreprocessMatrixMedia(evt)
  508. if content == nil {
  509. return
  510. }
  511. err = portal.user.Conn.Send(whatsapp.DocumentMessage{
  512. Content: content,
  513. Thumbnail: thumbnail,
  514. Type: evt.Content.Info.MimeType,
  515. Info: info,
  516. })
  517. default:
  518. portal.log.Debugln("Unhandled Matrix event:", evt)
  519. return
  520. }
  521. portal.MarkHandled(info.Id, evt.ID)
  522. if err != nil {
  523. portal.log.Errorfln("Error handling Matrix event %s: %v", evt.ID, err)
  524. } else {
  525. portal.log.Debugln("Handled Matrix event:", evt)
  526. }
  527. }