portal.go 162 KB

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