portal.go 156 KB

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