portal.go 165 KB

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