1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
use std::{cell::RefCell, collections::HashSet};
use futures_util::StreamExt;
use gettextrs::gettext;
use gtk::{
glib,
glib::{clone, closure_local},
prelude::*,
subclass::prelude::*,
};
use matrix_sdk::{
deserialized_responses::{
AmbiguityChange, MemberEvent, SyncOrStrippedState, SyncTimelineEvent,
},
event_handler::EventHandlerDropGuard,
room::Room as MatrixRoom,
send_queue::RoomSendQueueUpdate,
sync::{JoinedRoomUpdate, LeftRoomUpdate},
DisplayName, Result as MatrixResult, RoomInfo, RoomMemberships, RoomState,
};
use ruma::{
api::client::error::{ErrorKind, RetryAfter},
events::{
room::{
avatar::RoomAvatarEventContent, encryption::SyncRoomEncryptionEvent,
guest_access::GuestAccess, history_visibility::HistoryVisibility,
},
tag::{TagInfo, TagName},
typing::TypingEventContent,
AnyRoomAccountDataEvent, AnySyncStateEvent, AnySyncTimelineEvent, SyncEphemeralRoomEvent,
SyncStateEvent,
},
EventId, MatrixToUri, MatrixUri, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId,
};
use tokio_stream::wrappers::BroadcastStream;
use tracing::{debug, error, warn};
mod aliases;
mod event;
mod highlight_flags;
mod join_rule;
mod member;
mod member_list;
mod permissions;
mod room_type;
mod timeline;
mod typing_list;
pub use self::{
aliases::{AddAltAliasError, RegisterLocalAliasError, RoomAliases},
event::*,
highlight_flags::HighlightFlags,
join_rule::{JoinRule, JoinRuleValue},
member::{Member, Membership},
member_list::MemberList,
permissions::*,
room_type::RoomType,
timeline::*,
typing_list::TypingList,
};
use super::{
notifications::NotificationsRoomSetting, room_list::RoomMetainfo, IdentityVerification,
Session, User,
};
use crate::{
components::{AtRoom, AvatarImage, AvatarUriSource, PillSource},
gettext_f,
prelude::*,
spawn, spawn_tokio,
utils::{string::linkify, BoundObjectWeakRef},
};
/// The default duration in seconds that we wait for to retry failed sending
/// requests.
const DEFAULT_RETRY_AFTER: u32 = 30;
mod imp {
use std::{
cell::{Cell, OnceCell},
marker::PhantomData,
time::SystemTime,
};
use glib::subclass::Signal;
use once_cell::sync::Lazy;
use super::*;
#[derive(Default, glib::Properties)]
#[properties(wrapper_type = super::Room)]
pub struct Room {
/// The room API of the SDK.
pub matrix_room: OnceCell<MatrixRoom>,
/// The current session.
#[property(get, set = Self::set_session, construct_only)]
pub session: glib::WeakRef<Session>,
/// The ID of this room, as a string.
#[property(get = Self::room_id_string)]
pub room_id_string: PhantomData<String>,
/// The aliases of this room.
#[property(get)]
pub aliases: RoomAliases,
/// The version of this room.
#[property(get = Self::version)]
pub version: PhantomData<String>,
/// Whether this room is federated.
#[property(get = Self::federated)]
pub federated: PhantomData<bool>,
/// The name that is set for this room.
///
/// This can be empty, the display name should be used instead in the
/// interface.
#[property(get = Self::name)]
pub name: PhantomData<Option<String>>,
/// Whether this room has an avatar explicitly set.
///
/// This is `false` if there is no avatar or if the avatar is the one
/// from the other member.
#[property(get)]
pub has_avatar: Cell<bool>,
/// The category of this room.
#[property(get, builder(RoomType::default()))]
pub category: Cell<RoomType>,
/// The timeline of this room.
#[property(get)]
pub timeline: OnceCell<Timeline>,
/// The member corresponding to our own user.
#[property(get)]
pub own_member: OnceCell<Member>,
/// The members of this room.
#[property(get)]
pub members: glib::WeakRef<MemberList>,
/// The number of joined members in the room, according to the
/// homeserver.
#[property(get)]
pub joined_members_count: Cell<u64>,
/// The user who sent the invite to this room.
///
/// This is only set when this room is an invitation.
#[property(get)]
pub inviter: RefCell<Option<Member>>,
/// The permissions of our own user in this room
#[property(get)]
pub permissions: Permissions,
/// The timestamp of the room's latest activity.
///
/// This is the timestamp of the latest event that counts as possibly
/// unread.
///
/// If it is not known, it will return `0`.
#[property(get)]
pub latest_activity: Cell<u64>,
/// Whether all messages of this room are read.
#[property(get)]
pub is_read: Cell<bool>,
/// The highlight state of the room.
#[property(get)]
pub highlight: Cell<HighlightFlags>,
/// The ID of the room that was upgraded and that this one replaces.
pub predecessor_id: OnceCell<OwnedRoomId>,
/// The ID of the room that was upgraded and that this one replaces, as
/// a string.
#[property(get = Self::predecessor_id_string)]
pub predecessor_id_string: PhantomData<Option<String>>,
/// The ID of the successor of this Room, if this room was upgraded.
pub successor_id: OnceCell<OwnedRoomId>,
/// The ID of the successor of this Room, if this room was upgraded, as
/// a string.
#[property(get = Self::successor_id_string)]
pub successor_id_string: PhantomData<Option<String>>,
/// The successor of this Room, if this room was upgraded and the
/// successor was joined.
#[property(get)]
pub successor: glib::WeakRef<super::Room>,
/// An ongoing identity verification in this room.
#[property(get, set = Self::set_verification, nullable, explicit_notify)]
pub verification: BoundObjectWeakRef<IdentityVerification>,
/// Whether this room is encrypted.
#[property(get)]
pub is_encrypted: Cell<bool>,
/// The list of members currently typing in this room.
#[property(get)]
pub typing_list: TypingList,
/// Whether this room is a direct chat.
#[property(get)]
pub is_direct: Cell<bool>,
/// The other member of the room, if this room is a direct chat and
/// there is only one other member.
#[property(get)]
pub direct_member: RefCell<Option<Member>>,
/// The number of unread notifications of this room.
#[property(get = Self::notification_count)]
pub notification_count: PhantomData<u64>,
/// The topic of this room.
#[property(get = Self::topic)]
pub topic: PhantomData<Option<String>>,
/// The linkified topic of this room.
///
/// This is the string that should be used in the interface when markup
/// is allowed.
#[property(get)]
pub topic_linkified: RefCell<Option<String>>,
/// Whether this room has been upgraded.
#[property(get = Self::is_tombstoned)]
pub is_tombstoned: PhantomData<bool>,
/// The notifications settings for this room.
#[property(get, set = Self::set_notifications_setting, explicit_notify, builder(NotificationsRoomSetting::default()))]
pub notifications_setting: Cell<NotificationsRoomSetting>,
/// The join rule of this room.
#[property(get)]
pub join_rule: JoinRule,
/// Whether guests are allowed.
#[property(get)]
pub guests_allowed: Cell<bool>,
/// The visibility of the history.
#[property(get, builder(HistoryVisibilityValue::default()))]
pub history_visibility: Cell<HistoryVisibilityValue>,
pub typing_drop_guard: OnceCell<EventHandlerDropGuard>,
}
#[glib::object_subclass]
impl ObjectSubclass for Room {
const NAME: &'static str = "Room";
type Type = super::Room;
type ParentType = PillSource;
}
#[glib::derived_properties]
impl ObjectImpl for Room {
fn signals() -> &'static [Signal] {
static SIGNALS: Lazy<Vec<Signal>> =
Lazy::new(|| vec![Signal::builder("room-forgotten").build()]);
SIGNALS.as_ref()
}
}
impl PillSourceImpl for Room {
fn identifier(&self) -> String {
self.aliases
.alias_string()
.unwrap_or_else(|| self.room_id_string())
}
}
impl Room {
/// Set the current session
fn set_session(&self, session: Session) {
self.session.set(Some(&session));
let own_member = Member::new(&self.obj(), session.user_id().clone());
self.own_member.set(own_member).unwrap();
}
/// The room API of the SDK.
pub fn matrix_room(&self) -> &MatrixRoom {
self.matrix_room.get().unwrap()
}
/// The room ID of this room, as a string.
fn room_id_string(&self) -> String {
self.matrix_room().room_id().to_string()
}
/// The version of this room.
fn version(&self) -> String {
self.matrix_room()
.create_content()
.map(|c| c.room_version.to_string())
.unwrap_or_default()
}
/// Whether this room is federated.
fn federated(&self) -> bool {
self.matrix_room()
.create_content()
.map(|c| c.federate)
.unwrap_or_default()
}
/// The name of this room.
///
/// This can be empty, the display name should be used instead in the
/// interface.
fn name(&self) -> Option<String> {
self.matrix_room().name()
}
/// Set whether this room has an avatar explicitly set.
pub fn set_has_avatar(&self, has_avatar: bool) {
if self.has_avatar.get() == has_avatar {
return;
}
self.has_avatar.set(has_avatar);
self.obj().notify_has_avatar();
}
/// The number of unread notifications of this room.
fn notification_count(&self) -> u64 {
self.matrix_room()
.unread_notification_counts()
.notification_count
}
/// The topic of this room.
fn topic(&self) -> Option<String> {
self.matrix_room()
.topic()
.filter(|topic| !topic.trim().is_empty())
}
/// Update the topic of this room.
pub(super) fn update_topic(&self) {
let topic_linkified = self.topic().map(|t| {
// Detect links.
let mut s = linkify(&t);
// Remove trailing spaces.
s.truncate_end_whitespaces();
s
});
self.topic_linkified.replace(topic_linkified);
let obj = self.obj();
obj.notify_topic();
obj.notify_topic_linkified();
}
/// Whether this room was tombstoned.
fn is_tombstoned(&self) -> bool {
self.matrix_room().is_tombstoned()
}
/// The ID of the room that was upgraded and that this one replaces, as
/// a string.
fn predecessor_id_string(&self) -> Option<String> {
self.predecessor_id.get().map(ToString::to_string)
}
/// The ID of the successor of this Room, if this room was upgraded.
fn successor_id_string(&self) -> Option<String> {
self.successor_id.get().map(ToString::to_string)
}
/// Set an ongoing verification in this room.
fn set_verification(&self, verification: Option<IdentityVerification>) {
if self.verification.obj().is_some() && verification.is_some() {
// Just keep the same verification until it is dropped. Then we will look if
// there is an ongoing verification in the room.
return;
}
self.verification.disconnect_signals();
let verification = verification.or_else(|| {
// Look if there is an ongoing verification to replace it with.
let room_id = self.matrix_room().room_id();
self.session
.upgrade()
.map(|s| s.verification_list())
.and_then(|list| list.ongoing_room_verification(room_id))
});
if let Some(verification) = &verification {
let state_handler = verification.connect_is_finished_notify(clone!(
#[weak(rename_to = imp)]
self,
move |_| {
imp.set_verification(None);
}
));
let dismiss_handler = verification.connect_dismiss(clone!(
#[weak(rename_to = imp)]
self,
move |_| {
imp.set_verification(None);
}
));
self.verification
.set(verification, vec![state_handler, dismiss_handler]);
}
self.obj().notify_verification();
}
/// Set the notifications setting for this room.
fn set_notifications_setting(&self, setting: NotificationsRoomSetting) {
if self.notifications_setting.get() == setting {
return;
}
self.notifications_setting.set(setting);
self.obj().notify_notifications_setting();
}
/// Watch errors in the send queue to try to handle them.
pub(super) async fn watch_send_queue(&self) {
let matrix_room = self.matrix_room().clone();
let room_weak = glib::SendWeakRef::from(self.obj().downgrade());
spawn_tokio!(async move {
let send_queue = matrix_room.send_queue();
let subscriber = match send_queue.subscribe().await {
Ok((_, subscriber)) => BroadcastStream::new(subscriber),
Err(error) => {
warn!("Failed to listen to room send queue: {error}");
return;
}
};
subscriber
.for_each(move |update| {
let room_weak = room_weak.clone();
async move {
let Ok(RoomSendQueueUpdate::SendError {
error,
is_recoverable: true,
..
}) = update
else {
return;
};
let ctx = glib::MainContext::default();
ctx.spawn(async move {
spawn!(async move {
let Some(obj) = room_weak.upgrade() else {
return;
};
let Some(session) = obj.session() else {
return;
};
if session.is_offline() {
// The queue will be restarted when the session is back
// online.
return;
}
let duration = match error.client_api_error_kind() {
Some(ErrorKind::LimitExceeded {
retry_after: Some(retry_after),
}) => match retry_after {
RetryAfter::Delay(duration) => Some(*duration),
RetryAfter::DateTime(time) => {
time.duration_since(SystemTime::now()).ok()
}
},
_ => None,
};
let retry_after = duration
.and_then(|d| d.as_secs().try_into().ok())
.unwrap_or(DEFAULT_RETRY_AFTER);
glib::timeout_add_seconds_local_once(retry_after, move || {
let matrix_room = obj.matrix_room().clone();
// Getting a room's send queue requires a tokio executor.
spawn_tokio!(async move {
matrix_room.send_queue().set_enabled(true);
});
});
});
});
}
})
.await;
});
}
}
}
glib::wrapper! {
/// GObject representation of a Matrix room.
///
/// Handles populating the Timeline.
pub struct Room(ObjectSubclass<imp::Room>) @extends PillSource;
}
impl Room {
pub fn new(session: &Session, matrix_room: MatrixRoom, metainfo: Option<RoomMetainfo>) -> Self {
let this = glib::Object::builder::<Self>()
.property("session", session)
.build();
this.set_matrix_room(matrix_room);
if let Some(RoomMetainfo {
latest_activity,
is_read,
}) = metainfo
{
this.set_latest_activity(latest_activity);
this.set_is_read(is_read);
this.update_highlight();
}
this
}
/// The room API of the SDK.
pub fn matrix_room(&self) -> &MatrixRoom {
self.imp().matrix_room()
}
/// Set the room API of the SDK.
fn set_matrix_room(&self, matrix_room: MatrixRoom) {
let imp = self.imp();
self.set_joined_members_count(matrix_room.joined_members_count());
imp.matrix_room.set(matrix_room).unwrap();
imp.update_topic();
self.load_predecessor();
self.load_tombstone();
self.load_category();
self.set_up_typing();
self.init_timeline();
self.set_up_is_encrypted();
self.aliases().init(self);
self.update_guests_allowed();
self.update_history_visibility();
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.update_avatar().await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_display_name().await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_own_member().await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_is_direct().await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.watch_room_info().await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_inviter().await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.imp().permissions.init(&obj).await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.imp().join_rule.init(&obj).await;
}
)
);
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.imp().watch_send_queue().await;
}
)
);
}
fn init_timeline(&self) {
let timeline = self.imp().timeline.get_or_init(|| Timeline::new(self));
timeline.connect_read_change_trigger(clone!(
#[weak(rename_to = obj)]
self,
move |_| {
spawn!(glib::Priority::DEFAULT_IDLE, async move {
obj.handle_read_change_trigger().await
});
}
));
if !matches!(self.category(), RoomType::Left | RoomType::Outdated) {
// Load the room history when idle.
spawn!(
glib::source::Priority::LOW,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.timeline().load().await;
}
)
);
}
}
/// The ID of this room.
pub fn room_id(&self) -> &RoomId {
self.matrix_room().room_id()
}
/// The state of the room.
pub fn state(&self) -> RoomState {
self.matrix_room().state()
}
/// Set whether this room is a direct chat.
fn set_is_direct(&self, is_direct: bool) {
if self.is_direct() == is_direct {
return;
}
self.imp().is_direct.set(is_direct);
self.notify_is_direct();
spawn!(clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_direct_member().await;
}
));
}
/// Load whether the room is direct or not.
pub async fn load_is_direct(&self) {
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.is_direct().await });
match handle.await.unwrap() {
Ok(is_direct) => self.set_is_direct(is_direct),
Err(error) => {
error!(room_id = %self.room_id(), "Could not load whether room is direct: {error}");
}
}
}
/// The ID of the other user, if this is a direct chat and there is only one
/// other user.
async fn direct_user_id(&self) -> Option<OwnedUserId> {
let matrix_room = self.matrix_room();
// Check if the room direct and if there only one target.
let direct_targets = matrix_room.direct_targets();
if direct_targets.len() != 1 {
// It was a direct chat with several users.
return None;
}
let direct_target_user_id = direct_targets.into_iter().next().unwrap();
// Check that there are still at most 2 members.
let members_count = matrix_room.active_members_count();
if members_count > 2 {
// We only want a 1-to-1 room. The count might be 1 if the other user left, but
// we can reinvite them.
return None;
}
// Check that the members count is correct. It might not be correct if the room
// was just joined, or if it is in an invited state.
let matrix_room_clone = matrix_room.clone();
let handle =
spawn_tokio!(async move { matrix_room_clone.members(RoomMemberships::ACTIVE).await });
let members = match handle.await.unwrap() {
Ok(m) => m,
Err(error) => {
error!("Could not load room members: {error}");
vec![]
}
};
let members_count = members_count.max(members.len() as u64);
if members_count > 2 {
// Same as before.
return None;
}
let own_user_id = matrix_room.own_user_id();
// Get the other member from the list.
for member in members {
let user_id = member.user_id();
if user_id != direct_target_user_id && user_id != own_user_id {
// There is a non-direct member.
return None;
}
}
Some(direct_target_user_id)
}
/// Set the other member of the room, if this room is a direct chat and
/// there is only one other member..
fn set_direct_member(&self, member: Option<Member>) {
if self.direct_member() == member {
return;
}
self.imp().direct_member.replace(member);
self.notify_direct_member();
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.update_avatar().await;
}
)
);
}
/// Load the other member of the room, if this room is a direct chat and
/// there is only one other member.
async fn load_direct_member(&self) {
let Some(direct_user_id) = self.direct_user_id().await else {
self.set_direct_member(None);
return;
};
if self
.direct_member()
.is_some_and(|m| *m.user_id() == direct_user_id)
{
// Already up-to-date.
return;
}
let direct_member = if let Some(members) = self.members() {
members.get_or_create(direct_user_id.clone())
} else {
Member::new(self, direct_user_id.clone())
};
let matrix_room = self.matrix_room().clone();
let handle =
spawn_tokio!(async move { matrix_room.get_member_no_sync(&direct_user_id).await });
match handle.await.unwrap() {
Ok(Some(matrix_member)) => {
direct_member.update_from_room_member(&matrix_member);
}
Ok(None) => {}
Err(error) => {
error!("Could not get direct member: {error}");
}
}
self.set_direct_member(Some(direct_member));
}
/// Ensure the direct user of this room is an active member.
///
/// If there is supposed to be a direct user in this room but they have left
/// it, re-invite them.
///
/// This is a noop if there is no supposed direct user or if the user is
/// already an active member.
pub async fn ensure_direct_user(&self) -> Result<(), ()> {
let Some(member) = self.direct_member() else {
warn!("Cannot ensure direct user in a room without direct target");
return Ok(());
};
if self.matrix_room().active_members_count() == 2 {
return Ok(());
}
self.invite(&[member.user_id().clone()])
.await
.map_err(|_| ())
}
/// Forget a room that is left.
pub async fn forget(&self) -> MatrixResult<()> {
if self.category() != RoomType::Left {
warn!("Cannot forget a room that is not left");
return Ok(());
}
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.forget().await });
match handle.await.unwrap() {
Ok(_) => {
self.emit_by_name::<()>("room-forgotten", &[]);
Ok(())
}
Err(error) => {
error!("Could not forget the room: {error}");
// Load the previous category
self.load_category();
Err(error)
}
}
}
/// Whether this room is joined.
pub fn is_joined(&self) -> bool {
self.own_member().membership() == Membership::Join
}
fn set_category_internal(&self, category: RoomType) {
let old_category = self.category();
if old_category == RoomType::Outdated || old_category == category {
return;
}
self.imp().category.set(category);
self.notify_category();
}
/// Set the category of this room.
///
/// This makes the necessary to propagate the category to the homeserver.
///
/// Note: Rooms can't be moved to the invite category and they can't be
/// moved once they are upgraded.
pub async fn set_category(&self, category: RoomType) -> MatrixResult<()> {
let previous_category = self.category();
if previous_category == category {
return Ok(());
}
if previous_category == RoomType::Outdated {
warn!("Can't set the category of an upgraded room");
return Ok(());
}
match category {
RoomType::Invited => {
warn!("Rooms can’t be moved to the invite Category");
return Ok(());
}
RoomType::Outdated => {
// Outdated rooms don't need to propagate anything to the server
self.set_category_internal(category);
return Ok(());
}
_ => {}
}
self.set_category_internal(category);
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move {
match matrix_room.state() {
RoomState::Invited => match category {
RoomType::Invited => {}
RoomType::Favorite => {
if let Some(tags) = matrix_room.tags().await? {
if !tags.contains_key(&TagName::Favorite) {
matrix_room
.set_tag(TagName::Favorite, TagInfo::new())
.await?;
}
if tags.contains_key(&TagName::LowPriority) {
matrix_room.remove_tag(TagName::LowPriority).await?;
}
}
matrix_room.join().await?;
}
RoomType::Normal => {
if let Some(tags) = matrix_room.tags().await? {
if tags.contains_key(&TagName::Favorite) {
matrix_room.remove_tag(TagName::Favorite).await?;
}
if tags.contains_key(&TagName::LowPriority) {
matrix_room.remove_tag(TagName::LowPriority).await?;
}
}
if matrix_room.is_direct().await.unwrap_or_default() {
matrix_room.set_is_direct(false).await?;
}
matrix_room.join().await?;
}
RoomType::LowPriority => {
if let Some(tags) = matrix_room.tags().await? {
if tags.contains_key(&TagName::Favorite) {
matrix_room.remove_tag(TagName::Favorite).await?;
}
if !tags.contains_key(&TagName::LowPriority) {
matrix_room
.set_tag(TagName::LowPriority, TagInfo::new())
.await?;
}
}
matrix_room.join().await?;
}
RoomType::Left => {
matrix_room.leave().await?;
}
RoomType::Outdated | RoomType::Space | RoomType::Ignored => unimplemented!(),
},
RoomState::Joined => match category {
RoomType::Invited => {}
RoomType::Favorite => {
matrix_room
.set_tag(TagName::Favorite, TagInfo::new())
.await?;
if previous_category == RoomType::LowPriority {
matrix_room.remove_tag(TagName::LowPriority).await?;
}
}
RoomType::Normal => match previous_category {
RoomType::Favorite => {
matrix_room.remove_tag(TagName::Favorite).await?;
}
RoomType::LowPriority => {
matrix_room.remove_tag(TagName::LowPriority).await?;
}
_ => {}
},
RoomType::LowPriority => {
matrix_room
.set_tag(TagName::LowPriority, TagInfo::new())
.await?;
if previous_category == RoomType::Favorite {
matrix_room.remove_tag(TagName::Favorite).await?;
}
}
RoomType::Left => {
matrix_room.leave().await?;
}
RoomType::Outdated | RoomType::Space | RoomType::Ignored => unimplemented!(),
},
RoomState::Left => match category {
RoomType::Invited => {}
RoomType::Favorite => {
if let Some(tags) = matrix_room.tags().await? {
if !tags.contains_key(&TagName::Favorite) {
matrix_room
.set_tag(TagName::Favorite, TagInfo::new())
.await?;
}
if tags.contains_key(&TagName::LowPriority) {
matrix_room.remove_tag(TagName::LowPriority).await?;
}
}
matrix_room.join().await?;
}
RoomType::Normal => {
if let Some(tags) = matrix_room.tags().await? {
if tags.contains_key(&TagName::Favorite) {
matrix_room.remove_tag(TagName::Favorite).await?;
}
if tags.contains_key(&TagName::LowPriority) {
matrix_room.remove_tag(TagName::LowPriority).await?;
}
}
matrix_room.join().await?;
}
RoomType::LowPriority => {
if let Some(tags) = matrix_room.tags().await? {
if tags.contains_key(&TagName::Favorite) {
matrix_room.remove_tag(TagName::Favorite).await?;
}
if !tags.contains_key(&TagName::LowPriority) {
matrix_room
.set_tag(TagName::LowPriority, TagInfo::new())
.await?;
}
}
matrix_room.join().await?;
}
RoomType::Left => {}
RoomType::Outdated | RoomType::Space | RoomType::Ignored => unimplemented!(),
},
}
Result::<_, matrix_sdk::Error>::Ok(())
});
match handle.await.unwrap() {
Ok(_) => Ok(()),
Err(error) => {
error!("Could not set the room category: {error}");
// Load the previous category
self.load_category();
Err(error)
}
}
}
/// Load the category from the SDK.
fn load_category(&self) {
// Don't load the category if this room was upgraded
if self.category() == RoomType::Outdated {
return;
}
if self.inviter().is_some_and(|i| i.is_ignored()) {
self.set_category_internal(RoomType::Ignored);
return;
}
let matrix_room = self.matrix_room();
match matrix_room.state() {
RoomState::Joined => {
if matrix_room.is_space() {
self.set_category_internal(RoomType::Space);
} else {
let matrix_room = matrix_room.clone();
let tags = spawn_tokio!(async move { matrix_room.tags().await });
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
let mut category = RoomType::Normal;
if let Ok(Some(tags)) = tags.await.unwrap() {
if tags.contains_key(&TagName::Favorite) {
category = RoomType::Favorite;
} else if tags.contains_key(&TagName::LowPriority) {
category = RoomType::LowPriority;
}
}
obj.set_category_internal(category);
}
)
);
}
}
RoomState::Invited => self.set_category_internal(RoomType::Invited),
RoomState::Left => self.set_category_internal(RoomType::Left),
};
}
async fn watch_room_info(&self) {
let matrix_room = self.matrix_room();
let subscriber = matrix_room.subscribe_info();
let room_weak = glib::SendWeakRef::from(self.downgrade());
subscriber
.for_each(move |room_info| {
let room_weak = room_weak.clone();
async move {
let ctx = glib::MainContext::default();
ctx.spawn(async move {
spawn!(async move {
if let Some(obj) = room_weak.upgrade() {
obj.update_room_info(room_info)
}
});
});
}
})
.await;
}
fn update_room_info(&self, room_info: RoomInfo) {
self.set_joined_members_count(room_info.joined_members_count());
}
/// Start listening to typing events.
fn set_up_typing(&self) {
let imp = self.imp();
if imp.typing_drop_guard.get().is_some() {
// The event handler is already set up.
return;
}
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Joined {
return;
};
let room_weak = glib::SendWeakRef::from(self.downgrade());
let handle = matrix_room.add_event_handler(
move |event: SyncEphemeralRoomEvent<TypingEventContent>| {
let room_weak = room_weak.clone();
async move {
let ctx = glib::MainContext::default();
ctx.spawn(async move {
spawn!(async move {
if let Some(obj) = room_weak.upgrade() {
obj.handle_typing_event(event.content)
}
});
});
}
},
);
let drop_guard = matrix_room.client().event_handler_drop_guard(handle);
imp.typing_drop_guard.set(drop_guard).unwrap();
}
fn handle_typing_event(&self, content: TypingEventContent) {
let Some(session) = self.session() else {
return;
};
let typing_list = &self.imp().typing_list;
let Some(members) = self.members() else {
// If we don't have a members list, the room is not shown so we don't need to
// update the typing list.
typing_list.update(vec![]);
return;
};
let own_user_id = session.user_id();
let members = content
.user_ids
.into_iter()
.filter_map(|user_id| (user_id != *own_user_id).then(|| members.get_or_create(user_id)))
.collect();
typing_list.update(members);
}
/// Create and load our own member from the store.
async fn load_own_member(&self) {
let own_member = self.own_member();
let user_id = own_member.user_id().clone();
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.get_member_no_sync(&user_id).await });
match handle.await.unwrap() {
Ok(Some(matrix_member)) => own_member.update_from_room_member(&matrix_member),
Ok(None) => {}
Err(error) => error!(
"Could not load own member for room {}: {error}",
self.room_id()
),
}
}
/// The members of this room.
///
/// This creates the [`MemberList`] if no strong reference to it exists.
pub fn get_or_create_members(&self) -> MemberList {
let members = &self.imp().members;
if let Some(list) = members.upgrade() {
list
} else {
let list = MemberList::new(self);
members.set(Some(&list));
self.notify_members();
list
}
}
/// Set the number of joined members in the room, according to the
/// homeserver.
fn set_joined_members_count(&self, count: u64) {
if self.joined_members_count() == count {
return;
}
self.imp().joined_members_count.set(count);
self.notify_joined_members_count();
}
fn update_highlight(&self) {
let mut highlight = HighlightFlags::empty();
if matches!(self.category(), RoomType::Left) {
// Consider that all left rooms are read.
self.set_highlight(highlight);
return;
}
let counts = self.matrix_room().unread_notification_counts();
if counts.highlight_count > 0 {
highlight = HighlightFlags::all();
} else if counts.notification_count > 0 || !self.is_read() {
highlight = HighlightFlags::BOLD;
}
self.set_highlight(highlight);
}
/// Set how this room is highlighted.
fn set_highlight(&self, highlight: HighlightFlags) {
tracing::trace!("{}::set_highlight: {highlight:?}", self.human_readable_id());
if self.highlight() == highlight {
return;
}
tracing::trace!("{}: highlight changed", self.human_readable_id());
self.imp().highlight.set(highlight);
self.notify_highlight();
}
/// Handle the trigger emitted when a read change might have occurred.
async fn handle_read_change_trigger(&self) {
tracing::trace!("{}::handle_read_change_trigger", self.human_readable_id());
if let Some(has_unread) = self.timeline().has_unread_messages().await {
self.set_is_read(!has_unread);
}
self.update_highlight();
}
/// Set whether all messages of this room are read.
fn set_is_read(&self, is_read: bool) {
tracing::trace!("{}::set_is_read: {is_read:?}", self.human_readable_id());
if is_read == self.is_read() {
return;
}
tracing::trace!("{}: is_read changed", self.human_readable_id());
self.imp().is_read.set(is_read);
self.notify_is_read();
}
/// Load the display name from the SDK.
async fn load_display_name(&self) {
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.compute_display_name().await });
// FIXME: We should retry if the request failed
match handle.await.unwrap() {
Ok(display_name) => {
let name = match display_name {
DisplayName::Named(s)
| DisplayName::Calculated(s)
| DisplayName::Aliased(s) => s,
// Translators: This is the name of a room that is empty but had another user
// before. Do NOT translate the content between '{' and '}',
// this is a variable name.
DisplayName::EmptyWas(s) => {
gettext_f("Empty Room (was {user})", &[("user", &s)])
}
// Translators: This is the name of a room without other users.
DisplayName::Empty => gettext("Empty Room"),
};
self.set_display_name(name);
}
Err(error) => error!("Could not fetch display name: {error}"),
};
if self.display_name().is_empty() {
// Translators: This is displayed when the room name is unknown yet.
self.set_display_name(gettext("Unknown"));
}
}
/// Load the member that invited us to this room, when applicable.
async fn load_inviter(&self) {
let Some(session) = self.session() else {
return;
};
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Invited {
return;
}
let own_user_id = session.user_id().clone();
let matrix_room_clone = matrix_room.clone();
let handle =
spawn_tokio!(async move { matrix_room_clone.get_member_no_sync(&own_user_id).await });
let own_member = match handle.await.unwrap() {
Ok(Some(member)) => member,
Ok(None) => return,
Err(error) => {
error!("Could not get room member: {error}");
return;
}
};
let inviter_id = match &**own_member.event() {
MemberEvent::Sync(_) => return,
MemberEvent::Stripped(event) => event.sender.clone(),
};
let inviter_id_clone = inviter_id.clone();
let matrix_room = matrix_room.clone();
let handle =
spawn_tokio!(async move { matrix_room.get_member_no_sync(&inviter_id_clone).await });
let inviter_member = match handle.await.unwrap() {
Ok(Some(member)) => member,
Ok(None) => return,
Err(error) => {
error!("Could not get room member: {error}");
return;
}
};
let inviter = Member::new(self, inviter_id);
inviter.update_from_room_member(&inviter_member);
inviter
.upcast_ref::<User>()
.connect_is_ignored_notify(clone!(
#[weak(rename_to = obj)]
self,
move |_| {
obj.load_category();
}
));
self.imp().inviter.replace(Some(inviter));
self.notify_inviter();
self.load_category();
}
/// Update the room state based on the new sync response
/// FIXME: We should use the sdk's event handler to get updates
pub fn update_for_events(&self, batch: Vec<SyncTimelineEvent>) {
// FIXME: notify only when the count has changed
self.notify_notification_count();
let events: Vec<_> = batch
.iter()
.flat_map(|e| e.event.deserialize().ok())
.collect();
let own_member = self.own_member();
let own_user_id = own_member.user_id();
let direct_member = self.direct_member();
let direct_member_id = direct_member.as_ref().map(|m| m.user_id());
for event in events.iter() {
if let AnySyncTimelineEvent::State(state_event) = event {
match state_event {
AnySyncStateEvent::RoomMember(event) => {
let user_id = event.state_key();
if let Some(members) = self.members() {
members.update_member(user_id.clone());
} else if user_id == own_user_id {
own_member.update();
} else if direct_member_id.is_some_and(|id| id == user_id) {
if let Some(member) = &direct_member {
member.update();
}
}
// It might change the direct member.
spawn!(clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_direct_member().await;
obj.load_display_name().await;
}
));
}
AnySyncStateEvent::RoomAvatar(_) => {
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.update_avatar().await;
}
)
);
}
AnySyncStateEvent::RoomName(_) => {
self.notify_name();
spawn!(clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_display_name().await;
}
));
}
AnySyncStateEvent::RoomTopic(_) => {
self.imp().update_topic();
}
AnySyncStateEvent::RoomTombstone(_) => {
self.load_tombstone();
}
AnySyncStateEvent::RoomGuestAccess(_) => {
self.update_guests_allowed();
}
AnySyncStateEvent::RoomHistoryVisibility(_) => {
self.update_history_visibility();
}
_ => {}
}
}
}
}
/// Set the timestamp of the room's latest possibly unread event.
fn set_latest_activity(&self, latest_activity: u64) {
if latest_activity == self.latest_activity() {
return;
}
self.imp().latest_activity.set(latest_activity);
self.notify_latest_activity();
}
/// Toggle the `key` reaction on the given related event in this room.
pub async fn toggle_reaction(&self, key: String, event: &Event) -> Result<(), ()> {
let timeline = self.timeline().matrix_timeline();
let event_timeline_id = event.timeline_id();
let handle =
spawn_tokio!(async move { timeline.toggle_reaction(&event_timeline_id, &key).await });
if let Err(error) = handle.await.unwrap() {
error!("Could not toggle reaction: {error}");
return Err(());
}
Ok(())
}
/// Redact the given events in this room because of the given reason.
///
/// Returns `Ok(())` if all the redactions are successful, otherwise
/// returns the list of events that could not be redacted.
pub async fn redact<'a>(
&self,
events: &'a [OwnedEventId],
reason: Option<String>,
) -> Result<(), Vec<&'a EventId>> {
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Joined {
return Ok(());
};
let events_clone = events.to_owned();
let matrix_room = matrix_room.clone();
let handle = spawn_tokio!(async move {
let mut failed_redactions = Vec::new();
for (i, event_id) in events_clone.iter().enumerate() {
match matrix_room.redact(event_id, reason.as_deref(), None).await {
Ok(_) => {}
Err(error) => {
error!("Could not redact event with ID {event_id}: {error}");
failed_redactions.push(i);
}
}
}
failed_redactions
});
let failed_redactions = handle.await.unwrap();
let failed_redactions = failed_redactions
.into_iter()
.map(|i| &*events[i])
.collect::<Vec<_>>();
if failed_redactions.is_empty() {
Ok(())
} else {
Err(failed_redactions)
}
}
pub fn send_typing_notification(&self, is_typing: bool) {
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Joined {
return;
};
let matrix_room = matrix_room.clone();
let handle = spawn_tokio!(async move { matrix_room.typing_notice(is_typing).await });
spawn!(glib::Priority::DEFAULT_IDLE, async move {
match handle.await.unwrap() {
Ok(_) => {}
Err(error) => error!("Could not send typing notification: {error}"),
};
});
}
pub async fn accept_invite(&self) -> MatrixResult<()> {
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Invited {
error!("Can’t accept invite, because this room isn’t an invited room");
return Ok(());
}
let matrix_room = matrix_room.clone();
let handle = spawn_tokio!(async move { matrix_room.join().await });
match handle.await.unwrap() {
Ok(_) => Ok(()),
Err(error) => {
error!("Accepting invitation failed: {error}");
Err(error)
}
}
}
pub async fn decline_invite(&self) -> MatrixResult<()> {
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Invited {
error!("Cannot decline invite, because this room is not an invited room");
return Ok(());
}
let matrix_room = matrix_room.clone();
let handle = spawn_tokio!(async move { matrix_room.leave().await });
match handle.await.unwrap() {
Ok(_) => Ok(()),
Err(error) => {
error!("Declining invitation failed: {error}");
Err(error)
}
}
}
/// Reload the room from the SDK when its state might have changed.
pub fn update_room(&self) {
let state = self.matrix_room().state();
let category = self.category();
// Check if the previous state was different.
if category.is_state(state) {
// Nothing needs to be reloaded.
return;
}
debug!(room_id = %self.room_id(), ?state, "The state of `Room` changed");
if state == RoomState::Joined {
if let Some(members) = self.members() {
// If we where invited or left before, the list was likely not completed or
// might have changed.
members.reload();
}
}
self.load_category();
spawn!(clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_inviter().await;
}
));
}
pub fn handle_left_update(&self, update: LeftRoomUpdate) {
self.update_for_events(update.timeline.events);
self.handle_ambiguity_changes(update.ambiguity_changes.values());
}
pub fn handle_joined_update(&self, update: JoinedRoomUpdate) {
if update
.account_data
.iter()
.any(|e| matches!(e.deserialize(), Ok(AnyRoomAccountDataEvent::Tag(_))))
{
self.load_category();
}
self.update_for_events(update.timeline.events);
self.handle_ambiguity_changes(update.ambiguity_changes.values());
}
/// Handle changes in the ambiguity of members display names.
fn handle_ambiguity_changes<'a>(&self, changes: impl Iterator<Item = &'a AmbiguityChange>) {
// Use a set to make sure we update members only once.
let user_ids = changes.flat_map(|c| c.user_ids()).collect::<HashSet<_>>();
if let Some(members) = self.members() {
for user_id in user_ids {
members.update_member(user_id.to_owned());
}
} else {
let own_member = self.own_member();
let own_user_id = own_member.user_id();
for user_id in user_ids {
if user_id == *own_user_id {
own_member.update();
}
}
}
}
/// Connect to the signal emitted when the room was forgotten.
pub fn connect_room_forgotten<F: Fn(&Self) + 'static>(&self, f: F) -> glib::SignalHandlerId {
self.connect_closure(
"room-forgotten",
true,
closure_local!(move |obj: Self| {
f(&obj);
}),
)
}
/// The ID of the predecessor of this room, if this room is an upgrade to a
/// previous room.
pub fn predecessor_id(&self) -> Option<&OwnedRoomId> {
self.imp().predecessor_id.get()
}
/// Load the predecessor of this room.
fn load_predecessor(&self) {
if self.predecessor_id().is_some() {
return;
}
let Some(event) = self.matrix_room().create_content() else {
return;
};
let Some(predecessor) = event.predecessor else {
return;
};
self.imp().predecessor_id.set(predecessor.room_id).unwrap();
self.notify_predecessor_id_string();
}
/// The ID of the successor of this Room, if this room was upgraded.
pub fn successor_id(&self) -> Option<&RoomId> {
self.imp().successor_id.get().map(std::ops::Deref::deref)
}
/// Set the successor of this Room.
fn set_successor(&self, successor: &Room) {
self.imp().successor.set(Some(successor));
self.notify_successor();
}
/// Load the tombstone for this room.
pub fn load_tombstone(&self) {
let imp = self.imp();
if !self.is_tombstoned() || self.successor_id().is_some() {
return;
}
if let Some(room_tombstone) = self.matrix_room().tombstone() {
imp.successor_id
.set(room_tombstone.replacement_room)
.unwrap();
self.notify_successor_id_string();
};
if !self.update_outdated() {
if let Some(session) = self.session() {
session
.room_list()
.add_tombstoned_room(self.room_id().to_owned());
}
}
self.notify_is_tombstoned();
}
/// Update whether this `Room` is outdated.
///
/// A room is outdated when it was tombstoned and we joined its successor.
///
/// Returns `true` if the `Room` was set as outdated, `false` otherwise.
pub fn update_outdated(&self) -> bool {
if self.category() == RoomType::Outdated {
return true;
}
let Some(session) = self.session() else {
return false;
};
let room_list = session.room_list();
if let Some(successor_id) = self.successor_id() {
if let Some(successor) = room_list.get(successor_id) {
// The Matrix spec says that we should use the "predecessor" field of the
// m.room.create event of the successor, not the "successor" field of the
// m.room.tombstone event, so check it just to be sure.
if let Some(predecessor_id) = successor.predecessor_id() {
if predecessor_id == self.room_id() {
self.set_successor(&successor);
self.set_category_internal(RoomType::Outdated);
return true;
}
}
}
}
// The tombstone event can be redacted and we lose the successor, so search in
// the room predecessors of other rooms.
for room in room_list.iter::<Room>() {
let Ok(room) = room else {
break;
};
if let Some(predecessor_id) = room.predecessor_id() {
if predecessor_id == self.room_id() {
self.set_successor(&room);
self.set_category_internal(RoomType::Outdated);
return true;
}
}
}
false
}
/// Invite the given users to this room.
///
/// Returns `Ok(())` if all the invites are sent successfully, otherwise
/// returns the list of users who could not be invited.
pub async fn invite<'a>(&self, user_ids: &'a [OwnedUserId]) -> Result<(), Vec<&'a UserId>> {
let matrix_room = self.matrix_room();
if matrix_room.state() != RoomState::Joined {
error!("Can’t invite users, because this room isn’t a joined room");
return Ok(());
}
let user_ids_clone = user_ids.to_owned();
let matrix_room = matrix_room.clone();
let handle = spawn_tokio!(async move {
let invitations = user_ids_clone
.iter()
.map(|user_id| matrix_room.invite_user_by_id(user_id));
futures_util::future::join_all(invitations).await
});
let mut failed_invites = Vec::new();
for (index, result) in handle.await.unwrap().iter().enumerate() {
match result {
Ok(_) => {}
Err(error) => {
error!("Could not invite user with ID {}: {error}", user_ids[index],);
failed_invites.push(&*user_ids[index]);
}
}
}
if failed_invites.is_empty() {
Ok(())
} else {
Err(failed_invites)
}
}
/// Kick the given users from this room.
///
/// The users are a list of `(user_id, reason)` tuples.
///
/// Returns `Ok(())` if all the kicks are sent successfully, otherwise
/// returns the list of users who could not be kicked.
pub async fn kick<'a>(
&self,
users: &'a [(OwnedUserId, Option<String>)],
) -> Result<(), Vec<&'a UserId>> {
let users_clone = users.to_owned();
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move {
let futures = users_clone
.iter()
.map(|(user_id, reason)| matrix_room.kick_user(user_id, reason.as_deref()));
futures_util::future::join_all(futures).await
});
let mut failed_kicks = Vec::new();
for (index, result) in handle.await.unwrap().iter().enumerate() {
match result {
Ok(_) => {}
Err(error) => {
error!("Could not kick user with ID {}: {error}", users[index].0);
failed_kicks.push(&*users[index].0);
}
}
}
if failed_kicks.is_empty() {
Ok(())
} else {
Err(failed_kicks)
}
}
/// Ban the given users from this room.
///
/// The users are a list of `(user_id, reason)` tuples.
///
/// Returns `Ok(())` if all the bans are sent successfully, otherwise
/// returns the list of users who could not be banned.
pub async fn ban<'a>(
&self,
users: &'a [(OwnedUserId, Option<String>)],
) -> Result<(), Vec<&'a UserId>> {
let users_clone = users.to_owned();
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move {
let futures = users_clone
.iter()
.map(|(user_id, reason)| matrix_room.ban_user(user_id, reason.as_deref()));
futures_util::future::join_all(futures).await
});
let mut failed_bans = Vec::new();
for (index, result) in handle.await.unwrap().iter().enumerate() {
match result {
Ok(_) => {}
Err(error) => {
error!("Could not ban user with ID {}: {error}", users[index].0);
failed_bans.push(&*users[index].0);
}
}
}
if failed_bans.is_empty() {
Ok(())
} else {
Err(failed_bans)
}
}
/// Unban the given users from this room.
///
/// The users are a list of `(user_id, reason)` tuples.
///
/// Returns `Ok(())` if all the unbans are sent successfully, otherwise
/// returns the list of users who could not be unbanned.
pub async fn unban<'a>(
&self,
users: &'a [(OwnedUserId, Option<String>)],
) -> Result<(), Vec<&'a UserId>> {
let users_clone = users.to_owned();
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move {
let futures = users_clone
.iter()
.map(|(user_id, reason)| matrix_room.unban_user(user_id, reason.as_deref()));
futures_util::future::join_all(futures).await
});
let mut failed_unbans = Vec::new();
for (index, result) in handle.await.unwrap().iter().enumerate() {
match result {
Ok(_) => {}
Err(error) => {
error!("Could not unban user with ID {}: {error}", users[index].0);
failed_unbans.push(&*users[index].0);
}
}
}
if failed_unbans.is_empty() {
Ok(())
} else {
Err(failed_unbans)
}
}
/// Update the latest activity of the room with the given events.
///
/// The events must be in reverse chronological order.
pub fn update_latest_activity<'a>(&self, events: impl IntoIterator<Item = &'a Event>) {
let mut latest_activity = self.latest_activity();
for event in events {
if event.counts_as_unread() {
latest_activity = latest_activity.max(event.origin_server_ts_u64());
break;
}
}
self.set_latest_activity(latest_activity);
}
/// Listen to changes in room encryption.
fn set_up_is_encrypted(&self) {
let matrix_room = self.matrix_room();
let obj_weak = glib::SendWeakRef::from(self.downgrade());
matrix_room.add_event_handler(move |_: SyncRoomEncryptionEvent| {
let obj_weak = obj_weak.clone();
async move {
let ctx = glib::MainContext::default();
ctx.spawn(async move {
spawn!(async move {
if let Some(obj) = obj_weak.upgrade() {
obj.load_is_encrypted().await;
}
});
});
}
});
spawn!(
glib::Priority::DEFAULT_IDLE,
clone!(
#[weak(rename_to = obj)]
self,
async move {
obj.load_is_encrypted().await;
}
)
);
}
/// Load whether the room is encrypted from the SDK.
async fn load_is_encrypted(&self) {
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.is_encrypted().await });
match handle.await.unwrap() {
Ok(true) => {
self.imp().is_encrypted.set(true);
self.notify_is_encrypted();
}
Ok(false) => {}
Err(error) => {
error!("Could not load room encryption state: {error}");
}
}
}
/// Enable encryption for this room.
pub async fn enable_encryption(&self) -> Result<(), ()> {
if self.is_encrypted() {
// Nothing to do.
return Ok(());
}
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.enable_encryption().await });
match handle.await.unwrap() {
Ok(_) => Ok(()),
Err(error) => {
error!("Could not enabled room encryption: {error}");
Err(())
}
}
}
/// Get a human-readable ID for this `Room`.
///
/// This is to identify the room easily in logs.
pub fn human_readable_id(&self) -> String {
format!("{} ({})", self.display_name(), self.room_id())
}
/// Update the avatar for the room.
async fn update_avatar(&self) {
let Some(session) = self.session() else {
return;
};
let imp = self.imp();
let avatar_data = self.avatar_data();
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move {
matrix_room
.get_state_event_static::<RoomAvatarEventContent>()
.await
});
let avatar_event = match handle.await.unwrap() {
Ok(Some(raw_event)) => match raw_event.deserialize() {
Ok(event) => Some(event),
Err(error) => {
warn!("Could not deserialize room avatar event: {error}");
None
}
},
Ok(None) => None,
Err(error) => {
warn!("Could not get room avatar event: {error}");
None
}
};
let (avatar_url, avatar_info) = match avatar_event {
Some(event) => match event {
SyncOrStrippedState::Sync(event) => match event {
SyncStateEvent::Original(e) => (e.content.url, e.content.info),
SyncStateEvent::Redacted(_) => (None, None),
},
SyncOrStrippedState::Stripped(event) => (event.content.url, event.content.info),
},
None => (None, None),
};
if let Some(avatar_url) = avatar_url {
imp.set_has_avatar(true);
if let Some(avatar_image) = avatar_data
.image()
.filter(|i| i.uri_source() == AvatarUriSource::Room)
{
avatar_image.set_uri_and_info(Some(avatar_url), avatar_info);
} else {
let avatar_image = AvatarImage::new(
&session,
AvatarUriSource::Room,
Some(avatar_url),
avatar_info,
);
avatar_data.set_image(Some(avatar_image.clone()));
}
return;
}
imp.set_has_avatar(false);
// If we have a direct member, use their avatar.
if let Some(direct_member) = self.direct_member() {
avatar_data.set_image(direct_member.avatar_data().image());
}
let avatar_image = avatar_data.image();
if let Some(avatar_image) = avatar_image
.as_ref()
.filter(|i| i.uri_source() == AvatarUriSource::Room)
{
// The room has no avatar, make sure we remove it.
avatar_image.set_uri_and_info(None, None);
} else if avatar_image.is_none() {
// We always need an avatar image, even if it is empty.
avatar_data.set_image(Some(AvatarImage::new(
&session,
AvatarUriSource::Room,
None,
None,
)))
}
}
/// The `matrix.to` URI representation for this room.
pub async fn matrix_to_uri(&self) -> MatrixToUri {
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.matrix_to_permalink().await });
match handle.await.unwrap() {
Ok(permalink) => {
return permalink;
}
Err(error) => {
error!("Could not get room event permalink: {error}");
}
}
// Fallback to using just the room ID, without routing.
self.room_id().matrix_to_uri()
}
/// The `matrix:` URI representation for this room.
pub async fn matrix_uri(&self) -> MatrixUri {
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move { matrix_room.matrix_permalink(false).await });
match handle.await.unwrap() {
Ok(permalink) => {
return permalink;
}
Err(error) => {
error!("Could not get room event permalink: {error}");
}
}
// Fallback to using just the room ID, without routing.
self.room_id().matrix_uri(false)
}
/// The `matrix.to` URI representation for the given event in this room.
pub async fn matrix_to_event_uri(&self, event_id: OwnedEventId) -> MatrixToUri {
let matrix_room = self.matrix_room().clone();
let event_id_clone = event_id.clone();
let handle =
spawn_tokio!(
async move { matrix_room.matrix_to_event_permalink(event_id_clone).await }
);
match handle.await.unwrap() {
Ok(permalink) => {
return permalink;
}
Err(error) => {
error!("Could not get room event permalink: {error}");
}
}
// Fallback to using just the room ID, without routing.
self.room_id().matrix_to_event_uri(event_id)
}
/// The `matrix:` URI representation for the given event in this room.
pub async fn matrix_event_uri(&self, event_id: OwnedEventId) -> MatrixUri {
let matrix_room = self.matrix_room().clone();
let event_id_clone = event_id.clone();
let handle =
spawn_tokio!(async move { matrix_room.matrix_event_permalink(event_id_clone).await });
match handle.await.unwrap() {
Ok(permalink) => {
return permalink;
}
Err(error) => {
error!("Could not get room event permalink: {error}");
}
}
// Fallback to using just the room ID, without routing.
self.room_id().matrix_event_uri(event_id)
}
/// Report the given events in this room.
///
/// The events are a list of `(event_id, reason)` tuples.
///
/// Returns `Ok(())` if all the reports are sent successfully, otherwise
/// returns the list of event IDs that could not be reported.
pub async fn report_events<'a>(
&self,
events: &'a [(OwnedEventId, Option<String>)],
) -> Result<(), Vec<&'a EventId>> {
let events_clone = events.to_owned();
let matrix_room = self.matrix_room().clone();
let handle = spawn_tokio!(async move {
let futures = events_clone
.into_iter()
.map(|(event_id, reason)| matrix_room.report_content(event_id, None, reason));
futures_util::future::join_all(futures).await
});
let mut failed = Vec::new();
for (index, result) in handle.await.unwrap().iter().enumerate() {
match result {
Ok(_) => {}
Err(error) => {
error!(
"Could not report content with event ID {}: {error}",
events[index].0,
);
failed.push(&*events[index].0);
}
}
}
if failed.is_empty() {
Ok(())
} else {
Err(failed)
}
}
/// Update whether guests are allowed.
fn update_guests_allowed(&self) {
let matrix_room = self.matrix_room();
let guests_allowed = matrix_room.guest_access() == GuestAccess::CanJoin;
if self.guests_allowed() == guests_allowed {
return;
}
self.imp().guests_allowed.set(guests_allowed);
self.notify_guests_allowed();
}
/// Update the visibility of the history.
fn update_history_visibility(&self) {
let matrix_room = self.matrix_room();
let visibility = matrix_room.history_visibility().into();
if self.history_visibility() == visibility {
return;
}
self.imp().history_visibility.set(visibility);
self.notify_history_visibility();
}
/// Constructs an `AtRoom` for this room.
pub fn at_room(&self) -> AtRoom {
let at_room = AtRoom::new(self.room_id().to_owned());
// Bind the avatar image so it always looks the same.
self.avatar_data()
.bind_property("image", &at_room.avatar_data(), "image")
.sync_create()
.build();
at_room
}
}
/// Supported values for the history visibility.
#[derive(Debug, Default, Hash, Eq, PartialEq, Clone, Copy, glib::Enum)]
#[enum_type(name = "HistoryVisibilityValue")]
pub enum HistoryVisibilityValue {
/// Anyone can read.
WorldReadable,
/// Members, since this was selected.
#[default]
Shared,
/// Members, since they were invited.
Invited,
/// Members, since they joined.
Joined,
/// Unsupported value.
Unsupported,
}
impl From<HistoryVisibility> for HistoryVisibilityValue {
fn from(value: HistoryVisibility) -> Self {
match value {
HistoryVisibility::Invited => Self::Invited,
HistoryVisibility::Joined => Self::Joined,
HistoryVisibility::Shared => Self::Shared,
HistoryVisibility::WorldReadable => Self::WorldReadable,
_ => Self::Unsupported,
}
}
}
impl From<HistoryVisibilityValue> for HistoryVisibility {
fn from(value: HistoryVisibilityValue) -> Self {
match value {
HistoryVisibilityValue::Invited => Self::Invited,
HistoryVisibilityValue::Joined => Self::Joined,
HistoryVisibilityValue::Shared => Self::Shared,
HistoryVisibilityValue::WorldReadable => Self::WorldReadable,
HistoryVisibilityValue::Unsupported => unimplemented!(),
}
}
}