portal.go 153 KB

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