portal.go 147 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "context"
  20. "crypto/sha256"
  21. "encoding/hex"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "image"
  26. "image/color"
  27. _ "image/gif"
  28. "image/jpeg"
  29. "image/png"
  30. "io"
  31. "math"
  32. "mime"
  33. "net/http"
  34. "reflect"
  35. "runtime/debug"
  36. "strconv"
  37. "strings"
  38. "sync"
  39. "time"
  40. "github.com/chai2010/webp"
  41. "github.com/tidwall/gjson"
  42. "golang.org/x/image/draw"
  43. "google.golang.org/protobuf/proto"
  44. log "maunium.net/go/maulogger/v2"
  45. "maunium.net/go/mautrix"
  46. "maunium.net/go/mautrix/appservice"
  47. "maunium.net/go/mautrix/bridge"
  48. "maunium.net/go/mautrix/bridge/bridgeconfig"
  49. "maunium.net/go/mautrix/crypto/attachment"
  50. "maunium.net/go/mautrix/event"
  51. "maunium.net/go/mautrix/format"
  52. "maunium.net/go/mautrix/id"
  53. "maunium.net/go/mautrix/util"
  54. "maunium.net/go/mautrix/util/dbutil"
  55. "maunium.net/go/mautrix/util/ffmpeg"
  56. "maunium.net/go/mautrix/util/variationselector"
  57. "go.mau.fi/whatsmeow"
  58. waProto "go.mau.fi/whatsmeow/binary/proto"
  59. "go.mau.fi/whatsmeow/types"
  60. "go.mau.fi/whatsmeow/types/events"
  61. "maunium.net/go/mautrix-whatsapp/database"
  62. )
  63. const StatusBroadcastTopic = "WhatsApp status updates from your contacts"
  64. const StatusBroadcastName = "WhatsApp Status Broadcast"
  65. const BroadcastTopic = "WhatsApp broadcast list"
  66. const UnnamedBroadcastName = "Unnamed broadcast list"
  67. const PrivateChatTopic = "WhatsApp private chat"
  68. var ErrStatusBroadcastDisabled = errors.New("status bridging is disabled")
  69. func (br *WABridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  70. br.portalsLock.Lock()
  71. defer br.portalsLock.Unlock()
  72. portal, ok := br.portalsByMXID[mxid]
  73. if !ok {
  74. return br.loadDBPortal(br.DB.Portal.GetByMXID(mxid), nil)
  75. }
  76. return portal
  77. }
  78. func (br *WABridge) GetIPortal(mxid id.RoomID) bridge.Portal {
  79. p := br.GetPortalByMXID(mxid)
  80. if p == nil {
  81. return nil
  82. }
  83. return p
  84. }
  85. func (portal *Portal) IsEncrypted() bool {
  86. return portal.Encrypted
  87. }
  88. func (portal *Portal) MarkEncrypted() {
  89. portal.Encrypted = true
  90. portal.Update(nil)
  91. }
  92. func (portal *Portal) ReceiveMatrixEvent(user bridge.User, evt *event.Event) {
  93. if user.GetPermissionLevel() >= bridgeconfig.PermissionLevelUser || portal.HasRelaybot() {
  94. portal.matrixMessages <- PortalMatrixMessage{user: user.(*User), evt: evt, receivedAt: time.Now()}
  95. }
  96. }
  97. func (br *WABridge) GetPortalByJID(key database.PortalKey) *Portal {
  98. br.portalsLock.Lock()
  99. defer br.portalsLock.Unlock()
  100. portal, ok := br.portalsByJID[key]
  101. if !ok {
  102. return br.loadDBPortal(br.DB.Portal.GetByJID(key), &key)
  103. }
  104. return portal
  105. }
  106. func (br *WABridge) GetAllPortals() []*Portal {
  107. return br.dbPortalsToPortals(br.DB.Portal.GetAll())
  108. }
  109. func (br *WABridge) GetAllIPortals() (iportals []bridge.Portal) {
  110. portals := br.GetAllPortals()
  111. iportals = make([]bridge.Portal, len(portals))
  112. for i, portal := range portals {
  113. iportals[i] = portal
  114. }
  115. return iportals
  116. }
  117. func (br *WABridge) GetAllPortalsByJID(jid types.JID) []*Portal {
  118. return br.dbPortalsToPortals(br.DB.Portal.GetAllByJID(jid))
  119. }
  120. func (br *WABridge) GetAllByParentGroup(jid types.JID) []*Portal {
  121. return br.dbPortalsToPortals(br.DB.Portal.GetAllByParentGroup(jid))
  122. }
  123. func (br *WABridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
  124. br.portalsLock.Lock()
  125. defer br.portalsLock.Unlock()
  126. output := make([]*Portal, len(dbPortals))
  127. for index, dbPortal := range dbPortals {
  128. if dbPortal == nil {
  129. continue
  130. }
  131. portal, ok := br.portalsByJID[dbPortal.Key]
  132. if !ok {
  133. portal = br.loadDBPortal(dbPortal, nil)
  134. }
  135. output[index] = portal
  136. }
  137. return output
  138. }
  139. func (br *WABridge) loadDBPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
  140. if dbPortal == nil {
  141. if key == nil {
  142. return nil
  143. }
  144. dbPortal = br.DB.Portal.New()
  145. dbPortal.Key = *key
  146. dbPortal.Insert()
  147. }
  148. portal := br.NewPortal(dbPortal)
  149. br.portalsByJID[portal.Key] = portal
  150. if len(portal.MXID) > 0 {
  151. br.portalsByMXID[portal.MXID] = portal
  152. }
  153. return portal
  154. }
  155. func (portal *Portal) GetUsers() []*User {
  156. return nil
  157. }
  158. func (br *WABridge) newBlankPortal(key database.PortalKey) *Portal {
  159. portal := &Portal{
  160. bridge: br,
  161. log: br.Log.Sub(fmt.Sprintf("Portal/%s", key)),
  162. messages: make(chan PortalMessage, br.Config.Bridge.PortalMessageBuffer),
  163. matrixMessages: make(chan PortalMatrixMessage, br.Config.Bridge.PortalMessageBuffer),
  164. mediaRetries: make(chan PortalMediaRetry, br.Config.Bridge.PortalMessageBuffer),
  165. mediaErrorCache: make(map[types.MessageID]*FailedMediaMeta),
  166. }
  167. go portal.handleMessageLoop()
  168. return portal
  169. }
  170. func (br *WABridge) NewManualPortal(key database.PortalKey) *Portal {
  171. portal := br.newBlankPortal(key)
  172. portal.Portal = br.DB.Portal.New()
  173. portal.Key = key
  174. return portal
  175. }
  176. func (br *WABridge) NewPortal(dbPortal *database.Portal) *Portal {
  177. portal := br.newBlankPortal(dbPortal.Key)
  178. portal.Portal = dbPortal
  179. return portal
  180. }
  181. const recentlyHandledLength = 100
  182. type fakeMessage struct {
  183. Sender types.JID
  184. Text string
  185. ID string
  186. Time time.Time
  187. Important bool
  188. }
  189. type PortalMessage struct {
  190. evt *events.Message
  191. undecryptable *events.UndecryptableMessage
  192. receipt *events.Receipt
  193. fake *fakeMessage
  194. source *User
  195. }
  196. type PortalMatrixMessage struct {
  197. evt *event.Event
  198. user *User
  199. receivedAt time.Time
  200. }
  201. type PortalMediaRetry struct {
  202. evt *events.MediaRetry
  203. source *User
  204. }
  205. type recentlyHandledWrapper struct {
  206. id types.MessageID
  207. err database.MessageErrorType
  208. }
  209. type Portal struct {
  210. *database.Portal
  211. bridge *WABridge
  212. log log.Logger
  213. roomCreateLock sync.Mutex
  214. encryptLock sync.Mutex
  215. backfillLock sync.Mutex
  216. avatarLock sync.Mutex
  217. latestEventBackfillLock sync.Mutex
  218. parentGroupUpdateLock sync.Mutex
  219. recentlyHandled [recentlyHandledLength]recentlyHandledWrapper
  220. recentlyHandledLock sync.Mutex
  221. recentlyHandledIndex uint8
  222. currentlyTyping []id.UserID
  223. currentlyTypingLock sync.Mutex
  224. messages chan PortalMessage
  225. matrixMessages chan PortalMatrixMessage
  226. mediaRetries chan PortalMediaRetry
  227. mediaErrorCache map[types.MessageID]*FailedMediaMeta
  228. relayUser *User
  229. parentPortal *Portal
  230. }
  231. var (
  232. _ bridge.Portal = (*Portal)(nil)
  233. _ bridge.ReadReceiptHandlingPortal = (*Portal)(nil)
  234. _ bridge.MembershipHandlingPortal = (*Portal)(nil)
  235. _ bridge.MetaHandlingPortal = (*Portal)(nil)
  236. _ bridge.TypingPortal = (*Portal)(nil)
  237. _ bridge.DisappearingPortal = (*Portal)(nil)
  238. )
  239. func (portal *Portal) handleMessageLoopItem(msg PortalMessage) {
  240. if len(portal.MXID) == 0 {
  241. if msg.fake == nil && msg.undecryptable == nil && (msg.evt == nil || !containsSupportedMessage(msg.evt.Message)) {
  242. portal.log.Debugln("Not creating portal room for incoming message: message is not a chat message")
  243. return
  244. }
  245. portal.log.Debugln("Creating Matrix room from incoming message")
  246. err := portal.CreateMatrixRoom(msg.source, nil, false, true)
  247. if err != nil {
  248. portal.log.Errorln("Failed to create portal room:", err)
  249. return
  250. }
  251. }
  252. portal.latestEventBackfillLock.Lock()
  253. defer portal.latestEventBackfillLock.Unlock()
  254. switch {
  255. case msg.evt != nil:
  256. portal.handleMessage(msg.source, msg.evt)
  257. case msg.receipt != nil:
  258. portal.handleReceipt(msg.receipt, msg.source)
  259. case msg.undecryptable != nil:
  260. portal.handleUndecryptableMessage(msg.source, msg.undecryptable)
  261. case msg.fake != nil:
  262. msg.fake.ID = "FAKE::" + msg.fake.ID
  263. portal.handleFakeMessage(*msg.fake)
  264. default:
  265. portal.log.Warnln("Unexpected PortalMessage with no message: %+v", msg)
  266. }
  267. }
  268. func (portal *Portal) handleMatrixMessageLoopItem(msg PortalMatrixMessage) {
  269. evtTS := time.UnixMilli(msg.evt.Timestamp)
  270. timings := messageTimings{
  271. initReceive: msg.evt.Mautrix.ReceivedAt.Sub(evtTS),
  272. decrypt: msg.evt.Mautrix.DecryptionDuration,
  273. portalQueue: time.Since(msg.receivedAt),
  274. totalReceive: time.Since(evtTS),
  275. }
  276. implicitRRStart := time.Now()
  277. portal.handleMatrixReadReceipt(msg.user, "", evtTS, false)
  278. timings.implicitRR = time.Since(implicitRRStart)
  279. switch msg.evt.Type {
  280. case event.EventMessage, event.EventSticker, TypeMSC3881V2PollResponse, TypeMSC3881PollResponse:
  281. portal.HandleMatrixMessage(msg.user, msg.evt, timings)
  282. case event.EventRedaction:
  283. portal.HandleMatrixRedaction(msg.user, msg.evt)
  284. case event.EventReaction:
  285. portal.HandleMatrixReaction(msg.user, msg.evt)
  286. default:
  287. portal.log.Warnln("Unsupported event type %+v in portal message channel", msg.evt.Type)
  288. }
  289. }
  290. func (portal *Portal) handleReceipt(receipt *events.Receipt, source *User) {
  291. // The order of the message ID array depends on the sender's platform, so we just have to find
  292. // the last message based on timestamp. Also, timestamps only have second precision, so if
  293. // there are many messages at the same second just mark them all as read, because we don't
  294. // know which one is last
  295. markAsRead := make([]*database.Message, 0, 1)
  296. var bestTimestamp time.Time
  297. for _, msgID := range receipt.MessageIDs {
  298. msg := portal.bridge.DB.Message.GetByJID(portal.Key, msgID)
  299. if msg == nil || msg.IsFakeMXID() {
  300. continue
  301. }
  302. if msg.Timestamp.After(bestTimestamp) {
  303. bestTimestamp = msg.Timestamp
  304. markAsRead = append(markAsRead[:0], msg)
  305. } else if msg != nil && msg.Timestamp.Equal(bestTimestamp) {
  306. markAsRead = append(markAsRead, msg)
  307. }
  308. }
  309. if receipt.Sender.User == source.JID.User {
  310. if len(markAsRead) > 0 {
  311. source.SetLastReadTS(portal.Key, markAsRead[0].Timestamp)
  312. } else {
  313. source.SetLastReadTS(portal.Key, receipt.Timestamp)
  314. }
  315. }
  316. intent := portal.bridge.GetPuppetByJID(receipt.Sender).IntentFor(portal)
  317. for _, msg := range markAsRead {
  318. err := intent.SetReadMarkers(portal.MXID, source.makeReadMarkerContent(msg.MXID, intent.IsCustomPuppet))
  319. if err != nil {
  320. portal.log.Warnfln("Failed to mark message %s as read by %s: %v", msg.MXID, intent.UserID, err)
  321. } else {
  322. portal.log.Debugfln("Marked %s as read by %s", msg.MXID, intent.UserID)
  323. }
  324. }
  325. }
  326. func (portal *Portal) handleMessageLoop() {
  327. for {
  328. select {
  329. case msg := <-portal.messages:
  330. portal.handleMessageLoopItem(msg)
  331. case msg := <-portal.matrixMessages:
  332. portal.handleMatrixMessageLoopItem(msg)
  333. case retry := <-portal.mediaRetries:
  334. portal.handleMediaRetry(retry.evt, retry.source)
  335. }
  336. }
  337. }
  338. func containsSupportedMessage(waMsg *waProto.Message) bool {
  339. if waMsg == nil {
  340. return false
  341. }
  342. return waMsg.Conversation != nil || waMsg.ExtendedTextMessage != nil || waMsg.ImageMessage != nil ||
  343. waMsg.StickerMessage != nil || waMsg.AudioMessage != nil || waMsg.VideoMessage != nil ||
  344. waMsg.DocumentMessage != nil || waMsg.ContactMessage != nil || waMsg.LocationMessage != nil ||
  345. waMsg.LiveLocationMessage != nil || waMsg.GroupInviteMessage != nil || waMsg.ContactsArrayMessage != nil ||
  346. waMsg.HighlyStructuredMessage != nil || waMsg.TemplateMessage != nil || waMsg.TemplateButtonReplyMessage != nil ||
  347. waMsg.ListMessage != nil || waMsg.ListResponseMessage != nil || waMsg.PollCreationMessage != nil
  348. }
  349. func getMessageType(waMsg *waProto.Message) string {
  350. switch {
  351. case waMsg == nil:
  352. return "ignore"
  353. case waMsg.Conversation != nil, waMsg.ExtendedTextMessage != nil:
  354. return "text"
  355. case waMsg.ImageMessage != nil:
  356. return fmt.Sprintf("image %s", waMsg.GetImageMessage().GetMimetype())
  357. case waMsg.StickerMessage != nil:
  358. return fmt.Sprintf("sticker %s", waMsg.GetStickerMessage().GetMimetype())
  359. case waMsg.VideoMessage != nil:
  360. return fmt.Sprintf("video %s", waMsg.GetVideoMessage().GetMimetype())
  361. case waMsg.AudioMessage != nil:
  362. return fmt.Sprintf("audio %s", waMsg.GetAudioMessage().GetMimetype())
  363. case waMsg.DocumentMessage != nil:
  364. return fmt.Sprintf("document %s", waMsg.GetDocumentMessage().GetMimetype())
  365. case waMsg.ContactMessage != nil:
  366. return "contact"
  367. case waMsg.ContactsArrayMessage != nil:
  368. return "contact array"
  369. case waMsg.LocationMessage != nil:
  370. return "location"
  371. case waMsg.LiveLocationMessage != nil:
  372. return "live location start"
  373. case waMsg.GroupInviteMessage != nil:
  374. return "group invite"
  375. case waMsg.ReactionMessage != nil:
  376. return "reaction"
  377. case waMsg.EncReactionMessage != nil:
  378. return "encrypted reaction"
  379. case waMsg.PollCreationMessage != nil:
  380. return "poll create"
  381. case waMsg.PollUpdateMessage != nil:
  382. return "poll update"
  383. case waMsg.ProtocolMessage != nil:
  384. switch waMsg.GetProtocolMessage().GetType() {
  385. case waProto.ProtocolMessage_REVOKE:
  386. if waMsg.GetProtocolMessage().GetKey() == nil {
  387. return "ignore"
  388. }
  389. return "revoke"
  390. case waProto.ProtocolMessage_MESSAGE_EDIT:
  391. return "edit"
  392. case waProto.ProtocolMessage_EPHEMERAL_SETTING:
  393. return "disappearing timer change"
  394. case waProto.ProtocolMessage_APP_STATE_SYNC_KEY_SHARE, waProto.ProtocolMessage_HISTORY_SYNC_NOTIFICATION, waProto.ProtocolMessage_INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC:
  395. return "ignore"
  396. default:
  397. return fmt.Sprintf("unknown_protocol_%d", waMsg.GetProtocolMessage().GetType())
  398. }
  399. case waMsg.ButtonsMessage != nil:
  400. return "buttons"
  401. case waMsg.ButtonsResponseMessage != nil:
  402. return "buttons response"
  403. case waMsg.TemplateMessage != nil:
  404. return "template"
  405. case waMsg.HighlyStructuredMessage != nil:
  406. return "highly structured template"
  407. case waMsg.TemplateButtonReplyMessage != nil:
  408. return "template button reply"
  409. case waMsg.InteractiveMessage != nil:
  410. return "interactive"
  411. case waMsg.ListMessage != nil:
  412. return "list"
  413. case waMsg.ProductMessage != nil:
  414. return "product"
  415. case waMsg.ListResponseMessage != nil:
  416. return "list response"
  417. case waMsg.OrderMessage != nil:
  418. return "order"
  419. case waMsg.InvoiceMessage != nil:
  420. return "invoice"
  421. case waMsg.SendPaymentMessage != nil, waMsg.RequestPaymentMessage != nil,
  422. waMsg.DeclinePaymentRequestMessage != nil, waMsg.CancelPaymentRequestMessage != nil,
  423. waMsg.PaymentInviteMessage != nil:
  424. return "payment"
  425. case waMsg.Call != nil:
  426. return "call"
  427. case waMsg.Chat != nil:
  428. return "chat"
  429. case waMsg.SenderKeyDistributionMessage != nil, waMsg.StickerSyncRmrMessage != nil:
  430. return "ignore"
  431. default:
  432. return "unknown"
  433. }
  434. }
  435. func pluralUnit(val int, name string) string {
  436. if val == 1 {
  437. return fmt.Sprintf("%d %s", val, name)
  438. } else if val == 0 {
  439. return ""
  440. }
  441. return fmt.Sprintf("%d %ss", val, name)
  442. }
  443. func naturalJoin(parts []string) string {
  444. if len(parts) == 0 {
  445. return ""
  446. } else if len(parts) == 1 {
  447. return parts[0]
  448. } else if len(parts) == 2 {
  449. return fmt.Sprintf("%s and %s", parts[0], parts[1])
  450. } else {
  451. return fmt.Sprintf("%s and %s", strings.Join(parts[:len(parts)-1], ", "), parts[len(parts)-1])
  452. }
  453. }
  454. func formatDuration(d time.Duration) string {
  455. const Day = time.Hour * 24
  456. var days, hours, minutes, seconds int
  457. days, d = int(d/Day), d%Day
  458. hours, d = int(d/time.Hour), d%time.Hour
  459. minutes, d = int(d/time.Minute), d%time.Minute
  460. seconds = int(d / time.Second)
  461. parts := make([]string, 0, 4)
  462. if days > 0 {
  463. parts = append(parts, pluralUnit(days, "day"))
  464. }
  465. if hours > 0 {
  466. parts = append(parts, pluralUnit(hours, "hour"))
  467. }
  468. if minutes > 0 {
  469. parts = append(parts, pluralUnit(seconds, "minute"))
  470. }
  471. if seconds > 0 {
  472. parts = append(parts, pluralUnit(seconds, "second"))
  473. }
  474. return naturalJoin(parts)
  475. }
  476. func (portal *Portal) convertMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, waMsg *waProto.Message, isBackfill bool) *ConvertedMessage {
  477. switch {
  478. case waMsg.Conversation != nil || waMsg.ExtendedTextMessage != nil:
  479. return portal.convertTextMessage(intent, source, waMsg)
  480. case waMsg.TemplateMessage != nil:
  481. return portal.convertTemplateMessage(intent, source, info, waMsg.GetTemplateMessage())
  482. case waMsg.HighlyStructuredMessage != nil:
  483. return portal.convertTemplateMessage(intent, source, info, waMsg.GetHighlyStructuredMessage().GetHydratedHsm())
  484. case waMsg.TemplateButtonReplyMessage != nil:
  485. return portal.convertTemplateButtonReplyMessage(intent, waMsg.GetTemplateButtonReplyMessage())
  486. case waMsg.ListMessage != nil:
  487. return portal.convertListMessage(intent, source, waMsg.GetListMessage())
  488. case waMsg.ListResponseMessage != nil:
  489. return portal.convertListResponseMessage(intent, waMsg.GetListResponseMessage())
  490. case waMsg.PollCreationMessage != nil:
  491. return portal.convertPollCreationMessage(intent, waMsg.GetPollCreationMessage())
  492. case waMsg.PollUpdateMessage != nil:
  493. return portal.convertPollUpdateMessage(intent, source, info, waMsg.GetPollUpdateMessage())
  494. case waMsg.ImageMessage != nil:
  495. return portal.convertMediaMessage(intent, source, info, waMsg.GetImageMessage(), "photo", isBackfill)
  496. case waMsg.StickerMessage != nil:
  497. return portal.convertMediaMessage(intent, source, info, waMsg.GetStickerMessage(), "sticker", isBackfill)
  498. case waMsg.VideoMessage != nil:
  499. return portal.convertMediaMessage(intent, source, info, waMsg.GetVideoMessage(), "video attachment", isBackfill)
  500. case waMsg.AudioMessage != nil:
  501. typeName := "audio attachment"
  502. if waMsg.GetAudioMessage().GetPtt() {
  503. typeName = "voice message"
  504. }
  505. return portal.convertMediaMessage(intent, source, info, waMsg.GetAudioMessage(), typeName, isBackfill)
  506. case waMsg.DocumentMessage != nil:
  507. return portal.convertMediaMessage(intent, source, info, waMsg.GetDocumentMessage(), "file attachment", isBackfill)
  508. case waMsg.ContactMessage != nil:
  509. return portal.convertContactMessage(intent, waMsg.GetContactMessage())
  510. case waMsg.ContactsArrayMessage != nil:
  511. return portal.convertContactsArrayMessage(intent, waMsg.GetContactsArrayMessage())
  512. case waMsg.LocationMessage != nil:
  513. return portal.convertLocationMessage(intent, waMsg.GetLocationMessage())
  514. case waMsg.LiveLocationMessage != nil:
  515. return portal.convertLiveLocationMessage(intent, waMsg.GetLiveLocationMessage())
  516. case waMsg.GroupInviteMessage != nil:
  517. return portal.convertGroupInviteMessage(intent, info, waMsg.GetGroupInviteMessage())
  518. case waMsg.ProtocolMessage != nil && waMsg.ProtocolMessage.GetType() == waProto.ProtocolMessage_EPHEMERAL_SETTING:
  519. portal.ExpirationTime = waMsg.ProtocolMessage.GetEphemeralExpiration()
  520. portal.Update(nil)
  521. return &ConvertedMessage{
  522. Intent: intent,
  523. Type: event.EventMessage,
  524. Content: &event.MessageEventContent{
  525. Body: portal.formatDisappearingMessageNotice(),
  526. MsgType: event.MsgNotice,
  527. },
  528. }
  529. default:
  530. return nil
  531. }
  532. }
  533. func (portal *Portal) UpdateGroupDisappearingMessages(sender *types.JID, timestamp time.Time, timer uint32) {
  534. if portal.ExpirationTime == timer {
  535. return
  536. }
  537. portal.ExpirationTime = timer
  538. portal.Update(nil)
  539. intent := portal.MainIntent()
  540. if sender != nil {
  541. intent = portal.bridge.GetPuppetByJID(sender.ToNonAD()).IntentFor(portal)
  542. } else {
  543. sender = &types.EmptyJID
  544. }
  545. _, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{
  546. Body: portal.formatDisappearingMessageNotice(),
  547. MsgType: event.MsgNotice,
  548. }, nil, timestamp.UnixMilli())
  549. if err != nil {
  550. portal.log.Warnfln("Failed to notify portal about disappearing message timer change by %s to %d", *sender, timer)
  551. }
  552. }
  553. func (portal *Portal) formatDisappearingMessageNotice() string {
  554. if portal.ExpirationTime == 0 {
  555. return "Turned off disappearing messages"
  556. } else {
  557. msg := fmt.Sprintf("Set the disappearing message timer to %s", formatDuration(time.Duration(portal.ExpirationTime)*time.Second))
  558. if !portal.bridge.Config.Bridge.DisappearingMessagesInGroups && portal.IsGroupChat() {
  559. msg += ". However, this bridge is not configured to disappear messages in group chats."
  560. }
  561. return msg
  562. }
  563. }
  564. const UndecryptableMessageNotice = "Decrypting message from WhatsApp failed, waiting for sender to re-send... " +
  565. "([learn more](https://faq.whatsapp.com/general/security-and-privacy/seeing-waiting-for-this-message-this-may-take-a-while))"
  566. var undecryptableMessageContent event.MessageEventContent
  567. func init() {
  568. undecryptableMessageContent = format.RenderMarkdown(UndecryptableMessageNotice, true, false)
  569. undecryptableMessageContent.MsgType = event.MsgNotice
  570. }
  571. func (portal *Portal) handleUndecryptableMessage(source *User, evt *events.UndecryptableMessage) {
  572. if len(portal.MXID) == 0 {
  573. portal.log.Warnln("handleUndecryptableMessage called even though portal.MXID is empty")
  574. return
  575. } else if portal.isRecentlyHandled(evt.Info.ID, database.MsgErrDecryptionFailed) {
  576. portal.log.Debugfln("Not handling %s (undecryptable): message was recently handled", evt.Info.ID)
  577. return
  578. } else if existingMsg := portal.bridge.DB.Message.GetByJID(portal.Key, evt.Info.ID); existingMsg != nil {
  579. portal.log.Debugfln("Not handling %s (undecryptable): message is duplicate", evt.Info.ID)
  580. return
  581. }
  582. metricType := "error"
  583. if evt.IsUnavailable {
  584. metricType = "unavailable"
  585. }
  586. Segment.Track(source.MXID, "WhatsApp undecryptable message", map[string]interface{}{
  587. "messageID": evt.Info.ID,
  588. "undecryptableType": metricType,
  589. })
  590. intent := portal.getMessageIntent(source, &evt.Info)
  591. if intent == nil {
  592. return
  593. } else if !intent.IsCustomPuppet && portal.IsPrivateChat() && evt.Info.Sender.User == portal.Key.Receiver.User {
  594. portal.log.Debugfln("Not handling %s (undecryptable): user doesn't have double puppeting enabled", evt.Info.ID)
  595. return
  596. }
  597. content := undecryptableMessageContent
  598. resp, err := portal.sendMessage(intent, event.EventMessage, &content, nil, evt.Info.Timestamp.UnixMilli())
  599. if err != nil {
  600. portal.log.Errorfln("Failed to send decryption error of %s to Matrix: %v", evt.Info.ID, err)
  601. return
  602. }
  603. portal.finishHandling(nil, &evt.Info, resp.EventID, database.MsgUnknown, database.MsgErrDecryptionFailed)
  604. }
  605. func (portal *Portal) handleFakeMessage(msg fakeMessage) {
  606. if portal.isRecentlyHandled(msg.ID, database.MsgNoError) {
  607. portal.log.Debugfln("Not handling %s (fake): message was recently handled", msg.ID)
  608. return
  609. } else if existingMsg := portal.bridge.DB.Message.GetByJID(portal.Key, msg.ID); existingMsg != nil {
  610. portal.log.Debugfln("Not handling %s (fake): message is duplicate", msg.ID)
  611. return
  612. }
  613. intent := portal.bridge.GetPuppetByJID(msg.Sender).IntentFor(portal)
  614. if !intent.IsCustomPuppet && portal.IsPrivateChat() && msg.Sender.User == portal.Key.Receiver.User {
  615. portal.log.Debugfln("Not handling %s (fake): user doesn't have double puppeting enabled", msg.ID)
  616. return
  617. }
  618. msgType := event.MsgNotice
  619. if msg.Important {
  620. msgType = event.MsgText
  621. }
  622. resp, err := portal.sendMessage(intent, event.EventMessage, &event.MessageEventContent{
  623. MsgType: msgType,
  624. Body: msg.Text,
  625. }, nil, msg.Time.UnixMilli())
  626. if err != nil {
  627. portal.log.Errorfln("Failed to send %s to Matrix: %v", msg.ID, err)
  628. } else {
  629. portal.finishHandling(nil, &types.MessageInfo{
  630. ID: msg.ID,
  631. Timestamp: msg.Time,
  632. MessageSource: types.MessageSource{
  633. Sender: msg.Sender,
  634. },
  635. }, resp.EventID, database.MsgFake, database.MsgNoError)
  636. }
  637. }
  638. func (portal *Portal) handleMessage(source *User, evt *events.Message) {
  639. if len(portal.MXID) == 0 {
  640. portal.log.Warnln("handleMessage called even though portal.MXID is empty")
  641. return
  642. }
  643. msgID := evt.Info.ID
  644. msgType := getMessageType(evt.Message)
  645. if msgType == "ignore" {
  646. return
  647. } else if portal.isRecentlyHandled(msgID, database.MsgNoError) {
  648. portal.log.Debugfln("Not handling %s (%s): message was recently handled", msgID, msgType)
  649. return
  650. }
  651. existingMsg := portal.bridge.DB.Message.GetByJID(portal.Key, msgID)
  652. if existingMsg != nil {
  653. if existingMsg.Error == database.MsgErrDecryptionFailed {
  654. Segment.Track(source.MXID, "WhatsApp undecryptable message resolved", map[string]interface{}{
  655. "messageID": evt.Info.ID,
  656. })
  657. portal.log.Debugfln("Got decryptable version of previously undecryptable message %s (%s)", msgID, msgType)
  658. } else {
  659. portal.log.Debugfln("Not handling %s (%s): message is duplicate", msgID, msgType)
  660. return
  661. }
  662. }
  663. var editTargetMsg *database.Message
  664. if msgType == "edit" {
  665. editTargetID := evt.Message.GetProtocolMessage().GetKey().GetId()
  666. editTargetMsg = portal.bridge.DB.Message.GetByJID(portal.Key, editTargetID)
  667. if editTargetMsg == nil {
  668. portal.log.Warnfln("Not handling %s: couldn't find edit target %s", msgID, editTargetID)
  669. return
  670. } else if editTargetMsg.Type != database.MsgNormal {
  671. portal.log.Warnfln("Not handling %s: edit target %s is not a normal message (it's %s)", msgID, editTargetID, editTargetMsg.Type)
  672. return
  673. } else if editTargetMsg.Sender.User != evt.Info.Sender.User {
  674. portal.log.Warnfln("Not handling %s: edit target %s was sent by %s, not %s", msgID, editTargetID, editTargetMsg.Sender.User, evt.Info.Sender.User)
  675. return
  676. }
  677. evt.Message = evt.Message.GetProtocolMessage().GetEditedMessage()
  678. }
  679. intent := portal.getMessageIntent(source, &evt.Info)
  680. if intent == nil {
  681. return
  682. } else if !intent.IsCustomPuppet && portal.IsPrivateChat() && evt.Info.Sender.User == portal.Key.Receiver.User {
  683. portal.log.Debugfln("Not handling %s (%s): user doesn't have double puppeting enabled", msgID, msgType)
  684. return
  685. }
  686. converted := portal.convertMessage(intent, source, &evt.Info, evt.Message, false)
  687. if converted != nil {
  688. if evt.Info.IsIncomingBroadcast() {
  689. if converted.Extra == nil {
  690. converted.Extra = map[string]interface{}{}
  691. }
  692. converted.Extra["fi.mau.whatsapp.source_broadcast_list"] = evt.Info.Chat.String()
  693. }
  694. if portal.bridge.Config.Bridge.CaptionInMessage {
  695. converted.MergeCaption()
  696. }
  697. var eventID id.EventID
  698. var lastEventID id.EventID
  699. if existingMsg != nil {
  700. portal.MarkDisappearing(nil, existingMsg.MXID, converted.ExpiresIn, false)
  701. converted.Content.SetEdit(existingMsg.MXID)
  702. } else if converted.ReplyTo != nil {
  703. portal.SetReply(converted.Content, converted.ReplyTo, false)
  704. }
  705. dbMsgType := database.MsgNormal
  706. if editTargetMsg != nil {
  707. dbMsgType = database.MsgEdit
  708. converted.Content.SetEdit(editTargetMsg.MXID)
  709. }
  710. resp, err := portal.sendMessage(converted.Intent, converted.Type, converted.Content, converted.Extra, evt.Info.Timestamp.UnixMilli())
  711. if err != nil {
  712. portal.log.Errorfln("Failed to send %s to Matrix: %v", msgID, err)
  713. } else {
  714. if editTargetMsg == nil {
  715. portal.MarkDisappearing(nil, resp.EventID, converted.ExpiresIn, false)
  716. }
  717. eventID = resp.EventID
  718. lastEventID = eventID
  719. }
  720. // TODO figure out how to handle captions with undecryptable messages turning decryptable
  721. if converted.Caption != nil && existingMsg == nil && editTargetMsg == nil {
  722. resp, err = portal.sendMessage(converted.Intent, converted.Type, converted.Caption, nil, evt.Info.Timestamp.UnixMilli())
  723. if err != nil {
  724. portal.log.Errorfln("Failed to send caption of %s to Matrix: %v", msgID, err)
  725. } else {
  726. portal.MarkDisappearing(nil, resp.EventID, converted.ExpiresIn, false)
  727. lastEventID = resp.EventID
  728. }
  729. }
  730. if converted.MultiEvent != nil && existingMsg == nil && editTargetMsg == nil {
  731. for index, subEvt := range converted.MultiEvent {
  732. resp, err = portal.sendMessage(converted.Intent, converted.Type, subEvt, nil, evt.Info.Timestamp.UnixMilli())
  733. if err != nil {
  734. portal.log.Errorfln("Failed to send sub-event %d of %s to Matrix: %v", index+1, msgID, err)
  735. } else {
  736. portal.MarkDisappearing(nil, resp.EventID, converted.ExpiresIn, false)
  737. lastEventID = resp.EventID
  738. }
  739. }
  740. }
  741. if source.MXID == intent.UserID && portal.bridge.Config.Homeserver.Software != bridgeconfig.SoftwareHungry {
  742. // There are some edge cases (like call notices) where previous messages aren't marked as read
  743. // when the user sends a message from another device, so just mark the new message as read to be safe.
  744. // Hungryserv does this automatically, so the bridge doesn't need to do it manually.
  745. err = intent.SetReadMarkers(portal.MXID, source.makeReadMarkerContent(lastEventID, true))
  746. if err != nil {
  747. portal.log.Warnfln("Failed to mark own message %s as read by %s: %v", lastEventID, source.MXID, err)
  748. }
  749. }
  750. if len(eventID) != 0 {
  751. portal.finishHandling(existingMsg, &evt.Info, eventID, dbMsgType, converted.Error)
  752. }
  753. } else if msgType == "reaction" || msgType == "encrypted reaction" {
  754. if evt.Message.GetEncReactionMessage() != nil {
  755. decryptedReaction, err := source.Client.DecryptReaction(evt)
  756. if err != nil {
  757. portal.log.Errorfln("Failed to decrypt reaction from %s to %s: %v", evt.Info.Sender, evt.Message.GetEncReactionMessage().GetTargetMessageKey().GetId(), err)
  758. } else {
  759. portal.HandleMessageReaction(intent, source, &evt.Info, decryptedReaction, existingMsg)
  760. }
  761. } else {
  762. portal.HandleMessageReaction(intent, source, &evt.Info, evt.Message.GetReactionMessage(), existingMsg)
  763. }
  764. } else if msgType == "revoke" {
  765. portal.HandleMessageRevoke(source, &evt.Info, evt.Message.GetProtocolMessage().GetKey())
  766. if existingMsg != nil {
  767. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  768. Reason: "The undecryptable message was actually the deletion of another message",
  769. })
  770. existingMsg.UpdateMXID(nil, "net.maunium.whatsapp.fake::"+existingMsg.MXID, database.MsgFake, database.MsgNoError)
  771. }
  772. } else {
  773. portal.log.Warnfln("Unhandled message: %+v (%s)", evt.Info, msgType)
  774. if existingMsg != nil {
  775. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  776. Reason: "The undecryptable message contained an unsupported message type",
  777. })
  778. existingMsg.UpdateMXID(nil, "net.maunium.whatsapp.fake::"+existingMsg.MXID, database.MsgFake, database.MsgNoError)
  779. }
  780. return
  781. }
  782. portal.bridge.Metrics.TrackWhatsAppMessage(evt.Info.Timestamp, strings.Split(msgType, " ")[0])
  783. }
  784. func (portal *Portal) isRecentlyHandled(id types.MessageID, error database.MessageErrorType) bool {
  785. start := portal.recentlyHandledIndex
  786. lookingForMsg := recentlyHandledWrapper{id, error}
  787. for i := start; i != start; i = (i - 1) % recentlyHandledLength {
  788. if portal.recentlyHandled[i] == lookingForMsg {
  789. return true
  790. }
  791. }
  792. return false
  793. }
  794. func (portal *Portal) markHandled(txn dbutil.Transaction, msg *database.Message, info *types.MessageInfo, mxid id.EventID, isSent, recent bool, msgType database.MessageType, errType database.MessageErrorType) *database.Message {
  795. if msg == nil {
  796. msg = portal.bridge.DB.Message.New()
  797. msg.Chat = portal.Key
  798. msg.JID = info.ID
  799. msg.MXID = mxid
  800. msg.Timestamp = info.Timestamp
  801. msg.Sender = info.Sender
  802. msg.Sent = isSent
  803. msg.Type = msgType
  804. msg.Error = errType
  805. if info.IsIncomingBroadcast() {
  806. msg.BroadcastListJID = info.Chat
  807. }
  808. msg.Insert(txn)
  809. } else {
  810. msg.UpdateMXID(txn, mxid, msgType, errType)
  811. }
  812. if recent {
  813. portal.recentlyHandledLock.Lock()
  814. index := portal.recentlyHandledIndex
  815. portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength
  816. portal.recentlyHandledLock.Unlock()
  817. portal.recentlyHandled[index] = recentlyHandledWrapper{msg.JID, errType}
  818. }
  819. return msg
  820. }
  821. func (portal *Portal) getMessagePuppet(user *User, info *types.MessageInfo) (puppet *Puppet) {
  822. if info.IsFromMe {
  823. return portal.bridge.GetPuppetByJID(user.JID)
  824. } else if portal.IsPrivateChat() {
  825. puppet = portal.bridge.GetPuppetByJID(portal.Key.JID)
  826. } else if !info.Sender.IsEmpty() {
  827. puppet = portal.bridge.GetPuppetByJID(info.Sender)
  828. }
  829. if puppet == nil {
  830. portal.log.Warnfln("Message %+v doesn't seem to have a valid sender (%s): puppet is nil", *info, info.Sender)
  831. return nil
  832. }
  833. user.EnqueuePortalResync(portal)
  834. puppet.SyncContact(user, true, true, "handling message")
  835. return puppet
  836. }
  837. func (portal *Portal) getMessageIntent(user *User, info *types.MessageInfo) *appservice.IntentAPI {
  838. puppet := portal.getMessagePuppet(user, info)
  839. if puppet == nil {
  840. return nil
  841. }
  842. return puppet.IntentFor(portal)
  843. }
  844. func (portal *Portal) finishHandling(existing *database.Message, message *types.MessageInfo, mxid id.EventID, msgType database.MessageType, errType database.MessageErrorType) {
  845. portal.markHandled(nil, existing, message, mxid, true, true, msgType, errType)
  846. portal.sendDeliveryReceipt(mxid)
  847. var suffix string
  848. if errType == database.MsgErrDecryptionFailed {
  849. suffix = "(undecryptable message error notice)"
  850. } else if errType == database.MsgErrMediaNotFound {
  851. suffix = "(media not found notice)"
  852. }
  853. portal.log.Debugfln("Handled message %s (%s) -> %s %s", message.ID, msgType, mxid, suffix)
  854. }
  855. func (portal *Portal) kickExtraUsers(participantMap map[types.JID]bool) {
  856. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  857. if err != nil {
  858. portal.log.Warnln("Failed to get member list:", err)
  859. return
  860. }
  861. for member := range members.Joined {
  862. jid, ok := portal.bridge.ParsePuppetMXID(member)
  863. if ok {
  864. _, shouldBePresent := participantMap[jid]
  865. if !shouldBePresent {
  866. _, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  867. UserID: member,
  868. Reason: "User had left this WhatsApp chat",
  869. })
  870. if err != nil {
  871. portal.log.Warnfln("Failed to kick user %s who had left: %v", member, err)
  872. }
  873. }
  874. }
  875. }
  876. }
  877. //func (portal *Portal) SyncBroadcastRecipients(source *User, metadata *whatsapp.BroadcastListInfo) {
  878. // participantMap := make(map[whatsapp.JID]bool)
  879. // for _, recipient := range metadata.Recipients {
  880. // participantMap[recipient.JID] = true
  881. //
  882. // puppet := portal.bridge.GetPuppetByJID(recipient.JID)
  883. // puppet.SyncContactIfNecessary(source)
  884. // err := puppet.DefaultIntent().EnsureJoined(portal.MXID)
  885. // if err != nil {
  886. // portal.log.Warnfln("Failed to make puppet of %s join %s: %v", recipient.JID, portal.MXID, err)
  887. // }
  888. // }
  889. // portal.kickExtraUsers(participantMap)
  890. //}
  891. func (portal *Portal) syncParticipant(source *User, participant types.GroupParticipant, puppet *Puppet, user *User, wg *sync.WaitGroup) {
  892. defer func() {
  893. wg.Done()
  894. if err := recover(); err != nil {
  895. portal.log.Errorfln("Syncing participant %s panicked: %v\n%s", participant.JID, err, debug.Stack())
  896. }
  897. }()
  898. puppet.SyncContact(source, true, false, "group participant")
  899. if portal.MXID != "" {
  900. if user != nil && user != source {
  901. portal.ensureUserInvited(user)
  902. }
  903. if user == nil || !puppet.IntentFor(portal).IsCustomPuppet {
  904. err := puppet.IntentFor(portal).EnsureJoined(portal.MXID)
  905. if err != nil {
  906. portal.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.JID, portal.MXID, err)
  907. }
  908. }
  909. }
  910. }
  911. func (portal *Portal) SyncParticipants(source *User, metadata *types.GroupInfo) ([]id.UserID, *event.PowerLevelsEventContent) {
  912. changed := false
  913. var levels *event.PowerLevelsEventContent
  914. var err error
  915. if portal.MXID != "" {
  916. levels, err = portal.MainIntent().PowerLevels(portal.MXID)
  917. }
  918. if levels == nil || err != nil {
  919. levels = portal.GetBasePowerLevels()
  920. changed = true
  921. }
  922. changed = portal.applyPowerLevelFixes(levels) || changed
  923. var wg sync.WaitGroup
  924. wg.Add(len(metadata.Participants))
  925. participantMap := make(map[types.JID]bool)
  926. userIDs := make([]id.UserID, 0, len(metadata.Participants))
  927. for _, participant := range metadata.Participants {
  928. portal.log.Debugfln("Syncing participant %s (admin: %t)", participant.JID, participant.IsAdmin)
  929. participantMap[participant.JID] = true
  930. puppet := portal.bridge.GetPuppetByJID(participant.JID)
  931. user := portal.bridge.GetUserByJID(participant.JID)
  932. if portal.bridge.Config.Bridge.ParallelMemberSync {
  933. go portal.syncParticipant(source, participant, puppet, user, &wg)
  934. } else {
  935. portal.syncParticipant(source, participant, puppet, user, &wg)
  936. }
  937. expectedLevel := 0
  938. if participant.IsSuperAdmin {
  939. expectedLevel = 95
  940. } else if participant.IsAdmin {
  941. expectedLevel = 50
  942. }
  943. changed = levels.EnsureUserLevel(puppet.MXID, expectedLevel) || changed
  944. if user != nil {
  945. userIDs = append(userIDs, user.MXID)
  946. changed = levels.EnsureUserLevel(user.MXID, expectedLevel) || changed
  947. }
  948. if user == nil || puppet.CustomMXID != user.MXID {
  949. userIDs = append(userIDs, puppet.MXID)
  950. }
  951. }
  952. if portal.MXID != "" {
  953. if changed {
  954. _, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  955. if err != nil {
  956. portal.log.Errorln("Failed to change power levels:", err)
  957. }
  958. }
  959. portal.kickExtraUsers(participantMap)
  960. }
  961. wg.Wait()
  962. portal.log.Debugln("Participant sync completed")
  963. return userIDs, levels
  964. }
  965. func reuploadAvatar(intent *appservice.IntentAPI, url string) (id.ContentURI, error) {
  966. getResp, err := http.DefaultClient.Get(url)
  967. if err != nil {
  968. return id.ContentURI{}, fmt.Errorf("failed to download avatar: %w", err)
  969. }
  970. data, err := io.ReadAll(getResp.Body)
  971. _ = getResp.Body.Close()
  972. if err != nil {
  973. return id.ContentURI{}, fmt.Errorf("failed to read avatar bytes: %w", err)
  974. }
  975. resp, err := intent.UploadBytes(data, http.DetectContentType(data))
  976. if err != nil {
  977. return id.ContentURI{}, fmt.Errorf("failed to upload avatar to Matrix: %w", err)
  978. }
  979. return resp.ContentURI, nil
  980. }
  981. func (user *User) updateAvatar(jid types.JID, isCommunity bool, avatarID *string, avatarURL *id.ContentURI, avatarSet *bool, log log.Logger, intent *appservice.IntentAPI) bool {
  982. currentID := ""
  983. if *avatarSet && *avatarID != "remove" && *avatarID != "unauthorized" {
  984. currentID = *avatarID
  985. }
  986. avatar, err := user.Client.GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{
  987. Preview: false,
  988. ExistingID: currentID,
  989. IsCommunity: isCommunity,
  990. })
  991. if errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) {
  992. if *avatarID == "" {
  993. *avatarID = "unauthorized"
  994. *avatarSet = false
  995. return true
  996. }
  997. return false
  998. } else if errors.Is(err, whatsmeow.ErrProfilePictureNotSet) {
  999. avatar = &types.ProfilePictureInfo{ID: "remove"}
  1000. if avatar.ID == *avatarID && *avatarSet {
  1001. return false
  1002. }
  1003. *avatarID = avatar.ID
  1004. *avatarURL = id.ContentURI{}
  1005. return true
  1006. } else if err != nil {
  1007. log.Warnln("Failed to get avatar URL:", err)
  1008. return false
  1009. } else if avatar == nil {
  1010. // Avatar hasn't changed
  1011. return false
  1012. }
  1013. if avatar.ID == *avatarID && *avatarSet {
  1014. return false
  1015. } else if len(avatar.URL) == 0 {
  1016. log.Warnln("Didn't get URL in response to avatar query")
  1017. return false
  1018. } else if avatar.ID != *avatarID || avatarURL.IsEmpty() {
  1019. url, err := reuploadAvatar(intent, avatar.URL)
  1020. if err != nil {
  1021. log.Warnln("Failed to reupload avatar:", err)
  1022. return false
  1023. }
  1024. *avatarURL = url
  1025. }
  1026. log.Debugfln("Updated avatar %s -> %s", *avatarID, avatar.ID)
  1027. *avatarID = avatar.ID
  1028. *avatarSet = false
  1029. return true
  1030. }
  1031. func (portal *Portal) UpdateAvatar(user *User, setBy types.JID, updateInfo bool) bool {
  1032. portal.avatarLock.Lock()
  1033. defer portal.avatarLock.Unlock()
  1034. changed := user.updateAvatar(portal.Key.JID, portal.IsParent, &portal.Avatar, &portal.AvatarURL, &portal.AvatarSet, portal.log, portal.MainIntent())
  1035. if !changed || portal.Avatar == "unauthorized" {
  1036. if changed || updateInfo {
  1037. portal.Update(nil)
  1038. }
  1039. return changed
  1040. }
  1041. if len(portal.MXID) > 0 {
  1042. intent := portal.MainIntent()
  1043. if !setBy.IsEmpty() {
  1044. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  1045. }
  1046. _, err := intent.SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1047. if errors.Is(err, mautrix.MForbidden) && intent != portal.MainIntent() {
  1048. _, err = portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
  1049. }
  1050. if err != nil {
  1051. portal.log.Warnln("Failed to set room avatar:", err)
  1052. return true
  1053. } else {
  1054. portal.AvatarSet = true
  1055. }
  1056. }
  1057. if updateInfo {
  1058. portal.UpdateBridgeInfo()
  1059. portal.Update(nil)
  1060. portal.updateChildRooms()
  1061. }
  1062. return true
  1063. }
  1064. func (portal *Portal) UpdateName(name string, setBy types.JID, updateInfo bool) bool {
  1065. if name == "" && portal.IsBroadcastList() {
  1066. name = UnnamedBroadcastName
  1067. }
  1068. if portal.Name != name || (!portal.NameSet && len(portal.MXID) > 0) {
  1069. portal.log.Debugfln("Updating name %q -> %q", portal.Name, name)
  1070. portal.Name = name
  1071. portal.NameSet = false
  1072. if updateInfo {
  1073. defer portal.Update(nil)
  1074. }
  1075. if len(portal.MXID) > 0 {
  1076. intent := portal.MainIntent()
  1077. if !setBy.IsEmpty() {
  1078. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  1079. }
  1080. _, err := intent.SetRoomName(portal.MXID, name)
  1081. if errors.Is(err, mautrix.MForbidden) && intent != portal.MainIntent() {
  1082. _, err = portal.MainIntent().SetRoomName(portal.MXID, name)
  1083. }
  1084. if err == nil {
  1085. portal.NameSet = true
  1086. if updateInfo {
  1087. portal.UpdateBridgeInfo()
  1088. portal.updateChildRooms()
  1089. }
  1090. return true
  1091. } else {
  1092. portal.log.Warnln("Failed to set room name:", err)
  1093. }
  1094. }
  1095. }
  1096. return false
  1097. }
  1098. func (portal *Portal) UpdateTopic(topic string, setBy types.JID, updateInfo bool) bool {
  1099. if portal.Topic != topic || !portal.TopicSet {
  1100. portal.log.Debugfln("Updating topic %q -> %q", portal.Topic, topic)
  1101. portal.Topic = topic
  1102. portal.TopicSet = false
  1103. intent := portal.MainIntent()
  1104. if !setBy.IsEmpty() {
  1105. intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
  1106. }
  1107. _, err := intent.SetRoomTopic(portal.MXID, topic)
  1108. if errors.Is(err, mautrix.MForbidden) && intent != portal.MainIntent() {
  1109. _, err = portal.MainIntent().SetRoomTopic(portal.MXID, topic)
  1110. }
  1111. if err == nil {
  1112. portal.TopicSet = true
  1113. if updateInfo {
  1114. portal.UpdateBridgeInfo()
  1115. portal.Update(nil)
  1116. }
  1117. return true
  1118. } else {
  1119. portal.log.Warnln("Failed to set room topic:", err)
  1120. }
  1121. }
  1122. return false
  1123. }
  1124. func (portal *Portal) UpdateParentGroup(source *User, parent types.JID, updateInfo bool) bool {
  1125. portal.parentGroupUpdateLock.Lock()
  1126. defer portal.parentGroupUpdateLock.Unlock()
  1127. if portal.ParentGroup != parent {
  1128. portal.log.Debugfln("Updating parent group %v -> %v", portal.ParentGroup, parent)
  1129. portal.updateCommunitySpace(source, false, false)
  1130. portal.ParentGroup = parent
  1131. portal.parentPortal = nil
  1132. portal.InSpace = false
  1133. portal.updateCommunitySpace(source, true, false)
  1134. if updateInfo {
  1135. portal.UpdateBridgeInfo()
  1136. portal.Update(nil)
  1137. }
  1138. return true
  1139. } else if !portal.ParentGroup.IsEmpty() && !portal.InSpace {
  1140. return portal.updateCommunitySpace(source, true, updateInfo)
  1141. }
  1142. return false
  1143. }
  1144. func (portal *Portal) UpdateMetadata(user *User, groupInfo *types.GroupInfo) bool {
  1145. if portal.IsPrivateChat() {
  1146. return false
  1147. } else if portal.IsStatusBroadcastList() {
  1148. update := false
  1149. update = portal.UpdateName(StatusBroadcastName, types.EmptyJID, false) || update
  1150. update = portal.UpdateTopic(StatusBroadcastTopic, types.EmptyJID, false) || update
  1151. return update
  1152. } else if portal.IsBroadcastList() {
  1153. update := false
  1154. //broadcastMetadata, err := user.Conn.GetBroadcastMetadata(portal.Key.JID)
  1155. //if err == nil && broadcastMetadata.Status == 200 {
  1156. // portal.SyncBroadcastRecipients(user, broadcastMetadata)
  1157. // update = portal.UpdateName(broadcastMetadata.Name, "", nil, false) || update
  1158. //} else {
  1159. // user.Conn.Store.ContactsLock.RLock()
  1160. // contact, _ := user.Conn.Store.Contacts[portal.Key.JID]
  1161. // user.Conn.Store.ContactsLock.RUnlock()
  1162. // update = portal.UpdateName(contact.Name, "", nil, false) || update
  1163. //}
  1164. //update = portal.UpdateTopic(BroadcastTopic, "", nil, false) || update
  1165. return update
  1166. }
  1167. if groupInfo == nil {
  1168. var err error
  1169. groupInfo, err = user.Client.GetGroupInfo(portal.Key.JID)
  1170. if err != nil {
  1171. portal.log.Errorln("Failed to get group info:", err)
  1172. return false
  1173. }
  1174. }
  1175. portal.SyncParticipants(user, groupInfo)
  1176. update := false
  1177. update = portal.UpdateName(groupInfo.Name, groupInfo.NameSetBy, false) || update
  1178. update = portal.UpdateTopic(groupInfo.Topic, groupInfo.TopicSetBy, false) || update
  1179. update = portal.UpdateParentGroup(user, groupInfo.LinkedParentJID, false) || update
  1180. if portal.ExpirationTime != groupInfo.DisappearingTimer {
  1181. update = true
  1182. portal.ExpirationTime = groupInfo.DisappearingTimer
  1183. }
  1184. if portal.IsParent != groupInfo.IsParent {
  1185. if portal.MXID != "" {
  1186. portal.log.Warnfln("Existing group changed is_parent from %t to %t", portal.IsParent, groupInfo.IsParent)
  1187. }
  1188. portal.IsParent = groupInfo.IsParent
  1189. update = true
  1190. }
  1191. portal.RestrictMessageSending(groupInfo.IsAnnounce)
  1192. portal.RestrictMetadataChanges(groupInfo.IsLocked)
  1193. return update
  1194. }
  1195. func (portal *Portal) ensureUserInvited(user *User) bool {
  1196. return user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat())
  1197. }
  1198. func (portal *Portal) UpdateMatrixRoom(user *User, groupInfo *types.GroupInfo) bool {
  1199. if len(portal.MXID) == 0 {
  1200. return false
  1201. }
  1202. portal.log.Infoln("Syncing portal for", user.MXID)
  1203. portal.ensureUserInvited(user)
  1204. go portal.addToPersonalSpace(user)
  1205. update := false
  1206. update = portal.UpdateMetadata(user, groupInfo) || update
  1207. if !portal.IsPrivateChat() && !portal.IsBroadcastList() {
  1208. update = portal.UpdateAvatar(user, types.EmptyJID, false) || update
  1209. }
  1210. if update || portal.LastSync.Add(24*time.Hour).Before(time.Now()) {
  1211. portal.LastSync = time.Now()
  1212. portal.Update(nil)
  1213. portal.UpdateBridgeInfo()
  1214. portal.updateChildRooms()
  1215. }
  1216. return true
  1217. }
  1218. func (portal *Portal) GetBasePowerLevels() *event.PowerLevelsEventContent {
  1219. anyone := 0
  1220. nope := 99
  1221. invite := 50
  1222. if portal.bridge.Config.Bridge.AllowUserInvite {
  1223. invite = 0
  1224. }
  1225. return &event.PowerLevelsEventContent{
  1226. UsersDefault: anyone,
  1227. EventsDefault: anyone,
  1228. RedactPtr: &anyone,
  1229. StateDefaultPtr: &nope,
  1230. BanPtr: &nope,
  1231. InvitePtr: &invite,
  1232. Users: map[id.UserID]int{
  1233. portal.MainIntent().UserID: 100,
  1234. },
  1235. Events: map[string]int{
  1236. event.StateRoomName.Type: anyone,
  1237. event.StateRoomAvatar.Type: anyone,
  1238. event.StateTopic.Type: anyone,
  1239. event.EventReaction.Type: anyone,
  1240. event.EventRedaction.Type: anyone,
  1241. },
  1242. }
  1243. }
  1244. func (portal *Portal) applyPowerLevelFixes(levels *event.PowerLevelsEventContent) bool {
  1245. changed := false
  1246. changed = levels.EnsureEventLevel(event.EventReaction, 0) || changed
  1247. changed = levels.EnsureEventLevel(event.EventRedaction, 0) || changed
  1248. return changed
  1249. }
  1250. func (portal *Portal) ChangeAdminStatus(jids []types.JID, setAdmin bool) id.EventID {
  1251. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1252. if err != nil {
  1253. levels = portal.GetBasePowerLevels()
  1254. }
  1255. newLevel := 0
  1256. if setAdmin {
  1257. newLevel = 50
  1258. }
  1259. changed := portal.applyPowerLevelFixes(levels)
  1260. for _, jid := range jids {
  1261. puppet := portal.bridge.GetPuppetByJID(jid)
  1262. changed = levels.EnsureUserLevel(puppet.MXID, newLevel) || changed
  1263. user := portal.bridge.GetUserByJID(jid)
  1264. if user != nil {
  1265. changed = levels.EnsureUserLevel(user.MXID, newLevel) || changed
  1266. }
  1267. }
  1268. if changed {
  1269. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1270. if err != nil {
  1271. portal.log.Errorln("Failed to change power levels:", err)
  1272. } else {
  1273. return resp.EventID
  1274. }
  1275. }
  1276. return ""
  1277. }
  1278. func (portal *Portal) RestrictMessageSending(restrict bool) id.EventID {
  1279. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1280. if err != nil {
  1281. levels = portal.GetBasePowerLevels()
  1282. }
  1283. newLevel := 0
  1284. if restrict {
  1285. newLevel = 50
  1286. }
  1287. changed := portal.applyPowerLevelFixes(levels)
  1288. if levels.EventsDefault == newLevel && !changed {
  1289. return ""
  1290. }
  1291. levels.EventsDefault = newLevel
  1292. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1293. if err != nil {
  1294. portal.log.Errorln("Failed to change power levels:", err)
  1295. return ""
  1296. } else {
  1297. return resp.EventID
  1298. }
  1299. }
  1300. func (portal *Portal) RestrictMetadataChanges(restrict bool) id.EventID {
  1301. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1302. if err != nil {
  1303. levels = portal.GetBasePowerLevels()
  1304. }
  1305. newLevel := 0
  1306. if restrict {
  1307. newLevel = 50
  1308. }
  1309. changed := portal.applyPowerLevelFixes(levels)
  1310. changed = levels.EnsureEventLevel(event.StateRoomName, newLevel) || changed
  1311. changed = levels.EnsureEventLevel(event.StateRoomAvatar, newLevel) || changed
  1312. changed = levels.EnsureEventLevel(event.StateTopic, newLevel) || changed
  1313. if changed {
  1314. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1315. if err != nil {
  1316. portal.log.Errorln("Failed to change power levels:", err)
  1317. } else {
  1318. return resp.EventID
  1319. }
  1320. }
  1321. return ""
  1322. }
  1323. func (portal *Portal) getBridgeInfoStateKey() string {
  1324. return fmt.Sprintf("net.maunium.whatsapp://whatsapp/%s", portal.Key.JID)
  1325. }
  1326. func (portal *Portal) getBridgeInfo() (string, event.BridgeEventContent) {
  1327. bridgeInfo := event.BridgeEventContent{
  1328. BridgeBot: portal.bridge.Bot.UserID,
  1329. Creator: portal.MainIntent().UserID,
  1330. Protocol: event.BridgeInfoSection{
  1331. ID: "whatsapp",
  1332. DisplayName: "WhatsApp",
  1333. AvatarURL: portal.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
  1334. ExternalURL: "https://www.whatsapp.com/",
  1335. },
  1336. Channel: event.BridgeInfoSection{
  1337. ID: portal.Key.JID.String(),
  1338. DisplayName: portal.Name,
  1339. AvatarURL: portal.AvatarURL.CUString(),
  1340. },
  1341. }
  1342. if parent := portal.GetParentPortal(); parent != nil {
  1343. bridgeInfo.Network = &event.BridgeInfoSection{
  1344. ID: parent.Key.JID.String(),
  1345. DisplayName: parent.Name,
  1346. AvatarURL: parent.AvatarURL.CUString(),
  1347. }
  1348. }
  1349. return portal.getBridgeInfoStateKey(), bridgeInfo
  1350. }
  1351. func (portal *Portal) UpdateBridgeInfo() {
  1352. if len(portal.MXID) == 0 {
  1353. portal.log.Debugln("Not updating bridge info: no Matrix room created")
  1354. return
  1355. }
  1356. portal.log.Debugln("Updating bridge info...")
  1357. stateKey, content := portal.getBridgeInfo()
  1358. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateBridge, stateKey, content)
  1359. if err != nil {
  1360. portal.log.Warnln("Failed to update m.bridge:", err)
  1361. }
  1362. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1363. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
  1364. if err != nil {
  1365. portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
  1366. }
  1367. }
  1368. func (portal *Portal) updateChildRooms() {
  1369. if !portal.IsParent {
  1370. return
  1371. }
  1372. children := portal.bridge.GetAllByParentGroup(portal.Key.JID)
  1373. for _, child := range children {
  1374. changed := child.updateCommunitySpace(nil, true, false)
  1375. child.UpdateBridgeInfo()
  1376. if changed {
  1377. portal.Update(nil)
  1378. }
  1379. }
  1380. }
  1381. func (portal *Portal) GetEncryptionEventContent() (evt *event.EncryptionEventContent) {
  1382. evt = &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1}
  1383. if rot := portal.bridge.Config.Bridge.Encryption.Rotation; rot.EnableCustom {
  1384. evt.RotationPeriodMillis = rot.Milliseconds
  1385. evt.RotationPeriodMessages = rot.Messages
  1386. }
  1387. return
  1388. }
  1389. func (portal *Portal) CreateMatrixRoom(user *User, groupInfo *types.GroupInfo, isFullInfo, backfill bool) error {
  1390. portal.roomCreateLock.Lock()
  1391. defer portal.roomCreateLock.Unlock()
  1392. if len(portal.MXID) > 0 {
  1393. return nil
  1394. }
  1395. intent := portal.MainIntent()
  1396. if err := intent.EnsureRegistered(); err != nil {
  1397. return err
  1398. }
  1399. portal.log.Infoln("Creating Matrix room. Info source:", user.MXID)
  1400. //var broadcastMetadata *types.BroadcastListInfo
  1401. if portal.IsPrivateChat() {
  1402. puppet := portal.bridge.GetPuppetByJID(portal.Key.JID)
  1403. puppet.SyncContact(user, true, false, "creating private chat portal")
  1404. if portal.bridge.Config.Bridge.PrivateChatPortalMeta || portal.bridge.Config.Bridge.Encryption.Default {
  1405. portal.Name = puppet.Displayname
  1406. portal.AvatarURL = puppet.AvatarURL
  1407. portal.Avatar = puppet.Avatar
  1408. } else {
  1409. portal.Name = ""
  1410. }
  1411. portal.Topic = PrivateChatTopic
  1412. } else if portal.IsStatusBroadcastList() {
  1413. if !portal.bridge.Config.Bridge.EnableStatusBroadcast {
  1414. portal.log.Debugln("Status bridging is disabled in config, not creating room after all")
  1415. return ErrStatusBroadcastDisabled
  1416. }
  1417. portal.Name = StatusBroadcastName
  1418. portal.Topic = StatusBroadcastTopic
  1419. } else if portal.IsBroadcastList() {
  1420. //var err error
  1421. //broadcastMetadata, err = user.Conn.GetBroadcastMetadata(portal.Key.JID)
  1422. //if err == nil && broadcastMetadata.Status == 200 {
  1423. // portal.Name = broadcastMetadata.Name
  1424. //} else {
  1425. // user.Conn.Store.ContactsLock.RLock()
  1426. // contact, _ := user.Conn.Store.Contacts[portal.Key.JID]
  1427. // user.Conn.Store.ContactsLock.RUnlock()
  1428. // portal.Name = contact.Name
  1429. //}
  1430. //if len(portal.Name) == 0 {
  1431. // portal.Name = UnnamedBroadcastName
  1432. //}
  1433. //portal.Topic = BroadcastTopic
  1434. portal.log.Debugln("Broadcast list is not yet supported, not creating room after all")
  1435. return fmt.Errorf("broadcast list bridging is currently not supported")
  1436. } else {
  1437. if groupInfo == nil || !isFullInfo {
  1438. foundInfo, err := user.Client.GetGroupInfo(portal.Key.JID)
  1439. // Ensure that the user is actually a participant in the conversation
  1440. // before creating the matrix room
  1441. if errors.Is(err, whatsmeow.ErrNotInGroup) {
  1442. user.log.Debugfln("Skipping creating matrix room for %s because the user is not a participant", portal.Key.JID)
  1443. user.bridge.DB.Backfill.DeleteAllForPortal(user.MXID, portal.Key)
  1444. user.bridge.DB.HistorySync.DeleteAllMessagesForPortal(user.MXID, portal.Key)
  1445. return err
  1446. } else if err != nil {
  1447. portal.log.Warnfln("Failed to get group info through %s: %v", user.JID, err)
  1448. } else {
  1449. groupInfo = foundInfo
  1450. isFullInfo = true
  1451. }
  1452. }
  1453. if groupInfo != nil {
  1454. portal.Name = groupInfo.Name
  1455. portal.Topic = groupInfo.Topic
  1456. portal.IsParent = groupInfo.IsParent
  1457. portal.ParentGroup = groupInfo.LinkedParentJID
  1458. if groupInfo.IsEphemeral {
  1459. portal.ExpirationTime = groupInfo.DisappearingTimer
  1460. }
  1461. }
  1462. portal.UpdateAvatar(user, types.EmptyJID, false)
  1463. }
  1464. powerLevels := portal.GetBasePowerLevels()
  1465. if groupInfo != nil {
  1466. if groupInfo.IsAnnounce {
  1467. powerLevels.EventsDefault = 50
  1468. }
  1469. if groupInfo.IsLocked {
  1470. powerLevels.EnsureEventLevel(event.StateRoomName, 50)
  1471. powerLevels.EnsureEventLevel(event.StateRoomAvatar, 50)
  1472. powerLevels.EnsureEventLevel(event.StateTopic, 50)
  1473. }
  1474. }
  1475. bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
  1476. initialState := []*event.Event{{
  1477. Type: event.StatePowerLevels,
  1478. Content: event.Content{
  1479. Parsed: powerLevels,
  1480. },
  1481. }, {
  1482. Type: event.StateBridge,
  1483. Content: event.Content{Parsed: bridgeInfo},
  1484. StateKey: &bridgeInfoStateKey,
  1485. }, {
  1486. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1487. Type: event.StateHalfShotBridge,
  1488. Content: event.Content{Parsed: bridgeInfo},
  1489. StateKey: &bridgeInfoStateKey,
  1490. }}
  1491. if !portal.AvatarURL.IsEmpty() {
  1492. initialState = append(initialState, &event.Event{
  1493. Type: event.StateRoomAvatar,
  1494. Content: event.Content{
  1495. Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL},
  1496. },
  1497. })
  1498. portal.AvatarSet = true
  1499. }
  1500. var invite []id.UserID
  1501. if portal.bridge.Config.Bridge.Encryption.Default {
  1502. initialState = append(initialState, &event.Event{
  1503. Type: event.StateEncryption,
  1504. Content: event.Content{
  1505. Parsed: portal.GetEncryptionEventContent(),
  1506. },
  1507. })
  1508. portal.Encrypted = true
  1509. if portal.IsPrivateChat() {
  1510. invite = append(invite, portal.bridge.Bot.UserID)
  1511. }
  1512. }
  1513. creationContent := make(map[string]interface{})
  1514. if !portal.bridge.Config.Bridge.FederateRooms {
  1515. creationContent["m.federate"] = false
  1516. }
  1517. if portal.IsParent {
  1518. creationContent["type"] = event.RoomTypeSpace
  1519. } else if parent := portal.GetParentPortal(); parent != nil && parent.MXID != "" {
  1520. initialState = append(initialState, &event.Event{
  1521. Type: event.StateSpaceParent,
  1522. StateKey: proto.String(parent.MXID.String()),
  1523. Content: event.Content{
  1524. Parsed: &event.SpaceParentEventContent{
  1525. Via: []string{portal.bridge.Config.Homeserver.Domain},
  1526. Canonical: true,
  1527. },
  1528. },
  1529. })
  1530. }
  1531. autoJoinInvites := portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry
  1532. if autoJoinInvites {
  1533. portal.log.Debugfln("Hungryserv mode: adding all group members in create request")
  1534. if groupInfo != nil {
  1535. // TODO non-hungryserv could also include all members in invites, and then send joins manually?
  1536. participants, powerLevels := portal.SyncParticipants(user, groupInfo)
  1537. invite = append(invite, participants...)
  1538. if initialState[0].Type != event.StatePowerLevels {
  1539. panic(fmt.Errorf("unexpected type %s in first initial state event", initialState[0].Type.Type))
  1540. }
  1541. initialState[0].Content.Parsed = powerLevels
  1542. } else {
  1543. invite = append(invite, user.MXID)
  1544. }
  1545. }
  1546. resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
  1547. Visibility: "private",
  1548. Name: portal.Name,
  1549. Topic: portal.Topic,
  1550. Invite: invite,
  1551. Preset: "private_chat",
  1552. IsDirect: portal.IsPrivateChat(),
  1553. InitialState: initialState,
  1554. CreationContent: creationContent,
  1555. BeeperAutoJoinInvites: autoJoinInvites,
  1556. })
  1557. if err != nil {
  1558. return err
  1559. }
  1560. portal.log.Infoln("Matrix room created:", resp.RoomID)
  1561. portal.InSpace = false
  1562. portal.NameSet = len(portal.Name) > 0
  1563. portal.TopicSet = len(portal.Topic) > 0
  1564. portal.MXID = resp.RoomID
  1565. portal.bridge.portalsLock.Lock()
  1566. portal.bridge.portalsByMXID[portal.MXID] = portal
  1567. portal.bridge.portalsLock.Unlock()
  1568. portal.Update(nil)
  1569. // We set the memberships beforehand to make sure the encryption key exchange in initial backfill knows the users are here.
  1570. inviteMembership := event.MembershipInvite
  1571. if autoJoinInvites {
  1572. inviteMembership = event.MembershipJoin
  1573. }
  1574. for _, userID := range invite {
  1575. portal.bridge.StateStore.SetMembership(portal.MXID, userID, inviteMembership)
  1576. }
  1577. if !autoJoinInvites {
  1578. portal.ensureUserInvited(user)
  1579. }
  1580. user.syncChatDoublePuppetDetails(portal, true)
  1581. go portal.updateCommunitySpace(user, true, true)
  1582. go portal.addToPersonalSpace(user)
  1583. if groupInfo != nil && !autoJoinInvites {
  1584. portal.SyncParticipants(user, groupInfo)
  1585. }
  1586. //if broadcastMetadata != nil {
  1587. // portal.SyncBroadcastRecipients(user, broadcastMetadata)
  1588. //}
  1589. if portal.IsPrivateChat() {
  1590. puppet := user.bridge.GetPuppetByJID(portal.Key.JID)
  1591. if portal.bridge.Config.Bridge.Encryption.Default {
  1592. err = portal.bridge.Bot.EnsureJoined(portal.MXID)
  1593. if err != nil {
  1594. portal.log.Errorln("Failed to join created portal with bridge bot for e2be:", err)
  1595. }
  1596. }
  1597. user.UpdateDirectChats(map[id.UserID][]id.RoomID{puppet.MXID: {portal.MXID}})
  1598. } else if portal.IsParent {
  1599. portal.updateChildRooms()
  1600. }
  1601. firstEventResp, err := portal.MainIntent().SendMessageEvent(portal.MXID, PortalCreationDummyEvent, struct{}{})
  1602. if err != nil {
  1603. portal.log.Errorln("Failed to send dummy event to mark portal creation:", err)
  1604. } else {
  1605. portal.FirstEventID = firstEventResp.EventID
  1606. portal.Update(nil)
  1607. }
  1608. if user.bridge.Config.Bridge.HistorySync.Backfill && backfill {
  1609. portals := []*Portal{portal}
  1610. user.EnqueueImmediateBackfills(portals)
  1611. user.EnqueueDeferredBackfills(portals)
  1612. user.BackfillQueue.ReCheck()
  1613. }
  1614. return nil
  1615. }
  1616. func (portal *Portal) addToPersonalSpace(user *User) {
  1617. spaceID := user.GetSpaceRoom()
  1618. if len(spaceID) == 0 || user.IsInSpace(portal.Key) {
  1619. return
  1620. }
  1621. _, err := portal.bridge.Bot.SendStateEvent(spaceID, event.StateSpaceChild, portal.MXID.String(), &event.SpaceChildEventContent{
  1622. Via: []string{portal.bridge.Config.Homeserver.Domain},
  1623. })
  1624. if err != nil {
  1625. portal.log.Errorfln("Failed to add room to %s's personal filtering space (%s): %v", user.MXID, spaceID, err)
  1626. } else {
  1627. portal.log.Debugfln("Added room to %s's personal filtering space (%s)", user.MXID, spaceID)
  1628. user.MarkInSpace(portal.Key)
  1629. }
  1630. }
  1631. func (portal *Portal) removeSpaceParentEvent(space id.RoomID) {
  1632. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, space.String(), &event.SpaceParentEventContent{})
  1633. if err != nil {
  1634. portal.log.Warnfln("Failed to send m.space.parent event to remove portal from %s: %v", space, err)
  1635. }
  1636. }
  1637. func (portal *Portal) updateCommunitySpace(user *User, add, updateInfo bool) bool {
  1638. if add == portal.InSpace {
  1639. return false
  1640. }
  1641. space := portal.GetParentPortal()
  1642. if space == nil {
  1643. return false
  1644. } else if space.MXID == "" {
  1645. if !add || user == nil {
  1646. return false
  1647. }
  1648. portal.log.Debugfln("Creating portal for parent group %v", space.Key.JID)
  1649. err := space.CreateMatrixRoom(user, nil, false, false)
  1650. if err != nil {
  1651. portal.log.Debugfln("Failed to create portal for parent group: %v", err)
  1652. return false
  1653. }
  1654. }
  1655. var action string
  1656. var parentContent event.SpaceParentEventContent
  1657. var childContent event.SpaceChildEventContent
  1658. if add {
  1659. parentContent.Canonical = true
  1660. parentContent.Via = []string{portal.bridge.Config.Homeserver.Domain}
  1661. childContent.Via = []string{portal.bridge.Config.Homeserver.Domain}
  1662. action = "add portal to"
  1663. portal.log.Debugfln("Adding %s to space %s (%s)", portal.MXID, space.MXID, space.Key.JID)
  1664. } else {
  1665. action = "remove portal from"
  1666. portal.log.Debugfln("Removing %s from space %s (%s)", portal.MXID, space.MXID, space.Key.JID)
  1667. }
  1668. _, err := space.MainIntent().SendStateEvent(space.MXID, event.StateSpaceChild, portal.MXID.String(), &childContent)
  1669. if err != nil {
  1670. portal.log.Errorfln("Failed to send m.space.child event to %s %s: %v", action, space.MXID, err)
  1671. return false
  1672. }
  1673. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, space.MXID.String(), &parentContent)
  1674. if err != nil {
  1675. portal.log.Warnfln("Failed to send m.space.parent event to %s %s: %v", action, space.MXID, err)
  1676. }
  1677. portal.InSpace = add
  1678. if updateInfo {
  1679. portal.Update(nil)
  1680. portal.UpdateBridgeInfo()
  1681. }
  1682. return true
  1683. }
  1684. func (portal *Portal) IsPrivateChat() bool {
  1685. return portal.Key.JID.Server == types.DefaultUserServer
  1686. }
  1687. func (portal *Portal) IsGroupChat() bool {
  1688. return portal.Key.JID.Server == types.GroupServer
  1689. }
  1690. func (portal *Portal) IsBroadcastList() bool {
  1691. return portal.Key.JID.Server == types.BroadcastServer
  1692. }
  1693. func (portal *Portal) IsStatusBroadcastList() bool {
  1694. return portal.Key.JID == types.StatusBroadcastJID
  1695. }
  1696. func (portal *Portal) HasRelaybot() bool {
  1697. return portal.bridge.Config.Bridge.Relay.Enabled && len(portal.RelayUserID) > 0
  1698. }
  1699. func (portal *Portal) GetRelayUser() *User {
  1700. if !portal.HasRelaybot() {
  1701. return nil
  1702. } else if portal.relayUser == nil {
  1703. portal.relayUser = portal.bridge.GetUserByMXID(portal.RelayUserID)
  1704. }
  1705. return portal.relayUser
  1706. }
  1707. func (portal *Portal) GetParentPortal() *Portal {
  1708. if portal.ParentGroup.IsEmpty() {
  1709. return nil
  1710. } else if portal.parentPortal == nil {
  1711. portal.parentPortal = portal.bridge.GetPortalByJID(database.NewPortalKey(portal.ParentGroup, portal.ParentGroup))
  1712. }
  1713. return portal.parentPortal
  1714. }
  1715. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  1716. if portal.IsPrivateChat() {
  1717. return portal.bridge.GetPuppetByJID(portal.Key.JID).DefaultIntent()
  1718. }
  1719. return portal.bridge.Bot
  1720. }
  1721. func (portal *Portal) SetReply(content *event.MessageEventContent, replyTo *ReplyInfo, isBackfill bool) bool {
  1722. if replyTo == nil {
  1723. return false
  1724. }
  1725. message := portal.bridge.DB.Message.GetByJID(portal.Key, replyTo.MessageID)
  1726. if message == nil || message.IsFakeMXID() {
  1727. if isBackfill && portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  1728. content.RelatesTo = (&event.RelatesTo{}).SetReplyTo(portal.deterministicEventID(replyTo.Sender, replyTo.MessageID, ""))
  1729. return true
  1730. }
  1731. return false
  1732. }
  1733. evt, err := portal.MainIntent().GetEvent(portal.MXID, message.MXID)
  1734. if err != nil {
  1735. portal.log.Warnln("Failed to get reply target:", err)
  1736. content.RelatesTo = (&event.RelatesTo{}).SetReplyTo(message.MXID)
  1737. return true
  1738. }
  1739. _ = evt.Content.ParseRaw(evt.Type)
  1740. if evt.Type == event.EventEncrypted {
  1741. decryptedEvt, err := portal.bridge.Crypto.Decrypt(evt)
  1742. if err != nil {
  1743. portal.log.Warnln("Failed to decrypt reply target:", err)
  1744. } else {
  1745. evt = decryptedEvt
  1746. }
  1747. }
  1748. content.SetReply(evt)
  1749. return true
  1750. }
  1751. func (portal *Portal) HandleMessageReaction(intent *appservice.IntentAPI, user *User, info *types.MessageInfo, reaction *waProto.ReactionMessage, existingMsg *database.Message) {
  1752. if existingMsg != nil {
  1753. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  1754. Reason: "The undecryptable message was actually a reaction",
  1755. })
  1756. }
  1757. targetJID := reaction.GetKey().GetId()
  1758. if reaction.GetText() == "" {
  1759. existing := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, info.Sender)
  1760. if existing == nil {
  1761. portal.log.Debugfln("Dropping removal %s of unknown reaction to %s from %s", info.ID, targetJID, info.Sender)
  1762. return
  1763. }
  1764. resp, err := intent.RedactEvent(portal.MXID, existing.MXID)
  1765. if err != nil {
  1766. portal.log.Errorfln("Failed to redact reaction %s/%s from %s to %s: %v", existing.MXID, existing.JID, info.Sender, targetJID, err)
  1767. }
  1768. portal.finishHandling(existingMsg, info, resp.EventID, database.MsgReaction, database.MsgNoError)
  1769. existing.Delete()
  1770. } else {
  1771. target := portal.bridge.DB.Message.GetByJID(portal.Key, targetJID)
  1772. if target == nil {
  1773. portal.log.Debugfln("Dropping reaction %s from %s to unknown message %s", info.ID, info.Sender, targetJID)
  1774. return
  1775. }
  1776. var content event.ReactionEventContent
  1777. content.RelatesTo = event.RelatesTo{
  1778. Type: event.RelAnnotation,
  1779. EventID: target.MXID,
  1780. Key: variationselector.Add(reaction.GetText()),
  1781. }
  1782. resp, err := intent.SendMassagedMessageEvent(portal.MXID, event.EventReaction, &content, info.Timestamp.UnixMilli())
  1783. if err != nil {
  1784. portal.log.Errorfln("Failed to bridge reaction %s from %s to %s: %v", info.ID, info.Sender, target.JID, err)
  1785. return
  1786. }
  1787. portal.finishHandling(existingMsg, info, resp.EventID, database.MsgReaction, database.MsgNoError)
  1788. portal.upsertReaction(nil, intent, target.JID, info.Sender, resp.EventID, info.ID)
  1789. }
  1790. }
  1791. func (portal *Portal) HandleMessageRevoke(user *User, info *types.MessageInfo, key *waProto.MessageKey) bool {
  1792. msg := portal.bridge.DB.Message.GetByJID(portal.Key, key.GetId())
  1793. if msg == nil || msg.IsFakeMXID() {
  1794. return false
  1795. }
  1796. intent := portal.bridge.GetPuppetByJID(info.Sender).IntentFor(portal)
  1797. _, err := intent.RedactEvent(portal.MXID, msg.MXID)
  1798. if err != nil {
  1799. if errors.Is(err, mautrix.MForbidden) {
  1800. _, err = portal.MainIntent().RedactEvent(portal.MXID, msg.MXID)
  1801. if err != nil {
  1802. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  1803. }
  1804. }
  1805. } else {
  1806. msg.Delete()
  1807. }
  1808. return true
  1809. }
  1810. func (portal *Portal) deleteForMe(user *User, content *events.DeleteForMe) bool {
  1811. matrixUsers, err := portal.GetMatrixUsers()
  1812. if err != nil {
  1813. portal.log.Errorln("Failed to get Matrix users in portal to see if DeleteForMe should be handled:", err)
  1814. return false
  1815. }
  1816. if len(matrixUsers) == 1 && matrixUsers[0] == user.MXID {
  1817. msg := portal.bridge.DB.Message.GetByJID(portal.Key, content.MessageID)
  1818. if msg == nil || msg.IsFakeMXID() {
  1819. return false
  1820. }
  1821. _, err := portal.MainIntent().RedactEvent(portal.MXID, msg.MXID)
  1822. if err != nil {
  1823. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  1824. } else {
  1825. msg.Delete()
  1826. }
  1827. return true
  1828. }
  1829. return false
  1830. }
  1831. func (portal *Portal) sendMainIntentMessage(content *event.MessageEventContent) (*mautrix.RespSendEvent, error) {
  1832. return portal.sendMessage(portal.MainIntent(), event.EventMessage, content, nil, 0)
  1833. }
  1834. func (portal *Portal) encrypt(intent *appservice.IntentAPI, content *event.Content, eventType event.Type) (event.Type, error) {
  1835. if !portal.Encrypted || portal.bridge.Crypto == nil {
  1836. return eventType, nil
  1837. }
  1838. intent.AddDoublePuppetValue(content)
  1839. // TODO maybe the locking should be inside mautrix-go?
  1840. portal.encryptLock.Lock()
  1841. defer portal.encryptLock.Unlock()
  1842. err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, content)
  1843. if err != nil {
  1844. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  1845. }
  1846. return event.EventEncrypted, nil
  1847. }
  1848. func (portal *Portal) sendMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  1849. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  1850. var err error
  1851. eventType, err = portal.encrypt(intent, &wrappedContent, eventType)
  1852. if err != nil {
  1853. return nil, err
  1854. }
  1855. _, _ = intent.UserTyping(portal.MXID, false, 0)
  1856. if timestamp == 0 {
  1857. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  1858. } else {
  1859. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  1860. }
  1861. }
  1862. type ReplyInfo struct {
  1863. MessageID types.MessageID
  1864. Sender types.JID
  1865. }
  1866. type Replyable interface {
  1867. GetStanzaId() string
  1868. GetParticipant() string
  1869. }
  1870. func GetReply(replyable Replyable) *ReplyInfo {
  1871. if replyable.GetStanzaId() == "" {
  1872. return nil
  1873. }
  1874. sender, err := types.ParseJID(replyable.GetParticipant())
  1875. if err != nil {
  1876. return nil
  1877. }
  1878. return &ReplyInfo{
  1879. MessageID: types.MessageID(replyable.GetStanzaId()),
  1880. Sender: sender,
  1881. }
  1882. }
  1883. type ConvertedMessage struct {
  1884. Intent *appservice.IntentAPI
  1885. Type event.Type
  1886. Content *event.MessageEventContent
  1887. Extra map[string]interface{}
  1888. Caption *event.MessageEventContent
  1889. MultiEvent []*event.MessageEventContent
  1890. ReplyTo *ReplyInfo
  1891. ExpiresIn uint32
  1892. Error database.MessageErrorType
  1893. MediaKey []byte
  1894. }
  1895. func (cm *ConvertedMessage) MergeCaption() {
  1896. if cm.Caption == nil {
  1897. return
  1898. }
  1899. cm.Content.FileName = cm.Content.Body
  1900. extensibleCaption := map[string]interface{}{
  1901. "org.matrix.msc1767.text": cm.Caption.Body,
  1902. }
  1903. cm.Extra["org.matrix.msc1767.caption"] = extensibleCaption
  1904. cm.Content.Body = cm.Caption.Body
  1905. if cm.Caption.Format == event.FormatHTML {
  1906. cm.Content.Format = event.FormatHTML
  1907. cm.Content.FormattedBody = cm.Caption.FormattedBody
  1908. extensibleCaption["org.matrix.msc1767.html"] = cm.Caption.FormattedBody
  1909. }
  1910. cm.Caption = nil
  1911. }
  1912. func (portal *Portal) convertTextMessage(intent *appservice.IntentAPI, source *User, msg *waProto.Message) *ConvertedMessage {
  1913. content := &event.MessageEventContent{
  1914. Body: msg.GetConversation(),
  1915. MsgType: event.MsgText,
  1916. }
  1917. if len(msg.GetExtendedTextMessage().GetText()) > 0 {
  1918. content.Body = msg.GetExtendedTextMessage().GetText()
  1919. }
  1920. contextInfo := msg.GetExtendedTextMessage().GetContextInfo()
  1921. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, content, contextInfo.GetMentionedJid(), false, false)
  1922. expiresIn := contextInfo.GetExpiration()
  1923. extraAttrs := map[string]interface{}{}
  1924. extraAttrs["com.beeper.linkpreviews"] = portal.convertURLPreviewToBeeper(intent, source, msg.GetExtendedTextMessage())
  1925. return &ConvertedMessage{
  1926. Intent: intent,
  1927. Type: event.EventMessage,
  1928. Content: content,
  1929. ReplyTo: GetReply(contextInfo),
  1930. ExpiresIn: expiresIn,
  1931. Extra: extraAttrs,
  1932. }
  1933. }
  1934. func (portal *Portal) convertTemplateMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, tplMsg *waProto.TemplateMessage) *ConvertedMessage {
  1935. converted := &ConvertedMessage{
  1936. Intent: intent,
  1937. Type: event.EventMessage,
  1938. Content: &event.MessageEventContent{
  1939. Body: "Unsupported business message",
  1940. MsgType: event.MsgText,
  1941. },
  1942. ReplyTo: GetReply(tplMsg.GetContextInfo()),
  1943. ExpiresIn: tplMsg.GetContextInfo().GetExpiration(),
  1944. }
  1945. tpl := tplMsg.GetHydratedTemplate()
  1946. if tpl == nil {
  1947. return converted
  1948. }
  1949. content := tpl.GetHydratedContentText()
  1950. if buttons := tpl.GetHydratedButtons(); len(buttons) > 0 {
  1951. addButtonText := false
  1952. descriptions := make([]string, len(buttons))
  1953. for i, rawButton := range buttons {
  1954. switch button := rawButton.GetHydratedButton().(type) {
  1955. case *waProto.HydratedTemplateButton_QuickReplyButton:
  1956. descriptions[i] = fmt.Sprintf("<%s>", button.QuickReplyButton.GetDisplayText())
  1957. addButtonText = true
  1958. case *waProto.HydratedTemplateButton_UrlButton:
  1959. descriptions[i] = fmt.Sprintf("[%s](%s)", button.UrlButton.GetDisplayText(), button.UrlButton.GetUrl())
  1960. case *waProto.HydratedTemplateButton_CallButton:
  1961. descriptions[i] = fmt.Sprintf("[%s](tel:%s)", button.CallButton.GetDisplayText(), button.CallButton.GetPhoneNumber())
  1962. }
  1963. }
  1964. description := strings.Join(descriptions, " - ")
  1965. if addButtonText {
  1966. description += "\nUse the WhatsApp app to click buttons"
  1967. }
  1968. content = fmt.Sprintf("%s\n\n%s", content, description)
  1969. }
  1970. if footer := tpl.GetHydratedFooterText(); footer != "" {
  1971. content = fmt.Sprintf("%s\n\n%s", content, footer)
  1972. }
  1973. var convertedTitle *ConvertedMessage
  1974. switch title := tpl.GetTitle().(type) {
  1975. case *waProto.TemplateMessage_HydratedFourRowTemplate_DocumentMessage:
  1976. convertedTitle = portal.convertMediaMessage(intent, source, info, title.DocumentMessage, "file attachment", false)
  1977. case *waProto.TemplateMessage_HydratedFourRowTemplate_ImageMessage:
  1978. convertedTitle = portal.convertMediaMessage(intent, source, info, title.ImageMessage, "photo", false)
  1979. case *waProto.TemplateMessage_HydratedFourRowTemplate_VideoMessage:
  1980. convertedTitle = portal.convertMediaMessage(intent, source, info, title.VideoMessage, "video attachment", false)
  1981. case *waProto.TemplateMessage_HydratedFourRowTemplate_LocationMessage:
  1982. content = fmt.Sprintf("Unsupported location message\n\n%s", content)
  1983. case *waProto.TemplateMessage_HydratedFourRowTemplate_HydratedTitleText:
  1984. content = fmt.Sprintf("%s\n\n%s", title.HydratedTitleText, content)
  1985. }
  1986. converted.Content.Body = content
  1987. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, converted.Content, nil, true, false)
  1988. if convertedTitle != nil {
  1989. converted.MediaKey = convertedTitle.MediaKey
  1990. converted.Extra = convertedTitle.Extra
  1991. converted.Caption = converted.Content
  1992. converted.Content = convertedTitle.Content
  1993. converted.Error = convertedTitle.Error
  1994. }
  1995. if converted.Extra == nil {
  1996. converted.Extra = make(map[string]interface{})
  1997. }
  1998. converted.Extra["fi.mau.whatsapp.hydrated_template_id"] = tpl.GetTemplateId()
  1999. return converted
  2000. }
  2001. func (portal *Portal) convertTemplateButtonReplyMessage(intent *appservice.IntentAPI, msg *waProto.TemplateButtonReplyMessage) *ConvertedMessage {
  2002. return &ConvertedMessage{
  2003. Intent: intent,
  2004. Type: event.EventMessage,
  2005. Content: &event.MessageEventContent{
  2006. Body: msg.GetSelectedDisplayText(),
  2007. MsgType: event.MsgText,
  2008. },
  2009. Extra: map[string]interface{}{
  2010. "fi.mau.whatsapp.template_button_reply": map[string]interface{}{
  2011. "id": msg.GetSelectedId(),
  2012. "index": msg.GetSelectedIndex(),
  2013. },
  2014. },
  2015. ReplyTo: GetReply(msg.GetContextInfo()),
  2016. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2017. }
  2018. }
  2019. func (portal *Portal) convertListMessage(intent *appservice.IntentAPI, source *User, msg *waProto.ListMessage) *ConvertedMessage {
  2020. converted := &ConvertedMessage{
  2021. Intent: intent,
  2022. Type: event.EventMessage,
  2023. Content: &event.MessageEventContent{
  2024. Body: "Unsupported business message",
  2025. MsgType: event.MsgText,
  2026. },
  2027. ReplyTo: GetReply(msg.GetContextInfo()),
  2028. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2029. }
  2030. body := msg.GetDescription()
  2031. if msg.GetTitle() != "" {
  2032. if body == "" {
  2033. body = msg.GetTitle()
  2034. } else {
  2035. body = fmt.Sprintf("%s\n\n%s", msg.GetTitle(), body)
  2036. }
  2037. }
  2038. randomID := util.RandomString(64)
  2039. body = fmt.Sprintf("%s\n%s", body, randomID)
  2040. if msg.GetFooterText() != "" {
  2041. body = fmt.Sprintf("%s\n\n%s", body, msg.GetFooterText())
  2042. }
  2043. converted.Content.Body = body
  2044. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, converted.Content, nil, false, true)
  2045. var optionsMarkdown strings.Builder
  2046. _, _ = fmt.Fprintf(&optionsMarkdown, "#### %s\n", msg.GetButtonText())
  2047. for _, section := range msg.GetSections() {
  2048. nesting := ""
  2049. if section.GetTitle() != "" {
  2050. _, _ = fmt.Fprintf(&optionsMarkdown, "* %s\n", section.GetTitle())
  2051. nesting = " "
  2052. }
  2053. for _, row := range section.GetRows() {
  2054. if row.GetDescription() != "" {
  2055. _, _ = fmt.Fprintf(&optionsMarkdown, "%s* %s: %s\n", nesting, row.GetTitle(), row.GetDescription())
  2056. } else {
  2057. _, _ = fmt.Fprintf(&optionsMarkdown, "%s* %s\n", nesting, row.GetTitle())
  2058. }
  2059. }
  2060. }
  2061. optionsMarkdown.WriteString("\nUse the WhatsApp app to respond")
  2062. rendered := format.RenderMarkdown(optionsMarkdown.String(), true, false)
  2063. converted.Content.Body = strings.Replace(converted.Content.Body, randomID, rendered.Body, 1)
  2064. converted.Content.FormattedBody = strings.Replace(converted.Content.FormattedBody, randomID, rendered.FormattedBody, 1)
  2065. return converted
  2066. }
  2067. func (portal *Portal) convertListResponseMessage(intent *appservice.IntentAPI, msg *waProto.ListResponseMessage) *ConvertedMessage {
  2068. var body string
  2069. if msg.GetTitle() != "" {
  2070. if msg.GetDescription() != "" {
  2071. body = fmt.Sprintf("%s\n\n%s", msg.GetTitle(), msg.GetDescription())
  2072. } else {
  2073. body = msg.GetTitle()
  2074. }
  2075. } else if msg.GetDescription() != "" {
  2076. body = msg.GetDescription()
  2077. } else {
  2078. body = "Unsupported list reply message"
  2079. }
  2080. return &ConvertedMessage{
  2081. Intent: intent,
  2082. Type: event.EventMessage,
  2083. Content: &event.MessageEventContent{
  2084. Body: body,
  2085. MsgType: event.MsgText,
  2086. },
  2087. Extra: map[string]interface{}{
  2088. "fi.mau.whatsapp.list_reply": map[string]interface{}{
  2089. "row_id": msg.GetSingleSelectReply().GetSelectedRowId(),
  2090. },
  2091. },
  2092. ReplyTo: GetReply(msg.GetContextInfo()),
  2093. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2094. }
  2095. }
  2096. func (portal *Portal) convertPollUpdateMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg *waProto.PollUpdateMessage) *ConvertedMessage {
  2097. if !portal.bridge.Config.Bridge.ExtEvPolls {
  2098. return nil
  2099. }
  2100. pollMessage := portal.bridge.DB.Message.GetByJID(portal.Key, msg.GetPollCreationMessageKey().GetId())
  2101. if pollMessage == nil {
  2102. portal.log.Warnfln("Failed to convert vote message %s: poll message %s not found", info.ID, msg.GetPollCreationMessageKey().GetId())
  2103. return nil
  2104. }
  2105. vote, err := source.Client.DecryptPollVote(&events.Message{
  2106. Info: *info,
  2107. Message: &waProto.Message{PollUpdateMessage: msg},
  2108. })
  2109. if err != nil {
  2110. portal.log.Errorfln("Failed to decrypt vote message %s: %v", info.ID, err)
  2111. return nil
  2112. }
  2113. selectedHashes := make([]string, len(vote.GetSelectedOptions()))
  2114. for i, opt := range vote.GetSelectedOptions() {
  2115. selectedHashes[i] = hex.EncodeToString(opt)
  2116. }
  2117. evtType := TypeMSC3881PollResponse
  2118. //if portal.bridge.Config.Bridge.ExtEvPolls == 2 {
  2119. // evtType = TypeMSC3881V2PollResponse
  2120. //}
  2121. return &ConvertedMessage{
  2122. Intent: intent,
  2123. Type: evtType,
  2124. Content: &event.MessageEventContent{
  2125. RelatesTo: &event.RelatesTo{
  2126. Type: event.RelReference,
  2127. EventID: pollMessage.MXID,
  2128. },
  2129. },
  2130. Extra: map[string]any{
  2131. "org.matrix.msc3381.poll.response": map[string]any{
  2132. "answers": selectedHashes,
  2133. },
  2134. "org.matrix.msc3381.v2.selections": selectedHashes,
  2135. },
  2136. }
  2137. }
  2138. func (portal *Portal) convertPollCreationMessage(intent *appservice.IntentAPI, msg *waProto.PollCreationMessage) *ConvertedMessage {
  2139. optionNames := make([]string, len(msg.GetOptions()))
  2140. optionsListText := make([]string, len(optionNames))
  2141. optionsListHTML := make([]string, len(optionNames))
  2142. msc3381Answers := make([]map[string]any, len(optionNames))
  2143. msc3381V2Answers := make([]map[string]any, len(optionNames))
  2144. for i, opt := range msg.GetOptions() {
  2145. optionNames[i] = opt.GetOptionName()
  2146. optionsListText[i] = fmt.Sprintf("%d. %s\n", i+1, optionNames[i])
  2147. optionsListHTML[i] = fmt.Sprintf("<li>%s</li>", event.TextToHTML(optionNames[i]))
  2148. optionHash := sha256.Sum256([]byte(opt.GetOptionName()))
  2149. optionHashStr := hex.EncodeToString(optionHash[:])
  2150. msc3381Answers[i] = map[string]any{
  2151. "id": optionHashStr,
  2152. "org.matrix.msc1767.text": opt.GetOptionName(),
  2153. }
  2154. msc3381V2Answers[i] = map[string]any{
  2155. "org.matrix.msc3381.v2.id": optionHashStr,
  2156. "org.matrix.msc1767.markup": []map[string]any{
  2157. {"mimetype": "text/plain", "body": opt.GetOptionName()},
  2158. },
  2159. }
  2160. }
  2161. body := fmt.Sprintf("%s\n\n%s", msg.GetName(), strings.Join(optionsListText, "\n"))
  2162. formattedBody := fmt.Sprintf("<p>%s</p><ol>%s</ol>", event.TextToHTML(msg.GetName()), strings.Join(optionsListHTML, ""))
  2163. maxChoices := int(msg.GetSelectableOptionsCount())
  2164. if maxChoices <= 0 {
  2165. maxChoices = len(optionNames)
  2166. }
  2167. evtType := event.EventMessage
  2168. if portal.bridge.Config.Bridge.ExtEvPolls {
  2169. evtType.Type = "org.matrix.msc3381.poll.start"
  2170. }
  2171. //else if portal.bridge.Config.Bridge.ExtEvPolls == 2 {
  2172. // evtType.Type = "org.matrix.msc3381.v2.poll.start"
  2173. //}
  2174. return &ConvertedMessage{
  2175. Intent: intent,
  2176. Type: evtType,
  2177. Content: &event.MessageEventContent{
  2178. Body: body,
  2179. MsgType: event.MsgText,
  2180. Format: event.FormatHTML,
  2181. FormattedBody: formattedBody,
  2182. },
  2183. Extra: map[string]any{
  2184. // Custom metadata
  2185. "fi.mau.whatsapp.poll": map[string]any{
  2186. "option_names": optionNames,
  2187. "selectable_options_count": msg.GetSelectableOptionsCount(),
  2188. },
  2189. // Current extensible events (as of November 2022)
  2190. "org.matrix.msc1767.markup": []map[string]any{
  2191. {"mimetype": "text/html", "body": formattedBody},
  2192. {"mimetype": "text/plain", "body": body},
  2193. },
  2194. "org.matrix.msc3381.v2.poll": map[string]any{
  2195. "kind": "org.matrix.msc3381.v2.disclosed",
  2196. "max_selections": maxChoices,
  2197. "question": map[string]any{
  2198. "org.matrix.msc1767.markup": []map[string]any{
  2199. {"mimetype": "text/plain", "body": msg.GetName()},
  2200. },
  2201. },
  2202. "answers": msc3381V2Answers,
  2203. },
  2204. // Legacy extensible events
  2205. "org.matrix.msc1767.message": []map[string]any{
  2206. {"mimetype": "text/html", "body": formattedBody},
  2207. {"mimetype": "text/plain", "body": body},
  2208. },
  2209. "org.matrix.msc3381.poll.start": map[string]any{
  2210. "kind": "org.matrix.msc3381.poll.disclosed",
  2211. "max_selections": maxChoices,
  2212. "question": map[string]any{
  2213. "org.matrix.msc1767.text": msg.GetName(),
  2214. },
  2215. "answers": msc3381Answers,
  2216. },
  2217. },
  2218. ReplyTo: GetReply(msg.GetContextInfo()),
  2219. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2220. }
  2221. }
  2222. func (portal *Portal) convertLiveLocationMessage(intent *appservice.IntentAPI, msg *waProto.LiveLocationMessage) *ConvertedMessage {
  2223. content := &event.MessageEventContent{
  2224. Body: "Started sharing live location",
  2225. MsgType: event.MsgNotice,
  2226. }
  2227. if len(msg.GetCaption()) > 0 {
  2228. content.Body += ": " + msg.GetCaption()
  2229. }
  2230. return &ConvertedMessage{
  2231. Intent: intent,
  2232. Type: event.EventMessage,
  2233. Content: content,
  2234. ReplyTo: GetReply(msg.GetContextInfo()),
  2235. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2236. }
  2237. }
  2238. func (portal *Portal) convertLocationMessage(intent *appservice.IntentAPI, msg *waProto.LocationMessage) *ConvertedMessage {
  2239. url := msg.GetUrl()
  2240. if len(url) == 0 {
  2241. url = fmt.Sprintf("https://maps.google.com/?q=%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude())
  2242. }
  2243. name := msg.GetName()
  2244. if len(name) == 0 {
  2245. latChar := 'N'
  2246. if msg.GetDegreesLatitude() < 0 {
  2247. latChar = 'S'
  2248. }
  2249. longChar := 'E'
  2250. if msg.GetDegreesLongitude() < 0 {
  2251. longChar = 'W'
  2252. }
  2253. name = fmt.Sprintf("%.4f° %c %.4f° %c", math.Abs(msg.GetDegreesLatitude()), latChar, math.Abs(msg.GetDegreesLongitude()), longChar)
  2254. }
  2255. content := &event.MessageEventContent{
  2256. MsgType: event.MsgLocation,
  2257. Body: fmt.Sprintf("Location: %s\n%s\n%s", name, msg.GetAddress(), url),
  2258. Format: event.FormatHTML,
  2259. FormattedBody: fmt.Sprintf("Location: <a href='%s'>%s</a><br>%s", url, name, msg.GetAddress()),
  2260. GeoURI: fmt.Sprintf("geo:%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude()),
  2261. }
  2262. if len(msg.GetJpegThumbnail()) > 0 {
  2263. thumbnailMime := http.DetectContentType(msg.GetJpegThumbnail())
  2264. uploadedThumbnail, _ := intent.UploadBytes(msg.GetJpegThumbnail(), thumbnailMime)
  2265. if uploadedThumbnail != nil {
  2266. cfg, _, _ := image.DecodeConfig(bytes.NewReader(msg.GetJpegThumbnail()))
  2267. content.Info = &event.FileInfo{
  2268. ThumbnailInfo: &event.FileInfo{
  2269. Size: len(msg.GetJpegThumbnail()),
  2270. Width: cfg.Width,
  2271. Height: cfg.Height,
  2272. MimeType: thumbnailMime,
  2273. },
  2274. ThumbnailURL: uploadedThumbnail.ContentURI.CUString(),
  2275. }
  2276. }
  2277. }
  2278. return &ConvertedMessage{
  2279. Intent: intent,
  2280. Type: event.EventMessage,
  2281. Content: content,
  2282. ReplyTo: GetReply(msg.GetContextInfo()),
  2283. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2284. }
  2285. }
  2286. const inviteMsg = `%s<hr/>This invitation to join "%s" expires at %s. Reply to this message with <code>!wa accept</code> to accept the invite.`
  2287. const inviteMetaField = "fi.mau.whatsapp.invite"
  2288. const escapedInviteMetaField = `fi\.mau\.whatsapp\.invite`
  2289. type InviteMeta struct {
  2290. JID types.JID `json:"jid"`
  2291. Code string `json:"code"`
  2292. Expiration int64 `json:"expiration,string"`
  2293. Inviter types.JID `json:"inviter"`
  2294. }
  2295. func (portal *Portal) convertGroupInviteMessage(intent *appservice.IntentAPI, info *types.MessageInfo, msg *waProto.GroupInviteMessage) *ConvertedMessage {
  2296. expiry := time.Unix(msg.GetInviteExpiration(), 0)
  2297. htmlMessage := fmt.Sprintf(inviteMsg, event.TextToHTML(msg.GetCaption()), msg.GetGroupName(), expiry)
  2298. content := &event.MessageEventContent{
  2299. MsgType: event.MsgText,
  2300. Body: format.HTMLToText(htmlMessage),
  2301. Format: event.FormatHTML,
  2302. FormattedBody: htmlMessage,
  2303. }
  2304. groupJID, err := types.ParseJID(msg.GetGroupJid())
  2305. if err != nil {
  2306. portal.log.Errorfln("Failed to parse invite group JID: %v", err)
  2307. }
  2308. extraAttrs := map[string]interface{}{
  2309. inviteMetaField: InviteMeta{
  2310. JID: groupJID,
  2311. Code: msg.GetInviteCode(),
  2312. Expiration: msg.GetInviteExpiration(),
  2313. Inviter: info.Sender.ToNonAD(),
  2314. },
  2315. }
  2316. return &ConvertedMessage{
  2317. Intent: intent,
  2318. Type: event.EventMessage,
  2319. Content: content,
  2320. Extra: extraAttrs,
  2321. ReplyTo: GetReply(msg.GetContextInfo()),
  2322. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2323. }
  2324. }
  2325. func (portal *Portal) convertContactMessage(intent *appservice.IntentAPI, msg *waProto.ContactMessage) *ConvertedMessage {
  2326. fileName := fmt.Sprintf("%s.vcf", msg.GetDisplayName())
  2327. data := []byte(msg.GetVcard())
  2328. mimeType := "text/vcard"
  2329. uploadMimeType, file := portal.encryptFileInPlace(data, mimeType)
  2330. uploadResp, err := intent.UploadBytesWithName(data, uploadMimeType, fileName)
  2331. if err != nil {
  2332. portal.log.Errorfln("Failed to upload vcard of %s: %v", msg.GetDisplayName(), err)
  2333. return nil
  2334. }
  2335. content := &event.MessageEventContent{
  2336. Body: fileName,
  2337. MsgType: event.MsgFile,
  2338. File: file,
  2339. Info: &event.FileInfo{
  2340. MimeType: mimeType,
  2341. Size: len(msg.GetVcard()),
  2342. },
  2343. }
  2344. if content.File != nil {
  2345. content.File.URL = uploadResp.ContentURI.CUString()
  2346. } else {
  2347. content.URL = uploadResp.ContentURI.CUString()
  2348. }
  2349. return &ConvertedMessage{
  2350. Intent: intent,
  2351. Type: event.EventMessage,
  2352. Content: content,
  2353. ReplyTo: GetReply(msg.GetContextInfo()),
  2354. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2355. }
  2356. }
  2357. func (portal *Portal) convertContactsArrayMessage(intent *appservice.IntentAPI, msg *waProto.ContactsArrayMessage) *ConvertedMessage {
  2358. name := msg.GetDisplayName()
  2359. if len(name) == 0 {
  2360. name = fmt.Sprintf("%d contacts", len(msg.GetContacts()))
  2361. }
  2362. contacts := make([]*event.MessageEventContent, 0, len(msg.GetContacts()))
  2363. for _, contact := range msg.GetContacts() {
  2364. converted := portal.convertContactMessage(intent, contact)
  2365. if converted != nil {
  2366. contacts = append(contacts, converted.Content)
  2367. }
  2368. }
  2369. return &ConvertedMessage{
  2370. Intent: intent,
  2371. Type: event.EventMessage,
  2372. Content: &event.MessageEventContent{
  2373. MsgType: event.MsgNotice,
  2374. Body: fmt.Sprintf("Sent %s", name),
  2375. },
  2376. ReplyTo: GetReply(msg.GetContextInfo()),
  2377. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2378. MultiEvent: contacts,
  2379. }
  2380. }
  2381. func (portal *Portal) tryKickUser(userID id.UserID, intent *appservice.IntentAPI) error {
  2382. _, err := intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
  2383. if err != nil {
  2384. httpErr, ok := err.(mautrix.HTTPError)
  2385. if ok && httpErr.RespError != nil && httpErr.RespError.ErrCode == "M_FORBIDDEN" {
  2386. _, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
  2387. }
  2388. }
  2389. return err
  2390. }
  2391. func (portal *Portal) removeUser(isSameUser bool, kicker *appservice.IntentAPI, target id.UserID, targetIntent *appservice.IntentAPI) {
  2392. if !isSameUser || targetIntent == nil {
  2393. err := portal.tryKickUser(target, kicker)
  2394. if err != nil {
  2395. portal.log.Warnfln("Failed to kick %s from %s: %v", target, portal.MXID, err)
  2396. if targetIntent != nil {
  2397. _, _ = targetIntent.LeaveRoom(portal.MXID)
  2398. }
  2399. }
  2400. } else {
  2401. _, err := targetIntent.LeaveRoom(portal.MXID)
  2402. if err != nil {
  2403. portal.log.Warnfln("Failed to leave portal as %s: %v", target, err)
  2404. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: target})
  2405. }
  2406. }
  2407. portal.CleanupIfEmpty()
  2408. }
  2409. func (portal *Portal) HandleWhatsAppKick(source *User, senderJID types.JID, jids []types.JID) {
  2410. sender := portal.bridge.GetPuppetByJID(senderJID)
  2411. senderIntent := sender.IntentFor(portal)
  2412. for _, jid := range jids {
  2413. //if source != nil && source.JID.User == jid.User {
  2414. // portal.log.Debugln("Ignoring self-kick by", source.MXID)
  2415. // continue
  2416. //}
  2417. puppet := portal.bridge.GetPuppetByJID(jid)
  2418. portal.removeUser(puppet.JID == sender.JID, senderIntent, puppet.MXID, puppet.DefaultIntent())
  2419. if !portal.IsBroadcastList() {
  2420. user := portal.bridge.GetUserByJID(jid)
  2421. if user != nil {
  2422. var customIntent *appservice.IntentAPI
  2423. if puppet.CustomMXID == user.MXID {
  2424. customIntent = puppet.CustomIntent()
  2425. }
  2426. portal.removeUser(puppet.JID == sender.JID, senderIntent, user.MXID, customIntent)
  2427. }
  2428. }
  2429. }
  2430. }
  2431. func (portal *Portal) HandleWhatsAppInvite(source *User, senderJID *types.JID, jids []types.JID) (evtID id.EventID) {
  2432. intent := portal.MainIntent()
  2433. if senderJID != nil && !senderJID.IsEmpty() {
  2434. sender := portal.bridge.GetPuppetByJID(*senderJID)
  2435. intent = sender.IntentFor(portal)
  2436. }
  2437. for _, jid := range jids {
  2438. puppet := portal.bridge.GetPuppetByJID(jid)
  2439. puppet.SyncContact(source, true, false, "handling whatsapp invite")
  2440. resp, err := intent.SendStateEvent(portal.MXID, event.StateMember, puppet.MXID.String(), &event.MemberEventContent{
  2441. Membership: event.MembershipInvite,
  2442. Displayname: puppet.Displayname,
  2443. AvatarURL: puppet.AvatarURL.CUString(),
  2444. })
  2445. if err != nil {
  2446. portal.log.Warnfln("Failed to invite %s as %s: %v", puppet.MXID, intent.UserID, err)
  2447. _ = portal.MainIntent().EnsureInvited(portal.MXID, puppet.MXID)
  2448. } else {
  2449. evtID = resp.EventID
  2450. }
  2451. err = puppet.DefaultIntent().EnsureJoined(portal.MXID)
  2452. if err != nil {
  2453. portal.log.Errorfln("Failed to ensure %s is joined: %v", puppet.MXID, err)
  2454. }
  2455. }
  2456. return
  2457. }
  2458. func (portal *Portal) HandleWhatsAppDeleteChat(user *User) {
  2459. if portal.MXID == "" {
  2460. return
  2461. }
  2462. matrixUsers, err := portal.GetMatrixUsers()
  2463. if err != nil {
  2464. portal.log.Errorln("Failed to get Matrix users to see if DeleteChat should be handled:", err)
  2465. return
  2466. }
  2467. if len(matrixUsers) > 1 {
  2468. portal.log.Infoln("Portal contains more than one Matrix user, so deleteChat will not be handled.")
  2469. return
  2470. } else if (len(matrixUsers) == 1 && matrixUsers[0] == user.MXID) || len(matrixUsers) < 1 {
  2471. portal.log.Debugln("User deleted chat and there are no other Matrix users using it, deleting portal...")
  2472. portal.Delete()
  2473. portal.Cleanup(false)
  2474. }
  2475. }
  2476. const failedMediaField = "fi.mau.whatsapp.failed_media"
  2477. type FailedMediaKeys struct {
  2478. Key []byte `json:"key"`
  2479. Length int `json:"length"`
  2480. Type whatsmeow.MediaType `json:"type"`
  2481. SHA256 []byte `json:"sha256"`
  2482. EncSHA256 []byte `json:"enc_sha256"`
  2483. }
  2484. type FailedMediaMeta struct {
  2485. Type event.Type `json:"type"`
  2486. Content *event.MessageEventContent `json:"content"`
  2487. ExtraContent map[string]interface{} `json:"extra_content,omitempty"`
  2488. Media FailedMediaKeys `json:"whatsapp_media"`
  2489. }
  2490. func shallowCopyMap(data map[string]interface{}) map[string]interface{} {
  2491. newMap := make(map[string]interface{}, len(data))
  2492. for key, value := range data {
  2493. newMap[key] = value
  2494. }
  2495. return newMap
  2496. }
  2497. func (portal *Portal) makeMediaBridgeFailureMessage(info *types.MessageInfo, bridgeErr error, converted *ConvertedMessage, keys *FailedMediaKeys, userFriendlyError string) *ConvertedMessage {
  2498. if errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith410) {
  2499. portal.log.Debugfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
  2500. } else {
  2501. portal.log.Errorfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
  2502. }
  2503. if keys != nil {
  2504. if portal.bridge.Config.Bridge.CaptionInMessage {
  2505. converted.MergeCaption()
  2506. }
  2507. meta := &FailedMediaMeta{
  2508. Type: converted.Type,
  2509. Content: converted.Content,
  2510. ExtraContent: shallowCopyMap(converted.Extra),
  2511. Media: *keys,
  2512. }
  2513. converted.Extra[failedMediaField] = meta
  2514. portal.mediaErrorCache[info.ID] = meta
  2515. }
  2516. converted.Type = event.EventMessage
  2517. body := userFriendlyError
  2518. if body == "" {
  2519. body = fmt.Sprintf("Failed to bridge media: %v", bridgeErr)
  2520. }
  2521. converted.Content = &event.MessageEventContent{
  2522. MsgType: event.MsgNotice,
  2523. Body: body,
  2524. }
  2525. return converted
  2526. }
  2527. func (portal *Portal) encryptFileInPlace(data []byte, mimeType string) (string, *event.EncryptedFileInfo) {
  2528. if !portal.Encrypted {
  2529. return mimeType, nil
  2530. }
  2531. file := &event.EncryptedFileInfo{
  2532. EncryptedFile: *attachment.NewEncryptedFile(),
  2533. URL: "",
  2534. }
  2535. file.EncryptInPlace(data)
  2536. return "application/octet-stream", file
  2537. }
  2538. type MediaMessage interface {
  2539. whatsmeow.DownloadableMessage
  2540. GetContextInfo() *waProto.ContextInfo
  2541. GetFileLength() uint64
  2542. GetMimetype() string
  2543. }
  2544. type MediaMessageWithThumbnail interface {
  2545. MediaMessage
  2546. GetJpegThumbnail() []byte
  2547. }
  2548. type MediaMessageWithCaption interface {
  2549. MediaMessage
  2550. GetCaption() string
  2551. }
  2552. type MediaMessageWithDimensions interface {
  2553. MediaMessage
  2554. GetHeight() uint32
  2555. GetWidth() uint32
  2556. }
  2557. type MediaMessageWithFileName interface {
  2558. MediaMessage
  2559. GetFileName() string
  2560. }
  2561. type MediaMessageWithDuration interface {
  2562. MediaMessage
  2563. GetSeconds() uint32
  2564. }
  2565. const WhatsAppStickerSize = 190
  2566. func (portal *Portal) convertMediaMessageContent(intent *appservice.IntentAPI, msg MediaMessage) *ConvertedMessage {
  2567. content := &event.MessageEventContent{
  2568. Info: &event.FileInfo{
  2569. MimeType: msg.GetMimetype(),
  2570. Size: int(msg.GetFileLength()),
  2571. },
  2572. }
  2573. extraContent := map[string]interface{}{}
  2574. messageWithDimensions, ok := msg.(MediaMessageWithDimensions)
  2575. if ok {
  2576. content.Info.Width = int(messageWithDimensions.GetWidth())
  2577. content.Info.Height = int(messageWithDimensions.GetHeight())
  2578. }
  2579. msgWithName, ok := msg.(MediaMessageWithFileName)
  2580. if ok && len(msgWithName.GetFileName()) > 0 {
  2581. content.Body = msgWithName.GetFileName()
  2582. } else {
  2583. mimeClass := strings.Split(msg.GetMimetype(), "/")[0]
  2584. switch mimeClass {
  2585. case "application":
  2586. content.Body = "file"
  2587. default:
  2588. content.Body = mimeClass
  2589. }
  2590. content.Body += util.ExtensionFromMimetype(msg.GetMimetype())
  2591. }
  2592. msgWithDuration, ok := msg.(MediaMessageWithDuration)
  2593. if ok {
  2594. content.Info.Duration = int(msgWithDuration.GetSeconds()) * 1000
  2595. }
  2596. videoMessage, ok := msg.(*waProto.VideoMessage)
  2597. var isGIF bool
  2598. if ok && videoMessage.GetGifPlayback() {
  2599. isGIF = true
  2600. extraContent["info"] = map[string]interface{}{
  2601. "fi.mau.loop": true,
  2602. "fi.mau.autoplay": true,
  2603. "fi.mau.hide_controls": true,
  2604. "fi.mau.no_audio": true,
  2605. }
  2606. }
  2607. messageWithThumbnail, ok := msg.(MediaMessageWithThumbnail)
  2608. if ok && messageWithThumbnail.GetJpegThumbnail() != nil && (portal.bridge.Config.Bridge.WhatsappThumbnail || isGIF) {
  2609. thumbnailData := messageWithThumbnail.GetJpegThumbnail()
  2610. thumbnailMime := http.DetectContentType(thumbnailData)
  2611. thumbnailCfg, _, _ := image.DecodeConfig(bytes.NewReader(thumbnailData))
  2612. thumbnailSize := len(thumbnailData)
  2613. thumbnailUploadMime, thumbnailFile := portal.encryptFileInPlace(thumbnailData, thumbnailMime)
  2614. uploadedThumbnail, err := intent.UploadBytes(thumbnailData, thumbnailUploadMime)
  2615. if err != nil {
  2616. portal.log.Warnfln("Failed to upload thumbnail: %v", err)
  2617. } else if uploadedThumbnail != nil {
  2618. if thumbnailFile != nil {
  2619. thumbnailFile.URL = uploadedThumbnail.ContentURI.CUString()
  2620. content.Info.ThumbnailFile = thumbnailFile
  2621. } else {
  2622. content.Info.ThumbnailURL = uploadedThumbnail.ContentURI.CUString()
  2623. }
  2624. content.Info.ThumbnailInfo = &event.FileInfo{
  2625. Size: thumbnailSize,
  2626. Width: thumbnailCfg.Width,
  2627. Height: thumbnailCfg.Height,
  2628. MimeType: thumbnailMime,
  2629. }
  2630. }
  2631. }
  2632. eventType := event.EventMessage
  2633. switch msg.(type) {
  2634. case *waProto.ImageMessage:
  2635. content.MsgType = event.MsgImage
  2636. case *waProto.StickerMessage:
  2637. eventType = event.EventSticker
  2638. if content.Info.Width > content.Info.Height {
  2639. content.Info.Height /= content.Info.Width / WhatsAppStickerSize
  2640. content.Info.Width = WhatsAppStickerSize
  2641. } else if content.Info.Width < content.Info.Height {
  2642. content.Info.Width /= content.Info.Height / WhatsAppStickerSize
  2643. content.Info.Height = WhatsAppStickerSize
  2644. } else {
  2645. content.Info.Width = WhatsAppStickerSize
  2646. content.Info.Height = WhatsAppStickerSize
  2647. }
  2648. case *waProto.VideoMessage:
  2649. content.MsgType = event.MsgVideo
  2650. case *waProto.AudioMessage:
  2651. content.MsgType = event.MsgAudio
  2652. case *waProto.DocumentMessage:
  2653. content.MsgType = event.MsgFile
  2654. default:
  2655. portal.log.Warnfln("Unexpected media type %T in convertMediaMessageContent", msg)
  2656. content.MsgType = event.MsgFile
  2657. }
  2658. audioMessage, ok := msg.(*waProto.AudioMessage)
  2659. if ok {
  2660. var waveform []int
  2661. if audioMessage.Waveform != nil {
  2662. waveform = make([]int, len(audioMessage.Waveform))
  2663. max := 0
  2664. for i, part := range audioMessage.Waveform {
  2665. waveform[i] = int(part)
  2666. if waveform[i] > max {
  2667. max = waveform[i]
  2668. }
  2669. }
  2670. multiplier := 0
  2671. if max > 0 {
  2672. multiplier = 1024 / max
  2673. }
  2674. if multiplier > 32 {
  2675. multiplier = 32
  2676. }
  2677. for i := range waveform {
  2678. waveform[i] *= multiplier
  2679. }
  2680. }
  2681. extraContent["org.matrix.msc1767.audio"] = map[string]interface{}{
  2682. "duration": int(audioMessage.GetSeconds()) * 1000,
  2683. "waveform": waveform,
  2684. }
  2685. if audioMessage.GetPtt() {
  2686. extraContent["org.matrix.msc3245.voice"] = map[string]interface{}{}
  2687. }
  2688. }
  2689. messageWithCaption, ok := msg.(MediaMessageWithCaption)
  2690. var captionContent *event.MessageEventContent
  2691. if ok && len(messageWithCaption.GetCaption()) > 0 {
  2692. captionContent = &event.MessageEventContent{
  2693. Body: messageWithCaption.GetCaption(),
  2694. MsgType: event.MsgNotice,
  2695. }
  2696. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, captionContent, msg.GetContextInfo().GetMentionedJid(), false, false)
  2697. }
  2698. return &ConvertedMessage{
  2699. Intent: intent,
  2700. Type: eventType,
  2701. Content: content,
  2702. Caption: captionContent,
  2703. ReplyTo: GetReply(msg.GetContextInfo()),
  2704. ExpiresIn: msg.GetContextInfo().GetExpiration(),
  2705. Extra: extraContent,
  2706. }
  2707. }
  2708. func (portal *Portal) uploadMedia(intent *appservice.IntentAPI, data []byte, content *event.MessageEventContent) error {
  2709. uploadMimeType, file := portal.encryptFileInPlace(data, content.Info.MimeType)
  2710. req := mautrix.ReqUploadMedia{
  2711. ContentBytes: data,
  2712. ContentType: uploadMimeType,
  2713. }
  2714. var mxc id.ContentURI
  2715. if portal.bridge.Config.Homeserver.AsyncMedia {
  2716. uploaded, err := intent.UnstableUploadAsync(req)
  2717. if err != nil {
  2718. return err
  2719. }
  2720. mxc = uploaded.ContentURI
  2721. } else {
  2722. uploaded, err := intent.UploadMedia(req)
  2723. if err != nil {
  2724. return err
  2725. }
  2726. mxc = uploaded.ContentURI
  2727. }
  2728. if file != nil {
  2729. file.URL = mxc.CUString()
  2730. content.File = file
  2731. } else {
  2732. content.URL = mxc.CUString()
  2733. }
  2734. content.Info.Size = len(data)
  2735. if content.Info.Width == 0 && content.Info.Height == 0 && strings.HasPrefix(content.Info.MimeType, "image/") {
  2736. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  2737. content.Info.Width, content.Info.Height = cfg.Width, cfg.Height
  2738. }
  2739. return nil
  2740. }
  2741. func (portal *Portal) convertMediaMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg MediaMessage, typeName string, isBackfill bool) *ConvertedMessage {
  2742. converted := portal.convertMediaMessageContent(intent, msg)
  2743. if msg.GetFileLength() > uint64(portal.bridge.MediaConfig.UploadSize) {
  2744. return portal.makeMediaBridgeFailureMessage(info, errors.New("file is too large"), converted, nil, fmt.Sprintf("Large %s not bridged - please use WhatsApp app to view", typeName))
  2745. }
  2746. data, err := source.Client.Download(msg)
  2747. if errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith410) {
  2748. converted.Error = database.MsgErrMediaNotFound
  2749. converted.MediaKey = msg.GetMediaKey()
  2750. errorText := fmt.Sprintf("Old %s.", typeName)
  2751. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia && isBackfill {
  2752. errorText += " Media will be automatically requested from your phone later."
  2753. } else {
  2754. errorText += " React with the \u267b (recycle) emoji to request this media from your phone."
  2755. }
  2756. return portal.makeMediaBridgeFailureMessage(info, err, converted, &FailedMediaKeys{
  2757. Key: msg.GetMediaKey(),
  2758. Length: int(msg.GetFileLength()),
  2759. Type: whatsmeow.GetMediaType(msg),
  2760. SHA256: msg.GetFileSha256(),
  2761. EncSHA256: msg.GetFileEncSha256(),
  2762. }, errorText)
  2763. } else if errors.Is(err, whatsmeow.ErrNoURLPresent) {
  2764. portal.log.Debugfln("No URL present error for media message %s, ignoring...", info.ID)
  2765. return nil
  2766. } else if errors.Is(err, whatsmeow.ErrFileLengthMismatch) || errors.Is(err, whatsmeow.ErrInvalidMediaSHA256) {
  2767. portal.log.Warnfln("Mismatching media checksums in %s: %v. Ignoring because WhatsApp seems to ignore them too", info.ID, err)
  2768. } else if err != nil {
  2769. return portal.makeMediaBridgeFailureMessage(info, err, converted, nil, "")
  2770. }
  2771. err = portal.uploadMedia(intent, data, converted.Content)
  2772. if err != nil {
  2773. if errors.Is(err, mautrix.MTooLarge) {
  2774. return portal.makeMediaBridgeFailureMessage(info, errors.New("homeserver rejected too large file"), converted, nil, "")
  2775. } else if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.IsStatus(413) {
  2776. return portal.makeMediaBridgeFailureMessage(info, errors.New("proxy rejected too large file"), converted, nil, "")
  2777. } else {
  2778. return portal.makeMediaBridgeFailureMessage(info, fmt.Errorf("failed to upload media: %w", err), converted, nil, "")
  2779. }
  2780. }
  2781. return converted
  2782. }
  2783. func (portal *Portal) fetchMediaRetryEvent(msg *database.Message) (*FailedMediaMeta, error) {
  2784. errorMeta, ok := portal.mediaErrorCache[msg.JID]
  2785. if ok {
  2786. return errorMeta, nil
  2787. }
  2788. evt, err := portal.MainIntent().GetEvent(portal.MXID, msg.MXID)
  2789. if err != nil {
  2790. return nil, fmt.Errorf("failed to fetch event %s: %w", msg.MXID, err)
  2791. }
  2792. if evt.Type == event.EventEncrypted {
  2793. err = evt.Content.ParseRaw(evt.Type)
  2794. if err != nil {
  2795. return nil, fmt.Errorf("failed to parse encrypted content in %s: %w", msg.MXID, err)
  2796. }
  2797. evt, err = portal.bridge.Crypto.Decrypt(evt)
  2798. if err != nil {
  2799. return nil, fmt.Errorf("failed to decrypt event %s: %w", msg.MXID, err)
  2800. }
  2801. }
  2802. errorMetaResult := gjson.GetBytes(evt.Content.VeryRaw, strings.ReplaceAll(failedMediaField, ".", "\\."))
  2803. if !errorMetaResult.Exists() || !errorMetaResult.IsObject() {
  2804. return nil, fmt.Errorf("didn't find failed media metadata in %s", msg.MXID)
  2805. }
  2806. var errorMetaBytes []byte
  2807. if errorMetaResult.Index > 0 {
  2808. errorMetaBytes = evt.Content.VeryRaw[errorMetaResult.Index : errorMetaResult.Index+len(errorMetaResult.Raw)]
  2809. } else {
  2810. errorMetaBytes = []byte(errorMetaResult.Raw)
  2811. }
  2812. err = json.Unmarshal(errorMetaBytes, &errorMeta)
  2813. if err != nil {
  2814. return nil, fmt.Errorf("failed to unmarshal failed media metadata in %s: %w", msg.MXID, err)
  2815. }
  2816. return errorMeta, nil
  2817. }
  2818. func (portal *Portal) sendMediaRetryFailureEdit(intent *appservice.IntentAPI, msg *database.Message, err error) {
  2819. content := event.MessageEventContent{
  2820. MsgType: event.MsgNotice,
  2821. Body: fmt.Sprintf("Failed to bridge media after re-requesting it from your phone: %v", err),
  2822. }
  2823. contentCopy := content
  2824. content.NewContent = &contentCopy
  2825. content.RelatesTo = &event.RelatesTo{
  2826. EventID: msg.MXID,
  2827. Type: event.RelReplace,
  2828. }
  2829. resp, sendErr := portal.sendMessage(intent, event.EventMessage, &content, nil, time.Now().UnixMilli())
  2830. if sendErr != nil {
  2831. portal.log.Warnfln("Failed to edit %s after retry failure for %s: %v", msg.MXID, msg.JID, sendErr)
  2832. } else {
  2833. portal.log.Debugfln("Successfully edited %s -> %s after retry failure for %s", msg.MXID, resp.EventID, msg.JID)
  2834. }
  2835. }
  2836. func (portal *Portal) handleMediaRetry(retry *events.MediaRetry, source *User) {
  2837. msg := portal.bridge.DB.Message.GetByJID(portal.Key, retry.MessageID)
  2838. if msg == nil {
  2839. portal.log.Warnfln("Dropping media retry notification for unknown message %s", retry.MessageID)
  2840. return
  2841. } else if msg.Error != database.MsgErrMediaNotFound {
  2842. portal.log.Warnfln("Dropping media retry notification for non-errored message %s / %s", retry.MessageID, msg.MXID)
  2843. return
  2844. }
  2845. meta, err := portal.fetchMediaRetryEvent(msg)
  2846. if err != nil {
  2847. portal.log.Warnfln("Can't handle media retry notification for %s: %v", retry.MessageID, err)
  2848. return
  2849. }
  2850. var puppet *Puppet
  2851. if retry.FromMe {
  2852. puppet = portal.bridge.GetPuppetByJID(source.JID)
  2853. } else if retry.ChatID.Server == types.DefaultUserServer {
  2854. puppet = portal.bridge.GetPuppetByJID(retry.ChatID)
  2855. } else {
  2856. puppet = portal.bridge.GetPuppetByJID(retry.SenderID)
  2857. }
  2858. intent := puppet.IntentFor(portal)
  2859. retryData, err := whatsmeow.DecryptMediaRetryNotification(retry, meta.Media.Key)
  2860. if err != nil {
  2861. portal.log.Warnfln("Failed to handle media retry notification for %s: %v", retry.MessageID, err)
  2862. portal.sendMediaRetryFailureEdit(intent, msg, err)
  2863. return
  2864. } else if retryData.GetResult() != waProto.MediaRetryNotification_SUCCESS {
  2865. errorName := waProto.MediaRetryNotification_ResultType_name[int32(retryData.GetResult())]
  2866. if retryData.GetDirectPath() == "" {
  2867. portal.log.Warnfln("Got error response in media retry notification for %s: %s", retry.MessageID, errorName)
  2868. portal.log.Debugfln("Error response contents: %+v", retryData)
  2869. if retryData.GetResult() == waProto.MediaRetryNotification_NOT_FOUND {
  2870. portal.sendMediaRetryFailureEdit(intent, msg, whatsmeow.ErrMediaNotAvailableOnPhone)
  2871. } else {
  2872. portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("phone sent error response: %s", errorName))
  2873. }
  2874. return
  2875. } else {
  2876. portal.log.Debugfln("Got error response %s in media retry notification for %s, but response also contains a new download URL - trying to download", retry.MessageID, errorName)
  2877. }
  2878. }
  2879. data, err := source.Client.DownloadMediaWithPath(retryData.GetDirectPath(), meta.Media.EncSHA256, meta.Media.SHA256, meta.Media.Key, meta.Media.Length, meta.Media.Type, "")
  2880. if err != nil {
  2881. portal.log.Warnfln("Failed to download media in %s after retry notification: %v", retry.MessageID, err)
  2882. portal.sendMediaRetryFailureEdit(intent, msg, err)
  2883. return
  2884. }
  2885. err = portal.uploadMedia(intent, data, meta.Content)
  2886. if err != nil {
  2887. portal.log.Warnfln("Failed to re-upload media for %s after retry notification: %v", retry.MessageID, err)
  2888. portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("re-uploading media failed: %v", err))
  2889. return
  2890. }
  2891. replaceContent := &event.MessageEventContent{
  2892. MsgType: meta.Content.MsgType,
  2893. Body: "* " + meta.Content.Body,
  2894. NewContent: meta.Content,
  2895. RelatesTo: &event.RelatesTo{
  2896. EventID: msg.MXID,
  2897. Type: event.RelReplace,
  2898. },
  2899. }
  2900. // Move the extra content into m.new_content too
  2901. meta.ExtraContent = map[string]interface{}{
  2902. "m.new_content": shallowCopyMap(meta.ExtraContent),
  2903. }
  2904. resp, err := portal.sendMessage(intent, meta.Type, replaceContent, meta.ExtraContent, time.Now().UnixMilli())
  2905. if err != nil {
  2906. portal.log.Warnfln("Failed to edit %s after retry notification for %s: %v", msg.MXID, retry.MessageID, err)
  2907. return
  2908. }
  2909. portal.log.Debugfln("Successfully edited %s -> %s after retry notification for %s", msg.MXID, resp.EventID, retry.MessageID)
  2910. msg.UpdateMXID(nil, resp.EventID, database.MsgNormal, database.MsgNoError)
  2911. }
  2912. func (portal *Portal) requestMediaRetry(user *User, eventID id.EventID, mediaKey []byte) (bool, error) {
  2913. msg := portal.bridge.DB.Message.GetByMXID(eventID)
  2914. if msg == nil {
  2915. err := errors.New(fmt.Sprintf("%s requested a media retry for unknown event %s", user.MXID, eventID))
  2916. portal.log.Debugfln(err.Error())
  2917. return false, err
  2918. } else if msg.Error != database.MsgErrMediaNotFound {
  2919. err := errors.New(fmt.Sprintf("%s requested a media retry for non-errored event %s", user.MXID, eventID))
  2920. portal.log.Debugfln(err.Error())
  2921. return false, err
  2922. }
  2923. // If the media key is not provided, grab it from the event in Matrix
  2924. if mediaKey == nil {
  2925. evt, err := portal.fetchMediaRetryEvent(msg)
  2926. if err != nil {
  2927. portal.log.Warnfln("Can't send media retry request for %s: %v", msg.JID, err)
  2928. return true, nil
  2929. }
  2930. mediaKey = evt.Media.Key
  2931. }
  2932. err := user.Client.SendMediaRetryReceipt(&types.MessageInfo{
  2933. ID: msg.JID,
  2934. MessageSource: types.MessageSource{
  2935. IsFromMe: msg.Sender.User == user.JID.User,
  2936. IsGroup: !portal.IsPrivateChat(),
  2937. Sender: msg.Sender,
  2938. Chat: portal.Key.JID,
  2939. },
  2940. }, mediaKey)
  2941. if err != nil {
  2942. portal.log.Warnfln("Failed to send media retry request for %s: %v", msg.JID, err)
  2943. } else {
  2944. portal.log.Debugfln("Sent media retry request for %s", msg.JID)
  2945. }
  2946. return true, err
  2947. }
  2948. const thumbnailMaxSize = 72
  2949. const thumbnailMinSize = 24
  2950. func createThumbnailAndGetSize(source []byte, pngThumbnail bool) ([]byte, int, int, error) {
  2951. src, _, err := image.Decode(bytes.NewReader(source))
  2952. if err != nil {
  2953. return nil, 0, 0, fmt.Errorf("failed to decode thumbnail: %w", err)
  2954. }
  2955. imageBounds := src.Bounds()
  2956. width, height := imageBounds.Max.X, imageBounds.Max.Y
  2957. var img image.Image
  2958. if width <= thumbnailMaxSize && height <= thumbnailMaxSize {
  2959. // No need to resize
  2960. img = src
  2961. } else {
  2962. if width == height {
  2963. width = thumbnailMaxSize
  2964. height = thumbnailMaxSize
  2965. } else if width < height {
  2966. width /= height / thumbnailMaxSize
  2967. height = thumbnailMaxSize
  2968. } else {
  2969. height /= width / thumbnailMaxSize
  2970. width = thumbnailMaxSize
  2971. }
  2972. if width < thumbnailMinSize {
  2973. width = thumbnailMinSize
  2974. }
  2975. if height < thumbnailMinSize {
  2976. height = thumbnailMinSize
  2977. }
  2978. dst := image.NewRGBA(image.Rect(0, 0, width, height))
  2979. draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  2980. img = dst
  2981. }
  2982. var buf bytes.Buffer
  2983. if pngThumbnail {
  2984. err = png.Encode(&buf, img)
  2985. } else {
  2986. err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpeg.DefaultQuality})
  2987. }
  2988. if err != nil {
  2989. return nil, width, height, fmt.Errorf("failed to re-encode thumbnail: %w", err)
  2990. }
  2991. return buf.Bytes(), width, height, nil
  2992. }
  2993. func createThumbnail(source []byte, png bool) ([]byte, error) {
  2994. data, _, _, err := createThumbnailAndGetSize(source, png)
  2995. return data, err
  2996. }
  2997. func (portal *Portal) downloadThumbnail(ctx context.Context, original []byte, thumbnailURL id.ContentURIString, eventID id.EventID, png bool) ([]byte, error) {
  2998. if len(thumbnailURL) == 0 {
  2999. // just fall back to making thumbnail of original
  3000. } else if mxc, err := thumbnailURL.Parse(); err != nil {
  3001. portal.log.Warnfln("Malformed thumbnail URL in %s: %v (falling back to generating thumbnail from source)", eventID, err)
  3002. } else if thumbnail, err := portal.MainIntent().DownloadBytesContext(ctx, mxc); err != nil {
  3003. portal.log.Warnfln("Failed to download thumbnail in %s: %v (falling back to generating thumbnail from source)", eventID, err)
  3004. } else {
  3005. return createThumbnail(thumbnail, png)
  3006. }
  3007. return createThumbnail(original, png)
  3008. }
  3009. func (portal *Portal) convertWebPtoPNG(webpImage []byte) ([]byte, error) {
  3010. webpDecoded, err := webp.Decode(bytes.NewReader(webpImage))
  3011. if err != nil {
  3012. return nil, fmt.Errorf("failed to decode webp image: %w", err)
  3013. }
  3014. var pngBuffer bytes.Buffer
  3015. if err = png.Encode(&pngBuffer, webpDecoded); err != nil {
  3016. return nil, fmt.Errorf("failed to encode png image: %w", err)
  3017. }
  3018. return pngBuffer.Bytes(), nil
  3019. }
  3020. type PaddedImage struct {
  3021. image.Image
  3022. Size int
  3023. OffsetX int
  3024. OffsetY int
  3025. }
  3026. func (img *PaddedImage) Bounds() image.Rectangle {
  3027. return image.Rect(0, 0, img.Size, img.Size)
  3028. }
  3029. func (img *PaddedImage) At(x, y int) color.Color {
  3030. return img.Image.At(x+img.OffsetX, y+img.OffsetY)
  3031. }
  3032. func (portal *Portal) convertToWebP(img []byte) ([]byte, error) {
  3033. decodedImg, _, err := image.Decode(bytes.NewReader(img))
  3034. if err != nil {
  3035. return img, fmt.Errorf("failed to decode image: %w", err)
  3036. }
  3037. bounds := decodedImg.Bounds()
  3038. width, height := bounds.Dx(), bounds.Dy()
  3039. if width != height {
  3040. paddedImg := &PaddedImage{
  3041. Image: decodedImg,
  3042. OffsetX: bounds.Min.Y,
  3043. OffsetY: bounds.Min.X,
  3044. }
  3045. if width > height {
  3046. paddedImg.Size = width
  3047. paddedImg.OffsetY -= (paddedImg.Size - height) / 2
  3048. } else {
  3049. paddedImg.Size = height
  3050. paddedImg.OffsetX -= (paddedImg.Size - width) / 2
  3051. }
  3052. decodedImg = paddedImg
  3053. }
  3054. var webpBuffer bytes.Buffer
  3055. if err = webp.Encode(&webpBuffer, decodedImg, nil); err != nil {
  3056. return img, fmt.Errorf("failed to encode webp image: %w", err)
  3057. }
  3058. return webpBuffer.Bytes(), nil
  3059. }
  3060. func (portal *Portal) preprocessMatrixMedia(ctx context.Context, sender *User, relaybotFormatted bool, content *event.MessageEventContent, eventID id.EventID, mediaType whatsmeow.MediaType) (*MediaUpload, error) {
  3061. fileName := content.Body
  3062. var caption string
  3063. var mentionedJIDs []string
  3064. var hasHTMLCaption bool
  3065. isSticker := string(content.MsgType) == event.EventSticker.Type
  3066. if content.FileName != "" && content.Body != content.FileName {
  3067. fileName = content.FileName
  3068. caption = content.Body
  3069. hasHTMLCaption = content.Format == event.FormatHTML
  3070. }
  3071. if relaybotFormatted || hasHTMLCaption {
  3072. caption, mentionedJIDs = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
  3073. }
  3074. var file *event.EncryptedFileInfo
  3075. rawMXC := content.URL
  3076. if content.File != nil {
  3077. file = content.File
  3078. rawMXC = file.URL
  3079. }
  3080. mxc, err := rawMXC.Parse()
  3081. if err != nil {
  3082. return nil, err
  3083. }
  3084. data, err := portal.MainIntent().DownloadBytesContext(ctx, mxc)
  3085. if err != nil {
  3086. return nil, util.NewDualError(errMediaDownloadFailed, err)
  3087. }
  3088. if file != nil {
  3089. err = file.DecryptInPlace(data)
  3090. if err != nil {
  3091. return nil, util.NewDualError(errMediaDecryptFailed, err)
  3092. }
  3093. }
  3094. mimeType := content.GetInfo().MimeType
  3095. var convertErr error
  3096. // Allowed mime types from https://developers.facebook.com/docs/whatsapp/on-premises/reference/media
  3097. switch {
  3098. case isSticker:
  3099. if mimeType != "image/webp" || content.Info.Width != content.Info.Height {
  3100. data, convertErr = portal.convertToWebP(data)
  3101. content.Info.MimeType = "image/webp"
  3102. }
  3103. case mediaType == whatsmeow.MediaVideo:
  3104. switch mimeType {
  3105. case "video/mp4", "video/3gpp":
  3106. // Allowed
  3107. case "image/gif":
  3108. data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "gif"}, []string{
  3109. "-pix_fmt", "yuv420p", "-c:v", "libx264", "-movflags", "+faststart",
  3110. "-filter:v", "crop='floor(in_w/2)*2:floor(in_h/2)*2'",
  3111. }, mimeType)
  3112. content.Info.MimeType = "video/mp4"
  3113. case "video/webm":
  3114. data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "webm"}, []string{
  3115. "-pix_fmt", "yuv420p", "-c:v", "libx264",
  3116. }, mimeType)
  3117. content.Info.MimeType = "video/mp4"
  3118. default:
  3119. return nil, fmt.Errorf("%w %q in video message", errMediaUnsupportedType, mimeType)
  3120. }
  3121. case mediaType == whatsmeow.MediaImage:
  3122. switch mimeType {
  3123. case "image/jpeg", "image/png":
  3124. // Allowed
  3125. case "image/webp":
  3126. data, convertErr = portal.convertWebPtoPNG(data)
  3127. content.Info.MimeType = "image/png"
  3128. default:
  3129. return nil, fmt.Errorf("%w %q in image message", errMediaUnsupportedType, mimeType)
  3130. }
  3131. case mediaType == whatsmeow.MediaAudio:
  3132. switch mimeType {
  3133. case "audio/aac", "audio/mp4", "audio/amr", "audio/mpeg", "audio/ogg; codecs=opus":
  3134. // Allowed
  3135. case "audio/ogg":
  3136. // Hopefully it's opus already
  3137. content.Info.MimeType = "audio/ogg; codecs=opus"
  3138. default:
  3139. return nil, fmt.Errorf("%w %q in audio message", errMediaUnsupportedType, mimeType)
  3140. }
  3141. case mediaType == whatsmeow.MediaDocument:
  3142. // Everything is allowed
  3143. }
  3144. if convertErr != nil {
  3145. if content.Info.MimeType != mimeType || data == nil {
  3146. return nil, util.NewDualError(fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, content.Info.MimeType), convertErr)
  3147. } else {
  3148. // If the mime type didn't change and the errored conversion function returned the original data, just log a warning and continue
  3149. portal.log.Warnfln("Failed to re-encode %s media: %v, continuing with original file", mimeType, convertErr)
  3150. }
  3151. }
  3152. uploadResp, err := sender.Client.Upload(ctx, data, mediaType)
  3153. if err != nil {
  3154. return nil, util.NewDualError(errMediaWhatsAppUploadFailed, err)
  3155. }
  3156. // Audio doesn't have thumbnails
  3157. var thumbnail []byte
  3158. if mediaType != whatsmeow.MediaAudio {
  3159. thumbnail, err = portal.downloadThumbnail(ctx, data, content.GetInfo().ThumbnailURL, eventID, isSticker)
  3160. // Ignore format errors for non-image files, we don't care about those thumbnails
  3161. if err != nil && (!errors.Is(err, image.ErrFormat) || mediaType == whatsmeow.MediaImage) {
  3162. portal.log.Warnfln("Failed to generate thumbnail for %s: %v", eventID, err)
  3163. }
  3164. }
  3165. return &MediaUpload{
  3166. UploadResponse: uploadResp,
  3167. FileName: fileName,
  3168. Caption: caption,
  3169. MentionedJIDs: mentionedJIDs,
  3170. Thumbnail: thumbnail,
  3171. FileLength: len(data),
  3172. }, nil
  3173. }
  3174. type MediaUpload struct {
  3175. whatsmeow.UploadResponse
  3176. Caption string
  3177. FileName string
  3178. MentionedJIDs []string
  3179. Thumbnail []byte
  3180. FileLength int
  3181. }
  3182. func (portal *Portal) addRelaybotFormat(sender *User, content *event.MessageEventContent) bool {
  3183. member := portal.MainIntent().Member(portal.MXID, sender.MXID)
  3184. if member == nil {
  3185. member = &event.MemberEventContent{}
  3186. }
  3187. content.EnsureHasHTML()
  3188. data, err := portal.bridge.Config.Bridge.Relay.FormatMessage(content, sender.MXID, *member)
  3189. if err != nil {
  3190. portal.log.Errorln("Failed to apply relaybot format:", err)
  3191. }
  3192. content.FormattedBody = data
  3193. return true
  3194. }
  3195. func addCodecToMime(mimeType, codec string) string {
  3196. mediaType, params, err := mime.ParseMediaType(mimeType)
  3197. if err != nil {
  3198. return mimeType
  3199. }
  3200. if _, ok := params["codecs"]; !ok {
  3201. params["codecs"] = codec
  3202. }
  3203. return mime.FormatMediaType(mediaType, params)
  3204. }
  3205. func parseGeoURI(uri string) (lat, long float64, err error) {
  3206. if !strings.HasPrefix(uri, "geo:") {
  3207. err = fmt.Errorf("uri doesn't have geo: prefix")
  3208. return
  3209. }
  3210. // Remove geo: prefix and anything after ;
  3211. coordinates := strings.Split(strings.TrimPrefix(uri, "geo:"), ";")[0]
  3212. if splitCoordinates := strings.Split(coordinates, ","); len(splitCoordinates) != 2 {
  3213. err = fmt.Errorf("didn't find exactly two numbers separated by a comma")
  3214. } else if lat, err = strconv.ParseFloat(splitCoordinates[0], 64); err != nil {
  3215. err = fmt.Errorf("latitude is not a number: %w", err)
  3216. } else if long, err = strconv.ParseFloat(splitCoordinates[1], 64); err != nil {
  3217. err = fmt.Errorf("longitude is not a number: %w", err)
  3218. }
  3219. return
  3220. }
  3221. func getUnstableWaveform(content map[string]interface{}) []byte {
  3222. audioInfo, ok := content["org.matrix.msc1767.audio"].(map[string]interface{})
  3223. if !ok {
  3224. return nil
  3225. }
  3226. waveform, ok := audioInfo["waveform"].([]interface{})
  3227. if !ok {
  3228. return nil
  3229. }
  3230. output := make([]byte, len(waveform))
  3231. var val float64
  3232. for i, part := range waveform {
  3233. val, ok = part.(float64)
  3234. if ok {
  3235. output[i] = byte(val / 4)
  3236. }
  3237. }
  3238. return output
  3239. }
  3240. var (
  3241. TypeMSC3881PollResponse = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.poll.response"}
  3242. TypeMSC3881V2PollResponse = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3881.v2.poll.response"}
  3243. )
  3244. type PollResponseContent struct {
  3245. RelatesTo event.RelatesTo `json:"m.relates_to"`
  3246. V1Response struct {
  3247. Answers []string `json:"answers"`
  3248. } `json:"org.matrix.msc3381.poll.response"`
  3249. V2Selections []string `json:"org.matrix.msc3381.v2.selections"`
  3250. }
  3251. func (content *PollResponseContent) GetRelatesTo() *event.RelatesTo {
  3252. return &content.RelatesTo
  3253. }
  3254. func (content *PollResponseContent) OptionalGetRelatesTo() *event.RelatesTo {
  3255. if content.RelatesTo.Type == "" {
  3256. return nil
  3257. }
  3258. return &content.RelatesTo
  3259. }
  3260. func (content *PollResponseContent) SetRelatesTo(rel *event.RelatesTo) {
  3261. content.RelatesTo = *rel
  3262. }
  3263. func init() {
  3264. event.TypeMap[TypeMSC3881PollResponse] = reflect.TypeOf(PollResponseContent{})
  3265. event.TypeMap[TypeMSC3881V2PollResponse] = reflect.TypeOf(PollResponseContent{})
  3266. }
  3267. func (portal *Portal) convertMatrixPollVote(_ context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, error) {
  3268. content, ok := evt.Content.Parsed.(*PollResponseContent)
  3269. if !ok {
  3270. return nil, sender, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3271. }
  3272. var answers []string
  3273. if content.V1Response.Answers != nil {
  3274. answers = content.V1Response.Answers
  3275. } else if content.V2Selections != nil {
  3276. answers = content.V2Selections
  3277. }
  3278. pollMsg := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
  3279. if pollMsg == nil {
  3280. return nil, sender, errTargetNotFound
  3281. }
  3282. pollMsgInfo := &types.MessageInfo{
  3283. MessageSource: types.MessageSource{
  3284. Chat: portal.Key.JID,
  3285. Sender: pollMsg.Sender,
  3286. IsFromMe: pollMsg.Sender.User == sender.JID.User,
  3287. IsGroup: portal.IsGroupChat(),
  3288. },
  3289. ID: pollMsg.JID,
  3290. Type: "poll",
  3291. }
  3292. optionHashes := make([][]byte, 0, len(answers))
  3293. for _, selection := range answers {
  3294. hash, _ := hex.DecodeString(selection)
  3295. if hash != nil && len(hash) == 32 {
  3296. optionHashes = append(optionHashes, hash)
  3297. }
  3298. }
  3299. pollUpdate, err := sender.Client.EncryptPollVote(pollMsgInfo, &waProto.PollVoteMessage{
  3300. SelectedOptions: optionHashes,
  3301. })
  3302. return &waProto.Message{PollUpdateMessage: pollUpdate}, sender, err
  3303. }
  3304. func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, error) {
  3305. if evt.Type == TypeMSC3881PollResponse || evt.Type == TypeMSC3881V2PollResponse {
  3306. return portal.convertMatrixPollVote(ctx, sender, evt)
  3307. }
  3308. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  3309. if !ok {
  3310. return nil, sender, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3311. }
  3312. var editRootMsg *database.Message
  3313. if editEventID := content.RelatesTo.GetReplaceID(); editEventID != "" && portal.bridge.Config.Bridge.SendWhatsAppEdits {
  3314. editRootMsg = portal.bridge.DB.Message.GetByMXID(editEventID)
  3315. if editRootMsg == nil || editRootMsg.Type != database.MsgNormal || editRootMsg.IsFakeJID() || editRootMsg.Sender.User != sender.JID.User {
  3316. return nil, sender, fmt.Errorf("edit rejected") // TODO more specific error message
  3317. }
  3318. if content.NewContent != nil {
  3319. content = content.NewContent
  3320. }
  3321. }
  3322. msg := &waProto.Message{}
  3323. var ctxInfo waProto.ContextInfo
  3324. replyToID := content.RelatesTo.GetReplyTo()
  3325. if len(replyToID) > 0 {
  3326. replyToMsg := portal.bridge.DB.Message.GetByMXID(replyToID)
  3327. if replyToMsg != nil && !replyToMsg.IsFakeJID() && replyToMsg.Type == database.MsgNormal {
  3328. ctxInfo.StanzaId = &replyToMsg.JID
  3329. ctxInfo.Participant = proto.String(replyToMsg.Sender.ToNonAD().String())
  3330. // Using blank content here seems to work fine on all official WhatsApp apps.
  3331. //
  3332. // We could probably invent a slightly more accurate version of the quoted message
  3333. // by fetching the Matrix event and converting it to the WhatsApp format, but that's
  3334. // a lot of work and this works fine.
  3335. ctxInfo.QuotedMessage = &waProto.Message{Conversation: proto.String("")}
  3336. }
  3337. }
  3338. if portal.ExpirationTime != 0 {
  3339. ctxInfo.Expiration = proto.Uint32(portal.ExpirationTime)
  3340. }
  3341. relaybotFormatted := false
  3342. if !sender.IsLoggedIn() || (portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User) {
  3343. if !portal.HasRelaybot() {
  3344. return nil, sender, errUserNotLoggedIn
  3345. }
  3346. relaybotFormatted = portal.addRelaybotFormat(sender, content)
  3347. sender = portal.GetRelayUser()
  3348. }
  3349. if evt.Type == event.EventSticker {
  3350. if relaybotFormatted {
  3351. // Stickers can't have captions, so force relaybot stickers to be images
  3352. content.MsgType = event.MsgImage
  3353. } else {
  3354. content.MsgType = event.MessageType(event.EventSticker.Type)
  3355. }
  3356. }
  3357. if content.MsgType == event.MsgImage && content.GetInfo().MimeType == "image/gif" {
  3358. content.MsgType = event.MsgVideo
  3359. }
  3360. switch content.MsgType {
  3361. case event.MsgText, event.MsgEmote, event.MsgNotice:
  3362. text := content.Body
  3363. if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
  3364. return nil, sender, errMNoticeDisabled
  3365. }
  3366. if content.Format == event.FormatHTML {
  3367. text, ctxInfo.MentionedJid = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
  3368. }
  3369. if content.MsgType == event.MsgEmote && !relaybotFormatted {
  3370. text = "/me " + text
  3371. }
  3372. msg.ExtendedTextMessage = &waProto.ExtendedTextMessage{
  3373. Text: &text,
  3374. ContextInfo: &ctxInfo,
  3375. }
  3376. hasPreview := portal.convertURLPreviewToWhatsApp(ctx, sender, evt, msg.ExtendedTextMessage)
  3377. if ctx.Err() != nil {
  3378. return nil, nil, ctx.Err()
  3379. }
  3380. if ctxInfo.StanzaId == nil && ctxInfo.MentionedJid == nil && ctxInfo.Expiration == nil && !hasPreview {
  3381. // No need for extended message
  3382. msg.ExtendedTextMessage = nil
  3383. msg.Conversation = &text
  3384. }
  3385. case event.MsgImage:
  3386. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
  3387. if media == nil {
  3388. return nil, sender, err
  3389. }
  3390. ctxInfo.MentionedJid = media.MentionedJIDs
  3391. msg.ImageMessage = &waProto.ImageMessage{
  3392. ContextInfo: &ctxInfo,
  3393. Caption: &media.Caption,
  3394. JpegThumbnail: media.Thumbnail,
  3395. Url: &media.URL,
  3396. MediaKey: media.MediaKey,
  3397. Mimetype: &content.GetInfo().MimeType,
  3398. FileEncSha256: media.FileEncSHA256,
  3399. FileSha256: media.FileSHA256,
  3400. FileLength: proto.Uint64(uint64(media.FileLength)),
  3401. }
  3402. case event.MessageType(event.EventSticker.Type):
  3403. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
  3404. if media == nil {
  3405. return nil, sender, err
  3406. }
  3407. ctxInfo.MentionedJid = media.MentionedJIDs
  3408. msg.StickerMessage = &waProto.StickerMessage{
  3409. ContextInfo: &ctxInfo,
  3410. PngThumbnail: media.Thumbnail,
  3411. Url: &media.URL,
  3412. MediaKey: media.MediaKey,
  3413. Mimetype: &content.GetInfo().MimeType,
  3414. FileEncSha256: media.FileEncSHA256,
  3415. FileSha256: media.FileSHA256,
  3416. FileLength: proto.Uint64(uint64(media.FileLength)),
  3417. }
  3418. case event.MsgVideo:
  3419. gifPlayback := content.GetInfo().MimeType == "image/gif"
  3420. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaVideo)
  3421. if media == nil {
  3422. return nil, sender, err
  3423. }
  3424. duration := uint32(content.GetInfo().Duration / 1000)
  3425. ctxInfo.MentionedJid = media.MentionedJIDs
  3426. msg.VideoMessage = &waProto.VideoMessage{
  3427. ContextInfo: &ctxInfo,
  3428. Caption: &media.Caption,
  3429. JpegThumbnail: media.Thumbnail,
  3430. Url: &media.URL,
  3431. MediaKey: media.MediaKey,
  3432. Mimetype: &content.GetInfo().MimeType,
  3433. GifPlayback: &gifPlayback,
  3434. Seconds: &duration,
  3435. FileEncSha256: media.FileEncSHA256,
  3436. FileSha256: media.FileSHA256,
  3437. FileLength: proto.Uint64(uint64(media.FileLength)),
  3438. }
  3439. case event.MsgAudio:
  3440. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaAudio)
  3441. if media == nil {
  3442. return nil, sender, err
  3443. }
  3444. duration := uint32(content.GetInfo().Duration / 1000)
  3445. msg.AudioMessage = &waProto.AudioMessage{
  3446. ContextInfo: &ctxInfo,
  3447. Url: &media.URL,
  3448. MediaKey: media.MediaKey,
  3449. Mimetype: &content.GetInfo().MimeType,
  3450. Seconds: &duration,
  3451. FileEncSha256: media.FileEncSHA256,
  3452. FileSha256: media.FileSHA256,
  3453. FileLength: proto.Uint64(uint64(media.FileLength)),
  3454. }
  3455. _, isMSC3245Voice := evt.Content.Raw["org.matrix.msc3245.voice"]
  3456. if isMSC3245Voice {
  3457. msg.AudioMessage.Waveform = getUnstableWaveform(evt.Content.Raw)
  3458. msg.AudioMessage.Ptt = proto.Bool(true)
  3459. // hacky hack to add the codecs param that whatsapp seems to require
  3460. msg.AudioMessage.Mimetype = proto.String(addCodecToMime(content.GetInfo().MimeType, "opus"))
  3461. }
  3462. case event.MsgFile:
  3463. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaDocument)
  3464. if media == nil {
  3465. return nil, sender, err
  3466. }
  3467. msg.DocumentMessage = &waProto.DocumentMessage{
  3468. ContextInfo: &ctxInfo,
  3469. Caption: &media.Caption,
  3470. JpegThumbnail: media.Thumbnail,
  3471. Url: &media.URL,
  3472. Title: &media.FileName,
  3473. FileName: &media.FileName,
  3474. MediaKey: media.MediaKey,
  3475. Mimetype: &content.GetInfo().MimeType,
  3476. FileEncSha256: media.FileEncSHA256,
  3477. FileSha256: media.FileSHA256,
  3478. FileLength: proto.Uint64(uint64(media.FileLength)),
  3479. }
  3480. if media.Caption != "" {
  3481. msg.DocumentWithCaptionMessage = &waProto.FutureProofMessage{
  3482. Message: &waProto.Message{
  3483. DocumentMessage: msg.DocumentMessage,
  3484. },
  3485. }
  3486. msg.DocumentMessage = nil
  3487. }
  3488. case event.MsgLocation:
  3489. lat, long, err := parseGeoURI(content.GeoURI)
  3490. if err != nil {
  3491. return nil, sender, fmt.Errorf("%w: %v", errInvalidGeoURI, err)
  3492. }
  3493. msg.LocationMessage = &waProto.LocationMessage{
  3494. DegreesLatitude: &lat,
  3495. DegreesLongitude: &long,
  3496. Comment: &content.Body,
  3497. ContextInfo: &ctxInfo,
  3498. }
  3499. default:
  3500. return nil, sender, fmt.Errorf("%w %q", errUnknownMsgType, content.MsgType)
  3501. }
  3502. if editRootMsg != nil {
  3503. msg = &waProto.Message{
  3504. EditedMessage: &waProto.FutureProofMessage{
  3505. Message: &waProto.Message{
  3506. ProtocolMessage: &waProto.ProtocolMessage{
  3507. Key: &waProto.MessageKey{
  3508. FromMe: proto.Bool(true),
  3509. Id: proto.String(editRootMsg.JID),
  3510. RemoteJid: proto.String(portal.Key.JID.String()),
  3511. },
  3512. Type: waProto.ProtocolMessage_MESSAGE_EDIT.Enum(),
  3513. EditedMessage: msg,
  3514. TimestampMs: proto.Int64(evt.Timestamp),
  3515. },
  3516. },
  3517. },
  3518. }
  3519. }
  3520. return msg, sender, nil
  3521. }
  3522. func (portal *Portal) generateMessageInfo(sender *User) *types.MessageInfo {
  3523. return &types.MessageInfo{
  3524. ID: whatsmeow.GenerateMessageID(),
  3525. Timestamp: time.Now(),
  3526. MessageSource: types.MessageSource{
  3527. Sender: sender.JID,
  3528. Chat: portal.Key.JID,
  3529. IsFromMe: true,
  3530. IsGroup: portal.Key.JID.Server == types.GroupServer || portal.Key.JID.Server == types.BroadcastServer,
  3531. },
  3532. }
  3533. }
  3534. func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event, timings messageTimings) {
  3535. start := time.Now()
  3536. ms := metricSender{portal: portal, timings: &timings}
  3537. allowRelay := evt.Type != TypeMSC3881PollResponse && evt.Type != TypeMSC3881V2PollResponse
  3538. if err := portal.canBridgeFrom(sender, allowRelay); err != nil {
  3539. go ms.sendMessageMetrics(evt, err, "Ignoring", true)
  3540. return
  3541. } else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
  3542. go ms.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", true)
  3543. return
  3544. }
  3545. messageAge := timings.totalReceive
  3546. origEvtID := evt.ID
  3547. var dbMsg *database.Message
  3548. if retryMeta := evt.Content.AsMessage().MessageSendRetry; retryMeta != nil {
  3549. origEvtID = retryMeta.OriginalEventID
  3550. dbMsg = portal.bridge.DB.Message.GetByMXID(origEvtID)
  3551. if dbMsg != nil && dbMsg.Sent {
  3552. portal.log.Debugfln("Ignoring retry request %s (#%d, age: %s) for %s/%s from %s as message was already sent", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
  3553. go ms.sendMessageMetrics(evt, nil, "", true)
  3554. return
  3555. } else if dbMsg != nil {
  3556. portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s/%s from %s", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, dbMsg.JID, evt.Sender)
  3557. } else {
  3558. portal.log.Debugfln("Got retry request %s (#%d, age: %s) for %s from %s (original message not known)", evt.ID, retryMeta.RetryCount, messageAge, origEvtID, evt.Sender)
  3559. }
  3560. } else {
  3561. portal.log.Debugfln("Received message %s from %s (age: %s)", evt.ID, evt.Sender, messageAge)
  3562. }
  3563. errorAfter := portal.bridge.Config.Bridge.MessageHandlingTimeout.ErrorAfter
  3564. deadline := portal.bridge.Config.Bridge.MessageHandlingTimeout.Deadline
  3565. isScheduled, _ := evt.Content.Raw["com.beeper.scheduled"].(bool)
  3566. if isScheduled {
  3567. portal.log.Debugfln("%s is a scheduled message, extending handling timeouts", evt.ID)
  3568. errorAfter *= 10
  3569. deadline *= 10
  3570. }
  3571. if errorAfter > 0 {
  3572. remainingTime := errorAfter - messageAge
  3573. if remainingTime < 0 {
  3574. go ms.sendMessageMetrics(evt, errTimeoutBeforeHandling, "Timeout handling", true)
  3575. return
  3576. } else if remainingTime < 1*time.Second {
  3577. portal.log.Warnfln("Message %s was delayed before reaching the bridge, only have %s (of %s timeout) until delay warning", evt.ID, remainingTime, errorAfter)
  3578. }
  3579. go func() {
  3580. time.Sleep(remainingTime)
  3581. ms.sendMessageMetrics(evt, errMessageTakingLong, "Timeout handling", false)
  3582. }()
  3583. }
  3584. ctx := context.Background()
  3585. if deadline > 0 {
  3586. var cancel context.CancelFunc
  3587. ctx, cancel = context.WithTimeout(ctx, deadline)
  3588. defer cancel()
  3589. }
  3590. timings.preproc = time.Since(start)
  3591. start = time.Now()
  3592. msg, sender, err := portal.convertMatrixMessage(ctx, sender, evt)
  3593. timings.convert = time.Since(start)
  3594. if msg == nil {
  3595. go ms.sendMessageMetrics(evt, err, "Error converting", true)
  3596. return
  3597. }
  3598. dbMsgType := database.MsgNormal
  3599. if msg.EditedMessage == nil {
  3600. portal.MarkDisappearing(nil, origEvtID, portal.ExpirationTime, true)
  3601. } else {
  3602. dbMsgType = database.MsgEdit
  3603. }
  3604. info := portal.generateMessageInfo(sender)
  3605. if dbMsg == nil {
  3606. dbMsg = portal.markHandled(nil, nil, info, evt.ID, false, true, dbMsgType, database.MsgNoError)
  3607. } else {
  3608. info.ID = dbMsg.JID
  3609. }
  3610. portal.log.Debugln("Sending event", evt.ID, "to WhatsApp", info.ID)
  3611. start = time.Now()
  3612. resp, err := sender.Client.SendMessage(ctx, portal.Key.JID, info.ID, msg)
  3613. timings.totalSend = time.Since(start)
  3614. timings.whatsmeow = resp.DebugTimings
  3615. go ms.sendMessageMetrics(evt, err, "Error sending", true)
  3616. if err == nil {
  3617. dbMsg.MarkSent(resp.Timestamp)
  3618. }
  3619. }
  3620. func (portal *Portal) HandleMatrixReaction(sender *User, evt *event.Event) {
  3621. if err := portal.canBridgeFrom(sender, false); err != nil {
  3622. go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
  3623. return
  3624. } else if portal.Key.JID.Server == types.BroadcastServer {
  3625. // TODO implement this, probably by only sending the reaction to the sender of the status message?
  3626. // (whatsapp hasn't published the feature yet)
  3627. go portal.sendMessageMetrics(evt, errBroadcastReactionNotSupported, "Ignoring", nil)
  3628. return
  3629. }
  3630. content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
  3631. if ok && strings.Contains(content.RelatesTo.Key, "retry") || strings.HasPrefix(content.RelatesTo.Key, "\u267b") { // ♻️
  3632. if retryRequested, _ := portal.requestMediaRetry(sender, content.RelatesTo.EventID, nil); retryRequested {
  3633. _, _ = portal.MainIntent().RedactEvent(portal.MXID, evt.ID, mautrix.ReqRedact{
  3634. Reason: "requested media from phone",
  3635. })
  3636. // Errored media, don't try to send as reaction
  3637. return
  3638. }
  3639. }
  3640. portal.log.Debugfln("Received reaction event %s from %s", evt.ID, evt.Sender)
  3641. err := portal.handleMatrixReaction(sender, evt)
  3642. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  3643. }
  3644. func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) error {
  3645. content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
  3646. if !ok {
  3647. return fmt.Errorf("unexpected parsed content type %T", evt.Content.Parsed)
  3648. }
  3649. target := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
  3650. if target == nil || target.Type == database.MsgReaction {
  3651. return fmt.Errorf("unknown target event %s", content.RelatesTo.EventID)
  3652. }
  3653. info := portal.generateMessageInfo(sender)
  3654. dbMsg := portal.markHandled(nil, nil, info, evt.ID, false, true, database.MsgReaction, database.MsgNoError)
  3655. portal.upsertReaction(nil, nil, target.JID, sender.JID, evt.ID, info.ID)
  3656. portal.log.Debugln("Sending reaction", evt.ID, "to WhatsApp", info.ID)
  3657. resp, err := portal.sendReactionToWhatsApp(sender, info.ID, target, content.RelatesTo.Key, evt.Timestamp)
  3658. if err == nil {
  3659. dbMsg.MarkSent(resp.Timestamp)
  3660. }
  3661. return err
  3662. }
  3663. func (portal *Portal) sendReactionToWhatsApp(sender *User, id types.MessageID, target *database.Message, key string, timestamp int64) (whatsmeow.SendResponse, error) {
  3664. var messageKeyParticipant *string
  3665. if !portal.IsPrivateChat() {
  3666. messageKeyParticipant = proto.String(target.Sender.ToNonAD().String())
  3667. }
  3668. key = variationselector.Remove(key)
  3669. return sender.Client.SendMessage(context.TODO(), portal.Key.JID, id, &waProto.Message{
  3670. ReactionMessage: &waProto.ReactionMessage{
  3671. Key: &waProto.MessageKey{
  3672. RemoteJid: proto.String(portal.Key.JID.String()),
  3673. FromMe: proto.Bool(target.Sender.User == sender.JID.User),
  3674. Id: proto.String(target.JID),
  3675. Participant: messageKeyParticipant,
  3676. },
  3677. Text: proto.String(key),
  3678. SenderTimestampMs: proto.Int64(timestamp),
  3679. },
  3680. })
  3681. }
  3682. func (portal *Portal) upsertReaction(txn dbutil.Transaction, intent *appservice.IntentAPI, targetJID types.MessageID, senderJID types.JID, mxid id.EventID, jid types.MessageID) {
  3683. dbReaction := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, senderJID)
  3684. if dbReaction == nil {
  3685. dbReaction = portal.bridge.DB.Reaction.New()
  3686. dbReaction.Chat = portal.Key
  3687. dbReaction.TargetJID = targetJID
  3688. dbReaction.Sender = senderJID
  3689. } else if intent != nil {
  3690. portal.log.Debugfln("Redacting old Matrix reaction %s after new one (%s) was sent", dbReaction.MXID, mxid)
  3691. var err error
  3692. if intent != nil {
  3693. _, err = intent.RedactEvent(portal.MXID, dbReaction.MXID)
  3694. }
  3695. if intent == nil || errors.Is(err, mautrix.MForbidden) {
  3696. _, err = portal.MainIntent().RedactEvent(portal.MXID, dbReaction.MXID)
  3697. }
  3698. if err != nil {
  3699. portal.log.Warnfln("Failed to remove old reaction %s: %v", dbReaction.MXID, err)
  3700. }
  3701. }
  3702. dbReaction.MXID = mxid
  3703. dbReaction.JID = jid
  3704. dbReaction.Upsert(txn)
  3705. }
  3706. func (portal *Portal) HandleMatrixRedaction(sender *User, evt *event.Event) {
  3707. if err := portal.canBridgeFrom(sender, true); err != nil {
  3708. go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
  3709. return
  3710. }
  3711. portal.log.Debugfln("Received redaction %s from %s", evt.ID, evt.Sender)
  3712. senderLogIdentifier := sender.MXID
  3713. if !sender.HasSession() {
  3714. sender = portal.GetRelayUser()
  3715. senderLogIdentifier += " (through relaybot)"
  3716. }
  3717. msg := portal.bridge.DB.Message.GetByMXID(evt.Redacts)
  3718. if msg == nil {
  3719. go portal.sendMessageMetrics(evt, errTargetNotFound, "Ignoring", nil)
  3720. } else if msg.IsFakeJID() {
  3721. go portal.sendMessageMetrics(evt, errTargetIsFake, "Ignoring", nil)
  3722. } else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
  3723. go portal.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", nil)
  3724. } else if msg.Type == database.MsgReaction {
  3725. if msg.Sender.User != sender.JID.User {
  3726. go portal.sendMessageMetrics(evt, errReactionSentBySomeoneElse, "Ignoring", nil)
  3727. } else if reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts); reaction == nil {
  3728. go portal.sendMessageMetrics(evt, errReactionDatabaseNotFound, "Ignoring", nil)
  3729. } else if reactionTarget := reaction.GetTarget(); reactionTarget == nil {
  3730. go portal.sendMessageMetrics(evt, errReactionTargetNotFound, "Ignoring", nil)
  3731. } else {
  3732. portal.log.Debugfln("Sending redaction reaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
  3733. _, err := portal.sendReactionToWhatsApp(sender, "", reactionTarget, "", evt.Timestamp)
  3734. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  3735. }
  3736. } else {
  3737. key := &waProto.MessageKey{
  3738. FromMe: proto.Bool(true),
  3739. Id: proto.String(msg.JID),
  3740. RemoteJid: proto.String(portal.Key.JID.String()),
  3741. }
  3742. if msg.Sender.User != sender.JID.User {
  3743. if portal.IsPrivateChat() {
  3744. go portal.sendMessageMetrics(evt, errDMSentByOtherUser, "Ignoring", nil)
  3745. return
  3746. }
  3747. key.FromMe = proto.Bool(false)
  3748. key.Participant = proto.String(msg.Sender.ToNonAD().String())
  3749. }
  3750. portal.log.Debugfln("Sending redaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
  3751. _, err := sender.Client.SendMessage(context.TODO(), portal.Key.JID, "", &waProto.Message{
  3752. ProtocolMessage: &waProto.ProtocolMessage{
  3753. Type: waProto.ProtocolMessage_REVOKE.Enum(),
  3754. Key: key,
  3755. },
  3756. })
  3757. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  3758. }
  3759. }
  3760. func (portal *Portal) HandleMatrixReadReceipt(sender bridge.User, eventID id.EventID, receipt event.ReadReceipt) {
  3761. portal.handleMatrixReadReceipt(sender.(*User), eventID, receipt.Timestamp, true)
  3762. }
  3763. func (portal *Portal) handleMatrixReadReceipt(sender *User, eventID id.EventID, receiptTimestamp time.Time, isExplicit bool) {
  3764. if !sender.IsLoggedIn() {
  3765. if isExplicit {
  3766. portal.log.Debugfln("Ignoring read receipt by %s/%s: user is not connected to WhatsApp", sender.MXID, sender.JID)
  3767. }
  3768. return
  3769. }
  3770. maxTimestamp := receiptTimestamp
  3771. // Implicit read receipts don't have an event ID that's already bridged
  3772. if isExplicit {
  3773. if message := portal.bridge.DB.Message.GetByMXID(eventID); message != nil {
  3774. maxTimestamp = message.Timestamp
  3775. }
  3776. }
  3777. prevTimestamp := sender.GetLastReadTS(portal.Key)
  3778. lastReadIsZero := false
  3779. if prevTimestamp.IsZero() {
  3780. prevTimestamp = maxTimestamp.Add(-2 * time.Second)
  3781. lastReadIsZero = true
  3782. }
  3783. messages := portal.bridge.DB.Message.GetMessagesBetween(portal.Key, prevTimestamp, maxTimestamp)
  3784. if len(messages) > 0 {
  3785. sender.SetLastReadTS(portal.Key, messages[len(messages)-1].Timestamp)
  3786. }
  3787. groupedMessages := make(map[types.JID][]types.MessageID)
  3788. for _, msg := range messages {
  3789. var key types.JID
  3790. if msg.IsFakeJID() || msg.Sender.User == sender.JID.User {
  3791. // Don't send read receipts for own messages or fake messages
  3792. continue
  3793. } else if !portal.IsPrivateChat() {
  3794. key = msg.Sender
  3795. } else if !msg.BroadcastListJID.IsEmpty() {
  3796. key = msg.BroadcastListJID
  3797. } // else: blank key (participant field isn't needed in direct chat read receipts)
  3798. groupedMessages[key] = append(groupedMessages[key], msg.JID)
  3799. }
  3800. // For explicit read receipts, log even if there are no targets. For implicit ones only log when there are targets
  3801. if len(groupedMessages) > 0 || isExplicit {
  3802. portal.log.Debugfln("Sending read receipts by %s (last read: %d, was zero: %t, explicit: %t): %v",
  3803. sender.JID, prevTimestamp.Unix(), lastReadIsZero, isExplicit, groupedMessages)
  3804. }
  3805. for messageSender, ids := range groupedMessages {
  3806. chatJID := portal.Key.JID
  3807. if messageSender.Server == types.BroadcastServer {
  3808. chatJID = messageSender
  3809. messageSender = portal.Key.JID
  3810. }
  3811. err := sender.Client.MarkRead(ids, receiptTimestamp, chatJID, messageSender)
  3812. if err != nil {
  3813. portal.log.Warnfln("Failed to mark %v as read by %s: %v", ids, sender.JID, err)
  3814. }
  3815. }
  3816. if isExplicit {
  3817. portal.ScheduleDisappearing()
  3818. }
  3819. }
  3820. func typingDiff(prev, new []id.UserID) (started, stopped []id.UserID) {
  3821. OuterNew:
  3822. for _, userID := range new {
  3823. for _, previousUserID := range prev {
  3824. if userID == previousUserID {
  3825. continue OuterNew
  3826. }
  3827. }
  3828. started = append(started, userID)
  3829. }
  3830. OuterPrev:
  3831. for _, userID := range prev {
  3832. for _, previousUserID := range new {
  3833. if userID == previousUserID {
  3834. continue OuterPrev
  3835. }
  3836. }
  3837. stopped = append(stopped, userID)
  3838. }
  3839. return
  3840. }
  3841. func (portal *Portal) setTyping(userIDs []id.UserID, state types.ChatPresence) {
  3842. for _, userID := range userIDs {
  3843. user := portal.bridge.GetUserByMXIDIfExists(userID)
  3844. if user == nil || !user.IsLoggedIn() {
  3845. continue
  3846. }
  3847. portal.log.Debugfln("Bridging typing change from %s to chat presence %s", state, user.MXID)
  3848. err := user.Client.SendChatPresence(portal.Key.JID, state, types.ChatPresenceMediaText)
  3849. if err != nil {
  3850. portal.log.Warnln("Error sending chat presence:", err)
  3851. }
  3852. if portal.bridge.Config.Bridge.SendPresenceOnTyping {
  3853. err = user.Client.SendPresence(types.PresenceAvailable)
  3854. if err != nil {
  3855. user.log.Warnln("Failed to set presence:", err)
  3856. }
  3857. }
  3858. }
  3859. }
  3860. func (portal *Portal) HandleMatrixTyping(newTyping []id.UserID) {
  3861. portal.currentlyTypingLock.Lock()
  3862. defer portal.currentlyTypingLock.Unlock()
  3863. startedTyping, stoppedTyping := typingDiff(portal.currentlyTyping, newTyping)
  3864. portal.currentlyTyping = newTyping
  3865. portal.setTyping(startedTyping, types.ChatPresenceComposing)
  3866. portal.setTyping(stoppedTyping, types.ChatPresencePaused)
  3867. }
  3868. func (portal *Portal) canBridgeFrom(sender *User, allowRelay bool) error {
  3869. if !sender.IsLoggedIn() {
  3870. if allowRelay && portal.HasRelaybot() {
  3871. return nil
  3872. } else if sender.Session != nil {
  3873. return errUserNotConnected
  3874. } else {
  3875. return errUserNotLoggedIn
  3876. }
  3877. } else if portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User && (!allowRelay || !portal.HasRelaybot()) {
  3878. return errDifferentUser
  3879. }
  3880. return nil
  3881. }
  3882. func (portal *Portal) resetChildSpaceStatus() {
  3883. for _, childPortal := range portal.bridge.portalsByJID {
  3884. if childPortal.ParentGroup == portal.Key.JID {
  3885. if portal.MXID != "" && childPortal.InSpace {
  3886. go childPortal.removeSpaceParentEvent(portal.MXID)
  3887. }
  3888. childPortal.InSpace = false
  3889. if childPortal.parentPortal == portal {
  3890. childPortal.parentPortal = nil
  3891. }
  3892. }
  3893. }
  3894. }
  3895. func (portal *Portal) Delete() {
  3896. portal.Portal.Delete()
  3897. portal.bridge.portalsLock.Lock()
  3898. delete(portal.bridge.portalsByJID, portal.Key)
  3899. if len(portal.MXID) > 0 {
  3900. delete(portal.bridge.portalsByMXID, portal.MXID)
  3901. }
  3902. portal.resetChildSpaceStatus()
  3903. portal.bridge.portalsLock.Unlock()
  3904. }
  3905. func (portal *Portal) GetMatrixUsers() ([]id.UserID, error) {
  3906. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  3907. if err != nil {
  3908. return nil, fmt.Errorf("failed to get member list: %w", err)
  3909. }
  3910. var users []id.UserID
  3911. for userID := range members.Joined {
  3912. _, isPuppet := portal.bridge.ParsePuppetMXID(userID)
  3913. if !isPuppet && userID != portal.bridge.Bot.UserID {
  3914. users = append(users, userID)
  3915. }
  3916. }
  3917. return users, nil
  3918. }
  3919. func (portal *Portal) CleanupIfEmpty() {
  3920. users, err := portal.GetMatrixUsers()
  3921. if err != nil {
  3922. portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  3923. return
  3924. }
  3925. if len(users) == 0 {
  3926. portal.log.Infoln("Room seems to be empty, cleaning up...")
  3927. portal.Delete()
  3928. portal.Cleanup(false)
  3929. }
  3930. }
  3931. func (portal *Portal) Cleanup(puppetsOnly bool) {
  3932. if len(portal.MXID) == 0 {
  3933. return
  3934. }
  3935. intent := portal.MainIntent()
  3936. members, err := intent.JoinedMembers(portal.MXID)
  3937. if err != nil {
  3938. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  3939. return
  3940. }
  3941. for member := range members.Joined {
  3942. if member == intent.UserID {
  3943. continue
  3944. }
  3945. puppet := portal.bridge.GetPuppetByMXID(member)
  3946. if puppet != nil {
  3947. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  3948. if err != nil {
  3949. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  3950. }
  3951. } else if !puppetsOnly {
  3952. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  3953. if err != nil {
  3954. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  3955. }
  3956. }
  3957. }
  3958. _, err = intent.LeaveRoom(portal.MXID)
  3959. if err != nil {
  3960. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  3961. }
  3962. }
  3963. func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
  3964. sender := brSender.(*User)
  3965. if portal.IsPrivateChat() {
  3966. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  3967. portal.Delete()
  3968. portal.Cleanup(false)
  3969. return
  3970. } else if portal.bridge.Config.Bridge.BridgeMatrixLeave {
  3971. err := sender.Client.LeaveGroup(portal.Key.JID)
  3972. if err != nil {
  3973. portal.log.Errorfln("Failed to leave group as %s: %v", sender.MXID, err)
  3974. return
  3975. }
  3976. //portal.log.Infoln("Leave response:", <-resp)
  3977. }
  3978. portal.CleanupIfEmpty()
  3979. }
  3980. func (portal *Portal) HandleMatrixKick(brSender bridge.User, brTarget bridge.Ghost) {
  3981. sender := brSender.(*User)
  3982. target := brTarget.(*Puppet)
  3983. _, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
  3984. target.JID: whatsmeow.ParticipantChangeRemove,
  3985. })
  3986. if err != nil {
  3987. portal.log.Errorfln("Failed to kick %s from group as %s: %v", target.JID, sender.MXID, err)
  3988. return
  3989. }
  3990. //portal.log.Infoln("Kick %s response: %s", puppet.JID, <-resp)
  3991. }
  3992. func (portal *Portal) HandleMatrixInvite(brSender bridge.User, brTarget bridge.Ghost) {
  3993. sender := brSender.(*User)
  3994. target := brTarget.(*Puppet)
  3995. _, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
  3996. target.JID: whatsmeow.ParticipantChangeAdd,
  3997. })
  3998. if err != nil {
  3999. portal.log.Errorfln("Failed to add %s to group as %s: %v", target.JID, sender.MXID, err)
  4000. return
  4001. }
  4002. //portal.log.Infofln("Add %s response: %s", puppet.JID, <-resp)
  4003. }
  4004. func (portal *Portal) HandleMatrixMeta(brSender bridge.User, evt *event.Event) {
  4005. sender := brSender.(*User)
  4006. if !sender.Whitelisted || !sender.IsLoggedIn() {
  4007. return
  4008. }
  4009. switch content := evt.Content.Parsed.(type) {
  4010. case *event.RoomNameEventContent:
  4011. if content.Name == portal.Name {
  4012. return
  4013. }
  4014. portal.Name = content.Name
  4015. err := sender.Client.SetGroupName(portal.Key.JID, content.Name)
  4016. if err != nil {
  4017. portal.log.Errorln("Failed to update group name:", err)
  4018. }
  4019. case *event.TopicEventContent:
  4020. if content.Topic == portal.Topic {
  4021. return
  4022. }
  4023. portal.Topic = content.Topic
  4024. err := sender.Client.SetGroupTopic(portal.Key.JID, "", "", content.Topic)
  4025. if err != nil {
  4026. portal.log.Errorln("Failed to update group description:", err)
  4027. }
  4028. case *event.RoomAvatarEventContent:
  4029. portal.avatarLock.Lock()
  4030. defer portal.avatarLock.Unlock()
  4031. if content.URL == portal.AvatarURL || (content.URL.IsEmpty() && portal.Avatar == "remove") {
  4032. return
  4033. }
  4034. var data []byte
  4035. var err error
  4036. if !content.URL.IsEmpty() {
  4037. data, err = portal.MainIntent().DownloadBytes(content.URL)
  4038. if err != nil {
  4039. portal.log.Errorfln("Failed to download updated avatar %s: %v", content.URL, err)
  4040. return
  4041. }
  4042. portal.log.Debugfln("%s set the group avatar to %s", sender.MXID, content.URL)
  4043. } else {
  4044. portal.log.Debugfln("%s removed the group avatar", sender.MXID)
  4045. }
  4046. newID, err := sender.Client.SetGroupPhoto(portal.Key.JID, data)
  4047. if err != nil {
  4048. portal.log.Errorfln("Failed to update group avatar: %v", err)
  4049. return
  4050. }
  4051. portal.log.Debugfln("Successfully updated group avatar to %s", newID)
  4052. portal.Avatar = newID
  4053. portal.AvatarURL = content.URL
  4054. portal.UpdateBridgeInfo()
  4055. portal.Update(nil)
  4056. }
  4057. }