portal.go 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535
  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. TypeMSC3381PollResponse.Type: anyone,
  1239. },
  1240. }
  1241. }
  1242. func (portal *Portal) applyPowerLevelFixes(levels *event.PowerLevelsEventContent) bool {
  1243. changed := false
  1244. changed = levels.EnsureEventLevel(event.EventReaction, 0) || changed
  1245. changed = levels.EnsureEventLevel(event.EventRedaction, 0) || changed
  1246. changed = levels.EnsureEventLevel(TypeMSC3381PollResponse, 0) || changed
  1247. return changed
  1248. }
  1249. func (portal *Portal) ChangeAdminStatus(jids []types.JID, setAdmin bool) id.EventID {
  1250. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1251. if err != nil {
  1252. levels = portal.GetBasePowerLevels()
  1253. }
  1254. newLevel := 0
  1255. if setAdmin {
  1256. newLevel = 50
  1257. }
  1258. changed := portal.applyPowerLevelFixes(levels)
  1259. for _, jid := range jids {
  1260. puppet := portal.bridge.GetPuppetByJID(jid)
  1261. changed = levels.EnsureUserLevel(puppet.MXID, newLevel) || changed
  1262. user := portal.bridge.GetUserByJID(jid)
  1263. if user != nil {
  1264. changed = levels.EnsureUserLevel(user.MXID, newLevel) || changed
  1265. }
  1266. }
  1267. if changed {
  1268. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1269. if err != nil {
  1270. portal.log.Errorln("Failed to change power levels:", err)
  1271. } else {
  1272. return resp.EventID
  1273. }
  1274. }
  1275. return ""
  1276. }
  1277. func (portal *Portal) RestrictMessageSending(restrict bool) id.EventID {
  1278. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1279. if err != nil {
  1280. levels = portal.GetBasePowerLevels()
  1281. }
  1282. newLevel := 0
  1283. if restrict {
  1284. newLevel = 50
  1285. }
  1286. changed := portal.applyPowerLevelFixes(levels)
  1287. if levels.EventsDefault == newLevel && !changed {
  1288. return ""
  1289. }
  1290. levels.EventsDefault = newLevel
  1291. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1292. if err != nil {
  1293. portal.log.Errorln("Failed to change power levels:", err)
  1294. return ""
  1295. } else {
  1296. return resp.EventID
  1297. }
  1298. }
  1299. func (portal *Portal) RestrictMetadataChanges(restrict bool) id.EventID {
  1300. levels, err := portal.MainIntent().PowerLevels(portal.MXID)
  1301. if err != nil {
  1302. levels = portal.GetBasePowerLevels()
  1303. }
  1304. newLevel := 0
  1305. if restrict {
  1306. newLevel = 50
  1307. }
  1308. changed := portal.applyPowerLevelFixes(levels)
  1309. changed = levels.EnsureEventLevel(event.StateRoomName, newLevel) || changed
  1310. changed = levels.EnsureEventLevel(event.StateRoomAvatar, newLevel) || changed
  1311. changed = levels.EnsureEventLevel(event.StateTopic, newLevel) || changed
  1312. if changed {
  1313. resp, err := portal.MainIntent().SetPowerLevels(portal.MXID, levels)
  1314. if err != nil {
  1315. portal.log.Errorln("Failed to change power levels:", err)
  1316. } else {
  1317. return resp.EventID
  1318. }
  1319. }
  1320. return ""
  1321. }
  1322. func (portal *Portal) getBridgeInfoStateKey() string {
  1323. return fmt.Sprintf("net.maunium.whatsapp://whatsapp/%s", portal.Key.JID)
  1324. }
  1325. func (portal *Portal) getBridgeInfo() (string, event.BridgeEventContent) {
  1326. bridgeInfo := event.BridgeEventContent{
  1327. BridgeBot: portal.bridge.Bot.UserID,
  1328. Creator: portal.MainIntent().UserID,
  1329. Protocol: event.BridgeInfoSection{
  1330. ID: "whatsapp",
  1331. DisplayName: "WhatsApp",
  1332. AvatarURL: portal.bridge.Config.AppService.Bot.ParsedAvatar.CUString(),
  1333. ExternalURL: "https://www.whatsapp.com/",
  1334. },
  1335. Channel: event.BridgeInfoSection{
  1336. ID: portal.Key.JID.String(),
  1337. DisplayName: portal.Name,
  1338. AvatarURL: portal.AvatarURL.CUString(),
  1339. },
  1340. }
  1341. if parent := portal.GetParentPortal(); parent != nil {
  1342. bridgeInfo.Network = &event.BridgeInfoSection{
  1343. ID: parent.Key.JID.String(),
  1344. DisplayName: parent.Name,
  1345. AvatarURL: parent.AvatarURL.CUString(),
  1346. }
  1347. }
  1348. return portal.getBridgeInfoStateKey(), bridgeInfo
  1349. }
  1350. func (portal *Portal) UpdateBridgeInfo() {
  1351. if len(portal.MXID) == 0 {
  1352. portal.log.Debugln("Not updating bridge info: no Matrix room created")
  1353. return
  1354. }
  1355. portal.log.Debugln("Updating bridge info...")
  1356. stateKey, content := portal.getBridgeInfo()
  1357. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateBridge, stateKey, content)
  1358. if err != nil {
  1359. portal.log.Warnln("Failed to update m.bridge:", err)
  1360. }
  1361. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1362. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateHalfShotBridge, stateKey, content)
  1363. if err != nil {
  1364. portal.log.Warnln("Failed to update uk.half-shot.bridge:", err)
  1365. }
  1366. }
  1367. func (portal *Portal) updateChildRooms() {
  1368. if !portal.IsParent {
  1369. return
  1370. }
  1371. children := portal.bridge.GetAllByParentGroup(portal.Key.JID)
  1372. for _, child := range children {
  1373. changed := child.updateCommunitySpace(nil, true, false)
  1374. child.UpdateBridgeInfo()
  1375. if changed {
  1376. portal.Update(nil)
  1377. }
  1378. }
  1379. }
  1380. func (portal *Portal) GetEncryptionEventContent() (evt *event.EncryptionEventContent) {
  1381. evt = &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1}
  1382. if rot := portal.bridge.Config.Bridge.Encryption.Rotation; rot.EnableCustom {
  1383. evt.RotationPeriodMillis = rot.Milliseconds
  1384. evt.RotationPeriodMessages = rot.Messages
  1385. }
  1386. return
  1387. }
  1388. func (portal *Portal) CreateMatrixRoom(user *User, groupInfo *types.GroupInfo, isFullInfo, backfill bool) error {
  1389. portal.roomCreateLock.Lock()
  1390. defer portal.roomCreateLock.Unlock()
  1391. if len(portal.MXID) > 0 {
  1392. return nil
  1393. }
  1394. intent := portal.MainIntent()
  1395. if err := intent.EnsureRegistered(); err != nil {
  1396. return err
  1397. }
  1398. portal.log.Infoln("Creating Matrix room. Info source:", user.MXID)
  1399. //var broadcastMetadata *types.BroadcastListInfo
  1400. if portal.IsPrivateChat() {
  1401. puppet := portal.bridge.GetPuppetByJID(portal.Key.JID)
  1402. puppet.SyncContact(user, true, false, "creating private chat portal")
  1403. if portal.bridge.Config.Bridge.PrivateChatPortalMeta || portal.bridge.Config.Bridge.Encryption.Default {
  1404. portal.Name = puppet.Displayname
  1405. portal.AvatarURL = puppet.AvatarURL
  1406. portal.Avatar = puppet.Avatar
  1407. } else {
  1408. portal.Name = ""
  1409. }
  1410. portal.Topic = PrivateChatTopic
  1411. } else if portal.IsStatusBroadcastList() {
  1412. if !portal.bridge.Config.Bridge.EnableStatusBroadcast {
  1413. portal.log.Debugln("Status bridging is disabled in config, not creating room after all")
  1414. return ErrStatusBroadcastDisabled
  1415. }
  1416. portal.Name = StatusBroadcastName
  1417. portal.Topic = StatusBroadcastTopic
  1418. } else if portal.IsBroadcastList() {
  1419. //var err error
  1420. //broadcastMetadata, err = user.Conn.GetBroadcastMetadata(portal.Key.JID)
  1421. //if err == nil && broadcastMetadata.Status == 200 {
  1422. // portal.Name = broadcastMetadata.Name
  1423. //} else {
  1424. // user.Conn.Store.ContactsLock.RLock()
  1425. // contact, _ := user.Conn.Store.Contacts[portal.Key.JID]
  1426. // user.Conn.Store.ContactsLock.RUnlock()
  1427. // portal.Name = contact.Name
  1428. //}
  1429. //if len(portal.Name) == 0 {
  1430. // portal.Name = UnnamedBroadcastName
  1431. //}
  1432. //portal.Topic = BroadcastTopic
  1433. portal.log.Debugln("Broadcast list is not yet supported, not creating room after all")
  1434. return fmt.Errorf("broadcast list bridging is currently not supported")
  1435. } else {
  1436. if groupInfo == nil || !isFullInfo {
  1437. foundInfo, err := user.Client.GetGroupInfo(portal.Key.JID)
  1438. // Ensure that the user is actually a participant in the conversation
  1439. // before creating the matrix room
  1440. if errors.Is(err, whatsmeow.ErrNotInGroup) {
  1441. user.log.Debugfln("Skipping creating matrix room for %s because the user is not a participant", portal.Key.JID)
  1442. user.bridge.DB.Backfill.DeleteAllForPortal(user.MXID, portal.Key)
  1443. user.bridge.DB.HistorySync.DeleteAllMessagesForPortal(user.MXID, portal.Key)
  1444. return err
  1445. } else if err != nil {
  1446. portal.log.Warnfln("Failed to get group info through %s: %v", user.JID, err)
  1447. } else {
  1448. groupInfo = foundInfo
  1449. isFullInfo = true
  1450. }
  1451. }
  1452. if groupInfo != nil {
  1453. portal.Name = groupInfo.Name
  1454. portal.Topic = groupInfo.Topic
  1455. portal.IsParent = groupInfo.IsParent
  1456. portal.ParentGroup = groupInfo.LinkedParentJID
  1457. if groupInfo.IsEphemeral {
  1458. portal.ExpirationTime = groupInfo.DisappearingTimer
  1459. }
  1460. }
  1461. portal.UpdateAvatar(user, types.EmptyJID, false)
  1462. }
  1463. powerLevels := portal.GetBasePowerLevels()
  1464. if groupInfo != nil {
  1465. if groupInfo.IsAnnounce {
  1466. powerLevels.EventsDefault = 50
  1467. }
  1468. if groupInfo.IsLocked {
  1469. powerLevels.EnsureEventLevel(event.StateRoomName, 50)
  1470. powerLevels.EnsureEventLevel(event.StateRoomAvatar, 50)
  1471. powerLevels.EnsureEventLevel(event.StateTopic, 50)
  1472. }
  1473. }
  1474. bridgeInfoStateKey, bridgeInfo := portal.getBridgeInfo()
  1475. initialState := []*event.Event{{
  1476. Type: event.StatePowerLevels,
  1477. Content: event.Content{
  1478. Parsed: powerLevels,
  1479. },
  1480. }, {
  1481. Type: event.StateBridge,
  1482. Content: event.Content{Parsed: bridgeInfo},
  1483. StateKey: &bridgeInfoStateKey,
  1484. }, {
  1485. // TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  1486. Type: event.StateHalfShotBridge,
  1487. Content: event.Content{Parsed: bridgeInfo},
  1488. StateKey: &bridgeInfoStateKey,
  1489. }}
  1490. if !portal.AvatarURL.IsEmpty() {
  1491. initialState = append(initialState, &event.Event{
  1492. Type: event.StateRoomAvatar,
  1493. Content: event.Content{
  1494. Parsed: event.RoomAvatarEventContent{URL: portal.AvatarURL},
  1495. },
  1496. })
  1497. portal.AvatarSet = true
  1498. }
  1499. var invite []id.UserID
  1500. if portal.bridge.Config.Bridge.Encryption.Default {
  1501. initialState = append(initialState, &event.Event{
  1502. Type: event.StateEncryption,
  1503. Content: event.Content{
  1504. Parsed: portal.GetEncryptionEventContent(),
  1505. },
  1506. })
  1507. portal.Encrypted = true
  1508. if portal.IsPrivateChat() {
  1509. invite = append(invite, portal.bridge.Bot.UserID)
  1510. }
  1511. }
  1512. creationContent := make(map[string]interface{})
  1513. if !portal.bridge.Config.Bridge.FederateRooms {
  1514. creationContent["m.federate"] = false
  1515. }
  1516. if portal.IsParent {
  1517. creationContent["type"] = event.RoomTypeSpace
  1518. } else if parent := portal.GetParentPortal(); parent != nil && parent.MXID != "" {
  1519. initialState = append(initialState, &event.Event{
  1520. Type: event.StateSpaceParent,
  1521. StateKey: proto.String(parent.MXID.String()),
  1522. Content: event.Content{
  1523. Parsed: &event.SpaceParentEventContent{
  1524. Via: []string{portal.bridge.Config.Homeserver.Domain},
  1525. Canonical: true,
  1526. },
  1527. },
  1528. })
  1529. }
  1530. autoJoinInvites := portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry
  1531. if autoJoinInvites {
  1532. portal.log.Debugfln("Hungryserv mode: adding all group members in create request")
  1533. if groupInfo != nil {
  1534. // TODO non-hungryserv could also include all members in invites, and then send joins manually?
  1535. participants, powerLevels := portal.SyncParticipants(user, groupInfo)
  1536. invite = append(invite, participants...)
  1537. if initialState[0].Type != event.StatePowerLevels {
  1538. panic(fmt.Errorf("unexpected type %s in first initial state event", initialState[0].Type.Type))
  1539. }
  1540. initialState[0].Content.Parsed = powerLevels
  1541. } else {
  1542. invite = append(invite, user.MXID)
  1543. }
  1544. }
  1545. resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
  1546. Visibility: "private",
  1547. Name: portal.Name,
  1548. Topic: portal.Topic,
  1549. Invite: invite,
  1550. Preset: "private_chat",
  1551. IsDirect: portal.IsPrivateChat(),
  1552. InitialState: initialState,
  1553. CreationContent: creationContent,
  1554. BeeperAutoJoinInvites: autoJoinInvites,
  1555. })
  1556. if err != nil {
  1557. return err
  1558. }
  1559. portal.log.Infoln("Matrix room created:", resp.RoomID)
  1560. portal.InSpace = false
  1561. portal.NameSet = len(portal.Name) > 0
  1562. portal.TopicSet = len(portal.Topic) > 0
  1563. portal.MXID = resp.RoomID
  1564. portal.bridge.portalsLock.Lock()
  1565. portal.bridge.portalsByMXID[portal.MXID] = portal
  1566. portal.bridge.portalsLock.Unlock()
  1567. portal.Update(nil)
  1568. // We set the memberships beforehand to make sure the encryption key exchange in initial backfill knows the users are here.
  1569. inviteMembership := event.MembershipInvite
  1570. if autoJoinInvites {
  1571. inviteMembership = event.MembershipJoin
  1572. }
  1573. for _, userID := range invite {
  1574. portal.bridge.StateStore.SetMembership(portal.MXID, userID, inviteMembership)
  1575. }
  1576. if !autoJoinInvites {
  1577. portal.ensureUserInvited(user)
  1578. }
  1579. user.syncChatDoublePuppetDetails(portal, true)
  1580. go portal.updateCommunitySpace(user, true, true)
  1581. go portal.addToPersonalSpace(user)
  1582. if groupInfo != nil && !autoJoinInvites {
  1583. portal.SyncParticipants(user, groupInfo)
  1584. }
  1585. //if broadcastMetadata != nil {
  1586. // portal.SyncBroadcastRecipients(user, broadcastMetadata)
  1587. //}
  1588. if portal.IsPrivateChat() {
  1589. puppet := user.bridge.GetPuppetByJID(portal.Key.JID)
  1590. if portal.bridge.Config.Bridge.Encryption.Default {
  1591. err = portal.bridge.Bot.EnsureJoined(portal.MXID)
  1592. if err != nil {
  1593. portal.log.Errorln("Failed to join created portal with bridge bot for e2be:", err)
  1594. }
  1595. }
  1596. user.UpdateDirectChats(map[id.UserID][]id.RoomID{puppet.MXID: {portal.MXID}})
  1597. } else if portal.IsParent {
  1598. portal.updateChildRooms()
  1599. }
  1600. firstEventResp, err := portal.MainIntent().SendMessageEvent(portal.MXID, PortalCreationDummyEvent, struct{}{})
  1601. if err != nil {
  1602. portal.log.Errorln("Failed to send dummy event to mark portal creation:", err)
  1603. } else {
  1604. portal.FirstEventID = firstEventResp.EventID
  1605. portal.Update(nil)
  1606. }
  1607. if user.bridge.Config.Bridge.HistorySync.Backfill && backfill {
  1608. portals := []*Portal{portal}
  1609. user.EnqueueImmediateBackfills(portals)
  1610. user.EnqueueDeferredBackfills(portals)
  1611. user.BackfillQueue.ReCheck()
  1612. }
  1613. return nil
  1614. }
  1615. func (portal *Portal) addToPersonalSpace(user *User) {
  1616. spaceID := user.GetSpaceRoom()
  1617. if len(spaceID) == 0 || user.IsInSpace(portal.Key) {
  1618. return
  1619. }
  1620. _, err := portal.bridge.Bot.SendStateEvent(spaceID, event.StateSpaceChild, portal.MXID.String(), &event.SpaceChildEventContent{
  1621. Via: []string{portal.bridge.Config.Homeserver.Domain},
  1622. })
  1623. if err != nil {
  1624. portal.log.Errorfln("Failed to add room to %s's personal filtering space (%s): %v", user.MXID, spaceID, err)
  1625. } else {
  1626. portal.log.Debugfln("Added room to %s's personal filtering space (%s)", user.MXID, spaceID)
  1627. user.MarkInSpace(portal.Key)
  1628. }
  1629. }
  1630. func (portal *Portal) removeSpaceParentEvent(space id.RoomID) {
  1631. _, err := portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, space.String(), &event.SpaceParentEventContent{})
  1632. if err != nil {
  1633. portal.log.Warnfln("Failed to send m.space.parent event to remove portal from %s: %v", space, err)
  1634. }
  1635. }
  1636. func (portal *Portal) updateCommunitySpace(user *User, add, updateInfo bool) bool {
  1637. if add == portal.InSpace {
  1638. return false
  1639. }
  1640. space := portal.GetParentPortal()
  1641. if space == nil {
  1642. return false
  1643. } else if space.MXID == "" {
  1644. if !add || user == nil {
  1645. return false
  1646. }
  1647. portal.log.Debugfln("Creating portal for parent group %v", space.Key.JID)
  1648. err := space.CreateMatrixRoom(user, nil, false, false)
  1649. if err != nil {
  1650. portal.log.Debugfln("Failed to create portal for parent group: %v", err)
  1651. return false
  1652. }
  1653. }
  1654. var action string
  1655. var parentContent event.SpaceParentEventContent
  1656. var childContent event.SpaceChildEventContent
  1657. if add {
  1658. parentContent.Canonical = true
  1659. parentContent.Via = []string{portal.bridge.Config.Homeserver.Domain}
  1660. childContent.Via = []string{portal.bridge.Config.Homeserver.Domain}
  1661. action = "add portal to"
  1662. portal.log.Debugfln("Adding %s to space %s (%s)", portal.MXID, space.MXID, space.Key.JID)
  1663. } else {
  1664. action = "remove portal from"
  1665. portal.log.Debugfln("Removing %s from space %s (%s)", portal.MXID, space.MXID, space.Key.JID)
  1666. }
  1667. _, err := space.MainIntent().SendStateEvent(space.MXID, event.StateSpaceChild, portal.MXID.String(), &childContent)
  1668. if err != nil {
  1669. portal.log.Errorfln("Failed to send m.space.child event to %s %s: %v", action, space.MXID, err)
  1670. return false
  1671. }
  1672. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateSpaceParent, space.MXID.String(), &parentContent)
  1673. if err != nil {
  1674. portal.log.Warnfln("Failed to send m.space.parent event to %s %s: %v", action, space.MXID, err)
  1675. }
  1676. portal.InSpace = add
  1677. if updateInfo {
  1678. portal.Update(nil)
  1679. portal.UpdateBridgeInfo()
  1680. }
  1681. return true
  1682. }
  1683. func (portal *Portal) IsPrivateChat() bool {
  1684. return portal.Key.JID.Server == types.DefaultUserServer
  1685. }
  1686. func (portal *Portal) IsGroupChat() bool {
  1687. return portal.Key.JID.Server == types.GroupServer
  1688. }
  1689. func (portal *Portal) IsBroadcastList() bool {
  1690. return portal.Key.JID.Server == types.BroadcastServer
  1691. }
  1692. func (portal *Portal) IsStatusBroadcastList() bool {
  1693. return portal.Key.JID == types.StatusBroadcastJID
  1694. }
  1695. func (portal *Portal) HasRelaybot() bool {
  1696. return portal.bridge.Config.Bridge.Relay.Enabled && len(portal.RelayUserID) > 0
  1697. }
  1698. func (portal *Portal) GetRelayUser() *User {
  1699. if !portal.HasRelaybot() {
  1700. return nil
  1701. } else if portal.relayUser == nil {
  1702. portal.relayUser = portal.bridge.GetUserByMXID(portal.RelayUserID)
  1703. }
  1704. return portal.relayUser
  1705. }
  1706. func (portal *Portal) GetParentPortal() *Portal {
  1707. if portal.ParentGroup.IsEmpty() {
  1708. return nil
  1709. } else if portal.parentPortal == nil {
  1710. portal.parentPortal = portal.bridge.GetPortalByJID(database.NewPortalKey(portal.ParentGroup, portal.ParentGroup))
  1711. }
  1712. return portal.parentPortal
  1713. }
  1714. func (portal *Portal) MainIntent() *appservice.IntentAPI {
  1715. if portal.IsPrivateChat() {
  1716. return portal.bridge.GetPuppetByJID(portal.Key.JID).DefaultIntent()
  1717. }
  1718. return portal.bridge.Bot
  1719. }
  1720. func (portal *Portal) SetReply(content *event.MessageEventContent, replyTo *ReplyInfo, isBackfill bool) bool {
  1721. if replyTo == nil {
  1722. return false
  1723. }
  1724. message := portal.bridge.DB.Message.GetByJID(portal.Key, replyTo.MessageID)
  1725. if message == nil || message.IsFakeMXID() {
  1726. if isBackfill && portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  1727. content.RelatesTo = (&event.RelatesTo{}).SetReplyTo(portal.deterministicEventID(replyTo.Sender, replyTo.MessageID, ""))
  1728. return true
  1729. }
  1730. return false
  1731. }
  1732. evt, err := portal.MainIntent().GetEvent(portal.MXID, message.MXID)
  1733. if err != nil {
  1734. portal.log.Warnln("Failed to get reply target:", err)
  1735. content.RelatesTo = (&event.RelatesTo{}).SetReplyTo(message.MXID)
  1736. return true
  1737. }
  1738. _ = evt.Content.ParseRaw(evt.Type)
  1739. if evt.Type == event.EventEncrypted {
  1740. decryptedEvt, err := portal.bridge.Crypto.Decrypt(evt)
  1741. if err != nil {
  1742. portal.log.Warnln("Failed to decrypt reply target:", err)
  1743. } else {
  1744. evt = decryptedEvt
  1745. }
  1746. }
  1747. content.SetReply(evt)
  1748. return true
  1749. }
  1750. func (portal *Portal) HandleMessageReaction(intent *appservice.IntentAPI, user *User, info *types.MessageInfo, reaction *waProto.ReactionMessage, existingMsg *database.Message) {
  1751. if existingMsg != nil {
  1752. _, _ = portal.MainIntent().RedactEvent(portal.MXID, existingMsg.MXID, mautrix.ReqRedact{
  1753. Reason: "The undecryptable message was actually a reaction",
  1754. })
  1755. }
  1756. targetJID := reaction.GetKey().GetId()
  1757. if reaction.GetText() == "" {
  1758. existing := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, info.Sender)
  1759. if existing == nil {
  1760. portal.log.Debugfln("Dropping removal %s of unknown reaction to %s from %s", info.ID, targetJID, info.Sender)
  1761. return
  1762. }
  1763. resp, err := intent.RedactEvent(portal.MXID, existing.MXID)
  1764. if err != nil {
  1765. portal.log.Errorfln("Failed to redact reaction %s/%s from %s to %s: %v", existing.MXID, existing.JID, info.Sender, targetJID, err)
  1766. }
  1767. portal.finishHandling(existingMsg, info, resp.EventID, database.MsgReaction, database.MsgNoError)
  1768. existing.Delete()
  1769. } else {
  1770. target := portal.bridge.DB.Message.GetByJID(portal.Key, targetJID)
  1771. if target == nil {
  1772. portal.log.Debugfln("Dropping reaction %s from %s to unknown message %s", info.ID, info.Sender, targetJID)
  1773. return
  1774. }
  1775. var content event.ReactionEventContent
  1776. content.RelatesTo = event.RelatesTo{
  1777. Type: event.RelAnnotation,
  1778. EventID: target.MXID,
  1779. Key: variationselector.Add(reaction.GetText()),
  1780. }
  1781. resp, err := intent.SendMassagedMessageEvent(portal.MXID, event.EventReaction, &content, info.Timestamp.UnixMilli())
  1782. if err != nil {
  1783. portal.log.Errorfln("Failed to bridge reaction %s from %s to %s: %v", info.ID, info.Sender, target.JID, err)
  1784. return
  1785. }
  1786. portal.finishHandling(existingMsg, info, resp.EventID, database.MsgReaction, database.MsgNoError)
  1787. portal.upsertReaction(nil, intent, target.JID, info.Sender, resp.EventID, info.ID)
  1788. }
  1789. }
  1790. func (portal *Portal) HandleMessageRevoke(user *User, info *types.MessageInfo, key *waProto.MessageKey) bool {
  1791. msg := portal.bridge.DB.Message.GetByJID(portal.Key, key.GetId())
  1792. if msg == nil || msg.IsFakeMXID() {
  1793. return false
  1794. }
  1795. intent := portal.bridge.GetPuppetByJID(info.Sender).IntentFor(portal)
  1796. _, err := intent.RedactEvent(portal.MXID, msg.MXID)
  1797. if err != nil {
  1798. if errors.Is(err, mautrix.MForbidden) {
  1799. _, err = portal.MainIntent().RedactEvent(portal.MXID, msg.MXID)
  1800. if err != nil {
  1801. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  1802. }
  1803. }
  1804. } else {
  1805. msg.Delete()
  1806. }
  1807. return true
  1808. }
  1809. func (portal *Portal) deleteForMe(user *User, content *events.DeleteForMe) bool {
  1810. matrixUsers, err := portal.GetMatrixUsers()
  1811. if err != nil {
  1812. portal.log.Errorln("Failed to get Matrix users in portal to see if DeleteForMe should be handled:", err)
  1813. return false
  1814. }
  1815. if len(matrixUsers) == 1 && matrixUsers[0] == user.MXID {
  1816. msg := portal.bridge.DB.Message.GetByJID(portal.Key, content.MessageID)
  1817. if msg == nil || msg.IsFakeMXID() {
  1818. return false
  1819. }
  1820. _, err := portal.MainIntent().RedactEvent(portal.MXID, msg.MXID)
  1821. if err != nil {
  1822. portal.log.Errorln("Failed to redact %s: %v", msg.JID, err)
  1823. } else {
  1824. msg.Delete()
  1825. }
  1826. return true
  1827. }
  1828. return false
  1829. }
  1830. func (portal *Portal) sendMainIntentMessage(content *event.MessageEventContent) (*mautrix.RespSendEvent, error) {
  1831. return portal.sendMessage(portal.MainIntent(), event.EventMessage, content, nil, 0)
  1832. }
  1833. func (portal *Portal) encrypt(intent *appservice.IntentAPI, content *event.Content, eventType event.Type) (event.Type, error) {
  1834. if !portal.Encrypted || portal.bridge.Crypto == nil {
  1835. return eventType, nil
  1836. }
  1837. intent.AddDoublePuppetValue(content)
  1838. // TODO maybe the locking should be inside mautrix-go?
  1839. portal.encryptLock.Lock()
  1840. defer portal.encryptLock.Unlock()
  1841. err := portal.bridge.Crypto.Encrypt(portal.MXID, eventType, content)
  1842. if err != nil {
  1843. return eventType, fmt.Errorf("failed to encrypt event: %w", err)
  1844. }
  1845. return event.EventEncrypted, nil
  1846. }
  1847. func (portal *Portal) sendMessage(intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, timestamp int64) (*mautrix.RespSendEvent, error) {
  1848. wrappedContent := event.Content{Parsed: content, Raw: extraContent}
  1849. var err error
  1850. eventType, err = portal.encrypt(intent, &wrappedContent, eventType)
  1851. if err != nil {
  1852. return nil, err
  1853. }
  1854. _, _ = intent.UserTyping(portal.MXID, false, 0)
  1855. if timestamp == 0 {
  1856. return intent.SendMessageEvent(portal.MXID, eventType, &wrappedContent)
  1857. } else {
  1858. return intent.SendMassagedMessageEvent(portal.MXID, eventType, &wrappedContent, timestamp)
  1859. }
  1860. }
  1861. type ReplyInfo struct {
  1862. MessageID types.MessageID
  1863. Sender types.JID
  1864. }
  1865. type Replyable interface {
  1866. GetStanzaId() string
  1867. GetParticipant() string
  1868. }
  1869. func GetReply(replyable Replyable) *ReplyInfo {
  1870. if replyable.GetStanzaId() == "" {
  1871. return nil
  1872. }
  1873. sender, err := types.ParseJID(replyable.GetParticipant())
  1874. if err != nil {
  1875. return nil
  1876. }
  1877. return &ReplyInfo{
  1878. MessageID: types.MessageID(replyable.GetStanzaId()),
  1879. Sender: sender,
  1880. }
  1881. }
  1882. type ConvertedMessage struct {
  1883. Intent *appservice.IntentAPI
  1884. Type event.Type
  1885. Content *event.MessageEventContent
  1886. Extra map[string]interface{}
  1887. Caption *event.MessageEventContent
  1888. MultiEvent []*event.MessageEventContent
  1889. ReplyTo *ReplyInfo
  1890. ExpiresIn time.Duration
  1891. Error database.MessageErrorType
  1892. MediaKey []byte
  1893. }
  1894. func (cm *ConvertedMessage) MergeCaption() {
  1895. if cm.Caption == nil {
  1896. return
  1897. }
  1898. cm.Content.FileName = cm.Content.Body
  1899. extensibleCaption := map[string]interface{}{
  1900. "org.matrix.msc1767.text": cm.Caption.Body,
  1901. }
  1902. cm.Extra["org.matrix.msc1767.caption"] = extensibleCaption
  1903. cm.Content.Body = cm.Caption.Body
  1904. if cm.Caption.Format == event.FormatHTML {
  1905. cm.Content.Format = event.FormatHTML
  1906. cm.Content.FormattedBody = cm.Caption.FormattedBody
  1907. extensibleCaption["org.matrix.msc1767.html"] = cm.Caption.FormattedBody
  1908. }
  1909. cm.Caption = nil
  1910. }
  1911. func (portal *Portal) convertTextMessage(intent *appservice.IntentAPI, source *User, msg *waProto.Message) *ConvertedMessage {
  1912. content := &event.MessageEventContent{
  1913. Body: msg.GetConversation(),
  1914. MsgType: event.MsgText,
  1915. }
  1916. if len(msg.GetExtendedTextMessage().GetText()) > 0 {
  1917. content.Body = msg.GetExtendedTextMessage().GetText()
  1918. }
  1919. contextInfo := msg.GetExtendedTextMessage().GetContextInfo()
  1920. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, content, contextInfo.GetMentionedJid(), false, false)
  1921. expiresIn := time.Duration(contextInfo.GetExpiration()) * time.Second
  1922. extraAttrs := map[string]interface{}{}
  1923. extraAttrs["com.beeper.linkpreviews"] = portal.convertURLPreviewToBeeper(intent, source, msg.GetExtendedTextMessage())
  1924. return &ConvertedMessage{
  1925. Intent: intent,
  1926. Type: event.EventMessage,
  1927. Content: content,
  1928. ReplyTo: GetReply(contextInfo),
  1929. ExpiresIn: expiresIn,
  1930. Extra: extraAttrs,
  1931. }
  1932. }
  1933. func (portal *Portal) convertTemplateMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, tplMsg *waProto.TemplateMessage) *ConvertedMessage {
  1934. converted := &ConvertedMessage{
  1935. Intent: intent,
  1936. Type: event.EventMessage,
  1937. Content: &event.MessageEventContent{
  1938. Body: "Unsupported business message",
  1939. MsgType: event.MsgText,
  1940. },
  1941. ReplyTo: GetReply(tplMsg.GetContextInfo()),
  1942. ExpiresIn: time.Duration(tplMsg.GetContextInfo().GetExpiration()) * time.Second,
  1943. }
  1944. tpl := tplMsg.GetHydratedTemplate()
  1945. if tpl == nil {
  1946. return converted
  1947. }
  1948. content := tpl.GetHydratedContentText()
  1949. if buttons := tpl.GetHydratedButtons(); len(buttons) > 0 {
  1950. addButtonText := false
  1951. descriptions := make([]string, len(buttons))
  1952. for i, rawButton := range buttons {
  1953. switch button := rawButton.GetHydratedButton().(type) {
  1954. case *waProto.HydratedTemplateButton_QuickReplyButton:
  1955. descriptions[i] = fmt.Sprintf("<%s>", button.QuickReplyButton.GetDisplayText())
  1956. addButtonText = true
  1957. case *waProto.HydratedTemplateButton_UrlButton:
  1958. descriptions[i] = fmt.Sprintf("[%s](%s)", button.UrlButton.GetDisplayText(), button.UrlButton.GetUrl())
  1959. case *waProto.HydratedTemplateButton_CallButton:
  1960. descriptions[i] = fmt.Sprintf("[%s](tel:%s)", button.CallButton.GetDisplayText(), button.CallButton.GetPhoneNumber())
  1961. }
  1962. }
  1963. description := strings.Join(descriptions, " - ")
  1964. if addButtonText {
  1965. description += "\nUse the WhatsApp app to click buttons"
  1966. }
  1967. content = fmt.Sprintf("%s\n\n%s", content, description)
  1968. }
  1969. if footer := tpl.GetHydratedFooterText(); footer != "" {
  1970. content = fmt.Sprintf("%s\n\n%s", content, footer)
  1971. }
  1972. var convertedTitle *ConvertedMessage
  1973. switch title := tpl.GetTitle().(type) {
  1974. case *waProto.TemplateMessage_HydratedFourRowTemplate_DocumentMessage:
  1975. convertedTitle = portal.convertMediaMessage(intent, source, info, title.DocumentMessage, "file attachment", false)
  1976. case *waProto.TemplateMessage_HydratedFourRowTemplate_ImageMessage:
  1977. convertedTitle = portal.convertMediaMessage(intent, source, info, title.ImageMessage, "photo", false)
  1978. case *waProto.TemplateMessage_HydratedFourRowTemplate_VideoMessage:
  1979. convertedTitle = portal.convertMediaMessage(intent, source, info, title.VideoMessage, "video attachment", false)
  1980. case *waProto.TemplateMessage_HydratedFourRowTemplate_LocationMessage:
  1981. content = fmt.Sprintf("Unsupported location message\n\n%s", content)
  1982. case *waProto.TemplateMessage_HydratedFourRowTemplate_HydratedTitleText:
  1983. content = fmt.Sprintf("%s\n\n%s", title.HydratedTitleText, content)
  1984. }
  1985. converted.Content.Body = content
  1986. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, converted.Content, nil, true, false)
  1987. if convertedTitle != nil {
  1988. converted.MediaKey = convertedTitle.MediaKey
  1989. converted.Extra = convertedTitle.Extra
  1990. converted.Caption = converted.Content
  1991. converted.Content = convertedTitle.Content
  1992. converted.Error = convertedTitle.Error
  1993. }
  1994. if converted.Extra == nil {
  1995. converted.Extra = make(map[string]interface{})
  1996. }
  1997. converted.Extra["fi.mau.whatsapp.hydrated_template_id"] = tpl.GetTemplateId()
  1998. return converted
  1999. }
  2000. func (portal *Portal) convertTemplateButtonReplyMessage(intent *appservice.IntentAPI, msg *waProto.TemplateButtonReplyMessage) *ConvertedMessage {
  2001. return &ConvertedMessage{
  2002. Intent: intent,
  2003. Type: event.EventMessage,
  2004. Content: &event.MessageEventContent{
  2005. Body: msg.GetSelectedDisplayText(),
  2006. MsgType: event.MsgText,
  2007. },
  2008. Extra: map[string]interface{}{
  2009. "fi.mau.whatsapp.template_button_reply": map[string]interface{}{
  2010. "id": msg.GetSelectedId(),
  2011. "index": msg.GetSelectedIndex(),
  2012. },
  2013. },
  2014. ReplyTo: GetReply(msg.GetContextInfo()),
  2015. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2016. }
  2017. }
  2018. func (portal *Portal) convertListMessage(intent *appservice.IntentAPI, source *User, msg *waProto.ListMessage) *ConvertedMessage {
  2019. converted := &ConvertedMessage{
  2020. Intent: intent,
  2021. Type: event.EventMessage,
  2022. Content: &event.MessageEventContent{
  2023. Body: "Unsupported business message",
  2024. MsgType: event.MsgText,
  2025. },
  2026. ReplyTo: GetReply(msg.GetContextInfo()),
  2027. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2028. }
  2029. body := msg.GetDescription()
  2030. if msg.GetTitle() != "" {
  2031. if body == "" {
  2032. body = msg.GetTitle()
  2033. } else {
  2034. body = fmt.Sprintf("%s\n\n%s", msg.GetTitle(), body)
  2035. }
  2036. }
  2037. randomID := util.RandomString(64)
  2038. body = fmt.Sprintf("%s\n%s", body, randomID)
  2039. if msg.GetFooterText() != "" {
  2040. body = fmt.Sprintf("%s\n\n%s", body, msg.GetFooterText())
  2041. }
  2042. converted.Content.Body = body
  2043. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, converted.Content, nil, false, true)
  2044. var optionsMarkdown strings.Builder
  2045. _, _ = fmt.Fprintf(&optionsMarkdown, "#### %s\n", msg.GetButtonText())
  2046. for _, section := range msg.GetSections() {
  2047. nesting := ""
  2048. if section.GetTitle() != "" {
  2049. _, _ = fmt.Fprintf(&optionsMarkdown, "* %s\n", section.GetTitle())
  2050. nesting = " "
  2051. }
  2052. for _, row := range section.GetRows() {
  2053. if row.GetDescription() != "" {
  2054. _, _ = fmt.Fprintf(&optionsMarkdown, "%s* %s: %s\n", nesting, row.GetTitle(), row.GetDescription())
  2055. } else {
  2056. _, _ = fmt.Fprintf(&optionsMarkdown, "%s* %s\n", nesting, row.GetTitle())
  2057. }
  2058. }
  2059. }
  2060. optionsMarkdown.WriteString("\nUse the WhatsApp app to respond")
  2061. rendered := format.RenderMarkdown(optionsMarkdown.String(), true, false)
  2062. converted.Content.Body = strings.Replace(converted.Content.Body, randomID, rendered.Body, 1)
  2063. converted.Content.FormattedBody = strings.Replace(converted.Content.FormattedBody, randomID, rendered.FormattedBody, 1)
  2064. return converted
  2065. }
  2066. func (portal *Portal) convertListResponseMessage(intent *appservice.IntentAPI, msg *waProto.ListResponseMessage) *ConvertedMessage {
  2067. var body string
  2068. if msg.GetTitle() != "" {
  2069. if msg.GetDescription() != "" {
  2070. body = fmt.Sprintf("%s\n\n%s", msg.GetTitle(), msg.GetDescription())
  2071. } else {
  2072. body = msg.GetTitle()
  2073. }
  2074. } else if msg.GetDescription() != "" {
  2075. body = msg.GetDescription()
  2076. } else {
  2077. body = "Unsupported list reply message"
  2078. }
  2079. return &ConvertedMessage{
  2080. Intent: intent,
  2081. Type: event.EventMessage,
  2082. Content: &event.MessageEventContent{
  2083. Body: body,
  2084. MsgType: event.MsgText,
  2085. },
  2086. Extra: map[string]interface{}{
  2087. "fi.mau.whatsapp.list_reply": map[string]interface{}{
  2088. "row_id": msg.GetSingleSelectReply().GetSelectedRowId(),
  2089. },
  2090. },
  2091. ReplyTo: GetReply(msg.GetContextInfo()),
  2092. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2093. }
  2094. }
  2095. func (portal *Portal) convertPollUpdateMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg *waProto.PollUpdateMessage) *ConvertedMessage {
  2096. pollMessage := portal.bridge.DB.Message.GetByJID(portal.Key, msg.GetPollCreationMessageKey().GetId())
  2097. if pollMessage == nil {
  2098. portal.log.Warnfln("Failed to convert vote message %s: poll message %s not found", info.ID, msg.GetPollCreationMessageKey().GetId())
  2099. return nil
  2100. }
  2101. vote, err := source.Client.DecryptPollVote(&events.Message{
  2102. Info: *info,
  2103. Message: &waProto.Message{PollUpdateMessage: msg},
  2104. })
  2105. if err != nil {
  2106. portal.log.Errorfln("Failed to decrypt vote message %s: %v", info.ID, err)
  2107. return nil
  2108. }
  2109. selectedHashes := make([]string, len(vote.GetSelectedOptions()))
  2110. if pollMessage.Type == database.MsgMatrixPoll {
  2111. mappedAnswers := pollMessage.GetPollOptionIDs(vote.GetSelectedOptions())
  2112. for i, opt := range vote.GetSelectedOptions() {
  2113. if len(opt) != 32 {
  2114. portal.log.Warnfln("Unexpected option hash length %d in %s's vote to %s", len(opt), info.Sender, pollMessage.MXID)
  2115. continue
  2116. }
  2117. var ok bool
  2118. selectedHashes[i], ok = mappedAnswers[*(*[32]byte)(opt)]
  2119. if !ok {
  2120. portal.log.Warnfln("Didn't find ID for option %X in %s's vote to %s", opt, info.Sender, pollMessage.MXID)
  2121. }
  2122. }
  2123. } else {
  2124. for i, opt := range vote.GetSelectedOptions() {
  2125. selectedHashes[i] = hex.EncodeToString(opt)
  2126. }
  2127. }
  2128. evtType := TypeMSC3381PollResponse
  2129. //if portal.bridge.Config.Bridge.ExtEvPolls == 2 {
  2130. // evtType = TypeMSC3381V2PollResponse
  2131. //}
  2132. return &ConvertedMessage{
  2133. Intent: intent,
  2134. Type: evtType,
  2135. Content: &event.MessageEventContent{
  2136. RelatesTo: &event.RelatesTo{
  2137. Type: event.RelReference,
  2138. EventID: pollMessage.MXID,
  2139. },
  2140. },
  2141. Extra: map[string]any{
  2142. "org.matrix.msc3381.poll.response": map[string]any{
  2143. "answers": selectedHashes,
  2144. },
  2145. "org.matrix.msc3381.v2.selections": selectedHashes,
  2146. },
  2147. }
  2148. }
  2149. func (portal *Portal) convertPollCreationMessage(intent *appservice.IntentAPI, msg *waProto.PollCreationMessage) *ConvertedMessage {
  2150. optionNames := make([]string, len(msg.GetOptions()))
  2151. optionsListText := make([]string, len(optionNames))
  2152. optionsListHTML := make([]string, len(optionNames))
  2153. msc3381Answers := make([]map[string]any, len(optionNames))
  2154. msc3381V2Answers := make([]map[string]any, len(optionNames))
  2155. for i, opt := range msg.GetOptions() {
  2156. optionNames[i] = opt.GetOptionName()
  2157. optionsListText[i] = fmt.Sprintf("%d. %s\n", i+1, optionNames[i])
  2158. optionsListHTML[i] = fmt.Sprintf("<li>%s</li>", event.TextToHTML(optionNames[i]))
  2159. optionHash := sha256.Sum256([]byte(opt.GetOptionName()))
  2160. optionHashStr := hex.EncodeToString(optionHash[:])
  2161. msc3381Answers[i] = map[string]any{
  2162. "id": optionHashStr,
  2163. "org.matrix.msc1767.text": opt.GetOptionName(),
  2164. }
  2165. msc3381V2Answers[i] = map[string]any{
  2166. "org.matrix.msc3381.v2.id": optionHashStr,
  2167. "org.matrix.msc1767.markup": []map[string]any{
  2168. {"mimetype": "text/plain", "body": opt.GetOptionName()},
  2169. },
  2170. }
  2171. }
  2172. body := fmt.Sprintf("%s\n\n%s", msg.GetName(), strings.Join(optionsListText, "\n"))
  2173. formattedBody := fmt.Sprintf("<p>%s</p><ol>%s</ol>", event.TextToHTML(msg.GetName()), strings.Join(optionsListHTML, ""))
  2174. maxChoices := int(msg.GetSelectableOptionsCount())
  2175. if maxChoices <= 0 {
  2176. maxChoices = len(optionNames)
  2177. }
  2178. evtType := event.EventMessage
  2179. if portal.bridge.Config.Bridge.ExtEvPolls {
  2180. evtType = TypeMSC3381PollStart
  2181. }
  2182. //else if portal.bridge.Config.Bridge.ExtEvPolls == 2 {
  2183. // evtType.Type = "org.matrix.msc3381.v2.poll.start"
  2184. //}
  2185. return &ConvertedMessage{
  2186. Intent: intent,
  2187. Type: evtType,
  2188. Content: &event.MessageEventContent{
  2189. Body: body,
  2190. MsgType: event.MsgText,
  2191. Format: event.FormatHTML,
  2192. FormattedBody: formattedBody,
  2193. },
  2194. Extra: map[string]any{
  2195. // Custom metadata
  2196. "fi.mau.whatsapp.poll": map[string]any{
  2197. "option_names": optionNames,
  2198. "selectable_options_count": msg.GetSelectableOptionsCount(),
  2199. },
  2200. // Current extensible events (as of November 2022)
  2201. "org.matrix.msc1767.markup": []map[string]any{
  2202. {"mimetype": "text/html", "body": formattedBody},
  2203. {"mimetype": "text/plain", "body": body},
  2204. },
  2205. "org.matrix.msc3381.v2.poll": map[string]any{
  2206. "kind": "org.matrix.msc3381.v2.disclosed",
  2207. "max_selections": maxChoices,
  2208. "question": map[string]any{
  2209. "org.matrix.msc1767.markup": []map[string]any{
  2210. {"mimetype": "text/plain", "body": msg.GetName()},
  2211. },
  2212. },
  2213. "answers": msc3381V2Answers,
  2214. },
  2215. // Legacy extensible events
  2216. "org.matrix.msc1767.message": []map[string]any{
  2217. {"mimetype": "text/html", "body": formattedBody},
  2218. {"mimetype": "text/plain", "body": body},
  2219. },
  2220. "org.matrix.msc3381.poll.start": map[string]any{
  2221. "kind": "org.matrix.msc3381.poll.disclosed",
  2222. "max_selections": maxChoices,
  2223. "question": map[string]any{
  2224. "org.matrix.msc1767.text": msg.GetName(),
  2225. },
  2226. "answers": msc3381Answers,
  2227. },
  2228. },
  2229. ReplyTo: GetReply(msg.GetContextInfo()),
  2230. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2231. }
  2232. }
  2233. func (portal *Portal) convertLiveLocationMessage(intent *appservice.IntentAPI, msg *waProto.LiveLocationMessage) *ConvertedMessage {
  2234. content := &event.MessageEventContent{
  2235. Body: "Started sharing live location",
  2236. MsgType: event.MsgNotice,
  2237. }
  2238. if len(msg.GetCaption()) > 0 {
  2239. content.Body += ": " + msg.GetCaption()
  2240. }
  2241. return &ConvertedMessage{
  2242. Intent: intent,
  2243. Type: event.EventMessage,
  2244. Content: content,
  2245. ReplyTo: GetReply(msg.GetContextInfo()),
  2246. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2247. }
  2248. }
  2249. func (portal *Portal) convertLocationMessage(intent *appservice.IntentAPI, msg *waProto.LocationMessage) *ConvertedMessage {
  2250. url := msg.GetUrl()
  2251. if len(url) == 0 {
  2252. url = fmt.Sprintf("https://maps.google.com/?q=%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude())
  2253. }
  2254. name := msg.GetName()
  2255. if len(name) == 0 {
  2256. latChar := 'N'
  2257. if msg.GetDegreesLatitude() < 0 {
  2258. latChar = 'S'
  2259. }
  2260. longChar := 'E'
  2261. if msg.GetDegreesLongitude() < 0 {
  2262. longChar = 'W'
  2263. }
  2264. name = fmt.Sprintf("%.4f° %c %.4f° %c", math.Abs(msg.GetDegreesLatitude()), latChar, math.Abs(msg.GetDegreesLongitude()), longChar)
  2265. }
  2266. content := &event.MessageEventContent{
  2267. MsgType: event.MsgLocation,
  2268. Body: fmt.Sprintf("Location: %s\n%s\n%s", name, msg.GetAddress(), url),
  2269. Format: event.FormatHTML,
  2270. FormattedBody: fmt.Sprintf("Location: <a href='%s'>%s</a><br>%s", url, name, msg.GetAddress()),
  2271. GeoURI: fmt.Sprintf("geo:%.5f,%.5f", msg.GetDegreesLatitude(), msg.GetDegreesLongitude()),
  2272. }
  2273. if len(msg.GetJpegThumbnail()) > 0 {
  2274. thumbnailMime := http.DetectContentType(msg.GetJpegThumbnail())
  2275. uploadedThumbnail, _ := intent.UploadBytes(msg.GetJpegThumbnail(), thumbnailMime)
  2276. if uploadedThumbnail != nil {
  2277. cfg, _, _ := image.DecodeConfig(bytes.NewReader(msg.GetJpegThumbnail()))
  2278. content.Info = &event.FileInfo{
  2279. ThumbnailInfo: &event.FileInfo{
  2280. Size: len(msg.GetJpegThumbnail()),
  2281. Width: cfg.Width,
  2282. Height: cfg.Height,
  2283. MimeType: thumbnailMime,
  2284. },
  2285. ThumbnailURL: uploadedThumbnail.ContentURI.CUString(),
  2286. }
  2287. }
  2288. }
  2289. return &ConvertedMessage{
  2290. Intent: intent,
  2291. Type: event.EventMessage,
  2292. Content: content,
  2293. ReplyTo: GetReply(msg.GetContextInfo()),
  2294. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2295. }
  2296. }
  2297. 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.`
  2298. const inviteMetaField = "fi.mau.whatsapp.invite"
  2299. const escapedInviteMetaField = `fi\.mau\.whatsapp\.invite`
  2300. type InviteMeta struct {
  2301. JID types.JID `json:"jid"`
  2302. Code string `json:"code"`
  2303. Expiration int64 `json:"expiration,string"`
  2304. Inviter types.JID `json:"inviter"`
  2305. }
  2306. func (portal *Portal) convertGroupInviteMessage(intent *appservice.IntentAPI, info *types.MessageInfo, msg *waProto.GroupInviteMessage) *ConvertedMessage {
  2307. expiry := time.Unix(msg.GetInviteExpiration(), 0)
  2308. htmlMessage := fmt.Sprintf(inviteMsg, event.TextToHTML(msg.GetCaption()), msg.GetGroupName(), expiry)
  2309. content := &event.MessageEventContent{
  2310. MsgType: event.MsgText,
  2311. Body: format.HTMLToText(htmlMessage),
  2312. Format: event.FormatHTML,
  2313. FormattedBody: htmlMessage,
  2314. }
  2315. groupJID, err := types.ParseJID(msg.GetGroupJid())
  2316. if err != nil {
  2317. portal.log.Errorfln("Failed to parse invite group JID: %v", err)
  2318. }
  2319. extraAttrs := map[string]interface{}{
  2320. inviteMetaField: InviteMeta{
  2321. JID: groupJID,
  2322. Code: msg.GetInviteCode(),
  2323. Expiration: msg.GetInviteExpiration(),
  2324. Inviter: info.Sender.ToNonAD(),
  2325. },
  2326. }
  2327. return &ConvertedMessage{
  2328. Intent: intent,
  2329. Type: event.EventMessage,
  2330. Content: content,
  2331. Extra: extraAttrs,
  2332. ReplyTo: GetReply(msg.GetContextInfo()),
  2333. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2334. }
  2335. }
  2336. func (portal *Portal) convertContactMessage(intent *appservice.IntentAPI, msg *waProto.ContactMessage) *ConvertedMessage {
  2337. fileName := fmt.Sprintf("%s.vcf", msg.GetDisplayName())
  2338. data := []byte(msg.GetVcard())
  2339. mimeType := "text/vcard"
  2340. uploadMimeType, file := portal.encryptFileInPlace(data, mimeType)
  2341. uploadResp, err := intent.UploadBytesWithName(data, uploadMimeType, fileName)
  2342. if err != nil {
  2343. portal.log.Errorfln("Failed to upload vcard of %s: %v", msg.GetDisplayName(), err)
  2344. return nil
  2345. }
  2346. content := &event.MessageEventContent{
  2347. Body: fileName,
  2348. MsgType: event.MsgFile,
  2349. File: file,
  2350. Info: &event.FileInfo{
  2351. MimeType: mimeType,
  2352. Size: len(msg.GetVcard()),
  2353. },
  2354. }
  2355. if content.File != nil {
  2356. content.File.URL = uploadResp.ContentURI.CUString()
  2357. } else {
  2358. content.URL = uploadResp.ContentURI.CUString()
  2359. }
  2360. return &ConvertedMessage{
  2361. Intent: intent,
  2362. Type: event.EventMessage,
  2363. Content: content,
  2364. ReplyTo: GetReply(msg.GetContextInfo()),
  2365. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2366. }
  2367. }
  2368. func (portal *Portal) convertContactsArrayMessage(intent *appservice.IntentAPI, msg *waProto.ContactsArrayMessage) *ConvertedMessage {
  2369. name := msg.GetDisplayName()
  2370. if len(name) == 0 {
  2371. name = fmt.Sprintf("%d contacts", len(msg.GetContacts()))
  2372. }
  2373. contacts := make([]*event.MessageEventContent, 0, len(msg.GetContacts()))
  2374. for _, contact := range msg.GetContacts() {
  2375. converted := portal.convertContactMessage(intent, contact)
  2376. if converted != nil {
  2377. contacts = append(contacts, converted.Content)
  2378. }
  2379. }
  2380. return &ConvertedMessage{
  2381. Intent: intent,
  2382. Type: event.EventMessage,
  2383. Content: &event.MessageEventContent{
  2384. MsgType: event.MsgNotice,
  2385. Body: fmt.Sprintf("Sent %s", name),
  2386. },
  2387. ReplyTo: GetReply(msg.GetContextInfo()),
  2388. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2389. MultiEvent: contacts,
  2390. }
  2391. }
  2392. func (portal *Portal) tryKickUser(userID id.UserID, intent *appservice.IntentAPI) error {
  2393. _, err := intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
  2394. if err != nil {
  2395. httpErr, ok := err.(mautrix.HTTPError)
  2396. if ok && httpErr.RespError != nil && httpErr.RespError.ErrCode == "M_FORBIDDEN" {
  2397. _, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: userID})
  2398. }
  2399. }
  2400. return err
  2401. }
  2402. func (portal *Portal) removeUser(isSameUser bool, kicker *appservice.IntentAPI, target id.UserID, targetIntent *appservice.IntentAPI) {
  2403. if !isSameUser || targetIntent == nil {
  2404. err := portal.tryKickUser(target, kicker)
  2405. if err != nil {
  2406. portal.log.Warnfln("Failed to kick %s from %s: %v", target, portal.MXID, err)
  2407. if targetIntent != nil {
  2408. _, _ = targetIntent.LeaveRoom(portal.MXID)
  2409. }
  2410. }
  2411. } else {
  2412. _, err := targetIntent.LeaveRoom(portal.MXID)
  2413. if err != nil {
  2414. portal.log.Warnfln("Failed to leave portal as %s: %v", target, err)
  2415. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: target})
  2416. }
  2417. }
  2418. portal.CleanupIfEmpty()
  2419. }
  2420. func (portal *Portal) HandleWhatsAppKick(source *User, senderJID types.JID, jids []types.JID) {
  2421. sender := portal.bridge.GetPuppetByJID(senderJID)
  2422. senderIntent := sender.IntentFor(portal)
  2423. for _, jid := range jids {
  2424. //if source != nil && source.JID.User == jid.User {
  2425. // portal.log.Debugln("Ignoring self-kick by", source.MXID)
  2426. // continue
  2427. //}
  2428. puppet := portal.bridge.GetPuppetByJID(jid)
  2429. portal.removeUser(puppet.JID == sender.JID, senderIntent, puppet.MXID, puppet.DefaultIntent())
  2430. if !portal.IsBroadcastList() {
  2431. user := portal.bridge.GetUserByJID(jid)
  2432. if user != nil {
  2433. var customIntent *appservice.IntentAPI
  2434. if puppet.CustomMXID == user.MXID {
  2435. customIntent = puppet.CustomIntent()
  2436. }
  2437. portal.removeUser(puppet.JID == sender.JID, senderIntent, user.MXID, customIntent)
  2438. }
  2439. }
  2440. }
  2441. }
  2442. func (portal *Portal) HandleWhatsAppInvite(source *User, senderJID *types.JID, jids []types.JID) (evtID id.EventID) {
  2443. intent := portal.MainIntent()
  2444. if senderJID != nil && !senderJID.IsEmpty() {
  2445. sender := portal.bridge.GetPuppetByJID(*senderJID)
  2446. intent = sender.IntentFor(portal)
  2447. }
  2448. for _, jid := range jids {
  2449. puppet := portal.bridge.GetPuppetByJID(jid)
  2450. puppet.SyncContact(source, true, false, "handling whatsapp invite")
  2451. resp, err := intent.SendStateEvent(portal.MXID, event.StateMember, puppet.MXID.String(), &event.MemberEventContent{
  2452. Membership: event.MembershipInvite,
  2453. Displayname: puppet.Displayname,
  2454. AvatarURL: puppet.AvatarURL.CUString(),
  2455. })
  2456. if err != nil {
  2457. portal.log.Warnfln("Failed to invite %s as %s: %v", puppet.MXID, intent.UserID, err)
  2458. _ = portal.MainIntent().EnsureInvited(portal.MXID, puppet.MXID)
  2459. } else {
  2460. evtID = resp.EventID
  2461. }
  2462. err = puppet.DefaultIntent().EnsureJoined(portal.MXID)
  2463. if err != nil {
  2464. portal.log.Errorfln("Failed to ensure %s is joined: %v", puppet.MXID, err)
  2465. }
  2466. }
  2467. return
  2468. }
  2469. func (portal *Portal) HandleWhatsAppDeleteChat(user *User) {
  2470. if portal.MXID == "" {
  2471. return
  2472. }
  2473. matrixUsers, err := portal.GetMatrixUsers()
  2474. if err != nil {
  2475. portal.log.Errorln("Failed to get Matrix users to see if DeleteChat should be handled:", err)
  2476. return
  2477. }
  2478. if len(matrixUsers) > 1 {
  2479. portal.log.Infoln("Portal contains more than one Matrix user, so deleteChat will not be handled.")
  2480. return
  2481. } else if (len(matrixUsers) == 1 && matrixUsers[0] == user.MXID) || len(matrixUsers) < 1 {
  2482. portal.log.Debugln("User deleted chat and there are no other Matrix users using it, deleting portal...")
  2483. portal.Delete()
  2484. portal.Cleanup(false)
  2485. }
  2486. }
  2487. const failedMediaField = "fi.mau.whatsapp.failed_media"
  2488. type FailedMediaKeys struct {
  2489. Key []byte `json:"key"`
  2490. Length int `json:"length"`
  2491. Type whatsmeow.MediaType `json:"type"`
  2492. SHA256 []byte `json:"sha256"`
  2493. EncSHA256 []byte `json:"enc_sha256"`
  2494. }
  2495. type FailedMediaMeta struct {
  2496. Type event.Type `json:"type"`
  2497. Content *event.MessageEventContent `json:"content"`
  2498. ExtraContent map[string]interface{} `json:"extra_content,omitempty"`
  2499. Media FailedMediaKeys `json:"whatsapp_media"`
  2500. }
  2501. func shallowCopyMap(data map[string]interface{}) map[string]interface{} {
  2502. newMap := make(map[string]interface{}, len(data))
  2503. for key, value := range data {
  2504. newMap[key] = value
  2505. }
  2506. return newMap
  2507. }
  2508. func (portal *Portal) makeMediaBridgeFailureMessage(info *types.MessageInfo, bridgeErr error, converted *ConvertedMessage, keys *FailedMediaKeys, userFriendlyError string) *ConvertedMessage {
  2509. if errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(bridgeErr, whatsmeow.ErrMediaDownloadFailedWith410) {
  2510. portal.log.Debugfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
  2511. } else {
  2512. portal.log.Errorfln("Failed to bridge media for %s: %v", info.ID, bridgeErr)
  2513. }
  2514. if keys != nil {
  2515. if portal.bridge.Config.Bridge.CaptionInMessage {
  2516. converted.MergeCaption()
  2517. }
  2518. meta := &FailedMediaMeta{
  2519. Type: converted.Type,
  2520. Content: converted.Content,
  2521. ExtraContent: shallowCopyMap(converted.Extra),
  2522. Media: *keys,
  2523. }
  2524. converted.Extra[failedMediaField] = meta
  2525. portal.mediaErrorCache[info.ID] = meta
  2526. }
  2527. converted.Type = event.EventMessage
  2528. body := userFriendlyError
  2529. if body == "" {
  2530. body = fmt.Sprintf("Failed to bridge media: %v", bridgeErr)
  2531. }
  2532. converted.Content = &event.MessageEventContent{
  2533. MsgType: event.MsgNotice,
  2534. Body: body,
  2535. }
  2536. return converted
  2537. }
  2538. func (portal *Portal) encryptFileInPlace(data []byte, mimeType string) (string, *event.EncryptedFileInfo) {
  2539. if !portal.Encrypted {
  2540. return mimeType, nil
  2541. }
  2542. file := &event.EncryptedFileInfo{
  2543. EncryptedFile: *attachment.NewEncryptedFile(),
  2544. URL: "",
  2545. }
  2546. file.EncryptInPlace(data)
  2547. return "application/octet-stream", file
  2548. }
  2549. type MediaMessage interface {
  2550. whatsmeow.DownloadableMessage
  2551. GetContextInfo() *waProto.ContextInfo
  2552. GetFileLength() uint64
  2553. GetMimetype() string
  2554. }
  2555. type MediaMessageWithThumbnail interface {
  2556. MediaMessage
  2557. GetJpegThumbnail() []byte
  2558. }
  2559. type MediaMessageWithCaption interface {
  2560. MediaMessage
  2561. GetCaption() string
  2562. }
  2563. type MediaMessageWithDimensions interface {
  2564. MediaMessage
  2565. GetHeight() uint32
  2566. GetWidth() uint32
  2567. }
  2568. type MediaMessageWithFileName interface {
  2569. MediaMessage
  2570. GetFileName() string
  2571. }
  2572. type MediaMessageWithDuration interface {
  2573. MediaMessage
  2574. GetSeconds() uint32
  2575. }
  2576. const WhatsAppStickerSize = 190
  2577. func (portal *Portal) convertMediaMessageContent(intent *appservice.IntentAPI, msg MediaMessage) *ConvertedMessage {
  2578. content := &event.MessageEventContent{
  2579. Info: &event.FileInfo{
  2580. MimeType: msg.GetMimetype(),
  2581. Size: int(msg.GetFileLength()),
  2582. },
  2583. }
  2584. extraContent := map[string]interface{}{}
  2585. messageWithDimensions, ok := msg.(MediaMessageWithDimensions)
  2586. if ok {
  2587. content.Info.Width = int(messageWithDimensions.GetWidth())
  2588. content.Info.Height = int(messageWithDimensions.GetHeight())
  2589. }
  2590. msgWithName, ok := msg.(MediaMessageWithFileName)
  2591. if ok && len(msgWithName.GetFileName()) > 0 {
  2592. content.Body = msgWithName.GetFileName()
  2593. } else {
  2594. mimeClass := strings.Split(msg.GetMimetype(), "/")[0]
  2595. switch mimeClass {
  2596. case "application":
  2597. content.Body = "file"
  2598. default:
  2599. content.Body = mimeClass
  2600. }
  2601. content.Body += util.ExtensionFromMimetype(msg.GetMimetype())
  2602. }
  2603. msgWithDuration, ok := msg.(MediaMessageWithDuration)
  2604. if ok {
  2605. content.Info.Duration = int(msgWithDuration.GetSeconds()) * 1000
  2606. }
  2607. videoMessage, ok := msg.(*waProto.VideoMessage)
  2608. var isGIF bool
  2609. if ok && videoMessage.GetGifPlayback() {
  2610. isGIF = true
  2611. extraContent["info"] = map[string]interface{}{
  2612. "fi.mau.loop": true,
  2613. "fi.mau.autoplay": true,
  2614. "fi.mau.hide_controls": true,
  2615. "fi.mau.no_audio": true,
  2616. }
  2617. }
  2618. messageWithThumbnail, ok := msg.(MediaMessageWithThumbnail)
  2619. if ok && messageWithThumbnail.GetJpegThumbnail() != nil && (portal.bridge.Config.Bridge.WhatsappThumbnail || isGIF) {
  2620. thumbnailData := messageWithThumbnail.GetJpegThumbnail()
  2621. thumbnailMime := http.DetectContentType(thumbnailData)
  2622. thumbnailCfg, _, _ := image.DecodeConfig(bytes.NewReader(thumbnailData))
  2623. thumbnailSize := len(thumbnailData)
  2624. thumbnailUploadMime, thumbnailFile := portal.encryptFileInPlace(thumbnailData, thumbnailMime)
  2625. uploadedThumbnail, err := intent.UploadBytes(thumbnailData, thumbnailUploadMime)
  2626. if err != nil {
  2627. portal.log.Warnfln("Failed to upload thumbnail: %v", err)
  2628. } else if uploadedThumbnail != nil {
  2629. if thumbnailFile != nil {
  2630. thumbnailFile.URL = uploadedThumbnail.ContentURI.CUString()
  2631. content.Info.ThumbnailFile = thumbnailFile
  2632. } else {
  2633. content.Info.ThumbnailURL = uploadedThumbnail.ContentURI.CUString()
  2634. }
  2635. content.Info.ThumbnailInfo = &event.FileInfo{
  2636. Size: thumbnailSize,
  2637. Width: thumbnailCfg.Width,
  2638. Height: thumbnailCfg.Height,
  2639. MimeType: thumbnailMime,
  2640. }
  2641. }
  2642. }
  2643. eventType := event.EventMessage
  2644. switch msg.(type) {
  2645. case *waProto.ImageMessage:
  2646. content.MsgType = event.MsgImage
  2647. case *waProto.StickerMessage:
  2648. eventType = event.EventSticker
  2649. if content.Info.Width > content.Info.Height {
  2650. content.Info.Height /= content.Info.Width / WhatsAppStickerSize
  2651. content.Info.Width = WhatsAppStickerSize
  2652. } else if content.Info.Width < content.Info.Height {
  2653. content.Info.Width /= content.Info.Height / WhatsAppStickerSize
  2654. content.Info.Height = WhatsAppStickerSize
  2655. } else {
  2656. content.Info.Width = WhatsAppStickerSize
  2657. content.Info.Height = WhatsAppStickerSize
  2658. }
  2659. case *waProto.VideoMessage:
  2660. content.MsgType = event.MsgVideo
  2661. case *waProto.AudioMessage:
  2662. content.MsgType = event.MsgAudio
  2663. case *waProto.DocumentMessage:
  2664. content.MsgType = event.MsgFile
  2665. default:
  2666. portal.log.Warnfln("Unexpected media type %T in convertMediaMessageContent", msg)
  2667. content.MsgType = event.MsgFile
  2668. }
  2669. audioMessage, ok := msg.(*waProto.AudioMessage)
  2670. if ok {
  2671. var waveform []int
  2672. if audioMessage.Waveform != nil {
  2673. waveform = make([]int, len(audioMessage.Waveform))
  2674. max := 0
  2675. for i, part := range audioMessage.Waveform {
  2676. waveform[i] = int(part)
  2677. if waveform[i] > max {
  2678. max = waveform[i]
  2679. }
  2680. }
  2681. multiplier := 0
  2682. if max > 0 {
  2683. multiplier = 1024 / max
  2684. }
  2685. if multiplier > 32 {
  2686. multiplier = 32
  2687. }
  2688. for i := range waveform {
  2689. waveform[i] *= multiplier
  2690. }
  2691. }
  2692. extraContent["org.matrix.msc1767.audio"] = map[string]interface{}{
  2693. "duration": int(audioMessage.GetSeconds()) * 1000,
  2694. "waveform": waveform,
  2695. }
  2696. if audioMessage.GetPtt() {
  2697. extraContent["org.matrix.msc3245.voice"] = map[string]interface{}{}
  2698. }
  2699. }
  2700. messageWithCaption, ok := msg.(MediaMessageWithCaption)
  2701. var captionContent *event.MessageEventContent
  2702. if ok && len(messageWithCaption.GetCaption()) > 0 {
  2703. captionContent = &event.MessageEventContent{
  2704. Body: messageWithCaption.GetCaption(),
  2705. MsgType: event.MsgNotice,
  2706. }
  2707. portal.bridge.Formatter.ParseWhatsApp(portal.MXID, captionContent, msg.GetContextInfo().GetMentionedJid(), false, false)
  2708. }
  2709. return &ConvertedMessage{
  2710. Intent: intent,
  2711. Type: eventType,
  2712. Content: content,
  2713. Caption: captionContent,
  2714. ReplyTo: GetReply(msg.GetContextInfo()),
  2715. ExpiresIn: time.Duration(msg.GetContextInfo().GetExpiration()) * time.Second,
  2716. Extra: extraContent,
  2717. }
  2718. }
  2719. func (portal *Portal) uploadMedia(intent *appservice.IntentAPI, data []byte, content *event.MessageEventContent) error {
  2720. uploadMimeType, file := portal.encryptFileInPlace(data, content.Info.MimeType)
  2721. req := mautrix.ReqUploadMedia{
  2722. ContentBytes: data,
  2723. ContentType: uploadMimeType,
  2724. }
  2725. var mxc id.ContentURI
  2726. if portal.bridge.Config.Homeserver.AsyncMedia {
  2727. uploaded, err := intent.UnstableUploadAsync(req)
  2728. if err != nil {
  2729. return err
  2730. }
  2731. mxc = uploaded.ContentURI
  2732. } else {
  2733. uploaded, err := intent.UploadMedia(req)
  2734. if err != nil {
  2735. return err
  2736. }
  2737. mxc = uploaded.ContentURI
  2738. }
  2739. if file != nil {
  2740. file.URL = mxc.CUString()
  2741. content.File = file
  2742. } else {
  2743. content.URL = mxc.CUString()
  2744. }
  2745. content.Info.Size = len(data)
  2746. if content.Info.Width == 0 && content.Info.Height == 0 && strings.HasPrefix(content.Info.MimeType, "image/") {
  2747. cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
  2748. content.Info.Width, content.Info.Height = cfg.Width, cfg.Height
  2749. }
  2750. // This is a hack for bad clients like Element iOS that require a thumbnail (https://github.com/vector-im/element-ios/issues/4004)
  2751. if strings.HasPrefix(content.Info.MimeType, "image/") && content.Info.ThumbnailInfo == nil {
  2752. infoCopy := *content.Info
  2753. content.Info.ThumbnailInfo = &infoCopy
  2754. if content.File != nil {
  2755. content.Info.ThumbnailFile = file
  2756. } else {
  2757. content.Info.ThumbnailURL = content.URL
  2758. }
  2759. }
  2760. return nil
  2761. }
  2762. func (portal *Portal) convertMediaMessage(intent *appservice.IntentAPI, source *User, info *types.MessageInfo, msg MediaMessage, typeName string, isBackfill bool) *ConvertedMessage {
  2763. converted := portal.convertMediaMessageContent(intent, msg)
  2764. if msg.GetFileLength() > uint64(portal.bridge.MediaConfig.UploadSize) {
  2765. 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))
  2766. }
  2767. data, err := source.Client.Download(msg)
  2768. if errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith410) {
  2769. converted.Error = database.MsgErrMediaNotFound
  2770. converted.MediaKey = msg.GetMediaKey()
  2771. errorText := fmt.Sprintf("Old %s.", typeName)
  2772. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia && isBackfill {
  2773. errorText += " Media will be automatically requested from your phone later."
  2774. } else {
  2775. errorText += " React with the \u267b (recycle) emoji to request this media from your phone."
  2776. }
  2777. return portal.makeMediaBridgeFailureMessage(info, err, converted, &FailedMediaKeys{
  2778. Key: msg.GetMediaKey(),
  2779. Length: int(msg.GetFileLength()),
  2780. Type: whatsmeow.GetMediaType(msg),
  2781. SHA256: msg.GetFileSha256(),
  2782. EncSHA256: msg.GetFileEncSha256(),
  2783. }, errorText)
  2784. } else if errors.Is(err, whatsmeow.ErrNoURLPresent) {
  2785. portal.log.Debugfln("No URL present error for media message %s, ignoring...", info.ID)
  2786. return nil
  2787. } else if errors.Is(err, whatsmeow.ErrFileLengthMismatch) || errors.Is(err, whatsmeow.ErrInvalidMediaSHA256) {
  2788. portal.log.Warnfln("Mismatching media checksums in %s: %v. Ignoring because WhatsApp seems to ignore them too", info.ID, err)
  2789. } else if err != nil {
  2790. return portal.makeMediaBridgeFailureMessage(info, err, converted, nil, "")
  2791. }
  2792. err = portal.uploadMedia(intent, data, converted.Content)
  2793. if err != nil {
  2794. if errors.Is(err, mautrix.MTooLarge) {
  2795. return portal.makeMediaBridgeFailureMessage(info, errors.New("homeserver rejected too large file"), converted, nil, "")
  2796. } else if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.IsStatus(413) {
  2797. return portal.makeMediaBridgeFailureMessage(info, errors.New("proxy rejected too large file"), converted, nil, "")
  2798. } else {
  2799. return portal.makeMediaBridgeFailureMessage(info, fmt.Errorf("failed to upload media: %w", err), converted, nil, "")
  2800. }
  2801. }
  2802. return converted
  2803. }
  2804. func (portal *Portal) fetchMediaRetryEvent(msg *database.Message) (*FailedMediaMeta, error) {
  2805. errorMeta, ok := portal.mediaErrorCache[msg.JID]
  2806. if ok {
  2807. return errorMeta, nil
  2808. }
  2809. evt, err := portal.MainIntent().GetEvent(portal.MXID, msg.MXID)
  2810. if err != nil {
  2811. return nil, fmt.Errorf("failed to fetch event %s: %w", msg.MXID, err)
  2812. }
  2813. if evt.Type == event.EventEncrypted {
  2814. err = evt.Content.ParseRaw(evt.Type)
  2815. if err != nil {
  2816. return nil, fmt.Errorf("failed to parse encrypted content in %s: %w", msg.MXID, err)
  2817. }
  2818. evt, err = portal.bridge.Crypto.Decrypt(evt)
  2819. if err != nil {
  2820. return nil, fmt.Errorf("failed to decrypt event %s: %w", msg.MXID, err)
  2821. }
  2822. }
  2823. errorMetaResult := gjson.GetBytes(evt.Content.VeryRaw, strings.ReplaceAll(failedMediaField, ".", "\\."))
  2824. if !errorMetaResult.Exists() || !errorMetaResult.IsObject() {
  2825. return nil, fmt.Errorf("didn't find failed media metadata in %s", msg.MXID)
  2826. }
  2827. var errorMetaBytes []byte
  2828. if errorMetaResult.Index > 0 {
  2829. errorMetaBytes = evt.Content.VeryRaw[errorMetaResult.Index : errorMetaResult.Index+len(errorMetaResult.Raw)]
  2830. } else {
  2831. errorMetaBytes = []byte(errorMetaResult.Raw)
  2832. }
  2833. err = json.Unmarshal(errorMetaBytes, &errorMeta)
  2834. if err != nil {
  2835. return nil, fmt.Errorf("failed to unmarshal failed media metadata in %s: %w", msg.MXID, err)
  2836. }
  2837. return errorMeta, nil
  2838. }
  2839. func (portal *Portal) sendMediaRetryFailureEdit(intent *appservice.IntentAPI, msg *database.Message, err error) {
  2840. content := event.MessageEventContent{
  2841. MsgType: event.MsgNotice,
  2842. Body: fmt.Sprintf("Failed to bridge media after re-requesting it from your phone: %v", err),
  2843. }
  2844. contentCopy := content
  2845. content.NewContent = &contentCopy
  2846. content.RelatesTo = &event.RelatesTo{
  2847. EventID: msg.MXID,
  2848. Type: event.RelReplace,
  2849. }
  2850. resp, sendErr := portal.sendMessage(intent, event.EventMessage, &content, nil, time.Now().UnixMilli())
  2851. if sendErr != nil {
  2852. portal.log.Warnfln("Failed to edit %s after retry failure for %s: %v", msg.MXID, msg.JID, sendErr)
  2853. } else {
  2854. portal.log.Debugfln("Successfully edited %s -> %s after retry failure for %s", msg.MXID, resp.EventID, msg.JID)
  2855. }
  2856. }
  2857. func (portal *Portal) handleMediaRetry(retry *events.MediaRetry, source *User) {
  2858. msg := portal.bridge.DB.Message.GetByJID(portal.Key, retry.MessageID)
  2859. if msg == nil {
  2860. portal.log.Warnfln("Dropping media retry notification for unknown message %s", retry.MessageID)
  2861. return
  2862. } else if msg.Error != database.MsgErrMediaNotFound {
  2863. portal.log.Warnfln("Dropping media retry notification for non-errored message %s / %s", retry.MessageID, msg.MXID)
  2864. return
  2865. }
  2866. meta, err := portal.fetchMediaRetryEvent(msg)
  2867. if err != nil {
  2868. portal.log.Warnfln("Can't handle media retry notification for %s: %v", retry.MessageID, err)
  2869. return
  2870. }
  2871. var puppet *Puppet
  2872. if retry.FromMe {
  2873. puppet = portal.bridge.GetPuppetByJID(source.JID)
  2874. } else if retry.ChatID.Server == types.DefaultUserServer {
  2875. puppet = portal.bridge.GetPuppetByJID(retry.ChatID)
  2876. } else {
  2877. puppet = portal.bridge.GetPuppetByJID(retry.SenderID)
  2878. }
  2879. intent := puppet.IntentFor(portal)
  2880. retryData, err := whatsmeow.DecryptMediaRetryNotification(retry, meta.Media.Key)
  2881. if err != nil {
  2882. portal.log.Warnfln("Failed to handle media retry notification for %s: %v", retry.MessageID, err)
  2883. portal.sendMediaRetryFailureEdit(intent, msg, err)
  2884. return
  2885. } else if retryData.GetResult() != waProto.MediaRetryNotification_SUCCESS {
  2886. errorName := waProto.MediaRetryNotification_ResultType_name[int32(retryData.GetResult())]
  2887. if retryData.GetDirectPath() == "" {
  2888. portal.log.Warnfln("Got error response in media retry notification for %s: %s", retry.MessageID, errorName)
  2889. portal.log.Debugfln("Error response contents: %+v", retryData)
  2890. if retryData.GetResult() == waProto.MediaRetryNotification_NOT_FOUND {
  2891. portal.sendMediaRetryFailureEdit(intent, msg, whatsmeow.ErrMediaNotAvailableOnPhone)
  2892. } else {
  2893. portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("phone sent error response: %s", errorName))
  2894. }
  2895. return
  2896. } else {
  2897. 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)
  2898. }
  2899. }
  2900. data, err := source.Client.DownloadMediaWithPath(retryData.GetDirectPath(), meta.Media.EncSHA256, meta.Media.SHA256, meta.Media.Key, meta.Media.Length, meta.Media.Type, "")
  2901. if err != nil {
  2902. portal.log.Warnfln("Failed to download media in %s after retry notification: %v", retry.MessageID, err)
  2903. portal.sendMediaRetryFailureEdit(intent, msg, err)
  2904. return
  2905. }
  2906. err = portal.uploadMedia(intent, data, meta.Content)
  2907. if err != nil {
  2908. portal.log.Warnfln("Failed to re-upload media for %s after retry notification: %v", retry.MessageID, err)
  2909. portal.sendMediaRetryFailureEdit(intent, msg, fmt.Errorf("re-uploading media failed: %v", err))
  2910. return
  2911. }
  2912. replaceContent := &event.MessageEventContent{
  2913. MsgType: meta.Content.MsgType,
  2914. Body: "* " + meta.Content.Body,
  2915. NewContent: meta.Content,
  2916. RelatesTo: &event.RelatesTo{
  2917. EventID: msg.MXID,
  2918. Type: event.RelReplace,
  2919. },
  2920. }
  2921. // Move the extra content into m.new_content too
  2922. meta.ExtraContent = map[string]interface{}{
  2923. "m.new_content": shallowCopyMap(meta.ExtraContent),
  2924. }
  2925. resp, err := portal.sendMessage(intent, meta.Type, replaceContent, meta.ExtraContent, time.Now().UnixMilli())
  2926. if err != nil {
  2927. portal.log.Warnfln("Failed to edit %s after retry notification for %s: %v", msg.MXID, retry.MessageID, err)
  2928. return
  2929. }
  2930. portal.log.Debugfln("Successfully edited %s -> %s after retry notification for %s", msg.MXID, resp.EventID, retry.MessageID)
  2931. msg.UpdateMXID(nil, resp.EventID, database.MsgNormal, database.MsgNoError)
  2932. }
  2933. func (portal *Portal) requestMediaRetry(user *User, eventID id.EventID, mediaKey []byte) (bool, error) {
  2934. msg := portal.bridge.DB.Message.GetByMXID(eventID)
  2935. if msg == nil {
  2936. err := errors.New(fmt.Sprintf("%s requested a media retry for unknown event %s", user.MXID, eventID))
  2937. portal.log.Debugfln(err.Error())
  2938. return false, err
  2939. } else if msg.Error != database.MsgErrMediaNotFound {
  2940. err := errors.New(fmt.Sprintf("%s requested a media retry for non-errored event %s", user.MXID, eventID))
  2941. portal.log.Debugfln(err.Error())
  2942. return false, err
  2943. }
  2944. // If the media key is not provided, grab it from the event in Matrix
  2945. if mediaKey == nil {
  2946. evt, err := portal.fetchMediaRetryEvent(msg)
  2947. if err != nil {
  2948. portal.log.Warnfln("Can't send media retry request for %s: %v", msg.JID, err)
  2949. return true, nil
  2950. }
  2951. mediaKey = evt.Media.Key
  2952. }
  2953. err := user.Client.SendMediaRetryReceipt(&types.MessageInfo{
  2954. ID: msg.JID,
  2955. MessageSource: types.MessageSource{
  2956. IsFromMe: msg.Sender.User == user.JID.User,
  2957. IsGroup: !portal.IsPrivateChat(),
  2958. Sender: msg.Sender,
  2959. Chat: portal.Key.JID,
  2960. },
  2961. }, mediaKey)
  2962. if err != nil {
  2963. portal.log.Warnfln("Failed to send media retry request for %s: %v", msg.JID, err)
  2964. } else {
  2965. portal.log.Debugfln("Sent media retry request for %s", msg.JID)
  2966. }
  2967. return true, err
  2968. }
  2969. const thumbnailMaxSize = 72
  2970. const thumbnailMinSize = 24
  2971. func createThumbnailAndGetSize(source []byte, pngThumbnail bool) ([]byte, int, int, error) {
  2972. src, _, err := image.Decode(bytes.NewReader(source))
  2973. if err != nil {
  2974. return nil, 0, 0, fmt.Errorf("failed to decode thumbnail: %w", err)
  2975. }
  2976. imageBounds := src.Bounds()
  2977. width, height := imageBounds.Max.X, imageBounds.Max.Y
  2978. var img image.Image
  2979. if width <= thumbnailMaxSize && height <= thumbnailMaxSize {
  2980. // No need to resize
  2981. img = src
  2982. } else {
  2983. if width == height {
  2984. width = thumbnailMaxSize
  2985. height = thumbnailMaxSize
  2986. } else if width < height {
  2987. width /= height / thumbnailMaxSize
  2988. height = thumbnailMaxSize
  2989. } else {
  2990. height /= width / thumbnailMaxSize
  2991. width = thumbnailMaxSize
  2992. }
  2993. if width < thumbnailMinSize {
  2994. width = thumbnailMinSize
  2995. }
  2996. if height < thumbnailMinSize {
  2997. height = thumbnailMinSize
  2998. }
  2999. dst := image.NewRGBA(image.Rect(0, 0, width, height))
  3000. draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  3001. img = dst
  3002. }
  3003. var buf bytes.Buffer
  3004. if pngThumbnail {
  3005. err = png.Encode(&buf, img)
  3006. } else {
  3007. err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpeg.DefaultQuality})
  3008. }
  3009. if err != nil {
  3010. return nil, width, height, fmt.Errorf("failed to re-encode thumbnail: %w", err)
  3011. }
  3012. return buf.Bytes(), width, height, nil
  3013. }
  3014. func createThumbnail(source []byte, png bool) ([]byte, error) {
  3015. data, _, _, err := createThumbnailAndGetSize(source, png)
  3016. return data, err
  3017. }
  3018. func (portal *Portal) downloadThumbnail(ctx context.Context, original []byte, thumbnailURL id.ContentURIString, eventID id.EventID, png bool) ([]byte, error) {
  3019. if len(thumbnailURL) == 0 {
  3020. // just fall back to making thumbnail of original
  3021. } else if mxc, err := thumbnailURL.Parse(); err != nil {
  3022. portal.log.Warnfln("Malformed thumbnail URL in %s: %v (falling back to generating thumbnail from source)", eventID, err)
  3023. } else if thumbnail, err := portal.MainIntent().DownloadBytesContext(ctx, mxc); err != nil {
  3024. portal.log.Warnfln("Failed to download thumbnail in %s: %v (falling back to generating thumbnail from source)", eventID, err)
  3025. } else {
  3026. return createThumbnail(thumbnail, png)
  3027. }
  3028. return createThumbnail(original, png)
  3029. }
  3030. func (portal *Portal) convertWebPtoPNG(webpImage []byte) ([]byte, error) {
  3031. webpDecoded, err := webp.Decode(bytes.NewReader(webpImage))
  3032. if err != nil {
  3033. return nil, fmt.Errorf("failed to decode webp image: %w", err)
  3034. }
  3035. var pngBuffer bytes.Buffer
  3036. if err = png.Encode(&pngBuffer, webpDecoded); err != nil {
  3037. return nil, fmt.Errorf("failed to encode png image: %w", err)
  3038. }
  3039. return pngBuffer.Bytes(), nil
  3040. }
  3041. type PaddedImage struct {
  3042. image.Image
  3043. Size int
  3044. OffsetX int
  3045. OffsetY int
  3046. }
  3047. func (img *PaddedImage) Bounds() image.Rectangle {
  3048. return image.Rect(0, 0, img.Size, img.Size)
  3049. }
  3050. func (img *PaddedImage) At(x, y int) color.Color {
  3051. return img.Image.At(x+img.OffsetX, y+img.OffsetY)
  3052. }
  3053. func (portal *Portal) convertToWebP(img []byte) ([]byte, error) {
  3054. decodedImg, _, err := image.Decode(bytes.NewReader(img))
  3055. if err != nil {
  3056. return img, fmt.Errorf("failed to decode image: %w", err)
  3057. }
  3058. bounds := decodedImg.Bounds()
  3059. width, height := bounds.Dx(), bounds.Dy()
  3060. if width != height {
  3061. paddedImg := &PaddedImage{
  3062. Image: decodedImg,
  3063. OffsetX: bounds.Min.Y,
  3064. OffsetY: bounds.Min.X,
  3065. }
  3066. if width > height {
  3067. paddedImg.Size = width
  3068. paddedImg.OffsetY -= (paddedImg.Size - height) / 2
  3069. } else {
  3070. paddedImg.Size = height
  3071. paddedImg.OffsetX -= (paddedImg.Size - width) / 2
  3072. }
  3073. decodedImg = paddedImg
  3074. }
  3075. var webpBuffer bytes.Buffer
  3076. if err = webp.Encode(&webpBuffer, decodedImg, nil); err != nil {
  3077. return img, fmt.Errorf("failed to encode webp image: %w", err)
  3078. }
  3079. return webpBuffer.Bytes(), nil
  3080. }
  3081. func (portal *Portal) preprocessMatrixMedia(ctx context.Context, sender *User, relaybotFormatted bool, content *event.MessageEventContent, eventID id.EventID, mediaType whatsmeow.MediaType) (*MediaUpload, error) {
  3082. fileName := content.Body
  3083. var caption string
  3084. var mentionedJIDs []string
  3085. var hasHTMLCaption bool
  3086. isSticker := string(content.MsgType) == event.EventSticker.Type
  3087. if content.FileName != "" && content.Body != content.FileName {
  3088. fileName = content.FileName
  3089. caption = content.Body
  3090. hasHTMLCaption = content.Format == event.FormatHTML
  3091. }
  3092. if relaybotFormatted || hasHTMLCaption {
  3093. caption, mentionedJIDs = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
  3094. }
  3095. var file *event.EncryptedFileInfo
  3096. rawMXC := content.URL
  3097. if content.File != nil {
  3098. file = content.File
  3099. rawMXC = file.URL
  3100. }
  3101. mxc, err := rawMXC.Parse()
  3102. if err != nil {
  3103. return nil, err
  3104. }
  3105. data, err := portal.MainIntent().DownloadBytesContext(ctx, mxc)
  3106. if err != nil {
  3107. return nil, util.NewDualError(errMediaDownloadFailed, err)
  3108. }
  3109. if file != nil {
  3110. err = file.DecryptInPlace(data)
  3111. if err != nil {
  3112. return nil, util.NewDualError(errMediaDecryptFailed, err)
  3113. }
  3114. }
  3115. mimeType := content.GetInfo().MimeType
  3116. var convertErr error
  3117. // Allowed mime types from https://developers.facebook.com/docs/whatsapp/on-premises/reference/media
  3118. switch {
  3119. case isSticker:
  3120. if mimeType != "image/webp" || content.Info.Width != content.Info.Height {
  3121. data, convertErr = portal.convertToWebP(data)
  3122. content.Info.MimeType = "image/webp"
  3123. }
  3124. case mediaType == whatsmeow.MediaVideo:
  3125. switch mimeType {
  3126. case "video/mp4", "video/3gpp":
  3127. // Allowed
  3128. case "image/gif":
  3129. data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "gif"}, []string{
  3130. "-pix_fmt", "yuv420p", "-c:v", "libx264", "-movflags", "+faststart",
  3131. "-filter:v", "crop='floor(in_w/2)*2:floor(in_h/2)*2'",
  3132. }, mimeType)
  3133. content.Info.MimeType = "video/mp4"
  3134. case "video/webm":
  3135. data, convertErr = ffmpeg.ConvertBytes(ctx, data, ".mp4", []string{"-f", "webm"}, []string{
  3136. "-pix_fmt", "yuv420p", "-c:v", "libx264",
  3137. }, mimeType)
  3138. content.Info.MimeType = "video/mp4"
  3139. default:
  3140. return nil, fmt.Errorf("%w %q in video message", errMediaUnsupportedType, mimeType)
  3141. }
  3142. case mediaType == whatsmeow.MediaImage:
  3143. switch mimeType {
  3144. case "image/jpeg", "image/png":
  3145. // Allowed
  3146. case "image/webp":
  3147. data, convertErr = portal.convertWebPtoPNG(data)
  3148. content.Info.MimeType = "image/png"
  3149. default:
  3150. return nil, fmt.Errorf("%w %q in image message", errMediaUnsupportedType, mimeType)
  3151. }
  3152. case mediaType == whatsmeow.MediaAudio:
  3153. switch mimeType {
  3154. case "audio/aac", "audio/mp4", "audio/amr", "audio/mpeg", "audio/ogg; codecs=opus":
  3155. // Allowed
  3156. case "audio/ogg":
  3157. // Hopefully it's opus already
  3158. content.Info.MimeType = "audio/ogg; codecs=opus"
  3159. default:
  3160. return nil, fmt.Errorf("%w %q in audio message", errMediaUnsupportedType, mimeType)
  3161. }
  3162. case mediaType == whatsmeow.MediaDocument:
  3163. // Everything is allowed
  3164. }
  3165. if convertErr != nil {
  3166. if content.Info.MimeType != mimeType || data == nil {
  3167. return nil, util.NewDualError(fmt.Errorf("%w (%s to %s)", errMediaConvertFailed, mimeType, content.Info.MimeType), convertErr)
  3168. } else {
  3169. // If the mime type didn't change and the errored conversion function returned the original data, just log a warning and continue
  3170. portal.log.Warnfln("Failed to re-encode %s media: %v, continuing with original file", mimeType, convertErr)
  3171. }
  3172. }
  3173. uploadResp, err := sender.Client.Upload(ctx, data, mediaType)
  3174. if err != nil {
  3175. return nil, util.NewDualError(errMediaWhatsAppUploadFailed, err)
  3176. }
  3177. // Audio doesn't have thumbnails
  3178. var thumbnail []byte
  3179. if mediaType != whatsmeow.MediaAudio {
  3180. thumbnail, err = portal.downloadThumbnail(ctx, data, content.GetInfo().ThumbnailURL, eventID, isSticker)
  3181. // Ignore format errors for non-image files, we don't care about those thumbnails
  3182. if err != nil && (!errors.Is(err, image.ErrFormat) || mediaType == whatsmeow.MediaImage) {
  3183. portal.log.Warnfln("Failed to generate thumbnail for %s: %v", eventID, err)
  3184. }
  3185. }
  3186. return &MediaUpload{
  3187. UploadResponse: uploadResp,
  3188. FileName: fileName,
  3189. Caption: caption,
  3190. MentionedJIDs: mentionedJIDs,
  3191. Thumbnail: thumbnail,
  3192. FileLength: len(data),
  3193. }, nil
  3194. }
  3195. type MediaUpload struct {
  3196. whatsmeow.UploadResponse
  3197. Caption string
  3198. FileName string
  3199. MentionedJIDs []string
  3200. Thumbnail []byte
  3201. FileLength int
  3202. }
  3203. func (portal *Portal) addRelaybotFormat(sender *User, content *event.MessageEventContent) bool {
  3204. member := portal.MainIntent().Member(portal.MXID, sender.MXID)
  3205. if member == nil {
  3206. member = &event.MemberEventContent{}
  3207. }
  3208. content.EnsureHasHTML()
  3209. data, err := portal.bridge.Config.Bridge.Relay.FormatMessage(content, sender.MXID, *member)
  3210. if err != nil {
  3211. portal.log.Errorln("Failed to apply relaybot format:", err)
  3212. }
  3213. content.FormattedBody = data
  3214. return true
  3215. }
  3216. func addCodecToMime(mimeType, codec string) string {
  3217. mediaType, params, err := mime.ParseMediaType(mimeType)
  3218. if err != nil {
  3219. return mimeType
  3220. }
  3221. if _, ok := params["codecs"]; !ok {
  3222. params["codecs"] = codec
  3223. }
  3224. return mime.FormatMediaType(mediaType, params)
  3225. }
  3226. func parseGeoURI(uri string) (lat, long float64, err error) {
  3227. if !strings.HasPrefix(uri, "geo:") {
  3228. err = fmt.Errorf("uri doesn't have geo: prefix")
  3229. return
  3230. }
  3231. // Remove geo: prefix and anything after ;
  3232. coordinates := strings.Split(strings.TrimPrefix(uri, "geo:"), ";")[0]
  3233. if splitCoordinates := strings.Split(coordinates, ","); len(splitCoordinates) != 2 {
  3234. err = fmt.Errorf("didn't find exactly two numbers separated by a comma")
  3235. } else if lat, err = strconv.ParseFloat(splitCoordinates[0], 64); err != nil {
  3236. err = fmt.Errorf("latitude is not a number: %w", err)
  3237. } else if long, err = strconv.ParseFloat(splitCoordinates[1], 64); err != nil {
  3238. err = fmt.Errorf("longitude is not a number: %w", err)
  3239. }
  3240. return
  3241. }
  3242. func getUnstableWaveform(content map[string]interface{}) []byte {
  3243. audioInfo, ok := content["org.matrix.msc1767.audio"].(map[string]interface{})
  3244. if !ok {
  3245. return nil
  3246. }
  3247. waveform, ok := audioInfo["waveform"].([]interface{})
  3248. if !ok {
  3249. return nil
  3250. }
  3251. output := make([]byte, len(waveform))
  3252. var val float64
  3253. for i, part := range waveform {
  3254. val, ok = part.(float64)
  3255. if ok {
  3256. output[i] = byte(val / 4)
  3257. }
  3258. }
  3259. return output
  3260. }
  3261. var (
  3262. TypeMSC3381PollStart = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.poll.start"}
  3263. TypeMSC3381PollResponse = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.poll.response"}
  3264. TypeMSC3381V2PollResponse = event.Type{Class: event.MessageEventType, Type: "org.matrix.msc3381.v2.poll.response"}
  3265. )
  3266. type PollResponseContent struct {
  3267. RelatesTo event.RelatesTo `json:"m.relates_to"`
  3268. V1Response struct {
  3269. Answers []string `json:"answers"`
  3270. } `json:"org.matrix.msc3381.poll.response"`
  3271. V2Selections []string `json:"org.matrix.msc3381.v2.selections"`
  3272. }
  3273. func (content *PollResponseContent) GetRelatesTo() *event.RelatesTo {
  3274. return &content.RelatesTo
  3275. }
  3276. func (content *PollResponseContent) OptionalGetRelatesTo() *event.RelatesTo {
  3277. if content.RelatesTo.Type == "" {
  3278. return nil
  3279. }
  3280. return &content.RelatesTo
  3281. }
  3282. func (content *PollResponseContent) SetRelatesTo(rel *event.RelatesTo) {
  3283. content.RelatesTo = *rel
  3284. }
  3285. type MSC1767Message struct {
  3286. Text string `json:"org.matrix.msc1767.text,omitempty"`
  3287. HTML string `json:"org.matrix.msc1767.html,omitempty"`
  3288. Message []struct {
  3289. MimeType string `json:"mimetype"`
  3290. Body string `json:"body"`
  3291. } `json:"org.matrix.msc1767.message,omitempty"`
  3292. }
  3293. func (portal *Portal) msc1767ToWhatsApp(msg MSC1767Message, mentions bool) (string, []string) {
  3294. for _, part := range msg.Message {
  3295. if part.MimeType == "text/html" && msg.HTML == "" {
  3296. msg.HTML = part.Body
  3297. } else if part.MimeType == "text/plain" && msg.Text == "" {
  3298. msg.Text = part.Body
  3299. }
  3300. }
  3301. if msg.HTML != "" {
  3302. if mentions {
  3303. return portal.bridge.Formatter.ParseMatrix(msg.HTML)
  3304. } else {
  3305. return portal.bridge.Formatter.ParseMatrixWithoutMentions(msg.HTML), nil
  3306. }
  3307. }
  3308. return msg.Text, nil
  3309. }
  3310. type PollStartContent struct {
  3311. RelatesTo *event.RelatesTo `json:"m.relates_to"`
  3312. PollStart struct {
  3313. Kind string `json:"kind"`
  3314. MaxSelections int `json:"max_selections"`
  3315. Question MSC1767Message `json:"question"`
  3316. Answers []struct {
  3317. ID string `json:"id"`
  3318. MSC1767Message
  3319. } `json:"answers"`
  3320. } `json:"org.matrix.msc3381.poll.start"`
  3321. }
  3322. func (content *PollStartContent) GetRelatesTo() *event.RelatesTo {
  3323. if content.RelatesTo == nil {
  3324. content.RelatesTo = &event.RelatesTo{}
  3325. }
  3326. return content.RelatesTo
  3327. }
  3328. func (content *PollStartContent) OptionalGetRelatesTo() *event.RelatesTo {
  3329. return content.RelatesTo
  3330. }
  3331. func (content *PollStartContent) SetRelatesTo(rel *event.RelatesTo) {
  3332. content.RelatesTo = rel
  3333. }
  3334. func init() {
  3335. event.TypeMap[TypeMSC3381PollResponse] = reflect.TypeOf(PollResponseContent{})
  3336. event.TypeMap[TypeMSC3381V2PollResponse] = reflect.TypeOf(PollResponseContent{})
  3337. event.TypeMap[TypeMSC3381PollStart] = reflect.TypeOf(PollStartContent{})
  3338. }
  3339. func (portal *Portal) convertMatrixPollVote(_ context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, *extraConvertMeta, error) {
  3340. content, ok := evt.Content.Parsed.(*PollResponseContent)
  3341. if !ok {
  3342. return nil, sender, nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3343. }
  3344. var answers []string
  3345. if content.V1Response.Answers != nil {
  3346. answers = content.V1Response.Answers
  3347. } else if content.V2Selections != nil {
  3348. answers = content.V2Selections
  3349. }
  3350. pollMsg := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
  3351. if pollMsg == nil {
  3352. return nil, sender, nil, errTargetNotFound
  3353. }
  3354. pollMsgInfo := &types.MessageInfo{
  3355. MessageSource: types.MessageSource{
  3356. Chat: portal.Key.JID,
  3357. Sender: pollMsg.Sender,
  3358. IsFromMe: pollMsg.Sender.User == sender.JID.User,
  3359. IsGroup: portal.IsGroupChat(),
  3360. },
  3361. ID: pollMsg.JID,
  3362. Type: "poll",
  3363. }
  3364. optionHashes := make([][]byte, 0, len(answers))
  3365. if pollMsg.Type == database.MsgMatrixPoll {
  3366. mappedAnswers := pollMsg.GetPollOptionHashes(answers)
  3367. for _, selection := range answers {
  3368. hash, ok := mappedAnswers[selection]
  3369. if ok {
  3370. optionHashes = append(optionHashes, hash[:])
  3371. } else {
  3372. portal.log.Warnfln("Didn't find hash for option %s in %s's vote to %s", selection, evt.Sender, pollMsg.MXID)
  3373. }
  3374. }
  3375. } else {
  3376. for _, selection := range answers {
  3377. hash, _ := hex.DecodeString(selection)
  3378. if hash != nil && len(hash) == 32 {
  3379. optionHashes = append(optionHashes, hash)
  3380. }
  3381. }
  3382. }
  3383. pollUpdate, err := sender.Client.EncryptPollVote(pollMsgInfo, &waProto.PollVoteMessage{
  3384. SelectedOptions: optionHashes,
  3385. })
  3386. return &waProto.Message{PollUpdateMessage: pollUpdate}, sender, nil, err
  3387. }
  3388. func (portal *Portal) convertMatrixPollStart(_ context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, *extraConvertMeta, error) {
  3389. content, ok := evt.Content.Parsed.(*PollStartContent)
  3390. if !ok {
  3391. return nil, sender, nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3392. }
  3393. maxAnswers := content.PollStart.MaxSelections
  3394. if maxAnswers >= len(content.PollStart.Answers) || maxAnswers < 0 {
  3395. maxAnswers = 0
  3396. }
  3397. fmt.Printf("%+v\n", content.PollStart)
  3398. ctxInfo := portal.generateContextInfo(content.RelatesTo)
  3399. var question string
  3400. question, ctxInfo.MentionedJid = portal.msc1767ToWhatsApp(content.PollStart.Question, true)
  3401. if len(question) == 0 {
  3402. return nil, sender, nil, errPollMissingQuestion
  3403. }
  3404. options := make([]*waProto.PollCreationMessage_Option, len(content.PollStart.Answers))
  3405. optionMap := make(map[[32]byte]string, len(options))
  3406. for i, opt := range content.PollStart.Answers {
  3407. body, _ := portal.msc1767ToWhatsApp(opt.MSC1767Message, false)
  3408. hash := sha256.Sum256([]byte(body))
  3409. if _, alreadyExists := optionMap[hash]; alreadyExists {
  3410. portal.log.Warnfln("Poll %s by %s has option %q more than once, rejecting", evt.ID, evt.Sender, body)
  3411. return nil, sender, nil, errPollDuplicateOption
  3412. }
  3413. optionMap[hash] = opt.ID
  3414. options[i] = &waProto.PollCreationMessage_Option{
  3415. OptionName: proto.String(body),
  3416. }
  3417. }
  3418. secret := make([]byte, 32)
  3419. _, err := rand.Read(secret)
  3420. return &waProto.Message{
  3421. PollCreationMessage: &waProto.PollCreationMessage{
  3422. Name: proto.String(question),
  3423. Options: options,
  3424. SelectableOptionsCount: proto.Uint32(uint32(maxAnswers)),
  3425. ContextInfo: ctxInfo,
  3426. },
  3427. MessageContextInfo: &waProto.MessageContextInfo{
  3428. MessageSecret: secret,
  3429. },
  3430. }, sender, &extraConvertMeta{PollOptions: optionMap}, err
  3431. }
  3432. func (portal *Portal) generateContextInfo(relatesTo *event.RelatesTo) *waProto.ContextInfo {
  3433. var ctxInfo waProto.ContextInfo
  3434. replyToID := relatesTo.GetReplyTo()
  3435. if len(replyToID) > 0 {
  3436. replyToMsg := portal.bridge.DB.Message.GetByMXID(replyToID)
  3437. if replyToMsg != nil && !replyToMsg.IsFakeJID() && (replyToMsg.Type == database.MsgNormal || replyToMsg.Type == database.MsgMatrixPoll) {
  3438. ctxInfo.StanzaId = &replyToMsg.JID
  3439. ctxInfo.Participant = proto.String(replyToMsg.Sender.ToNonAD().String())
  3440. // Using blank content here seems to work fine on all official WhatsApp apps.
  3441. //
  3442. // We could probably invent a slightly more accurate version of the quoted message
  3443. // by fetching the Matrix event and converting it to the WhatsApp format, but that's
  3444. // a lot of work and this works fine.
  3445. ctxInfo.QuotedMessage = &waProto.Message{Conversation: proto.String("")}
  3446. }
  3447. }
  3448. if portal.ExpirationTime != 0 {
  3449. ctxInfo.Expiration = proto.Uint32(portal.ExpirationTime)
  3450. }
  3451. return &ctxInfo
  3452. }
  3453. type extraConvertMeta struct {
  3454. PollOptions map[[32]byte]string
  3455. EditRootMsg *database.Message
  3456. }
  3457. func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, evt *event.Event) (*waProto.Message, *User, *extraConvertMeta, error) {
  3458. if evt.Type == TypeMSC3381PollResponse || evt.Type == TypeMSC3381V2PollResponse {
  3459. return portal.convertMatrixPollVote(ctx, sender, evt)
  3460. } else if evt.Type == TypeMSC3381PollStart {
  3461. return portal.convertMatrixPollStart(ctx, sender, evt)
  3462. }
  3463. content, ok := evt.Content.Parsed.(*event.MessageEventContent)
  3464. if !ok {
  3465. return nil, sender, nil, fmt.Errorf("%w %T", errUnexpectedParsedContentType, evt.Content.Parsed)
  3466. }
  3467. extraMeta := &extraConvertMeta{}
  3468. var editRootMsg *database.Message
  3469. if editEventID := content.RelatesTo.GetReplaceID(); editEventID != "" && portal.bridge.Config.Bridge.SendWhatsAppEdits {
  3470. editRootMsg = portal.bridge.DB.Message.GetByMXID(editEventID)
  3471. if editRootMsg == nil || editRootMsg.Type != database.MsgNormal || editRootMsg.IsFakeJID() || editRootMsg.Sender.User != sender.JID.User {
  3472. return nil, sender, extraMeta, fmt.Errorf("edit rejected") // TODO more specific error message
  3473. }
  3474. extraMeta.EditRootMsg = editRootMsg
  3475. if content.NewContent != nil {
  3476. content = content.NewContent
  3477. }
  3478. }
  3479. msg := &waProto.Message{}
  3480. ctxInfo := portal.generateContextInfo(content.RelatesTo)
  3481. relaybotFormatted := false
  3482. if !sender.IsLoggedIn() || (portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User) {
  3483. if !portal.HasRelaybot() {
  3484. return nil, sender, extraMeta, errUserNotLoggedIn
  3485. }
  3486. relaybotFormatted = portal.addRelaybotFormat(sender, content)
  3487. sender = portal.GetRelayUser()
  3488. }
  3489. if evt.Type == event.EventSticker {
  3490. if relaybotFormatted {
  3491. // Stickers can't have captions, so force relaybot stickers to be images
  3492. content.MsgType = event.MsgImage
  3493. } else {
  3494. content.MsgType = event.MessageType(event.EventSticker.Type)
  3495. }
  3496. }
  3497. if content.MsgType == event.MsgImage && content.GetInfo().MimeType == "image/gif" {
  3498. content.MsgType = event.MsgVideo
  3499. }
  3500. switch content.MsgType {
  3501. case event.MsgText, event.MsgEmote, event.MsgNotice:
  3502. text := content.Body
  3503. if content.MsgType == event.MsgNotice && !portal.bridge.Config.Bridge.BridgeNotices {
  3504. return nil, sender, extraMeta, errMNoticeDisabled
  3505. }
  3506. if content.Format == event.FormatHTML {
  3507. text, ctxInfo.MentionedJid = portal.bridge.Formatter.ParseMatrix(content.FormattedBody)
  3508. }
  3509. if content.MsgType == event.MsgEmote && !relaybotFormatted {
  3510. text = "/me " + text
  3511. }
  3512. msg.ExtendedTextMessage = &waProto.ExtendedTextMessage{
  3513. Text: &text,
  3514. ContextInfo: ctxInfo,
  3515. }
  3516. hasPreview := portal.convertURLPreviewToWhatsApp(ctx, sender, evt, msg.ExtendedTextMessage)
  3517. if ctx.Err() != nil {
  3518. return nil, sender, extraMeta, ctx.Err()
  3519. }
  3520. if ctxInfo.StanzaId == nil && ctxInfo.MentionedJid == nil && ctxInfo.Expiration == nil && !hasPreview {
  3521. // No need for extended message
  3522. msg.ExtendedTextMessage = nil
  3523. msg.Conversation = &text
  3524. }
  3525. case event.MsgImage:
  3526. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
  3527. if media == nil {
  3528. return nil, sender, extraMeta, err
  3529. }
  3530. ctxInfo.MentionedJid = media.MentionedJIDs
  3531. msg.ImageMessage = &waProto.ImageMessage{
  3532. ContextInfo: ctxInfo,
  3533. Caption: &media.Caption,
  3534. JpegThumbnail: media.Thumbnail,
  3535. Url: &media.URL,
  3536. DirectPath: &media.DirectPath,
  3537. MediaKey: media.MediaKey,
  3538. Mimetype: &content.GetInfo().MimeType,
  3539. FileEncSha256: media.FileEncSHA256,
  3540. FileSha256: media.FileSHA256,
  3541. FileLength: proto.Uint64(uint64(media.FileLength)),
  3542. }
  3543. case event.MessageType(event.EventSticker.Type):
  3544. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaImage)
  3545. if media == nil {
  3546. return nil, sender, extraMeta, err
  3547. }
  3548. ctxInfo.MentionedJid = media.MentionedJIDs
  3549. msg.StickerMessage = &waProto.StickerMessage{
  3550. ContextInfo: ctxInfo,
  3551. PngThumbnail: media.Thumbnail,
  3552. Url: &media.URL,
  3553. DirectPath: &media.DirectPath,
  3554. MediaKey: media.MediaKey,
  3555. Mimetype: &content.GetInfo().MimeType,
  3556. FileEncSha256: media.FileEncSHA256,
  3557. FileSha256: media.FileSHA256,
  3558. FileLength: proto.Uint64(uint64(media.FileLength)),
  3559. }
  3560. case event.MsgVideo:
  3561. gifPlayback := content.GetInfo().MimeType == "image/gif"
  3562. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaVideo)
  3563. if media == nil {
  3564. return nil, sender, extraMeta, err
  3565. }
  3566. duration := uint32(content.GetInfo().Duration / 1000)
  3567. ctxInfo.MentionedJid = media.MentionedJIDs
  3568. msg.VideoMessage = &waProto.VideoMessage{
  3569. ContextInfo: ctxInfo,
  3570. Caption: &media.Caption,
  3571. JpegThumbnail: media.Thumbnail,
  3572. Url: &media.URL,
  3573. DirectPath: &media.DirectPath,
  3574. MediaKey: media.MediaKey,
  3575. Mimetype: &content.GetInfo().MimeType,
  3576. GifPlayback: &gifPlayback,
  3577. Seconds: &duration,
  3578. FileEncSha256: media.FileEncSHA256,
  3579. FileSha256: media.FileSHA256,
  3580. FileLength: proto.Uint64(uint64(media.FileLength)),
  3581. }
  3582. case event.MsgAudio:
  3583. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaAudio)
  3584. if media == nil {
  3585. return nil, sender, extraMeta, err
  3586. }
  3587. duration := uint32(content.GetInfo().Duration / 1000)
  3588. msg.AudioMessage = &waProto.AudioMessage{
  3589. ContextInfo: ctxInfo,
  3590. Url: &media.URL,
  3591. DirectPath: &media.DirectPath,
  3592. MediaKey: media.MediaKey,
  3593. Mimetype: &content.GetInfo().MimeType,
  3594. Seconds: &duration,
  3595. FileEncSha256: media.FileEncSHA256,
  3596. FileSha256: media.FileSHA256,
  3597. FileLength: proto.Uint64(uint64(media.FileLength)),
  3598. }
  3599. _, isMSC3245Voice := evt.Content.Raw["org.matrix.msc3245.voice"]
  3600. if isMSC3245Voice {
  3601. msg.AudioMessage.Waveform = getUnstableWaveform(evt.Content.Raw)
  3602. msg.AudioMessage.Ptt = proto.Bool(true)
  3603. // hacky hack to add the codecs param that whatsapp seems to require
  3604. msg.AudioMessage.Mimetype = proto.String(addCodecToMime(content.GetInfo().MimeType, "opus"))
  3605. }
  3606. case event.MsgFile:
  3607. media, err := portal.preprocessMatrixMedia(ctx, sender, relaybotFormatted, content, evt.ID, whatsmeow.MediaDocument)
  3608. if media == nil {
  3609. return nil, sender, extraMeta, err
  3610. }
  3611. msg.DocumentMessage = &waProto.DocumentMessage{
  3612. ContextInfo: ctxInfo,
  3613. Caption: &media.Caption,
  3614. JpegThumbnail: media.Thumbnail,
  3615. Url: &media.URL,
  3616. DirectPath: &media.DirectPath,
  3617. Title: &media.FileName,
  3618. FileName: &media.FileName,
  3619. MediaKey: media.MediaKey,
  3620. Mimetype: &content.GetInfo().MimeType,
  3621. FileEncSha256: media.FileEncSHA256,
  3622. FileSha256: media.FileSHA256,
  3623. FileLength: proto.Uint64(uint64(media.FileLength)),
  3624. }
  3625. if media.Caption != "" {
  3626. msg.DocumentWithCaptionMessage = &waProto.FutureProofMessage{
  3627. Message: &waProto.Message{
  3628. DocumentMessage: msg.DocumentMessage,
  3629. },
  3630. }
  3631. msg.DocumentMessage = nil
  3632. }
  3633. case event.MsgLocation:
  3634. lat, long, err := parseGeoURI(content.GeoURI)
  3635. if err != nil {
  3636. return nil, sender, extraMeta, fmt.Errorf("%w: %v", errInvalidGeoURI, err)
  3637. }
  3638. msg.LocationMessage = &waProto.LocationMessage{
  3639. DegreesLatitude: &lat,
  3640. DegreesLongitude: &long,
  3641. Comment: &content.Body,
  3642. ContextInfo: ctxInfo,
  3643. }
  3644. default:
  3645. return nil, sender, extraMeta, fmt.Errorf("%w %q", errUnknownMsgType, content.MsgType)
  3646. }
  3647. if editRootMsg != nil {
  3648. msg = &waProto.Message{
  3649. EditedMessage: &waProto.FutureProofMessage{
  3650. Message: &waProto.Message{
  3651. ProtocolMessage: &waProto.ProtocolMessage{
  3652. Key: &waProto.MessageKey{
  3653. FromMe: proto.Bool(true),
  3654. Id: proto.String(editRootMsg.JID),
  3655. RemoteJid: proto.String(portal.Key.JID.String()),
  3656. },
  3657. Type: waProto.ProtocolMessage_MESSAGE_EDIT.Enum(),
  3658. EditedMessage: msg,
  3659. TimestampMs: proto.Int64(evt.Timestamp),
  3660. },
  3661. },
  3662. },
  3663. }
  3664. }
  3665. return msg, sender, extraMeta, nil
  3666. }
  3667. func (portal *Portal) generateMessageInfo(sender *User) *types.MessageInfo {
  3668. return &types.MessageInfo{
  3669. ID: whatsmeow.GenerateMessageID(),
  3670. Timestamp: time.Now(),
  3671. MessageSource: types.MessageSource{
  3672. Sender: sender.JID,
  3673. Chat: portal.Key.JID,
  3674. IsFromMe: true,
  3675. IsGroup: portal.Key.JID.Server == types.GroupServer || portal.Key.JID.Server == types.BroadcastServer,
  3676. },
  3677. }
  3678. }
  3679. func (portal *Portal) HandleMatrixMessage(sender *User, evt *event.Event, timings messageTimings) {
  3680. start := time.Now()
  3681. ms := metricSender{portal: portal, timings: &timings}
  3682. allowRelay := evt.Type != TypeMSC3381PollResponse && evt.Type != TypeMSC3381V2PollResponse && evt.Type != TypeMSC3381PollStart
  3683. if err := portal.canBridgeFrom(sender, allowRelay); err != nil {
  3684. go ms.sendMessageMetrics(evt, err, "Ignoring", true)
  3685. return
  3686. } else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
  3687. go ms.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", true)
  3688. return
  3689. }
  3690. messageAge := timings.totalReceive
  3691. origEvtID := evt.ID
  3692. var dbMsg *database.Message
  3693. if retryMeta := evt.Content.AsMessage().MessageSendRetry; retryMeta != nil {
  3694. origEvtID = retryMeta.OriginalEventID
  3695. dbMsg = portal.bridge.DB.Message.GetByMXID(origEvtID)
  3696. if dbMsg != nil && dbMsg.Sent {
  3697. 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)
  3698. go ms.sendMessageMetrics(evt, nil, "", true)
  3699. return
  3700. } else if dbMsg != nil {
  3701. 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)
  3702. } else {
  3703. 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)
  3704. }
  3705. } else {
  3706. portal.log.Debugfln("Received message %s from %s (age: %s)", evt.ID, evt.Sender, messageAge)
  3707. }
  3708. errorAfter := portal.bridge.Config.Bridge.MessageHandlingTimeout.ErrorAfter
  3709. deadline := portal.bridge.Config.Bridge.MessageHandlingTimeout.Deadline
  3710. isScheduled, _ := evt.Content.Raw["com.beeper.scheduled"].(bool)
  3711. if isScheduled {
  3712. portal.log.Debugfln("%s is a scheduled message, extending handling timeouts", evt.ID)
  3713. errorAfter *= 10
  3714. deadline *= 10
  3715. }
  3716. if errorAfter > 0 {
  3717. remainingTime := errorAfter - messageAge
  3718. if remainingTime < 0 {
  3719. go ms.sendMessageMetrics(evt, errTimeoutBeforeHandling, "Timeout handling", true)
  3720. return
  3721. } else if remainingTime < 1*time.Second {
  3722. portal.log.Warnfln("Message %s was delayed before reaching the bridge, only have %s (of %s timeout) until delay warning", evt.ID, remainingTime, errorAfter)
  3723. }
  3724. go func() {
  3725. time.Sleep(remainingTime)
  3726. ms.sendMessageMetrics(evt, errMessageTakingLong, "Timeout handling", false)
  3727. }()
  3728. }
  3729. ctx := context.Background()
  3730. if deadline > 0 {
  3731. var cancel context.CancelFunc
  3732. ctx, cancel = context.WithTimeout(ctx, deadline)
  3733. defer cancel()
  3734. }
  3735. timings.preproc = time.Since(start)
  3736. start = time.Now()
  3737. msg, sender, extraMeta, err := portal.convertMatrixMessage(ctx, sender, evt)
  3738. timings.convert = time.Since(start)
  3739. if msg == nil {
  3740. go ms.sendMessageMetrics(evt, err, "Error converting", true)
  3741. return
  3742. }
  3743. dbMsgType := database.MsgNormal
  3744. if msg.PollCreationMessage != nil || msg.PollCreationMessageV2 != nil {
  3745. dbMsgType = database.MsgMatrixPoll
  3746. } else if msg.EditedMessage == nil {
  3747. portal.MarkDisappearing(nil, origEvtID, time.Duration(portal.ExpirationTime)*time.Second, time.Now())
  3748. } else {
  3749. dbMsgType = database.MsgEdit
  3750. }
  3751. info := portal.generateMessageInfo(sender)
  3752. if dbMsg == nil {
  3753. dbMsg = portal.markHandled(nil, nil, info, evt.ID, false, true, dbMsgType, database.MsgNoError)
  3754. } else {
  3755. info.ID = dbMsg.JID
  3756. }
  3757. if dbMsgType == database.MsgMatrixPoll && extraMeta != nil && extraMeta.PollOptions != nil {
  3758. dbMsg.PutPollOptions(extraMeta.PollOptions)
  3759. }
  3760. portal.log.Debugln("Sending event", evt.ID, "to WhatsApp", info.ID)
  3761. start = time.Now()
  3762. resp, err := sender.Client.SendMessage(ctx, portal.Key.JID, msg, whatsmeow.SendRequestExtra{ID: info.ID})
  3763. timings.totalSend = time.Since(start)
  3764. timings.whatsmeow = resp.DebugTimings
  3765. go ms.sendMessageMetrics(evt, err, "Error sending", true)
  3766. if err == nil {
  3767. dbMsg.MarkSent(resp.Timestamp)
  3768. }
  3769. }
  3770. func (portal *Portal) HandleMatrixReaction(sender *User, evt *event.Event) {
  3771. if err := portal.canBridgeFrom(sender, false); err != nil {
  3772. go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
  3773. return
  3774. } else if portal.Key.JID.Server == types.BroadcastServer {
  3775. // TODO implement this, probably by only sending the reaction to the sender of the status message?
  3776. // (whatsapp hasn't published the feature yet)
  3777. go portal.sendMessageMetrics(evt, errBroadcastReactionNotSupported, "Ignoring", nil)
  3778. return
  3779. }
  3780. content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
  3781. if ok && strings.Contains(content.RelatesTo.Key, "retry") || strings.HasPrefix(content.RelatesTo.Key, "\u267b") { // ♻️
  3782. if retryRequested, _ := portal.requestMediaRetry(sender, content.RelatesTo.EventID, nil); retryRequested {
  3783. _, _ = portal.MainIntent().RedactEvent(portal.MXID, evt.ID, mautrix.ReqRedact{
  3784. Reason: "requested media from phone",
  3785. })
  3786. // Errored media, don't try to send as reaction
  3787. return
  3788. }
  3789. }
  3790. portal.log.Debugfln("Received reaction event %s from %s", evt.ID, evt.Sender)
  3791. err := portal.handleMatrixReaction(sender, evt)
  3792. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  3793. }
  3794. func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) error {
  3795. content, ok := evt.Content.Parsed.(*event.ReactionEventContent)
  3796. if !ok {
  3797. return fmt.Errorf("unexpected parsed content type %T", evt.Content.Parsed)
  3798. }
  3799. target := portal.bridge.DB.Message.GetByMXID(content.RelatesTo.EventID)
  3800. if target == nil || target.Type == database.MsgReaction {
  3801. return fmt.Errorf("unknown target event %s", content.RelatesTo.EventID)
  3802. }
  3803. info := portal.generateMessageInfo(sender)
  3804. dbMsg := portal.markHandled(nil, nil, info, evt.ID, false, true, database.MsgReaction, database.MsgNoError)
  3805. portal.upsertReaction(nil, nil, target.JID, sender.JID, evt.ID, info.ID)
  3806. portal.log.Debugln("Sending reaction", evt.ID, "to WhatsApp", info.ID)
  3807. resp, err := portal.sendReactionToWhatsApp(sender, info.ID, target, content.RelatesTo.Key, evt.Timestamp)
  3808. if err == nil {
  3809. dbMsg.MarkSent(resp.Timestamp)
  3810. }
  3811. return err
  3812. }
  3813. func (portal *Portal) sendReactionToWhatsApp(sender *User, id types.MessageID, target *database.Message, key string, timestamp int64) (whatsmeow.SendResponse, error) {
  3814. var messageKeyParticipant *string
  3815. if !portal.IsPrivateChat() {
  3816. messageKeyParticipant = proto.String(target.Sender.ToNonAD().String())
  3817. }
  3818. key = variationselector.Remove(key)
  3819. return sender.Client.SendMessage(context.TODO(), portal.Key.JID, &waProto.Message{
  3820. ReactionMessage: &waProto.ReactionMessage{
  3821. Key: &waProto.MessageKey{
  3822. RemoteJid: proto.String(portal.Key.JID.String()),
  3823. FromMe: proto.Bool(target.Sender.User == sender.JID.User),
  3824. Id: proto.String(target.JID),
  3825. Participant: messageKeyParticipant,
  3826. },
  3827. Text: proto.String(key),
  3828. SenderTimestampMs: proto.Int64(timestamp),
  3829. },
  3830. }, whatsmeow.SendRequestExtra{ID: id})
  3831. }
  3832. func (portal *Portal) upsertReaction(txn dbutil.Transaction, intent *appservice.IntentAPI, targetJID types.MessageID, senderJID types.JID, mxid id.EventID, jid types.MessageID) {
  3833. dbReaction := portal.bridge.DB.Reaction.GetByTargetJID(portal.Key, targetJID, senderJID)
  3834. if dbReaction == nil {
  3835. dbReaction = portal.bridge.DB.Reaction.New()
  3836. dbReaction.Chat = portal.Key
  3837. dbReaction.TargetJID = targetJID
  3838. dbReaction.Sender = senderJID
  3839. } else if intent != nil {
  3840. portal.log.Debugfln("Redacting old Matrix reaction %s after new one (%s) was sent", dbReaction.MXID, mxid)
  3841. var err error
  3842. if intent != nil {
  3843. _, err = intent.RedactEvent(portal.MXID, dbReaction.MXID)
  3844. }
  3845. if intent == nil || errors.Is(err, mautrix.MForbidden) {
  3846. _, err = portal.MainIntent().RedactEvent(portal.MXID, dbReaction.MXID)
  3847. }
  3848. if err != nil {
  3849. portal.log.Warnfln("Failed to remove old reaction %s: %v", dbReaction.MXID, err)
  3850. }
  3851. }
  3852. dbReaction.MXID = mxid
  3853. dbReaction.JID = jid
  3854. dbReaction.Upsert(txn)
  3855. }
  3856. func (portal *Portal) HandleMatrixRedaction(sender *User, evt *event.Event) {
  3857. if err := portal.canBridgeFrom(sender, true); err != nil {
  3858. go portal.sendMessageMetrics(evt, err, "Ignoring", nil)
  3859. return
  3860. }
  3861. portal.log.Debugfln("Received redaction %s from %s", evt.ID, evt.Sender)
  3862. senderLogIdentifier := sender.MXID
  3863. if !sender.HasSession() {
  3864. sender = portal.GetRelayUser()
  3865. senderLogIdentifier += " (through relaybot)"
  3866. }
  3867. msg := portal.bridge.DB.Message.GetByMXID(evt.Redacts)
  3868. if msg == nil {
  3869. go portal.sendMessageMetrics(evt, errTargetNotFound, "Ignoring", nil)
  3870. } else if msg.IsFakeJID() {
  3871. go portal.sendMessageMetrics(evt, errTargetIsFake, "Ignoring", nil)
  3872. } else if portal.Key.JID == types.StatusBroadcastJID && portal.bridge.Config.Bridge.DisableStatusBroadcastSend {
  3873. go portal.sendMessageMetrics(evt, errBroadcastSendDisabled, "Ignoring", nil)
  3874. } else if msg.Type == database.MsgReaction {
  3875. if msg.Sender.User != sender.JID.User {
  3876. go portal.sendMessageMetrics(evt, errReactionSentBySomeoneElse, "Ignoring", nil)
  3877. } else if reaction := portal.bridge.DB.Reaction.GetByMXID(evt.Redacts); reaction == nil {
  3878. go portal.sendMessageMetrics(evt, errReactionDatabaseNotFound, "Ignoring", nil)
  3879. } else if reactionTarget := reaction.GetTarget(); reactionTarget == nil {
  3880. go portal.sendMessageMetrics(evt, errReactionTargetNotFound, "Ignoring", nil)
  3881. } else {
  3882. portal.log.Debugfln("Sending redaction reaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
  3883. _, err := portal.sendReactionToWhatsApp(sender, "", reactionTarget, "", evt.Timestamp)
  3884. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  3885. }
  3886. } else {
  3887. key := &waProto.MessageKey{
  3888. FromMe: proto.Bool(true),
  3889. Id: proto.String(msg.JID),
  3890. RemoteJid: proto.String(portal.Key.JID.String()),
  3891. }
  3892. if msg.Sender.User != sender.JID.User {
  3893. if portal.IsPrivateChat() {
  3894. go portal.sendMessageMetrics(evt, errDMSentByOtherUser, "Ignoring", nil)
  3895. return
  3896. }
  3897. key.FromMe = proto.Bool(false)
  3898. key.Participant = proto.String(msg.Sender.ToNonAD().String())
  3899. }
  3900. portal.log.Debugfln("Sending redaction %s of %s/%s to WhatsApp", evt.ID, msg.MXID, msg.JID)
  3901. _, err := sender.Client.SendMessage(context.TODO(), portal.Key.JID, &waProto.Message{
  3902. ProtocolMessage: &waProto.ProtocolMessage{
  3903. Type: waProto.ProtocolMessage_REVOKE.Enum(),
  3904. Key: key,
  3905. },
  3906. })
  3907. go portal.sendMessageMetrics(evt, err, "Error sending", nil)
  3908. }
  3909. }
  3910. func (portal *Portal) HandleMatrixReadReceipt(sender bridge.User, eventID id.EventID, receipt event.ReadReceipt) {
  3911. portal.handleMatrixReadReceipt(sender.(*User), eventID, receipt.Timestamp, true)
  3912. }
  3913. func (portal *Portal) handleMatrixReadReceipt(sender *User, eventID id.EventID, receiptTimestamp time.Time, isExplicit bool) {
  3914. if !sender.IsLoggedIn() {
  3915. if isExplicit {
  3916. portal.log.Debugfln("Ignoring read receipt by %s/%s: user is not connected to WhatsApp", sender.MXID, sender.JID)
  3917. }
  3918. return
  3919. }
  3920. maxTimestamp := receiptTimestamp
  3921. // Implicit read receipts don't have an event ID that's already bridged
  3922. if isExplicit {
  3923. if message := portal.bridge.DB.Message.GetByMXID(eventID); message != nil {
  3924. maxTimestamp = message.Timestamp
  3925. }
  3926. }
  3927. prevTimestamp := sender.GetLastReadTS(portal.Key)
  3928. lastReadIsZero := false
  3929. if prevTimestamp.IsZero() {
  3930. prevTimestamp = maxTimestamp.Add(-2 * time.Second)
  3931. lastReadIsZero = true
  3932. }
  3933. messages := portal.bridge.DB.Message.GetMessagesBetween(portal.Key, prevTimestamp, maxTimestamp)
  3934. if len(messages) > 0 {
  3935. sender.SetLastReadTS(portal.Key, messages[len(messages)-1].Timestamp)
  3936. }
  3937. groupedMessages := make(map[types.JID][]types.MessageID)
  3938. for _, msg := range messages {
  3939. var key types.JID
  3940. if msg.IsFakeJID() || msg.Sender.User == sender.JID.User {
  3941. // Don't send read receipts for own messages or fake messages
  3942. continue
  3943. } else if !portal.IsPrivateChat() {
  3944. key = msg.Sender
  3945. } else if !msg.BroadcastListJID.IsEmpty() {
  3946. key = msg.BroadcastListJID
  3947. } // else: blank key (participant field isn't needed in direct chat read receipts)
  3948. groupedMessages[key] = append(groupedMessages[key], msg.JID)
  3949. }
  3950. // For explicit read receipts, log even if there are no targets. For implicit ones only log when there are targets
  3951. if len(groupedMessages) > 0 || isExplicit {
  3952. portal.log.Debugfln("Sending read receipts by %s (last read: %d, was zero: %t, explicit: %t): %v",
  3953. sender.JID, prevTimestamp.Unix(), lastReadIsZero, isExplicit, groupedMessages)
  3954. }
  3955. for messageSender, ids := range groupedMessages {
  3956. chatJID := portal.Key.JID
  3957. if messageSender.Server == types.BroadcastServer {
  3958. chatJID = messageSender
  3959. messageSender = portal.Key.JID
  3960. }
  3961. err := sender.Client.MarkRead(ids, receiptTimestamp, chatJID, messageSender)
  3962. if err != nil {
  3963. portal.log.Warnfln("Failed to mark %v as read by %s: %v", ids, sender.JID, err)
  3964. }
  3965. }
  3966. }
  3967. func typingDiff(prev, new []id.UserID) (started, stopped []id.UserID) {
  3968. OuterNew:
  3969. for _, userID := range new {
  3970. for _, previousUserID := range prev {
  3971. if userID == previousUserID {
  3972. continue OuterNew
  3973. }
  3974. }
  3975. started = append(started, userID)
  3976. }
  3977. OuterPrev:
  3978. for _, userID := range prev {
  3979. for _, previousUserID := range new {
  3980. if userID == previousUserID {
  3981. continue OuterPrev
  3982. }
  3983. }
  3984. stopped = append(stopped, userID)
  3985. }
  3986. return
  3987. }
  3988. func (portal *Portal) setTyping(userIDs []id.UserID, state types.ChatPresence) {
  3989. for _, userID := range userIDs {
  3990. user := portal.bridge.GetUserByMXIDIfExists(userID)
  3991. if user == nil || !user.IsLoggedIn() {
  3992. continue
  3993. }
  3994. portal.log.Debugfln("Bridging typing change from %s to chat presence %s", state, user.MXID)
  3995. err := user.Client.SendChatPresence(portal.Key.JID, state, types.ChatPresenceMediaText)
  3996. if err != nil {
  3997. portal.log.Warnln("Error sending chat presence:", err)
  3998. }
  3999. if portal.bridge.Config.Bridge.SendPresenceOnTyping {
  4000. err = user.Client.SendPresence(types.PresenceAvailable)
  4001. if err != nil {
  4002. user.log.Warnln("Failed to set presence:", err)
  4003. }
  4004. }
  4005. }
  4006. }
  4007. func (portal *Portal) HandleMatrixTyping(newTyping []id.UserID) {
  4008. portal.currentlyTypingLock.Lock()
  4009. defer portal.currentlyTypingLock.Unlock()
  4010. startedTyping, stoppedTyping := typingDiff(portal.currentlyTyping, newTyping)
  4011. portal.currentlyTyping = newTyping
  4012. portal.setTyping(startedTyping, types.ChatPresenceComposing)
  4013. portal.setTyping(stoppedTyping, types.ChatPresencePaused)
  4014. }
  4015. func (portal *Portal) canBridgeFrom(sender *User, allowRelay bool) error {
  4016. if !sender.IsLoggedIn() {
  4017. if allowRelay && portal.HasRelaybot() {
  4018. return nil
  4019. } else if sender.Session != nil {
  4020. return errUserNotConnected
  4021. } else {
  4022. return errUserNotLoggedIn
  4023. }
  4024. } else if portal.IsPrivateChat() && sender.JID.User != portal.Key.Receiver.User && (!allowRelay || !portal.HasRelaybot()) {
  4025. return errDifferentUser
  4026. }
  4027. return nil
  4028. }
  4029. func (portal *Portal) resetChildSpaceStatus() {
  4030. for _, childPortal := range portal.bridge.portalsByJID {
  4031. if childPortal.ParentGroup == portal.Key.JID {
  4032. if portal.MXID != "" && childPortal.InSpace {
  4033. go childPortal.removeSpaceParentEvent(portal.MXID)
  4034. }
  4035. childPortal.InSpace = false
  4036. if childPortal.parentPortal == portal {
  4037. childPortal.parentPortal = nil
  4038. }
  4039. }
  4040. }
  4041. }
  4042. func (portal *Portal) Delete() {
  4043. portal.Portal.Delete()
  4044. portal.bridge.portalsLock.Lock()
  4045. delete(portal.bridge.portalsByJID, portal.Key)
  4046. if len(portal.MXID) > 0 {
  4047. delete(portal.bridge.portalsByMXID, portal.MXID)
  4048. }
  4049. portal.resetChildSpaceStatus()
  4050. portal.bridge.portalsLock.Unlock()
  4051. }
  4052. func (portal *Portal) GetMatrixUsers() ([]id.UserID, error) {
  4053. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  4054. if err != nil {
  4055. return nil, fmt.Errorf("failed to get member list: %w", err)
  4056. }
  4057. var users []id.UserID
  4058. for userID := range members.Joined {
  4059. _, isPuppet := portal.bridge.ParsePuppetMXID(userID)
  4060. if !isPuppet && userID != portal.bridge.Bot.UserID {
  4061. users = append(users, userID)
  4062. }
  4063. }
  4064. return users, nil
  4065. }
  4066. func (portal *Portal) CleanupIfEmpty() {
  4067. users, err := portal.GetMatrixUsers()
  4068. if err != nil {
  4069. portal.log.Errorfln("Failed to get Matrix user list to determine if portal needs to be cleaned up: %v", err)
  4070. return
  4071. }
  4072. if len(users) == 0 {
  4073. portal.log.Infoln("Room seems to be empty, cleaning up...")
  4074. portal.Delete()
  4075. portal.Cleanup(false)
  4076. }
  4077. }
  4078. func (portal *Portal) Cleanup(puppetsOnly bool) {
  4079. if len(portal.MXID) == 0 {
  4080. return
  4081. }
  4082. intent := portal.MainIntent()
  4083. if portal.bridge.SpecVersions.UnstableFeatures["com.beeper.room_yeeting"] {
  4084. err := intent.BeeperDeleteRoom(portal.MXID)
  4085. if err == nil || errors.Is(err, mautrix.MNotFound) {
  4086. return
  4087. }
  4088. portal.log.Warnfln("Failed to delete %s using hungryserv yeet endpoint, falling back to normal behavior: %v", portal.MXID, err)
  4089. }
  4090. members, err := intent.JoinedMembers(portal.MXID)
  4091. if err != nil {
  4092. portal.log.Errorln("Failed to get portal members for cleanup:", err)
  4093. return
  4094. }
  4095. for member := range members.Joined {
  4096. if member == intent.UserID {
  4097. continue
  4098. }
  4099. puppet := portal.bridge.GetPuppetByMXID(member)
  4100. if puppet != nil {
  4101. _, err = puppet.DefaultIntent().LeaveRoom(portal.MXID)
  4102. if err != nil {
  4103. portal.log.Errorln("Error leaving as puppet while cleaning up portal:", err)
  4104. }
  4105. } else if !puppetsOnly {
  4106. _, err = intent.KickUser(portal.MXID, &mautrix.ReqKickUser{UserID: member, Reason: "Deleting portal"})
  4107. if err != nil {
  4108. portal.log.Errorln("Error kicking user while cleaning up portal:", err)
  4109. }
  4110. }
  4111. }
  4112. _, err = intent.LeaveRoom(portal.MXID)
  4113. if err != nil {
  4114. portal.log.Errorln("Error leaving with main intent while cleaning up portal:", err)
  4115. }
  4116. }
  4117. func (portal *Portal) HandleMatrixLeave(brSender bridge.User) {
  4118. sender := brSender.(*User)
  4119. if portal.IsPrivateChat() {
  4120. portal.log.Debugln("User left private chat portal, cleaning up and deleting...")
  4121. portal.Delete()
  4122. portal.Cleanup(false)
  4123. return
  4124. } else if portal.bridge.Config.Bridge.BridgeMatrixLeave {
  4125. err := sender.Client.LeaveGroup(portal.Key.JID)
  4126. if err != nil {
  4127. portal.log.Errorfln("Failed to leave group as %s: %v", sender.MXID, err)
  4128. return
  4129. }
  4130. //portal.log.Infoln("Leave response:", <-resp)
  4131. }
  4132. portal.CleanupIfEmpty()
  4133. }
  4134. func (portal *Portal) HandleMatrixKick(brSender bridge.User, brTarget bridge.Ghost) {
  4135. sender := brSender.(*User)
  4136. target := brTarget.(*Puppet)
  4137. _, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
  4138. target.JID: whatsmeow.ParticipantChangeRemove,
  4139. })
  4140. if err != nil {
  4141. portal.log.Errorfln("Failed to kick %s from group as %s: %v", target.JID, sender.MXID, err)
  4142. return
  4143. }
  4144. //portal.log.Infoln("Kick %s response: %s", puppet.JID, <-resp)
  4145. }
  4146. func (portal *Portal) HandleMatrixInvite(brSender bridge.User, brTarget bridge.Ghost) {
  4147. sender := brSender.(*User)
  4148. target := brTarget.(*Puppet)
  4149. _, err := sender.Client.UpdateGroupParticipants(portal.Key.JID, map[types.JID]whatsmeow.ParticipantChange{
  4150. target.JID: whatsmeow.ParticipantChangeAdd,
  4151. })
  4152. if err != nil {
  4153. portal.log.Errorfln("Failed to add %s to group as %s: %v", target.JID, sender.MXID, err)
  4154. return
  4155. }
  4156. //portal.log.Infofln("Add %s response: %s", puppet.JID, <-resp)
  4157. }
  4158. func (portal *Portal) HandleMatrixMeta(brSender bridge.User, evt *event.Event) {
  4159. sender := brSender.(*User)
  4160. if !sender.Whitelisted || !sender.IsLoggedIn() {
  4161. return
  4162. }
  4163. switch content := evt.Content.Parsed.(type) {
  4164. case *event.RoomNameEventContent:
  4165. if content.Name == portal.Name {
  4166. return
  4167. }
  4168. portal.Name = content.Name
  4169. err := sender.Client.SetGroupName(portal.Key.JID, content.Name)
  4170. if err != nil {
  4171. portal.log.Errorln("Failed to update group name:", err)
  4172. }
  4173. case *event.TopicEventContent:
  4174. if content.Topic == portal.Topic {
  4175. return
  4176. }
  4177. portal.Topic = content.Topic
  4178. err := sender.Client.SetGroupTopic(portal.Key.JID, "", "", content.Topic)
  4179. if err != nil {
  4180. portal.log.Errorln("Failed to update group description:", err)
  4181. }
  4182. case *event.RoomAvatarEventContent:
  4183. portal.avatarLock.Lock()
  4184. defer portal.avatarLock.Unlock()
  4185. if content.URL == portal.AvatarURL || (content.URL.IsEmpty() && portal.Avatar == "remove") {
  4186. return
  4187. }
  4188. var data []byte
  4189. var err error
  4190. if !content.URL.IsEmpty() {
  4191. data, err = portal.MainIntent().DownloadBytes(content.URL)
  4192. if err != nil {
  4193. portal.log.Errorfln("Failed to download updated avatar %s: %v", content.URL, err)
  4194. return
  4195. }
  4196. portal.log.Debugfln("%s set the group avatar to %s", sender.MXID, content.URL)
  4197. } else {
  4198. portal.log.Debugfln("%s removed the group avatar", sender.MXID)
  4199. }
  4200. newID, err := sender.Client.SetGroupPhoto(portal.Key.JID, data)
  4201. if err != nil {
  4202. portal.log.Errorfln("Failed to update group avatar: %v", err)
  4203. return
  4204. }
  4205. portal.log.Debugfln("Successfully updated group avatar to %s", newID)
  4206. portal.Avatar = newID
  4207. portal.AvatarURL = content.URL
  4208. portal.UpdateBridgeInfo()
  4209. portal.Update(nil)
  4210. }
  4211. }