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
|
# -*- coding: utf-8 -*-
# Copyright © 2018, 2019 Damir Jelić <poljar@termina.org.uk>
# Copyright © 2018, 2019 Denis Kasak <dkasak@termina.org.uk>
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted, provided that the
# above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import unicode_literals
import argparse
import os
import re
import shlex
from builtins import str
from itertools import zip_longest
from collections import defaultdict
from functools import partial
from nio import EncryptionError, LocalProtocolError
from . import globals as G
from .colors import Formatted
from .globals import SERVERS, W, UPLOADS, SCRIPT_NAME
from .server import MatrixServer
from .utf import utf8_decode
from .utils import key_from_value, parse_redact_args
from .uploads import UploadsBuffer, Upload
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse # type: ignore
class ParseError(Exception):
pass
class WeechatArgParse(argparse.ArgumentParser):
def print_usage(self, file=None):
pass
def error(self, message):
message = (
"{prefix}Error: {message} for command {command} "
"(see /help {command})"
).format(prefix=W.prefix("error"), message=message, command=self.prog)
W.prnt("", message)
raise ParseError
class WeechatCommandParser(object):
@staticmethod
def _run_parser(parser, args):
try:
parsed_args = parser.parse_args(shlex.split(args))
return parsed_args
except ParseError:
return None
@staticmethod
def topic(args):
parser = WeechatArgParse(prog="topic")
parser.add_argument("-delete", action="store_true")
parser.add_argument("topic", nargs="*")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def kick(args):
parser = WeechatArgParse(prog="kick")
parser.add_argument("user_id")
parser.add_argument("reason", nargs="*")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def invite(args):
parser = WeechatArgParse(prog="invite")
parser.add_argument("user_id")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def join(args):
parser = WeechatArgParse(prog="join")
parser.add_argument("room_id")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def part(args):
parser = WeechatArgParse(prog="part")
parser.add_argument("room_id", nargs="?")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def devices(args):
parser = WeechatArgParse(prog="devices")
subparsers = parser.add_subparsers(dest="subcommand")
subparsers.add_parser("list")
delete_parser = subparsers.add_parser("delete")
delete_parser.add_argument("device_id")
name_parser = subparsers.add_parser("set-name")
name_parser.add_argument("device_id")
name_parser.add_argument("device_name", nargs="*")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def olm(args):
parser = WeechatArgParse(prog="olm")
subparsers = parser.add_subparsers(dest="subcommand")
info_parser = subparsers.add_parser("info")
info_parser.add_argument(
"category", nargs="?", default="private",
choices=[
"all",
"blacklisted",
"private",
"unverified",
"verified",
"ignored"
])
info_parser.add_argument("filter", nargs="?")
verify_parser = subparsers.add_parser("verify")
verify_parser.add_argument("user_filter")
verify_parser.add_argument("device_filter", nargs="?")
unverify_parser = subparsers.add_parser("unverify")
unverify_parser.add_argument("user_filter")
unverify_parser.add_argument("device_filter", nargs="?")
blacklist_parser = subparsers.add_parser("blacklist")
blacklist_parser.add_argument("user_filter")
blacklist_parser.add_argument("device_filter", nargs="?")
unblacklist_parser = subparsers.add_parser("unblacklist")
unblacklist_parser.add_argument("user_filter")
unblacklist_parser.add_argument("device_filter", nargs="?")
ignore_parser = subparsers.add_parser("ignore")
ignore_parser.add_argument("user_filter")
ignore_parser.add_argument("device_filter", nargs="?")
unignore_parser = subparsers.add_parser("unignore")
unignore_parser.add_argument("user_filter")
unignore_parser.add_argument("device_filter", nargs="?")
export_parser = subparsers.add_parser("export")
export_parser.add_argument("file")
export_parser.add_argument("passphrase")
import_parser = subparsers.add_parser("import")
import_parser.add_argument("file")
import_parser.add_argument("passphrase")
sas_parser = subparsers.add_parser("verification")
sas_parser.add_argument(
"action",
choices=[
"start",
"accept",
"confirm",
"cancel",
])
sas_parser.add_argument("user_id")
sas_parser.add_argument("device_id")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def room(args):
parser = WeechatArgParse(prog="room")
subparsers = parser.add_subparsers(dest="subcommand")
typing_notification = subparsers.add_parser("typing-notifications")
typing_notification.add_argument(
"state",
choices=["enable", "disable", "toggle"]
)
read_markers = subparsers.add_parser("read-markers")
read_markers.add_argument(
"state",
choices=["enable", "disable", "toggle"]
)
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def uploads(args):
parser = WeechatArgParse(prog="uploads")
subparsers = parser.add_subparsers(dest="subcommand")
subparsers.add_parser("list")
subparsers.add_parser("listfull")
subparsers.add_parser("up")
subparsers.add_parser("down")
return WeechatCommandParser._run_parser(parser, args)
@staticmethod
def upload(args):
parser = WeechatArgParse(prog="upload")
parser.add_argument("file")
return WeechatCommandParser._run_parser(parser, args)
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def partition_key(key):
groups = grouper(key, 4, " ")
return ' '.join(''.join(g) for g in groups)
def hook_commands():
W.hook_command(
# Command name and short description
"matrix",
"Matrix chat protocol command",
# Synopsis
(
"server add <server-name> <hostname>[:<port>] ||"
"server delete|list|listfull <server-name> ||"
"connect <server-name> ||"
"disconnect <server-name> ||"
"reconnect <server-name> ||"
"help <matrix-command>"
),
# Description
(
" server: list, add, or remove Matrix servers\n"
" connect: connect to Matrix servers\n"
"disconnect: disconnect from one or all Matrix servers\n"
" reconnect: reconnect to server(s)\n"
" help: show detailed command help\n\n"
"Use /matrix help [command] to find out more.\n"
),
# Completions
(
"server %(matrix_server_commands)|%* ||"
"connect %(matrix_servers) ||"
"disconnect %(matrix_servers) ||"
"reconnect %(matrix_servers) ||"
"help %(matrix_commands)"
),
# Function name
"matrix_command_cb",
"",
)
W.hook_command(
# Command name and short description
"redact",
"redact messages",
# Synopsis
('<event-id>[:"<message-part>"] [<reason>]'),
# Description
(
" event-id: event id of the message that will be redacted\n"
"message-part: an initial part of the message (ignored, only "
"used\n"
" as visual feedback when using completion)\n"
" reason: the redaction reason\n"
),
# Completions
("%(matrix_messages)"),
# Function name
"matrix_redact_command_cb",
"",
)
W.hook_command(
# Command name and short description
"reply-matrix",
"reply to a message",
# Synopsis
('<event-id>[:"<message-part>"] [<reply>]'),
# Description
(
" event-id: event id of the message that will be replied to\n"
"message-part: an initial part of the message (ignored, only "
"used\n"
" as visual feedback when using completion)\n"
" reply: the reply\n"
),
# Completions
("%(matrix_messages)"),
# Function name
"matrix_reply_command_cb",
"",
)
W.hook_command(
# Command name and short description
"topic",
"get/set the room topic",
# Synopsis
("[<topic>|-delete]"),
# Description
(" topic: topic to set\n" "-delete: delete room topic"),
# Completions
"",
# Callback
"matrix_topic_command_cb",
"",
)
W.hook_command(
# Command name and short description
"me",
"send an emote message to the current room",
# Synopsis
("<message>"),
# Description
("message: message to send"),
# Completions
"",
# Callback
"matrix_me_command_cb",
"",
)
W.hook_command(
# Command name and short description
"kick",
"kick a user from the current room",
# Synopsis
("<user-id> [<reason>]"),
# Description
(
"user-id: user-id to kick\n"
" reason: reason why the user was kicked"
),
# Completions
("%(matrix_users)"),
# Callback
"matrix_kick_command_cb",
"",
)
W.hook_command(
# Command name and short description
"invite",
"invite a user to the current room",
# Synopsis
("<user-id>"),
# Description
("user-id: user-id to invite"),
# Completions
("%(matrix_users)"),
# Callback
"matrix_invite_command_cb",
"",
)
W.hook_command(
# Command name and short description
"join",
"join a room",
# Synopsis
("<room-id>|<room-alias>"),
# Description
(
" room-id: room-id of the room to join\n"
"room-alias: room alias of the room to join"
),
# Completions
"",
# Callback
"matrix_join_command_cb",
"",
)
W.hook_command(
# Command name and short description
"part",
"leave a room",
# Synopsis
("[<room-name>]"),
# Description
(" room-name: room name of the room to leave"),
# Completions
"",
# Callback
"matrix_part_command_cb",
"",
)
W.hook_command(
# Command name and short description
"devices",
"list, delete or rename matrix devices",
# Synopsis
("list ||"
"delete <device-id> ||"
"set-name <name>"
),
# Description
("device-id: device id of the device to delete\n"
" name: new device name to set\n"),
# Completions
("list ||"
"delete %(matrix_own_devices) ||"
"set-name %(matrix_own_devices)"),
# Callback
"matrix_devices_command_cb",
"",
)
W.hook_command(
# Command name and short description
"olm",
"Matrix olm encryption configuration command",
# Synopsis
("info all|blacklisted|ignored|private|unverified|verified <filter>||"
"blacklist <user-id> <device-id> ||"
"unverify <user-id> <device-id> ||"
"verify <user-id> <device-id> ||"
"verification start|accept|cancel|confirm <user-id> <device-id> ||"
"ignore <user-id> <device-id> ||"
"unignore <user-id> <device-id> ||"
"export <file-name> <passphrase> ||"
"import <file-name> <passphrase>"
),
# Description
(" info: show info about known devices and their keys\n"
" blacklist: blacklist a device\n"
"unblacklist: unblacklist a device\n"
" unverify: unverify a device\n"
" verify: verify a device\n"
" ignore: ignore an unverifiable but non-blacklist-worthy device\n"
" unignore: unignore a device\n"
"verification: manage interactive device verification\n"
" export: export encryption keys\n"
" import: import encryption keys\n\n"
"Examples:"
"\n /olm verify @example:example.com *"
"\n /olm info all example*"
),
# Completions
('info all|blacklisted|ignored|private|unverified|verified ||'
'blacklist %(olm_user_ids) %(olm_devices) ||'
'unblacklist %(olm_user_ids) %(olm_devices) ||'
'unverify %(olm_user_ids) %(olm_devices) ||'
'verify %(olm_user_ids) %(olm_devices) ||'
'verification start|accept|cancel|confirm %(olm_user_ids) %(olm_devices) ||'
'ignore %(olm_user_ids) %(olm_devices) ||'
'unignore %(olm_user_ids) %(olm_devices) ||'
'export %(filename) ||'
'import %(filename)'
),
# Function name
'matrix_olm_command_cb',
'')
W.hook_command(
# Command name and short description
"room",
"change room state",
# Synopsis
("typing-notifications <state>||"
"read-markers <state>"
),
# Description
("state: one of enable, disable or toggle\n"),
# Completions
("typing-notifications enable|disable|toggle||"
"read-markers enable|disable|toggle"
),
# Callback
"matrix_room_command_cb",
"",
)
# W.hook_command(
# # Command name and short description
# "uploads",
# "Open the uploads buffer or list uploads in the core buffer",
# # Synopsis
# ("list||"
# "listfull"
# ),
# # Description
# (""),
# # Completions
# ("list ||"
# "listfull"),
# # Callback
# "matrix_uploads_command_cb",
# "",
# )
W.hook_command(
# Command name and short description
"upload",
"Upload a file to a room",
# Synopsis
("<file>"),
# Description
(""),
# Completions
("%(filename)"),
# Callback
"matrix_upload_command_cb",
"",
)
W.hook_command(
# Command name and short description
"send-anyways",
"Send the last message in a room ignorin unverified devices.",
# Synopsis
"",
# Description
"Send the last message in a room despite there being unverified "
"devices. The unverified devices will be marked as ignored after "
"running this command.",
# Completions
"",
# Callback
"matrix_send_anyways_cb",
"",
)
W.hook_command_run("/buffer clear", "matrix_command_buf_clear_cb", "")
if G.CONFIG.network.fetch_backlog_on_pgup:
hook_page_up()
def hook_key_bindings():
W.hook_hsignal("matrix_cursor_reply", "matrix_cursor_reply_signal_cb", "")
binding = "@chat(python.{}*):r".format(G.BUFFER_NAME_PREFIX)
W.key_bind("cursor", {
binding: "hsignal:matrix_cursor_reply",
})
def format_device(device_id, fp_key, display_name):
fp_key = partition_key(fp_key)
message = (" - Device ID: {device_color}{device_id}{ncolor}\n"
" - Display name: {device_color}{display_name}{ncolor}\n"
" - Device key: {key_color}{fp_key}{ncolor}").format(
device_color=W.color("chat_channel"),
device_id=device_id,
ncolor=W.color("reset"),
display_name=display_name,
key_color=W.color("chat_server"),
fp_key=fp_key)
return message
def olm_info_command(server, args):
def print_devices(
device_store,
filter_regex,
device_category="All",
predicate=None,
):
user_strings = []
try:
filter_regex = re.compile(args.filter) if args.filter else None
except re.error as e:
server.error("Invalid regular expression: {}.".format(e.args[0]))
return
for user_id in sorted(device_store.users):
device_strings = []
for device in device_store.active_user_devices(user_id):
if filter_regex:
if (not filter_regex.search(user_id) and
not filter_regex.search(device.id)):
continue
if predicate:
if not predicate(device):
continue
device_strings.append(format_device(
device.id,
device.ed25519,
device.display_name
))
if not device_strings:
continue
d_string = "\n".join(device_strings)
message = (" - User: {user_color}{user}{ncolor}\n").format(
user_color=W.color("chat_nick"),
user=user_id,
ncolor=W.color("reset"))
message += d_string
user_strings.append(message)
if not user_strings:
message = ("{prefix}matrix: No matching devices "
"found.").format(prefix=W.prefix("error"))
W.prnt(server.server_buffer, message)
return
server.info("{} devices:\n".format(device_category))
W.prnt(server.server_buffer, "\n".join(user_strings))
olm = server.client.olm
if not hasattr(args, 'category') or args.category == "private":
fp_key = partition_key(olm.account.identity_keys["ed25519"])
message = ("Identity keys:\n"
" - User: {user_color}{user}{ncolor}\n"
" - Device ID: {device_color}{device_id}{ncolor}\n"
" - Device key: {key_color}{fp_key}{ncolor}\n"
"").format(
user_color=W.color("chat_self"),
ncolor=W.color("reset"),
user=olm.user_id,
device_color=W.color("chat_channel"),
device_id=olm.device_id,
key_color=W.color("chat_server"),
fp_key=fp_key)
server.info(message)
elif args.category == "all":
print_devices(olm.device_store, args.filter)
elif args.category == "verified":
print_devices(
olm.device_store,
args.filter,
"Verified",
olm.is_device_verified
)
elif args.category == "unverified":
def predicate(device):
return not olm.is_device_verified(device)
print_devices(
olm.device_store,
args.filter,
"Unverified",
predicate
)
elif args.category == "blacklisted":
print_devices(
olm.device_store,
args.filter,
"Blacklisted",
olm.is_device_blacklisted
)
elif args.category == "ignored":
print_devices(
olm.device_store,
args.filter,
"Ignored",
olm.is_device_ignored
)
def olm_action_command(server, args, category, error_category, prefix, action):
device_store = server.client.olm.device_store
users = []
if args.user_filter == "*":
users = device_store.users
else:
users = [x for x in device_store.users if args.user_filter in x]
user_devices = {
user: device_store.active_user_devices(user) for user in users
}
if args.device_filter and args.device_filter != "*":
filtered_user_devices = {}
for user, device_list in user_devices.items():
filtered_devices = filter(
lambda x: args.device_filter in x.id,
device_list
)
filtered_user_devices[user] = list(filtered_devices)
user_devices = filtered_user_devices
changed_devices = defaultdict(list)
for user, device_list in user_devices.items():
for device in device_list:
if action(device):
changed_devices[user].append(device)
if not changed_devices:
message = ("{prefix}matrix: No matching {error_category} devices "
"found.").format(
prefix=W.prefix("error"),
error_category=error_category
)
W.prnt(server.server_buffer, message)
return
user_strings = []
for user_id, device_list in changed_devices.items():
device_strings = []
message = (" - User: {user_color}{user}{ncolor}\n").format(
user_color=W.color("chat_nick"),
user=user_id,
ncolor=W.color("reset"))
for device in device_list:
device_strings.append(format_device(
device.id,
device.ed25519,
device.display_name
))
if not device_strings:
continue
d_string = "\n".join(device_strings)
message += d_string
user_strings.append(message)
W.prnt(server.server_buffer,
"{}matrix: {} key(s):\n".format(W.prefix("prefix"), category))
W.prnt(server.server_buffer, "\n".join(user_strings))
pass
def olm_verify_command(server, args):
olm_action_command(
server,
args,
"Verified",
"unverified",
"join",
server.client.verify_device
)
def olm_unverify_command(server, args):
olm_action_command(
server,
args,
"Unverified",
"verified",
"quit",
server.client.unverify_device
)
def olm_blacklist_command(server, args):
olm_action_command(
server,
args,
"Blacklisted",
"unblacklisted",
"join",
server.client.blacklist_device
)
def olm_unblacklist_command(server, args):
olm_action_command(
server,
args,
"Unblacklisted",
"blacklisted",
"join",
server.client.unblacklist_device
)
def olm_ignore_command(server, args):
olm_action_command(
server,
args,
"Ignored",
"ignored",
"join",
server.client.ignore_device
)
def olm_unignore_command(server, args):
olm_action_command(
server,
args,
"Unignored",
"unignored",
"join",
server.client.unignore_device
)
def olm_export_command(server, args):
file_path = os.path.expanduser(args.file)
try:
server.client.export_keys(file_path, args.passphrase)
server.info("Successfully exported keys")
except (OSError, IOError) as e:
server.error("Error exporting keys: {}".format(str(e)))
def olm_import_command(server, args):
file_path = os.path.expanduser(args.file)
try:
server.client.import_keys(file_path, args.passphrase)
server.info("Successfully imported keys")
except (OSError, IOError, EncryptionError) as e:
server.error("Error importing keys: {}".format(str(e)))
def olm_sas_command(server, args):
try:
device_store = server.client.device_store
except LocalProtocolError:
server.error("The device store is not loaded")
return W.WEECHAT_RC_OK
try:
device = device_store[args.user_id][args.device_id]
except KeyError:
server.error("Device {} of user {} not found".format(
args.device_id,
args.user_id
))
return W.WEECHAT_RC_OK
if device.deleted:
server.error("Device {} of user {} is deleted.".format(
args.device_id,
args.user_id
))
return W.WEECHAT_RC_OK
if args.action == "start":
server.start_verification(device)
elif args.action in ["accept", "confirm", "cancel"]:
sas = server.client.get_active_sas(args.user_id, args.device_id)
if not sas:
server.error("No active key verification found for "
"device {} of user {}.".format(
args.device_id,
args.user_id
))
return W.WEECHAT_RC_OK
try:
if args.action == "accept":
server.accept_sas(sas)
elif args.action == "confirm":
server.confirm_sas(sas)
elif args.action == "cancel":
server.cancel_sas(sas)
except LocalProtocolError as e:
server.error(str(e))
@utf8_decode
def matrix_olm_command_cb(data, buffer, args):
def command(server, data, buffer, args):
parsed_args = WeechatCommandParser.olm(args)
if not parsed_args:
return W.WEECHAT_RC_OK
if not server.client.olm:
W.prnt(server.server_buffer, "{}matrix: Olm account isn't "
"loaded.".format(W.prefix("error")))
return W.WEECHAT_RC_OK
if not parsed_args.subcommand or parsed_args.subcommand == "info":
olm_info_command(server, parsed_args)
elif parsed_args.subcommand == "export":
olm_export_command(server, parsed_args)
elif parsed_args.subcommand == "import":
olm_import_command(server, parsed_args)
elif parsed_args.subcommand == "verify":
olm_verify_command(server, parsed_args)
elif parsed_args.subcommand == "unverify":
olm_unverify_command(server, parsed_args)
elif parsed_args.subcommand == "blacklist":
olm_blacklist_command(server, parsed_args)
elif parsed_args.subcommand == "unblacklist":
olm_unblacklist_command(server, parsed_args)
elif parsed_args.subcommand == "verification":
olm_sas_command(server, parsed_args)
elif parsed_args.subcommand == "ignore":
olm_ignore_command(server, parsed_args)
elif parsed_args.subcommand == "unignore":
olm_unignore_command(server, parsed_args)
else:
message = ("{prefix}matrix: Command not implemented.".format(
prefix=W.prefix("error")))
W.prnt(server.server_buffer, message)
W.bar_item_update("buffer_modes")
W.bar_item_update("matrix_modes")
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer in server.buffers.values():
return command(server, data, buffer, args)
elif buffer == server.server_buffer:
return command(server, data, buffer, args)
W.prnt("", "{prefix}matrix: command \"olm\" must be executed on a "
"matrix buffer (server or channel)".format(
prefix=W.prefix("error")
))
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_devices_command_cb(data, buffer, args):
for server in SERVERS.values():
if buffer in server.buffers.values() or buffer == server.server_buffer:
parsed_args = WeechatCommandParser.devices(args)
if not parsed_args:
return W.WEECHAT_RC_OK
if not parsed_args.subcommand or parsed_args.subcommand == "list":
server.devices()
elif parsed_args.subcommand == "delete":
server.delete_device(parsed_args.device_id)
elif parsed_args.subcommand == "set-name":
new_name = " ".join(parsed_args.device_name).strip("\"")
server.rename_device(parsed_args.device_id, new_name)
return W.WEECHAT_RC_OK
W.prnt("", "{prefix}matrix: command \"devices\" must be executed on a "
"matrix buffer (server or channel)".format(
prefix=W.prefix("error")
))
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_me_command_cb(data, buffer, args):
for server in SERVERS.values():
if buffer in server.buffers.values():
if not server.connected:
message = (
"{prefix}matrix: you are not connected to " "the server"
).format(prefix=W.prefix("error"))
W.prnt(server.server_buffer, message)
return W.WEECHAT_RC_ERROR
room_buffer = server.find_room_from_ptr(buffer)
if not server.client.logged_in:
room_buffer.error("You are not logged in.")
return W.WEECHAT_RC_ERROR
if not args:
return W.WEECHAT_RC_OK
formatted_data = Formatted.from_input_line(args)
server.room_send_message(room_buffer, formatted_data, "m.emote")
return W.WEECHAT_RC_OK
if buffer == server.server_buffer:
message = (
'{prefix}matrix: command "me" must be '
"executed on a Matrix channel buffer"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_OK
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_topic_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.topic(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer == server.server_buffer:
server.error(
'command "topic" must be ' "executed on a Matrix room buffer"
)
return W.WEECHAT_RC_OK
room = server.find_room_from_ptr(buffer)
if not room:
continue
if not parsed_args.topic and not parsed_args.delete:
# TODO print the current topic
return W.WEECHAT_RC_OK
if parsed_args.delete and parsed_args.topic:
# TODO error message
return W.WEECHAT_RC_OK
topic = "" if parsed_args.delete else " ".join(parsed_args.topic)
content = {"topic": topic}
server.room_send_state(room, content, "m.room.topic")
return W.WEECHAT_RC_OK
def matrix_fetch_old_messages(server, room_id):
room_buffer = server.find_room_from_id(room_id)
room = room_buffer.room
if room_buffer.backlog_pending:
return
prev_batch = room.prev_batch
if not prev_batch:
return
raise NotImplementedError
def check_server_existence(server_name, servers):
if server_name not in servers:
message = "{prefix}matrix: No such server: {server}".format(
prefix=W.prefix("error"), server=server_name
)
W.prnt("", message)
return False
return True
def hook_page_up():
G.CONFIG.page_up_hook = W.hook_command_run(
"/window page_up", "matrix_command_pgup_cb", ""
)
@utf8_decode
def matrix_command_buf_clear_cb(data, buffer, command):
for server in SERVERS.values():
if buffer in server.buffers.values():
room_buffer = server.find_room_from_ptr(buffer)
room_buffer.room.prev_batch = server.next_batch
return W.WEECHAT_RC_OK
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_command_pgup_cb(data, buffer, command):
# TODO the highlight status of a line isn't allowed to be updated/changed
# via hdata, therefore the highlight status of a messages can't be
# reoredered this would need to be fixed in weechat
# TODO we shouldn't fetch and print out more messages than
# max_buffer_lines_number or older messages than max_buffer_lines_minutes
for server in SERVERS.values():
if buffer in server.buffers.values():
window = W.window_search_with_buffer(buffer)
first_line_displayed = bool(
W.window_get_integer(window, "first_line_displayed")
)
room_buffer = server.find_room_from_ptr(buffer)
if first_line_displayed or room_buffer.weechat_buffer.num_lines == 0:
room_id = key_from_value(server.buffers, buffer)
server.room_get_messages(room_id)
return W.WEECHAT_RC_OK
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_join_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.join(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer in server.buffers.values() or buffer == server.server_buffer:
server.room_join(parsed_args.room_id)
break
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_part_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.part(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer in server.buffers.values() or buffer == server.server_buffer:
room_id = parsed_args.room_id
if not room_id:
if buffer == server.server_buffer:
server.error(
'command "part" must be '
"executed on a Matrix room buffer or a room "
"name needs to be given"
)
return W.WEECHAT_RC_OK
room_buffer = server.find_room_from_ptr(buffer)
room_id = room_buffer.room.room_id
server.room_leave(room_id)
break
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_invite_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.invite(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer == server.server_buffer:
server.error(
'command "invite" must be ' "executed on a Matrix room buffer"
)
return W.WEECHAT_RC_OK
room = server.find_room_from_ptr(buffer)
if not room:
continue
user_id = parsed_args.user_id
user_id = user_id if user_id.startswith("@") else "@" + user_id
server.room_invite(room, user_id)
break
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_room_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.room(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer == server.server_buffer:
server.error(
'command "room" must be ' "executed on a Matrix room buffer"
)
return W.WEECHAT_RC_OK
room = server.find_room_from_ptr(buffer)
if not room:
continue
if not parsed_args.subcommand or parsed_args.subcommand == "list":
server.error("command no subcommand found")
return W.WEECHAT_RC_OK
if parsed_args.subcommand == "typing-notifications":
if parsed_args.state == "enable":
room.typing_enabled = True
elif parsed_args.state == "disable":
room.typing_enabled = False
elif parsed_args.state == "toggle":
room.typing_enabled = not room.typing_enabled
break
elif parsed_args.subcommand == "read-markers":
if parsed_args.state == "enable":
room.read_markers_enabled = True
elif parsed_args.state == "disable":
room.read_markers_enabled = False
elif parsed_args.state == "toggle":
room.read_markers_enabled = not room.read_markers_enabled
break
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_uploads_command_cb(data, buffer, args):
if not args:
if not G.CONFIG.upload_buffer:
G.CONFIG.upload_buffer = UploadsBuffer()
G.CONFIG.upload_buffer.display()
return W.WEECHAT_RC_OK
parsed_args = WeechatCommandParser.uploads(args)
if not parsed_args:
return W.WEECHAT_RC_OK
if parsed_args.subcommand == "list":
pass
elif parsed_args.subcommand == "listfull":
pass
elif parsed_args.subcommand == "up":
if G.CONFIG.upload_buffer:
G.CONFIG.upload_buffer.move_line_up()
elif parsed_args.subcommand == "down":
if G.CONFIG.upload_buffer:
G.CONFIG.upload_buffer.move_line_down()
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_upload_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.upload(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer == server.server_buffer:
server.error(
'command "upload" must be ' "executed on a Matrix room buffer"
)
return W.WEECHAT_RC_OK
room_buffer = server.find_room_from_ptr(buffer)
if not room_buffer:
continue
upload = Upload(
server.name,
server.config.address,
server.client.access_token,
room_buffer.room.room_id,
parsed_args.file,
room_buffer.room.encrypted
)
UPLOADS[upload.uuid] = upload
if G.CONFIG.upload_buffer:
G.CONFIG.upload_buffer.render()
break
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_kick_command_cb(data, buffer, args):
parsed_args = WeechatCommandParser.kick(args)
if not parsed_args:
return W.WEECHAT_RC_OK
for server in SERVERS.values():
if buffer == server.server_buffer:
server.error(
'command "kick" must be ' "executed on a Matrix room buffer"
)
return W.WEECHAT_RC_OK
room = server.find_room_from_ptr(buffer)
if not room:
continue
user_id = parsed_args.user_id
user_id = user_id if user_id.startswith("@") else "@" + user_id
reason = " ".join(parsed_args.reason) if parsed_args.reason else None
server.room_kick(room, user_id, reason)
break
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_redact_command_cb(data, buffer, args):
def already_redacted(line):
if SCRIPT_NAME + "_redacted" in line.tags:
return True
return False
def predicate(event_id, line):
event_tag = SCRIPT_NAME + "_id_{}".format(event_id)
tags = line.tags
if event_tag in tags:
return True
return False
for server in SERVERS.values():
if buffer in server.buffers.values():
room_buffer = server.find_room_from_ptr(buffer)
event_id, reason = parse_redact_args(args)
if not event_id:
message = (
"{prefix}matrix: Invalid command "
"arguments (see /help redact)"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_ERROR
lines = room_buffer.weechat_buffer.find_lines(
partial(predicate, event_id), max_lines=1
)
if not lines:
room_buffer.error(
"No such message with event id "
"{event_id} found.".format(event_id=event_id))
return W.WEECHAT_RC_OK
if already_redacted(lines[0]):
room_buffer.error("Event already redacted.")
return W.WEECHAT_RC_OK
server.room_send_redaction(room_buffer, event_id, reason)
return W.WEECHAT_RC_OK
if buffer == server.server_buffer:
message = (
'{prefix}matrix: command "redact" must be '
"executed on a Matrix channel buffer"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_OK
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_reply_command_cb(data, buffer, args):
def predicate(event_id, line):
event_tag = SCRIPT_NAME + "_id_{}".format(event_id)
tags = line.tags
if event_tag in tags:
return True
return False
for server in SERVERS.values():
if buffer in server.buffers.values():
room_buffer = server.find_room_from_ptr(buffer)
# Intentional use of `parse_redact_args` which serves the
# necessary purpose
event_id, reply = parse_redact_args(args)
if not event_id or not reply:
message = (
"{prefix}matrix: Invalid command "
"arguments (see /help reply)"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_ERROR
lines = room_buffer.weechat_buffer.find_lines(
partial(predicate, event_id), max_lines=1
)
if not lines:
room_buffer.error(
"No such message with event id "
"{event_id} found.".format(event_id=event_id))
return W.WEECHAT_RC_OK
formatted_data = Formatted.from_input_line(reply)
server.room_send_message(
room_buffer,
formatted_data,
"m.text",
in_reply_to_event_id=event_id,
)
room_buffer.last_message = None
return W.WEECHAT_RC_OK
if buffer == server.server_buffer:
message = (
'{prefix}matrix: command "reply" must be '
"executed on a Matrix channel buffer"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_OK
return W.WEECHAT_RC_OK
def matrix_command_help(args):
if not args:
message = (
"{prefix}matrix: Too few arguments for command "
'"/matrix help" (see /matrix help help)'
).format(prefix=W.prefix("error"))
W.prnt("", message)
return
for command in args:
message = ""
if command == "connect":
message = (
"{delimiter_color}[{ncolor}matrix{delimiter_color}] "
"{ncolor}{cmd_color}/connect{ncolor} "
"<server-name> [<server-name>...]"
"\n\n"
"connect to Matrix server(s)"
"\n\n"
"server-name: server to connect to"
"(internal name)"
).format(
delimiter_color=W.color("chat_delimiters"),
cmd_color=W.color("chat_buffer"),
ncolor=W.color("reset"),
)
elif command == "disconnect":
message = (
"{delimiter_color}[{ncolor}matrix{delimiter_color}] "
"{ncolor}{cmd_color}/disconnect{ncolor} "
"<server-name> [<server-name>...]"
"\n\n"
"disconnect from Matrix server(s)"
"\n\n"
"server-name: server to disconnect"
"(internal name)"
).format(
delimiter_color=W.color("chat_delimiters"),
cmd_color=W.color("chat_buffer"),
ncolor=W.color("reset"),
)
elif command == "reconnect":
message = (
"{delimiter_color}[{ncolor}matrix{delimiter_color}] "
"{ncolor}{cmd_color}/reconnect{ncolor} "
"<server-name> [<server-name>...]"
"\n\n"
"reconnect to Matrix server(s)"
"\n\n"
"server-name: server to reconnect"
"(internal name)"
).format(
delimiter_color=W.color("chat_delimiters"),
cmd_color=W.color("chat_buffer"),
ncolor=W.color("reset"),
)
elif command == "server":
message = (
"{delimiter_color}[{ncolor}matrix{delimiter_color}] "
"{ncolor}{cmd_color}/server{ncolor} "
"add <server-name> <hostname>[:<port>]"
"\n "
"delete|list|listfull <server-name>"
"\n\n"
"list, add, or remove Matrix servers"
"\n\n"
" list: list servers (without argument, this "
"list is displayed)\n"
" listfull: list servers with detailed info for each "
"server\n"
" add: add a new server\n"
" delete: delete a server\n"
"server-name: server to reconnect (internal name)\n"
" hostname: name or IP address of server\n"
" port: port of server (default: 443)\n"
"\n"
"Examples:"
"\n /matrix server listfull"
"\n /matrix server add matrix matrix.org:80"
"\n /matrix server delete matrix"
).format(
delimiter_color=W.color("chat_delimiters"),
cmd_color=W.color("chat_buffer"),
ncolor=W.color("reset"),
)
elif command == "help":
message = (
"{delimiter_color}[{ncolor}matrix{delimiter_color}] "
"{ncolor}{cmd_color}/help{ncolor} "
"<matrix-command> [<matrix-command>...]"
"\n\n"
"display help about Matrix commands"
"\n\n"
"matrix-command: a Matrix command name"
"(internal name)"
).format(
delimiter_color=W.color("chat_delimiters"),
cmd_color=W.color("chat_buffer"),
ncolor=W.color("reset"),
)
else:
message = (
'{prefix}matrix: No help available, "{command}" '
"is not a matrix command"
).format(prefix=W.prefix("error"), command=command)
W.prnt("", "")
W.prnt("", message)
return
def matrix_server_command_listfull(args):
def get_value_string(value, default_value):
if value == default_value:
if not value:
value = "''"
value_string = " ({value})".format(value=value)
else:
value_string = "{color}{value}{ncolor}".format(
color=W.color("chat_value"),
value=value,
ncolor=W.color("reset"),
)
return value_string
for server_name in args:
if server_name not in SERVERS:
continue
server = SERVERS[server_name]
connected = ""
W.prnt("", "")
if server.connected:
connected = "connected"
else:
connected = "not connected"
message = (
"Server: {server_color}{server}{delimiter_color}"
" [{ncolor}{connected}{delimiter_color}]"
"{ncolor}"
).format(
server_color=W.color("chat_server"),
server=server.name,
delimiter_color=W.color("chat_delimiters"),
connected=connected,
ncolor=W.color("reset"),
)
W.prnt("", message)
option = server.config._option_ptrs["autoconnect"]
default_value = W.config_string_default(option)
value = W.config_string(option)
value_string = get_value_string(value, default_value)
message = " autoconnect. : {value}".format(value=value_string)
W.prnt("", message)
option = server.config._option_ptrs["address"]
default_value = W.config_string_default(option)
value = W.config_string(option)
value_string = get_value_string(value, default_value)
message = " address. . . : {value}".format(value=value_string)
W.prnt("", message)
option = server.config._option_ptrs["port"]
default_value = str(W.config_integer_default(option))
value = str(W.config_integer(option))
value_string = get_value_string(value, default_value)
message = " port . . . . : {value}".format(value=value_string)
W.prnt("", message)
option = server.config._option_ptrs["username"]
default_value = W.config_string_default(option)
value = W.config_string(option)
value_string = get_value_string(value, default_value)
message = " username . . : {value}".format(value=value_string)
W.prnt("", message)
option = server.config._option_ptrs["password"]
value = W.config_string(option)
if value:
value = "(hidden)"
value_string = get_value_string(value, "")
message = " password . . : {value}".format(value=value_string)
W.prnt("", message)
def matrix_server_command_delete(args):
for server_name in args:
if check_server_existence(server_name, SERVERS):
server = SERVERS[server_name]
if server.connected:
message = (
"{prefix}matrix: you can not delete server "
"{color}{server}{ncolor} because you are "
'connected to it. Try "/matrix disconnect '
'{color}{server}{ncolor}" before.'
).format(
prefix=W.prefix("error"),
color=W.color("chat_server"),
ncolor=W.color("reset"),
server=server.name,
)
W.prnt("", message)
return
for buf in list(server.buffers.values()):
W.buffer_close(buf)
if server.server_buffer:
W.buffer_close(server.server_buffer)
for option in server.config._option_ptrs.values():
W.config_option_free(option)
if server.timer_hook:
W.unhook(server.timer_hook)
server.timer_hook = None
message = (
"matrix: server {color}{server}{ncolor} has been " "deleted"
).format(
server=server.name,
color=W.color("chat_server"),
ncolor=W.color("reset"),
)
del SERVERS[server.name]
server = None
W.prnt("", message)
def matrix_server_command_add(args):
if len(args) < 2:
message = (
"{prefix}matrix: Too few arguments for command "
'"/matrix server add" (see /matrix help server)'
).format(prefix=W.prefix("error"))
W.prnt("", message)
return
if len(args) > 4:
message = (
"{prefix}matrix: Too many arguments for command "
'"/matrix server add" (see /matrix help server)'
).format(prefix=W.prefix("error"))
W.prnt("", message)
return
def remove_server(server):
for option in server.config._option_ptrs.values():
W.config_option_free(option)
del SERVERS[server.name]
server_name = args[0]
if server_name in SERVERS:
message = (
"{prefix}matrix: server {color}{server}{ncolor} "
"already exists, can't add it"
).format(
prefix=W.prefix("error"),
color=W.color("chat_server"),
server=server_name,
ncolor=W.color("reset"),
)
W.prnt("", message)
return
server = MatrixServer(server_name, G.CONFIG._ptr)
SERVERS[server.name] = server
if len(args) >= 2:
if args[1].startswith("http"):
homeserver= urlparse(args[1])
host = homeserver.hostname
port = str(homeserver.port) if homeserver.port else None
else:
try:
host, port = args[1].split(":", 1)
except ValueError:
host, port = args[1], None
return_code = W.config_option_set(
server.config._option_ptrs["address"], host, 1
)
if return_code == W.WEECHAT_CONFIG_OPTION_SET_ERROR:
remove_server(server)
message = (
"{prefix}Failed to set address for server "
"{color}{server}{ncolor}, failed to add "
"server."
).format(
prefix=W.prefix("error"),
color=W.color("chat_server"),
server=server.name,
ncolor=W.color("reset"),
)
W.prnt("", message)
server = None
return
if port:
return_code = W.config_option_set(
server.config._option_ptrs["port"], port, 1
)
if return_code == W.WEECHAT_CONFIG_OPTION_SET_ERROR:
remove_server(server)
message = (
"{prefix}Failed to set port for server "
"{color}{server}{ncolor}, failed to add "
"server."
).format(
prefix=W.prefix("error"),
color=W.color("chat_server"),
server=server.name,
ncolor=W.color("reset"),
)
W.prnt("", message)
server = None
return
if len(args) >= 3:
user = args[2]
return_code = W.config_option_set(
server.config._option_ptrs["username"], user, 1
)
if return_code == W.WEECHAT_CONFIG_OPTION_SET_ERROR:
remove_server(server)
message = (
"{prefix}Failed to set user for server "
"{color}{server}{ncolor}, failed to add "
"server."
).format(
prefix=W.prefix("error"),
color=W.color("chat_server"),
server=server.name,
ncolor=W.color("reset"),
)
W.prnt("", message)
server = None
return
if len(args) == 4:
password = args[3]
return_code = W.config_option_set(
server.config._option_ptrs["password"], password, 1
)
if return_code == W.WEECHAT_CONFIG_OPTION_SET_ERROR:
remove_server(server)
message = (
"{prefix}Failed to set password for server "
"{color}{server}{ncolor}, failed to add "
"server."
).format(
prefix=W.prefix("error"),
color=W.color("chat_server"),
server=server.name,
ncolor=W.color("reset"),
)
W.prnt("", message)
server = None
return
message = (
"matrix: server {color}{server}{ncolor} " "has been added"
).format(
server=server.name,
color=W.color("chat_server"),
ncolor=W.color("reset"),
)
W.prnt("", message)
def matrix_server_command(command, args):
def list_servers(_):
if SERVERS:
W.prnt("", "\nAll matrix servers:")
for server in SERVERS:
W.prnt(
"",
" {color}{server}".format(
color=W.color("chat_server"), server=server
),
)
# TODO the argument for list and listfull is used as a match word to
# find/filter servers, we're currently match exactly to the whole name
if command == "list":
list_servers(args)
elif command == "listfull":
matrix_server_command_listfull(args)
elif command == "add":
matrix_server_command_add(args)
elif command == "delete":
matrix_server_command_delete(args)
else:
message = (
"{prefix}matrix: Error: unknown matrix server command, "
'"{command}" (type /matrix help server for help)'
).format(prefix=W.prefix("error"), command=command)
W.prnt("", message)
@utf8_decode
def matrix_command_cb(data, buffer, args):
def connect_server(args):
for server_name in args:
if check_server_existence(server_name, SERVERS):
server = SERVERS[server_name]
server.connect()
def disconnect_server(args):
for server_name in args:
if check_server_existence(server_name, SERVERS):
server = SERVERS[server_name]
if server.connected or server.reconnect_time:
# W.unhook(server.timer_hook)
# server.timer_hook = None
server.access_token = ""
server.disconnect(reconnect=False)
split_args = list(filter(bool, args.split(" ")))
if len(split_args) < 1:
message = (
"{prefix}matrix: Too few arguments for command "
'"/matrix" '
"(see /help matrix)"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_ERROR
command, args = split_args[0], split_args[1:]
if command == "connect":
connect_server(args)
elif command == "disconnect":
disconnect_server(args)
elif command == "reconnect":
disconnect_server(args)
connect_server(args)
elif command == "server":
if len(args) >= 1:
subcommand, args = args[0], args[1:]
matrix_server_command(subcommand, args)
else:
matrix_server_command("list", "")
elif command == "help":
matrix_command_help(args)
else:
message = (
"{prefix}matrix: Error: unknown matrix command, "
'"{command}" (type /help matrix for help)'
).format(prefix=W.prefix("error"), command=command)
W.prnt("", message)
return W.WEECHAT_RC_OK
@utf8_decode
def matrix_send_anyways_cb(data, buffer, args):
for server in SERVERS.values():
if buffer in server.buffers.values():
room_buffer = server.find_room_from_ptr(buffer)
if not server.connected:
room_buffer.error("Server is disconnected")
break
if not server.client.logged_in:
room_buffer.error("You are not logged in.")
return W.WEECHAT_RC_ERROR
if not room_buffer.last_message:
room_buffer.error("No previously sent message found.")
break
server.room_send_message(
room_buffer,
room_buffer.last_message,
"m.text",
ignore_unverified_devices=True
)
room_buffer.last_message = None
break
else:
message = (
"{prefix}matrix: The 'send-anyways' command needs to be "
"run on a matrix room buffer"
).format(prefix=W.prefix("error"))
W.prnt("", message)
return W.WEECHAT_RC_ERROR
@utf8_decode
def matrix_cursor_reply_signal_cb(data, signal, ht):
tags = ht["_chat_line_tags"].split(",")
W.command("", "/cursor stop")
if "matrix_message" in tags:
for tag in tags:
if tag.startswith("matrix_id_"):
matrix_id = tag[10:]
break
else:
return W.WEECHAT_RC_OK
buffer_name = ht["_buffer_full_name"]
bufptr = W.buffer_search("==", buffer_name)
current_input = W.buffer_get_string(bufptr, "input")
input_pos = W.buffer_get_integer(bufptr, "input_pos")
new_prefix = "/reply-matrix {} ".format(matrix_id)
W.buffer_set(bufptr, "input", new_prefix + current_input)
W.buffer_set(bufptr, "input_pos", str(len(new_prefix) + input_pos))
return W.WEECHAT_RC_OK
|