portal.go 157 KB

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