portal.go 160 KB

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