Compare commits
1168 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2cc439853f | |||
| 76b2937c18 | |||
| f2a9f4ab33 | |||
| ec375e79d7 | |||
| 338a4d9761 | |||
| 83d457f2b3 | |||
| 3507095572 | |||
| 4e7cf481fd | |||
| 0915bb9402 | |||
| 7c5d1c2959 | |||
| 8aecf1f84b | |||
| 2c45d8dd5b | |||
| fac337eaf1 | |||
| e7d8948334 | |||
| 6b8831872c | |||
| 4e8c373d1b | |||
| 8865dab6b0 | |||
| e4a2bd2f69 | |||
| a132916525 | |||
| a9dcb34b2d | |||
| 74c43355e4 | |||
| 7255e86595 | |||
| e4098a226e | |||
| 5dea5977ad | |||
| 1c9a30773e | |||
| e276944b40 | |||
| 2e14991815 | |||
| 3083727aff | |||
| d778c639dc | |||
| 10de186598 | |||
| 64107fab17 | |||
| 52bfbddcca | |||
| 5d9cc490d7 | |||
| 13cac8db9a | |||
| 3ab5e4d8cc | |||
| 7e728dd5af | |||
| 597d2e3282 | |||
| 57611a3f30 | |||
| ec64c83cb0 | |||
| ecdaaea3b9 | |||
| bda41417aa | |||
| 5a76b5bcdc | |||
| 4edd8eaa7b | |||
| 742a925040 | |||
| bcede7710f | |||
| c02f67e0d1 | |||
| 31650aac96 | |||
| 730f6bab6f | |||
| f923552f86 | |||
| eca1032d16 | |||
| 570372fa83 | |||
| 5ed09ad783 | |||
| c385aa0b8d | |||
| ec152cbd9d | |||
| b36fc35e04 | |||
| 198e77cae9 | |||
| 9c4beb29a5 | |||
| 6accb530c6 | |||
| 1a77ba5fcd | |||
| 7e9dd8b895 | |||
| 78fcacf7aa | |||
| 077f5d588b | |||
| 8b73c67836 | |||
| 92fa05cb06 | |||
| 18f5a33279 | |||
| f9a6e9c4fb | |||
| abfefab545 | |||
| 79f8c520bd | |||
| fa35ed1cb6 | |||
| 2e8d612078 | |||
| 4801b0f323 | |||
| 783c94dadd | |||
| c8cf662ad0 | |||
| cd70e6b836 | |||
| 72cfbf71f8 | |||
| cb36800c75 | |||
| 559c504e8b | |||
| de3a37f40c | |||
| 6020cdf8bf | |||
| 429cb07b79 | |||
| 2cf93c5765 | |||
| db41c8d806 | |||
| 5313369d85 | |||
| c8c17dac01 | |||
| bbb864773f | |||
| 4767fec86e | |||
| 6d57f070f9 | |||
| 97d47d80ee | |||
| 35f59b5f95 | |||
| 697fb06909 | |||
| efd536357c | |||
| 2c917a559c | |||
| b97c1a1b59 | |||
| 9237046b96 | |||
| 646bbceb99 | |||
| e9e164c679 | |||
| 033c6c698a | |||
| 3d403c2471 | |||
| b22e3d2573 | |||
| 7d20c5b732 | |||
| 2ce2337674 | |||
| 3fe26ae4dd | |||
| 6f4faf7a58 | |||
| e1dcfb76f4 | |||
| f658f2c5b7 | |||
| dd7eed834c | |||
| e4f8b22bc6 | |||
| 0b8fa5ea06 | |||
| 140fcae403 | |||
| 95920728f4 | |||
| e85be95d2d | |||
| 3006b3ab3b | |||
| d4d6cfa87d | |||
| b8cfcbe5ee | |||
| 9875833c90 | |||
| 38d94484bb | |||
| 0b3014ff88 | |||
| 04c64949e7 | |||
| be59d50678 | |||
| 04e2497dd3 | |||
| 2e27e85ac5 | |||
| 2c59cb4871 | |||
| 64ddd07171 | |||
| 1b91fbc806 | |||
| 2b6cffc8ef | |||
| 5cc0afef85 | |||
| 52adbb7335 | |||
| dd3bdd2846 | |||
| f088599dec | |||
| fe573865aa | |||
| 5316ed57af | |||
| 1567239ae6 | |||
| 24c65f8942 | |||
| 213e63830d | |||
| efe532e4d0 | |||
| 8392f46db9 | |||
| 87cacc9b20 | |||
| d808893274 | |||
| ab671ac7eb | |||
| 2343e85f4d | |||
| 70a6b847e2 | |||
| a3f6bc2acb | |||
| 1bce95586b | |||
| 80aa557e0c | |||
| 686e26a503 | |||
| a33cdae4c3 | |||
| 258f665338 | |||
| 3b70829d72 | |||
| 524f60ab48 | |||
| fdc58ce450 | |||
| a4595b427d | |||
| 522e33be12 | |||
| 146a79b516 | |||
| 4f85cf1723 | |||
| d35799e2ce | |||
| a003e2e979 | |||
| f4b8e85689 | |||
| 6b94097f29 | |||
| 6e1dbf3a8e | |||
| 0dc56aad1c | |||
| a565853c5e | |||
| ac56ee1553 | |||
| 349914f447 | |||
| 2a1bddf5e4 | |||
| 668dad9c6f | |||
| 2b978be79c | |||
| 66917b6db0 | |||
| 292745866d | |||
| f86fabafbe | |||
| 48a624bd07 | |||
| 66c2e779ea | |||
| f84dcb64d3 | |||
| 95bb974ca6 | |||
| 953ef0e5bc | |||
| 1b2024e456 | |||
| e961c3a9ed | |||
| 22d50208d8 | |||
| b43cc72de2 | |||
| a06691b214 | |||
| 3461ee6a72 | |||
| 8662db67b8 | |||
| 321a7810c4 | |||
| eae7bba649 | |||
| 92c572d761 | |||
| 868ebf2025 | |||
| 9f9182c564 | |||
| c62774f1a6 | |||
| eace9b4ef6 | |||
| bc4610af04 | |||
| 729fa8eb46 | |||
| 8ca78e21b6 | |||
| b17454723e | |||
| 5e8aa8818f | |||
| ffcfd019c2 | |||
| 7298d9dfdc | |||
| be3b135cc7 | |||
| 9848f8b92c | |||
| 59eb7376c9 | |||
| ea017467fd | |||
| 2c0a2e694b | |||
| 993354bce5 | |||
| 8299b68b96 | |||
| bf9f9e1064 | |||
| 5cf8a7a8a4 | |||
| da91df5754 | |||
| 341b69ed75 | |||
| a7a3ce4ea1 | |||
| f83d03fb16 | |||
| 34e1935a97 | |||
| 0080b028bf | |||
| 689d84fa78 | |||
| 64c9759de8 | |||
| 31cac3eef3 | |||
| 4e670a8cbe | |||
| bbfcc9d7d8 | |||
| 29cc98a7f5 | |||
| 8e54d2e253 | |||
| dd69204f5a | |||
| 44a102c3b1 | |||
| f487853954 | |||
| a29d9cf4ff | |||
| 3fa6ed74e5 | |||
| d3c1c2be6c | |||
| f274fe1cf6 | |||
| f358eab214 | |||
| 59d76148dc | |||
| 489e520ddd | |||
| 60ecb03f64 | |||
| 8a99e67c6d | |||
| 482a52cb5e | |||
| ba13c5cae1 | |||
| 4b57be3917 | |||
| 9383e5eed2 | |||
| a3b4a5e30e | |||
| 72a45d7d80 | |||
| bcf464428a | |||
| f3b9f4bf73 | |||
| 10e54ed789 | |||
| 35da8df526 | |||
| fb1ab220ff | |||
| 2dd39fddf0 | |||
| 7f69e9f329 | |||
| 3f6a4237ad | |||
| ee04e8c17f | |||
| 7d75c15027 | |||
| 312a44d361 | |||
| 85d38e3db6 | |||
| 3a25ee2c93 | |||
| a4d49a41e0 | |||
| 7ba9e10f0f | |||
| 05e966011e | |||
| 9081f6bce4 | |||
| c126e8b615 | |||
| f454803ef7 | |||
| 40beb8f752 | |||
| 4d8d332732 | |||
| 7fb771b992 | |||
| d0900a95a7 | |||
| 8552d463a1 | |||
| 74d130644c | |||
| 976e0dd2b7 | |||
| 340c25ba0b | |||
| 7e8d4bc9a8 | |||
| 429544373a | |||
| 80dd6fa9e1 | |||
| 45ac120407 | |||
| 2c100ca1e5 | |||
| c54bd9e1ce | |||
| a2a35e481a | |||
| 84ff0c777d | |||
| 37ecd57a9b | |||
| 8578a9bd01 | |||
| 6b64f38fa3 | |||
| ea9206f56b | |||
| 467c0989e1 | |||
| 2a0d44acc5 | |||
| a9b28b54d5 | |||
| c296a5d4a4 | |||
| 10926a1240 | |||
| 992e962df7 | |||
| 7726925771 | |||
| a53b0e9837 | |||
| 26eb2d4e54 | |||
| b53b27cf2d | |||
| cecda22ec3 | |||
| dc5fe62e3a | |||
| c957989abb | |||
| 708fec6886 | |||
| 32db2355a2 | |||
| c1d4e8e482 | |||
| a00c58e521 | |||
| 698b56afcf | |||
| af285c5ffe | |||
| 37917c497e | |||
| 50ec2551f8 | |||
| 4519c88230 | |||
| d84724b8b0 | |||
| 56d21bdf59 | |||
| 260c1612a6 | |||
| 6ab3106b38 | |||
| c79d442158 | |||
| 7a6de144ce | |||
| 5240999f56 | |||
| 0a94e60e22 | |||
| c83fdab502 | |||
| ca0c2fd9e6 | |||
| a0c842acb6 | |||
| ba17246755 | |||
| af766449d2 | |||
| 30052b4d74 | |||
| 9f02b6edb0 | |||
| 22e24e6e6c | |||
| 48bc1995bb | |||
| 854e289bba | |||
| db9d55a5cc | |||
| cca0efbd8d | |||
| 596446d14b | |||
| 578bc7cd5a | |||
| d58eb52944 | |||
| 906d8322e3 | |||
| c2be26adb2 | |||
| cf88823e6f | |||
| 2fbee75453 | |||
| 07edcc4867 | |||
| 65d7934c21 | |||
| 842d98dc1c | |||
| b7e69ddc61 | |||
| 2dc6041bd7 | |||
| b007646d4b | |||
| 5580f3dc81 | |||
| 82f7905367 | |||
| 1d8699054c | |||
| 32c521cb79 | |||
| b4cf8cd451 | |||
| 80ff9d0f66 | |||
| b0e60e60e4 | |||
| c4b9a76931 | |||
| fe52f0ad10 | |||
| a9abf9a1af | |||
| 815f9605f9 | |||
| 9a9d6fc0bb | |||
| 2f691bf1b8 | |||
| 50984dab14 | |||
| 6f6ce4bcc7 | |||
| 119729393c | |||
| 9f3869e878 | |||
| 9fb2a73ec5 | |||
| 64b3699b3c | |||
| 76ad31a3bc | |||
| 71cdee5a4d | |||
| 2ae4b23528 | |||
| 39927ac6c0 | |||
| 3e6e59db29 | |||
| 36e2c6f66f | |||
| 69d56f4632 | |||
| af0f731a8a | |||
| cf8c05e1c5 | |||
| 7d5e307368 | |||
| 701b28c33c | |||
| a239ca439a | |||
| 578af19baa | |||
| 792ed007b5 | |||
| 539c2338fc | |||
| 792694b2d9 | |||
| 8e20d56091 | |||
| 1986142db3 | |||
| c52df5dc36 | |||
| 617d44ed75 | |||
| 91e6a73f33 | |||
| 25d7087d07 | |||
| f72267e81d | |||
| ab3b0f3c3c | |||
| 883c4dcf19 | |||
| a5aa73dea6 | |||
| ed90c2667a | |||
| 87d9477bc7 | |||
| b854119445 | |||
| 0e56ab131e | |||
| e319417fbc | |||
| 9e831689e9 | |||
| 0a5f4e6551 | |||
| aaf158cc29 | |||
| 2c2dd37275 | |||
| 4d4a3b6bf6 | |||
| b6b1d72ecb | |||
| 6fa44ce5e9 | |||
| 90e7a303ab | |||
| 54256be459 | |||
| 1c662c55cc | |||
| abd1adaabf | |||
| 5411de90fc | |||
| f9a692b5ef | |||
| 9205ef8024 | |||
| 4260afaa7e | |||
| ef3a60397f | |||
| 8acc51116d | |||
| cbbc5e8500 | |||
| 0192fb8308 | |||
| 3841528f5a | |||
| 91c3825ae3 | |||
| 8c26dd8382 | |||
| 01b317484f | |||
| 73a6ad2cf2 | |||
| 574312d7c5 | |||
| 6cb8e007aa | |||
| 22f6a12842 | |||
| c15508150a | |||
| a0f12a2c48 | |||
| c919a1762b | |||
| 6dc73bf710 | |||
| 623b802d56 | |||
| 0726289c7a | |||
| d2edf12fdf | |||
| 9694fb901a | |||
| a8982cf8c7 | |||
| f430ed7169 | |||
| 4f5a501be4 | |||
| 6c312efc9a | |||
| 1b987be562 | |||
| c84536fef7 | |||
| 1044298d76 | |||
| 4e971932d1 | |||
| 4834e2297a | |||
| 2a3f70eb4a | |||
| ea633ce3f9 | |||
| f6b64126cf | |||
| 9d3c15f284 | |||
| 7d224ec5ac | |||
| ed4e34b808 | |||
| f5c008c1a7 | |||
| dc71f74c0c | |||
| d5470de8fd | |||
| dff5903c53 | |||
| fc241b1cdc | |||
| 77ba732eec | |||
| 835175aa36 | |||
| 2e2827717d | |||
| 209f85c17e | |||
| 37c373c51f | |||
| 62fe03e8c1 | |||
| 427c28db7a | |||
| 835b363661 | |||
| df67ed57ee | |||
| 43b3cc2ca4 | |||
| 3c2268870b | |||
| fbb1267609 | |||
| 2c443a3b93 | |||
| 13fd8db0b7 | |||
| cdee0df5ab | |||
| 9e418afe64 | |||
| 7d43eb5d2e | |||
| de4c16431d | |||
| d3e6860b1c | |||
| 6bccf5595b | |||
| 35023efbf2 | |||
| d33460e3bd | |||
| eea059c0d3 | |||
| 2a327cc29e | |||
| 1ac1bf5b60 | |||
| ad5cace75b | |||
| bf49843721 | |||
| 25d9e3b1ca | |||
| dc07b2bdf4 | |||
| 0093acb578 | |||
| b89ecf4c03 | |||
| 468412100c | |||
| ea7e4b277f | |||
| 60e35c1bb9 | |||
| 117bb5bd86 | |||
| e8ba274776 | |||
| 76a1e20f13 | |||
| 8cab2fdcb6 | |||
| 354fcdc84b | |||
| 99e26a5805 | |||
| d354d6e788 | |||
| 28bcf479f3 | |||
| e3f8fc0e01 | |||
| e8184f0248 | |||
| 937de0fa00 | |||
| ac24bc86a0 | |||
| 1338a43c03 | |||
| 8889105d5a | |||
| 9cbe6b73fc | |||
| ff98fe38c2 | |||
| 9899c15d36 | |||
| 601b29c28b | |||
| 76e16b365d | |||
| 1021e8bc00 | |||
| 4f740fc9f8 | |||
| 75fc5c6e1e | |||
| 47cf63e0e6 | |||
| b4a1aacd12 | |||
| ad499b977e | |||
| b5c55f4e65 | |||
| 65b69829d7 | |||
| cf6eb604bd | |||
| 8655f5903a | |||
| 45f1dddb81 | |||
| 299d20aac9 | |||
| 43d16474c2 | |||
| ee08458df1 | |||
| c80958a776 | |||
| 13d8a8420a | |||
| 01a58ad2ed | |||
| a4e66e708a | |||
| 66e0698d2f | |||
| 935694cb64 | |||
| e2404f919e | |||
| c9810dd9eb | |||
| 6bfd3eada4 | |||
| 6852bae7f9 | |||
| 8536bdd614 | |||
| bd13c73f2f | |||
| 2a9ab569b4 | |||
| d6ebce0425 | |||
| 3af306abe0 | |||
| 30563f3648 | |||
| d6a2e7a9f7 | |||
| 32d686e908 | |||
| 05f906427e | |||
| d8653961af | |||
| d521bbc0fa | |||
| 281f7203dc | |||
| dd683af5f5 | |||
| 9a5506d901 | |||
| 5fc2907392 | |||
| 1443082991 | |||
| d4e3956941 | |||
| e3a457f84c | |||
| e40cd9f6a2 | |||
| eef498d47a | |||
| 8d4a9dc231 | |||
| e0d3c940f8 | |||
| be6d395ed6 | |||
| 87aa0b6659 | |||
| bb167b14ef | |||
| 351866d9e4 | |||
| 9a8f8433b0 | |||
| 4942789213 | |||
| 0741265837 | |||
| 06d4e1703e | |||
| 41be2a7b78 | |||
| 610d12283d | |||
| fee8da1613 | |||
| 28bed96e40 | |||
| 050800f5f7 | |||
| 21fe94b38c | |||
| ce639c12d8 | |||
| 78dd4e0086 | |||
| 0f7eebd683 | |||
| 860b635188 | |||
| 0710b4e8a1 | |||
| 823abc121e | |||
| 3fa6128561 | |||
| ca00e53a40 | |||
| 0003d2efd3 | |||
| 0efe9f05f2 | |||
| 88d0c5feb3 | |||
| 912aa38063 | |||
| 5fba658c66 | |||
| 070601689a | |||
| bde177fc34 | |||
| a593f71901 | |||
| 107fc501e4 | |||
| cd51fb85cf | |||
| 9591a05361 | |||
| ddfffaf6a2 | |||
| baffe1b79e | |||
| 145eb8f611 | |||
| a279835cf8 | |||
| 2dc04a8517 | |||
| 5c076933e7 | |||
| 417c2e4d1e | |||
| cbfb4d6d32 | |||
| 99ac768778 | |||
| 7177d0c37e | |||
| ff257fcd77 | |||
| 47243334f4 | |||
| 1693b643a7 | |||
| 9790dff27e | |||
| ab1d65e6f0 | |||
| 5bbadbbdc8 | |||
| ce92cd31bf | |||
| 8689d0e8b0 | |||
| f47e548b04 | |||
| 6fef2a9a87 | |||
| bc3ceab039 | |||
| b9a0e6cbb6 | |||
| c50fd4b3ac | |||
| 430f7b7217 | |||
| 72a3cea948 | |||
| fce22b08e9 | |||
| a2e64b4e0b | |||
| 1df87447bd | |||
| 75b2b3b163 | |||
| 80d90f93cd | |||
| e1ac4233c7 | |||
| 46c3bbff3c | |||
| 41b8292f25 | |||
| 366b95c8e8 | |||
| fecf068455 | |||
| 1da1133934 | |||
| c4ac84c1a1 | |||
| 2cf9dcafd9 | |||
| 784abcba4e | |||
| aaa44fb7aa | |||
| f7a4a23045 | |||
| 7e3c892ff6 | |||
| 36a654bcfe | |||
| e16182ee6a | |||
| 7c46bf4b9e | |||
| 7c82580b4b | |||
| 1e1e9b03c0 | |||
| 0587145145 | |||
| 7840da94b5 | |||
| 010866e0d0 | |||
| c54b057d90 | |||
| b55f3a9c4d | |||
| aa09e738e6 | |||
| 4254b85628 | |||
| 7d5e946067 | |||
| 9eda525d2a | |||
| 8ef337f40b | |||
| f5ac584ed5 | |||
| a3534d802a | |||
| 92b689255b | |||
| fb5167963a | |||
| 50ac4b6381 | |||
| d842fc73cb | |||
| 531d118ed0 | |||
| cead705c21 | |||
| e5a2afee37 | |||
| f2efb235eb | |||
| ffc1a5ad8f | |||
| 1c3764b099 | |||
| 5af045844e | |||
| be255ec7af | |||
| 7f7dec4e80 | |||
| 8a6687d00c | |||
| 1b719027e6 | |||
| d661f7b798 | |||
| e437869c13 | |||
| c979de9387 | |||
| be806949bf | |||
| 1c08725ade | |||
| bb939bc4cd | |||
| c88b28606e | |||
| 172dc91ec1 | |||
| 3a46bb4920 | |||
| aba2e6b140 | |||
| d678cdfff4 | |||
| 218752bb40 | |||
| 17b711d097 | |||
| 346090f7dc | |||
| 20dd6f8383 | |||
| c31e0a50b5 | |||
| c2172aa562 | |||
| 9174186442 | |||
| 8ef82abe9d | |||
| 9e58b6572e | |||
| 311e443d21 | |||
| 6a8fceff5b | |||
| 6ceb7f735c | |||
| 5c8f2034c3 | |||
| f8e429f08a | |||
| e84c793ba6 | |||
| 0812c9a3bc | |||
| 0d0b043bb8 | |||
| 16d3458e5a | |||
| f775e40b16 | |||
| cf847d3b8e | |||
| 53489e7356 | |||
| c028e1befc | |||
| 790bb04ae5 | |||
| 165f286bfd | |||
| 05dfe8c4a3 | |||
| ea37f05c11 | |||
| 379f428961 | |||
| 88ac3051f3 | |||
| 99f4fc8339 | |||
| 2480578bd9 | |||
| 5ae143c98e | |||
| 1473956a8a | |||
| 01426308c5 | |||
| a090d6de32 | |||
| e9ddd0caa8 | |||
| a258c59ca3 | |||
| 8021fcc24c | |||
| 55f7cbb1bb | |||
| dad0ccb3c0 | |||
| 06f1bcfb3f | |||
| 2e20ae2148 | |||
| 09676f8314 | |||
| 75b6e4f633 | |||
| 1bebdcba89 | |||
| c589f34986 | |||
| e970dadb6f | |||
| 0c0f7905da | |||
| af8bb6aa4d | |||
| ca132a6d18 | |||
| f519ea0193 | |||
| 1ae4a63d4e | |||
| 5c4db8df5b | |||
| 85eca1a75e | |||
| c3a21388f4 | |||
| 082ef79346 | |||
| 85dc424ea0 | |||
| b2e183e363 | |||
| e548836d38 | |||
| 4a2bb3d7fc | |||
| 65e0ebdb37 | |||
| d3d02f173a | |||
| c39d24ccdc | |||
| 1994ce38eb | |||
| 9aad6de823 | |||
| 3d3afdb645 | |||
| 983f5001ab | |||
| a80fdf0990 | |||
| 82d7e78455 | |||
| d514b929b3 | |||
| 720210ac08 | |||
| 2dfc05db5f | |||
| d551934ec1 | |||
| bac1e30cf0 | |||
| 8fdb2c4e57 | |||
| 8da1fb78b8 | |||
| cea8163366 | |||
| 388e4f8601 | |||
| 2756873c53 | |||
| a770e1f67e | |||
| f8c844c4c0 | |||
| 7f23d4cf68 | |||
| 247c75191b | |||
| 4f3e1b4fe6 | |||
| 6291e92ed7 | |||
| 5054afcbb5 | |||
| 980e0d6ef7 | |||
| 2f6147f325 | |||
| 56fb88b75e | |||
| 24bdda8ca1 | |||
| c38e46fc2a | |||
| 916cc3746d | |||
| a32bc2985a | |||
| 8d982b4615 | |||
| 10e77707d0 | |||
| b0fe208768 | |||
| b44d6d2d90 | |||
| 828047e272 | |||
| a9cb1bf518 | |||
| d71f421981 | |||
| 26e947992e | |||
| 78e4804774 | |||
| 5ccd1bc2fe | |||
| f758884c75 | |||
| 9d2d34a25c | |||
| fc23461445 | |||
| 5253504df9 | |||
| dd270b862e | |||
| 5bc1362493 | |||
| 96a0c923c2 | |||
| 23bb2871fd | |||
| d4ea5f8b38 | |||
| 4b2cdc3d39 | |||
| 4c54d9c9ea | |||
| 9541d5eceb | |||
| c9c1023ece | |||
| cb2073eb8b | |||
| d35104aea6 | |||
| ad342f2ca4 | |||
| 29541ff520 | |||
| 6a1c160608 | |||
| 731c802fcd | |||
| b6f15934f2 | |||
| 068449c59c | |||
| 4f36a2c7c1 | |||
| bb04231880 | |||
| 1ef790ce31 | |||
| 65490f3cf4 | |||
| ec43b5c822 | |||
| 81531235bc | |||
| 66683151ec | |||
| e751d140f2 | |||
| 0f8009b1e9 | |||
| 01e153662e | |||
| 08dd5b5b15 | |||
| c9ffd23729 | |||
| ccd2eaec70 | |||
| 79cdc2e952 | |||
| d5193438de | |||
| 0d22f7a6e3 | |||
| b36f962761 | |||
| ff3da70494 | |||
| 0848938174 | |||
| a82a124b11 | |||
| 1b7a10218a | |||
| 6c8cfc1b26 | |||
| 9b0be2dd55 | |||
| 704e00540e | |||
| 14b105e74f | |||
| f2390c4937 | |||
| 83a9de164e | |||
| a27af08410 | |||
| fd6e22fa5c | |||
| 9d6c3a2ed3 | |||
| 629a406051 | |||
| 1421ae0cce | |||
| 3cca11a997 | |||
| c08659c75a | |||
| d5f6e45363 | |||
| dbfb980bde | |||
| ae334b9a04 | |||
| 55b6773b5e | |||
| a22b83de44 | |||
| c5bec37401 | |||
| aaa4f96805 | |||
| 4736686454 | |||
| f3e1c755eb | |||
| ab098879fd | |||
| 76410ee7cb | |||
| af46aee191 | |||
| e4e100a184 | |||
| 54d7ac5542 | |||
| 54287c344f | |||
| ecdca21e32 | |||
| 2b92483c50 | |||
| ad7b7f5c06 | |||
| 340360e6a0 | |||
| 64d726ec2b | |||
| e4ce73cbba | |||
| 88d50879d5 | |||
| c8e44d4ab4 | |||
| e9348c9550 | |||
| d4b725a508 | |||
| 9830842707 | |||
| 6926bce139 | |||
| 0625b2d661 | |||
| 8aae5beb27 | |||
| 122699593d | |||
| 996e8ab445 | |||
| 23232cf88c | |||
| 87dc1a44b2 | |||
| dfca56b292 | |||
| c4b41f0a5c | |||
| 4d63cd75d4 | |||
| 64391ae20d | |||
| c55967c9f0 | |||
| c2879408cc | |||
| a46cc7a788 | |||
| 9f4f63f084 | |||
| e71f7280b8 | |||
| b4dd05ab04 | |||
| 2aa0ed3825 | |||
| bfaec2eb81 | |||
| 0f1ac98b9f | |||
| 2a65ccc674 | |||
| e16e53c261 | |||
| 96ac0a0b17 | |||
| 6cef4d81c6 | |||
| cea5210290 | |||
| 4cef2be0db | |||
| 34cc810d62 | |||
| bbc7912a49 | |||
| 2b5426fda3 | |||
| d97281bcdc | |||
| 298e326de7 | |||
| 90e7a09b7e | |||
| f6fb37f5da | |||
| ac4d7cc412 | |||
| 94a2344f3b | |||
| 998e2fa19c | |||
| 5082cd1c94 | |||
| 48665acf1d | |||
| bc160e0593 | |||
| 1fd920255f | |||
| c0ceb1b2b0 | |||
| f07009d0d2 | |||
| fa30cb5c1f | |||
| 5d48040eb8 | |||
| f6923a5e1b | |||
| 15fd394d54 | |||
| 1d9455f639 | |||
| 042d89cf65 | |||
| 7515b31164 | |||
| 99f84b5dfe | |||
| 2172587286 | |||
| 193c4409ee | |||
| 74bc89475e | |||
| 7c2e689813 | |||
| 0a171d242f | |||
| 7a4d29e1e4 | |||
| ecf0e262df | |||
| d035e9da73 | |||
| 74f3956608 | |||
| 62b66040e7 | |||
| 8a198e67a8 | |||
| d9e4cc9d4e | |||
| 371c6813de | |||
| 0f8a2e7c51 | |||
| 895f9ac98a | |||
| 86bda1bb45 | |||
| 99f0c02766 | |||
| 4a0d00e74c | |||
| f5c4b477e5 | |||
| b50558a37d | |||
| ad23445b69 | |||
| f473c02bc3 | |||
| f1b52e7465 | |||
| e6e6af0689 | |||
| 7a7c0b780f | |||
| 3775206ab3 | |||
| 1d54d6755c | |||
| 42fc48adfe | |||
| 3068d41570 | |||
| f51d43b999 | |||
| fb43f13ed5 | |||
| 25b1adf626 | |||
| 17aefd02da | |||
| b127afbf9b | |||
| b8f2c9a8f7 | |||
| d466060c44 | |||
| 42056b91c5 | |||
| 68e6a70234 | |||
| 642ea2baae | |||
| 005daa9ee2 | |||
| dad99823fc | |||
| 0d264e09a8 | |||
| 7029102c0f | |||
| 708110eb08 | |||
| c0da861562 | |||
| 844cf14bcd | |||
| fe32475e10 | |||
| f28f5915a4 | |||
| 1aa80c1a8f | |||
| 5d9b94fa5f | |||
| 6ef31599e9 | |||
| e961e0bcc6 | |||
| dc85754b1e | |||
| 04e2c03dae | |||
| 42d54dac5b | |||
| 767a51f994 | |||
| 313b5e5d07 | |||
| 961707dd30 | |||
| 90197f1a40 | |||
| 53a7111550 | |||
| 78d1f92c13 | |||
| 37b13fe31b | |||
| 39c9548983 | |||
| 606686ce84 | |||
| 649f8aa9a4 | |||
| 13db0eea93 | |||
| adbd048108 | |||
| 1639099401 | |||
| 7a373fa556 | |||
| 1f5261ff8f | |||
| 0833850f4f | |||
| 87a715aa10 | |||
| ea209498ba | |||
| 79341b8d28 | |||
| fd763b953d | |||
| 949c380235 | |||
| 81d982d254 | |||
| f7dfbbf3f4 | |||
| 1e0f2c72b5 | |||
| 73e7b8f635 | |||
| 8354bf6bb5 | |||
| db5441c3eb | |||
| bb13813952 | |||
| 2c47cdfac6 | |||
| d9dd304b26 | |||
| 45981b9c77 | |||
| c040c0d59c | |||
| 4c26d7e59a | |||
| ae792a7b33 | |||
| a3ed8dbce3 | |||
| d332a429d6 | |||
| 797ff06d10 | |||
| 193dcc714b | |||
| 445d997be8 | |||
| 8da06c969c | |||
| c87f410d3e | |||
| 824725a698 | |||
| 780edd7e57 | |||
| e231c3ec9a | |||
| f5e3b39105 | |||
| fbb9075bbe | |||
| 07f5348ff0 | |||
| 1ce8f08ff2 | |||
| a652fb1d8c | |||
| 41f2f64322 | |||
| 2eba5f687a | |||
| 423731751d | |||
| 92b86deeba | |||
| b4b1951509 | |||
| cc29aec3f6 | |||
| 65174d9998 | |||
| 4804023acf | |||
| 459128a417 | |||
| d40b0b896b | |||
| 006a5971ea | |||
| 4498ab4721 | |||
| 133e4af712 | |||
| 66d68f6b63 | |||
| a1297e90ce | |||
| c24cd8fbb1 | |||
| 59a0ca33ee | |||
| 502a3599fc | |||
| 6c0399ac7b | |||
| 68a743a563 | |||
| 22f430c340 | |||
| 91ae50911e | |||
| 2bf327dbc5 | |||
| 0e23aafa3d | |||
| 87c87f93ef | |||
| 578b025f17 | |||
| 73de61dabf | |||
| c4b2cf3553 | |||
| 733bbb30c3 | |||
| 88a8404898 | |||
| 54d2b4bba8 | |||
| 4448077d43 | |||
| 209d7cbdcc | |||
| 715b658a3d | |||
| 68648d7b5c | |||
| ad9cd27185 | |||
| ad67996d91 | |||
| b06e7932f0 | |||
| 7837f03532 | |||
| 42e33ab54d | |||
| 7f52238fbb | |||
| ae88aa0553 | |||
| 2d63c5b3ce | |||
| 77c57eb64b | |||
| c98e822e6d | |||
| 85a4982ad9 | |||
| b1c85d5cda | |||
| a469e6ed10 | |||
| 517c7d8b70 | |||
| 8bfb416735 | |||
| 9709768b17 | |||
| f6e3903b45 | |||
| b3082da999 | |||
| 61d9d6890a | |||
| 150321a4d7 | |||
| 3eefbc4e34 | |||
| ee8531143f | |||
| 96d3ca106a | |||
| 8d1de218a1 | |||
| cf9a1f3afb | |||
| 2c68bd7378 | |||
| 6ff89d1fe4 | |||
| 30768d0a06 | |||
| 7004da9268 | |||
| 0e6940eea5 | |||
| 7b4b7509f3 | |||
| 8bbd1f7db1 | |||
| a6f26c16fc | |||
| 13dddb4c10 | |||
| 3aff450bae | |||
| 97957a5731 | |||
| fe00145d1c | |||
| e2ba478095 | |||
| ed8c933772 | |||
| a8322992cc | |||
| e8c0312839 | |||
| e98acf39ae | |||
| 26b8efb1e6 | |||
| 8cce7a7c3a | |||
| 6d648d51da | |||
| 57a00468ba | |||
| cd055e1ba7 | |||
| 021b60a45e | |||
| 172e472221 | |||
| 0f706d511a | |||
| f57d1e7311 | |||
| fd4eb7aa49 | |||
| 4237c36dae | |||
| 633aea45d9 | |||
| 08b6f9dbbf | |||
| a9b362943f | |||
| ead445b81f | |||
| 1bea158191 | |||
| 3a22c1463a | |||
| 3a4628cb6e | |||
| 46cac040c7 | |||
| 64b60559ee | |||
| 56e4f00705 | |||
| da3e37ccc0 | |||
| f37ea89e98 | |||
| a41bf286f2 | |||
| 1f6b9bd04a | |||
| 836232db00 | |||
| 14c2312f9a | |||
| 5fa8dea06f | |||
| d5038e6b98 | |||
| 55046e15b2 | |||
| 8a7ccc0007 | |||
| 1372a16459 | |||
| 6c7f687539 | |||
| fed8adae97 | |||
| 566a2b3892 | |||
| 9e5cb84140 | |||
| 9e5843a0dc | |||
| 2aa48f37a9 | |||
| a1ba82c3b7 | |||
| 6fced123b1 | |||
| 22e4a189eb | |||
| c2e4f5596c | |||
| a26f2c2c36 | |||
| 74a0a3b621 | |||
| 5c46aad0d1 | |||
| 2d2fe86757 | |||
| fb37af12b4 | |||
| f635d87ea3 | |||
| 7c54436dff | |||
| 232ec6ee42 | |||
| 3e62a89b30 | |||
| 2f9cd15013 | |||
| aded9d9210 | |||
| 25252c7b79 | |||
| 8e98ca1ce8 | |||
| bbab5a1376 | |||
| caab071a55 | |||
| cf162e76ec | |||
| c1eb907e8a | |||
| 725b3a1182 | |||
| bc1d0c1d2a | |||
| 74935de459 | |||
| b4d23af05d | |||
| 2d13c30a26 | |||
| 29c71b48de | |||
| 03734a6745 | |||
| e96e1459eb | |||
| 1cf0a6b150 | |||
| 6e1d497e66 | |||
| 12d4025752 | |||
| 05853115c6 | |||
| bbc5f99ae9 | |||
| f9d2d32ef0 | |||
| c21a55ebc7 | |||
| 799dfdb2ac | |||
| 092b80ad02 | |||
| 51b868d9ce | |||
| 5930b2e3bb | |||
| 710976c27e | |||
| 0a6130607d | |||
| f926727a8d | |||
| 5c5915ae66 | |||
| f6b18497b4 | |||
| d8dc7c59f4 | |||
| d21ac58929 | |||
| 7f86ec6c5d | |||
| 1a1d7e6d90 | |||
| 4af4f90a3d | |||
| e003151c7b | |||
| ad11abb56e | |||
| 7d2af0ce75 | |||
| f66c182e82 | |||
| 91f34543dc | |||
| 95fad313c5 | |||
| 1560647a5d | |||
| 457df435ac | |||
| 7b0c58aa27 | |||
| 7dc5384d52 | |||
| c1f582f17a | |||
| eef48a9a56 | |||
| d7e40a86c6 | |||
| 4673546b42 | |||
| 2f75fa1cfe |
@@ -0,0 +1,8 @@
|
||||
engines:
|
||||
sonar-python:
|
||||
enabled: true
|
||||
checks:
|
||||
python:S107:
|
||||
enabled: false
|
||||
exclude_patterns:
|
||||
- "alembic/"
|
||||
@@ -0,0 +1,10 @@
|
||||
.editorconfig
|
||||
.codeclimate.yml
|
||||
*.png
|
||||
*.md
|
||||
logs
|
||||
.venv
|
||||
start
|
||||
config.yaml
|
||||
registration.yaml
|
||||
*.db
|
||||
@@ -8,5 +8,11 @@ charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.py]
|
||||
max_line_length = 99
|
||||
|
||||
[*.{yaml,yml,py}]
|
||||
indent_style = space
|
||||
|
||||
[.gitlab-ci.yml]
|
||||
indent_size = 2
|
||||
|
||||
+12
-6
@@ -1,12 +1,18 @@
|
||||
.idea/
|
||||
/.idea/
|
||||
|
||||
.venv
|
||||
/.venv
|
||||
/env/
|
||||
pip-selfcheck.json
|
||||
*.pyc
|
||||
__pycache__
|
||||
/build
|
||||
/dist
|
||||
/*.egg-info
|
||||
/.eggs
|
||||
|
||||
config.yaml
|
||||
registration.yaml
|
||||
/config.yaml
|
||||
/registration.yaml
|
||||
*.log*
|
||||
*.db
|
||||
*.session
|
||||
*.json
|
||||
*.pickle
|
||||
*.bak
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
image: docker:stable
|
||||
|
||||
stages:
|
||||
- build
|
||||
- manifest
|
||||
|
||||
default:
|
||||
before_script:
|
||||
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
|
||||
|
||||
build amd64:
|
||||
stage: build
|
||||
tags:
|
||||
- amd64
|
||||
script:
|
||||
- docker pull $CI_REGISTRY_IMAGE:latest || true
|
||||
- docker build --pull --cache-from $CI_REGISTRY_IMAGE:latest --build-arg TARGETARCH=amd64 --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 .
|
||||
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64
|
||||
- docker rmi $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64
|
||||
after_script:
|
||||
- |
|
||||
if [[ "$CI_COMMIT_BRANCH" == "master" && "$CI_JOB_STATUS" == "success" ]]; then
|
||||
apk add --update curl jq
|
||||
rm -rf /var/cache/apk/*
|
||||
|
||||
jq -n '
|
||||
{
|
||||
password: env.BEEPER_DEV_ADMIN_NIGHTLY_PASS,
|
||||
bridge: env.BEEPER_BRIDGE_TYPE,
|
||||
image: "\(env.CI_REGISTRY_IMAGE):\(env.CI_COMMIT_SHA)-amd64",
|
||||
channel: "STABLE"
|
||||
}
|
||||
' | curl "$BEEPER_DEV_ADMIN_API_URL" -H "Content-Type: application/json" -d @-
|
||||
|
||||
jq -n '
|
||||
{
|
||||
password: env.BEEPER_PROD_ADMIN_NIGHTLY_PASS,
|
||||
bridge: env.BEEPER_BRIDGE_TYPE,
|
||||
image: "\(env.CI_REGISTRY_IMAGE):\(env.CI_COMMIT_SHA)-amd64",
|
||||
channel: "INTERNAL",
|
||||
deployNext: true
|
||||
}
|
||||
' | curl "$BEEPER_PROD_ADMIN_API_URL" -H "Content-Type: application/json" -d @-
|
||||
fi
|
||||
|
||||
build arm64:
|
||||
stage: build
|
||||
tags:
|
||||
- arm64
|
||||
script:
|
||||
- docker pull $CI_REGISTRY_IMAGE:latest || true
|
||||
- docker build --pull --cache-from $CI_REGISTRY_IMAGE:latest --build-arg TARGETARCH=arm64 --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64 .
|
||||
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64
|
||||
- docker rmi $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64
|
||||
|
||||
manifest:
|
||||
stage: manifest
|
||||
before_script:
|
||||
- "mkdir -p $HOME/.docker && echo '{\"experimental\": \"enabled\"}' > $HOME/.docker/config.json"
|
||||
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
|
||||
script:
|
||||
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64
|
||||
- docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64
|
||||
- if [ "$CI_COMMIT_BRANCH" = "master" ]; then docker manifest create $CI_REGISTRY_IMAGE:latest $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64 && docker manifest push $CI_REGISTRY_IMAGE:latest; fi
|
||||
- if [ "$CI_COMMIT_BRANCH" != "master" ]; then docker manifest create $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64 && docker manifest push $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME; fi
|
||||
- docker rmi $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-amd64 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA-arm64
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
[settings]
|
||||
line_length=99
|
||||
indent=4
|
||||
|
||||
multi_line_output=5
|
||||
|
||||
sections=FUTURE,STDLIB,THIRDPARTY,TELETHON,MAUTRIX,FIRSTPARTY,LOCALFOLDER
|
||||
no_lines_before=LOCALFOLDER
|
||||
default_section=FIRSTPARTY
|
||||
|
||||
known_thirdparty=aiohttp,sqlalchemy,alembic,commonmark,ruamel.yaml,PIL,moviepy,prometheus_client,yarl,mako,pkg_resources
|
||||
known_telethon=telethon,alchemysession,cryptg
|
||||
known_mautrix=mautrix
|
||||
|
||||
balanced_wrapping=True
|
||||
length_sort=True
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
FROM dock.mau.dev/tulir/lottieconverter:alpine-3.14
|
||||
|
||||
ARG TARGETARCH=amd64
|
||||
|
||||
RUN apk add --no-cache \
|
||||
python3 py3-pip py3-setuptools py3-wheel \
|
||||
py3-virtualenv \
|
||||
py3-pillow \
|
||||
py3-aiohttp \
|
||||
py3-magic \
|
||||
py3-sqlalchemy \
|
||||
py3-telethon-session-sqlalchemy \
|
||||
py3-alembic \
|
||||
py3-psycopg2 \
|
||||
py3-ruamel.yaml \
|
||||
py3-commonmark \
|
||||
py3-prometheus-client \
|
||||
# Indirect dependencies
|
||||
py3-idna \
|
||||
#moviepy
|
||||
py3-decorator \
|
||||
py3-tqdm \
|
||||
py3-requests \
|
||||
#imageio
|
||||
py3-numpy \
|
||||
#py3-telethon \ (outdated)
|
||||
# Optional for socks proxies
|
||||
py3-pysocks \
|
||||
py3-pyaes \
|
||||
# cryptg
|
||||
py3-cffi \
|
||||
py3-qrcode \
|
||||
py3-brotli \
|
||||
# Other dependencies
|
||||
ffmpeg \
|
||||
ca-certificates \
|
||||
su-exec \
|
||||
netcat-openbsd \
|
||||
# encryption
|
||||
py3-olm \
|
||||
py3-pycryptodome \
|
||||
py3-unpaddedbase64 \
|
||||
py3-future \
|
||||
bash \
|
||||
curl \
|
||||
jq \
|
||||
yq
|
||||
|
||||
COPY requirements.txt /opt/mautrix-telegram/requirements.txt
|
||||
COPY optional-requirements.txt /opt/mautrix-telegram/optional-requirements.txt
|
||||
WORKDIR /opt/mautrix-telegram
|
||||
RUN apk add --virtual .build-deps \
|
||||
python3-dev \
|
||||
libffi-dev \
|
||||
build-base \
|
||||
&& sed -Ei 's/psycopg2-binary.+//' optional-requirements.txt \
|
||||
# TODO: unpin Pillow here after it's updated in Alpine
|
||||
&& pip3 install -r requirements.txt -r optional-requirements.txt 'pillow==8.2' \
|
||||
&& apk del .build-deps
|
||||
|
||||
COPY . /opt/mautrix-telegram
|
||||
RUN apk add git && pip3 install .[speedups,hq_thumbnails,metrics,e2be] && apk del git \
|
||||
# This doesn't make the image smaller, but it's needed so that the `version` command works properly
|
||||
&& cp mautrix_telegram/example-config.yaml . && rm -rf mautrix_telegram
|
||||
|
||||
VOLUME /data
|
||||
ENV UID=1337 GID=1337 \
|
||||
FFMPEG_BINARY=/usr/bin/ffmpeg
|
||||
|
||||
CMD ["/opt/mautrix-telegram/docker-run.sh"]
|
||||
@@ -1,23 +1,21 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
@@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
@@ -72,7 +60,7 @@ modification follow.
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
@@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
@@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
include README.md
|
||||
include LICENSE
|
||||
include requirements.txt
|
||||
include optional-requirements.txt
|
||||
@@ -1,12 +1,33 @@
|
||||
# mautrix-telegram
|
||||
A Matrix-Telegram puppeting bridge.
|
||||

|
||||
[](LICENSE)
|
||||
[](https://github.com/mautrix/telegram/releases)
|
||||
[](https://mau.dev/mautrix/telegram/container_registry)
|
||||
|
||||
### [Wiki](https://github.com/tulir/mautrix-telegram/wiki)
|
||||
A Matrix-Telegram hybrid puppeting/relaybot bridge.
|
||||
|
||||
### [Features & Roadmap](ROADMAP.md)
|
||||
## Sponsors
|
||||
* [Joel Lehtonen / Zouppen](https://github.com/zouppen)
|
||||
|
||||
### Documentation
|
||||
All setup and usage instructions are located on
|
||||
[docs.mau.fi](https://docs.mau.fi/bridges/python/telegram/index.html).
|
||||
Some quick links:
|
||||
|
||||
* [Bridge setup](https://docs.mau.fi/bridges/python/setup/index.html?bridge=telegram)
|
||||
(or [with Docker](https://docs.mau.fi/bridges/python/setup/docker.html?bridge=telegram))
|
||||
* Basic usage: [Authentication](https://docs.mau.fi/bridges/python/telegram/authentication.html),
|
||||
[Creating chats](https://docs.mau.fi/bridges/python/telegram/creating-and-managing-chats.html),
|
||||
[Relaybot setup](https://docs.mau.fi/bridges/python/telegram/relay-bot.html)
|
||||
|
||||
### Features & Roadmap
|
||||
[ROADMAP.md](https://github.com/mautrix/telegram/blob/master/ROADMAP.md)
|
||||
contains a general overview of what is supported by the bridge.
|
||||
|
||||
## Discussion
|
||||
Matrix room: [`#telegram:maunium.net`](https://matrix.to/#/#telegram:maunium.net)
|
||||
|
||||
A Telegram chat bridged to the Matrix room will be created once the bridge supports using a bot
|
||||
for unauthenticated users.
|
||||
Telegram chat: [`mautrix_telegram`](https://t.me/mautrix_telegram) (bridged to Matrix room)
|
||||
|
||||
## Preview
|
||||

|
||||
|
||||
+27
-59
@@ -1,95 +1,63 @@
|
||||
# Features & roadmap
|
||||
|
||||
* Matrix → Telegram
|
||||
* [x] Plaintext messages
|
||||
* [x] Formatted messages
|
||||
* [ ] Bot commands (!command -> /command)
|
||||
* [x] Mentions
|
||||
* [x] Rich quotes
|
||||
* [ ] Locations (not implemented in Riot)
|
||||
* [x] Images
|
||||
* [x] Files
|
||||
* [x] Message content (text, formatting, files, etc..)
|
||||
* [x] Message redactions
|
||||
* [ ] † Presence
|
||||
* [ ] † Typing notifications
|
||||
* [ ] † Read receipts
|
||||
* [ ] Pinning messages
|
||||
* [x] Message edits
|
||||
* [ ] ‡ Message history
|
||||
* [x] Presence
|
||||
* [x] Typing notifications
|
||||
* [x] Read receipts
|
||||
* [x] Pinning messages
|
||||
* [x] Power level
|
||||
* [x] Normal chats
|
||||
* [ ] Non-hardcoded PL requirements
|
||||
* [x] Supergroups/channels
|
||||
* [ ] Precise bridging (non-hardcoded PL requirements, bridge specific permissions, etc..)
|
||||
* [ ] Membership actions
|
||||
* [x] Inviting
|
||||
* [x] Puppets
|
||||
* [x] Matrix users who have logged into Telegram
|
||||
* [x] Kicking
|
||||
* [ ] Joining
|
||||
* [ ] Chat name as alias
|
||||
* [ ] ‡ Chat invite link as alias
|
||||
* [x] Leaving
|
||||
* [x] Membership actions (invite/kick/join/leave)
|
||||
* [x] Room metadata changes (name, topic, avatar)
|
||||
* [x] Initial room metadata
|
||||
* [ ] User metadata
|
||||
* [ ] Initial displayname/username/avatar at register
|
||||
* [ ] ‡ Changes to displayname/avatar
|
||||
* Telegram → Matrix
|
||||
* [x] Plaintext messages
|
||||
* [x] Formatted messages
|
||||
* [x] Bot commands (/command -> !command)
|
||||
* [x] Mentions
|
||||
* [x] Replies
|
||||
* [x] Forwards
|
||||
* [x] Images
|
||||
* [x] Locations
|
||||
* [x] Stickers
|
||||
* [x] Audio messages
|
||||
* [x] Video messages
|
||||
* [x] Documents
|
||||
* [ ] Message deletions (no way to tell difference between user-specific deletion and global deletion)
|
||||
* [ ] Message edits (not supported in Matrix)
|
||||
* [x] Message content (text, formatting, files, etc..)
|
||||
* [ ] Advanced message content/media
|
||||
* [x] Polls
|
||||
* [x] Games
|
||||
* [ ] Buttons
|
||||
* [x] Message deletions
|
||||
* [x] Message edits
|
||||
* [x] Message history
|
||||
* [x] Manually (`!tg backfill`)
|
||||
* [x] Automatically when creating portal
|
||||
* [x] Automatically for missed messages
|
||||
* [x] Avatars
|
||||
* [x] Presence
|
||||
* [x] Typing notifications
|
||||
* [x] Read receipts (private chat only)
|
||||
* [x] Pinning messages
|
||||
* [x] Admin/chat creator status
|
||||
* [ ] Supergroup/channel permissions (precise per-user not supported in Matrix)
|
||||
* [x] Membership actions
|
||||
* [x] Inviting
|
||||
* [x] Kicking
|
||||
* [x] Joining/leaving
|
||||
* [ ] Supergroup/channel permissions (precise per-user permissions not supported in Matrix)
|
||||
* [x] Membership actions (invite/kick/join/leave)
|
||||
* [ ] Chat metadata changes
|
||||
* [x] Title
|
||||
* [x] Avatar
|
||||
* [ ] † About text
|
||||
* [ ] † Public channel username
|
||||
* [x] Initial chat metadata (about text missing)
|
||||
* [x] User metadata
|
||||
* [x] Initial displayname/avatar
|
||||
* [x] Changes to displayname/avatar
|
||||
* [x] User metadata (displayname/avatar)
|
||||
* [x] Supergroup upgrade
|
||||
* Misc
|
||||
* [x] Automatic portal creation
|
||||
* [x] At startup
|
||||
* [x] When receiving invite or message
|
||||
* [x] Private chat creation by inviting Matrix puppet of Telegram user to new room
|
||||
* [ ] Option to use bot to relay messages for unauthenticated Matrix users
|
||||
* [ ] Option to use own Matrix account for messages sent from other Telegram clients
|
||||
* [Commands](https://github.com/tulir/mautrix-telegram/wiki/Management-commands)
|
||||
* [x] Logging in and out (`login` + code entering)
|
||||
* [x] Logging out
|
||||
* [ ] Registering (`register`)
|
||||
* [x] Searching for users (`search`)
|
||||
* [x] Starting private chats (`pm`)
|
||||
* [x] Joining chats with invite links (`join`)
|
||||
* [x] Creating a Telegram chat for an existing Matrix room (`create`)
|
||||
* [x] Upgrading the chat of a portal room into a supergroup (`upgrade`)
|
||||
* [x] Change username of supergroup/channel (`groupname`)
|
||||
* [x] Getting the Telegram invite link to a Matrix room (`invitelink`)
|
||||
* Bridge administration
|
||||
* [x] Clean up and forget a portal room (`deleteportal`)
|
||||
* [ ] Setting Matrix-only power levels (`powerlevel`)
|
||||
* [x] Option to use bot to relay messages for unauthenticated Matrix users (relaybot)
|
||||
* [x] Option to use own Matrix account for messages sent from other Telegram clients (double puppeting)
|
||||
* [ ] ‡ Calls (hard, not yet supported by Telethon)
|
||||
* [ ] ‡ Secret chats (i.e. End-to-bridge encryption on Telegram)
|
||||
* [x] End-to-bridge encryption in Matrix rooms (see [wiki](https://github.com/tulir/mautrix-telegram/wiki/End%E2%80%90to%E2%80%90bridge-encryption))
|
||||
|
||||
† Information not automatically sent from source, i.e. implementation may not be possible
|
||||
‡ Maybe, i.e. this feature may or may not be implemented at some point
|
||||
|
||||
@@ -35,9 +35,6 @@ script_location = alembic
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = sqlite:///mautrix-telegram.db
|
||||
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
+17
-4
@@ -1,19 +1,28 @@
|
||||
from __future__ import with_statement
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
from logging.config import fileConfig
|
||||
|
||||
import sys
|
||||
from os.path import abspath, dirname
|
||||
|
||||
sys.path.insert(0, dirname(dirname(abspath(__file__))))
|
||||
|
||||
from mautrix_telegram.base import Base
|
||||
from mautrix.util.db import Base
|
||||
import mautrix_telegram.db
|
||||
from mautrix_telegram.config import Config
|
||||
from alchemysession import AlchemySessionContainer
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
mxtg_config_path = context.get_x_argument(as_dictionary=True).get("config", "config.yaml")
|
||||
mxtg_config = Config(mxtg_config_path, None, None)
|
||||
mxtg_config.load()
|
||||
config.set_main_option("sqlalchemy.url", mxtg_config["appservice.database"].replace("%", "%%"))
|
||||
|
||||
AlchemySessionContainer.create_table_classes(None, "telethon_", Base)
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
@@ -24,6 +33,7 @@ fileConfig(config.config_file_name)
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
@@ -44,7 +54,8 @@ def run_migrations_offline():
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url, target_metadata=target_metadata, literal_binds=True)
|
||||
url=url, target_metadata=target_metadata, literal_binds=True,
|
||||
render_as_batch=True)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
@@ -65,12 +76,14 @@ def run_migrations_online():
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=True
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Add disable_updates field for puppets
|
||||
|
||||
Revision ID: 17574c57f3f8
|
||||
Revises: a9119be92164
|
||||
Create Date: 2019-05-15 00:24:46.967529
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '17574c57f3f8'
|
||||
down_revision = 'a9119be92164'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.add_column(sa.Column("disable_updates", sa.Boolean(), nullable=False,
|
||||
server_default=sa.sql.expression.false()))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.drop_column("disable_updates")
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Add TelegramFile table
|
||||
|
||||
Revision ID: 1b241f7e8530
|
||||
Revises: 97d2a942bcf8
|
||||
Create Date: 2018-02-19 23:52:06.605741
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1b241f7e8530'
|
||||
down_revision = '97d2a942bcf8'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('telegram_file',
|
||||
sa.Column('id', sa.String(), nullable=False),
|
||||
sa.Column('mxc', sa.String(), nullable=True),
|
||||
sa.Column('mime_type', sa.String(), nullable=True),
|
||||
sa.Column('was_converted', sa.Boolean(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('telegram_file')
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Add is_bot field to puppets
|
||||
|
||||
Revision ID: 1fa46383a9d3
|
||||
Revises: 30eca60587f1
|
||||
Create Date: 2018-04-29 23:44:40.102333
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1fa46383a9d3'
|
||||
down_revision = '30eca60587f1'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.add_column(sa.Column('is_bot', sa.Boolean(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.drop_column('is_bot')
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Add cascade rules to UserPortal
|
||||
|
||||
Revision ID: 2228d49c383f
|
||||
Revises: bcfefa1f1299
|
||||
Create Date: 2018-05-31 11:11:59.482112
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2228d49c383f'
|
||||
down_revision = 'bcfefa1f1299'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
try:
|
||||
with op.batch_alter_table("user_portal") as batch_op:
|
||||
batch_op.drop_constraint("user_portal_user_fkey", type_="foreignkey")
|
||||
batch_op.drop_constraint("user_portal_portal_fkey", type_="foreignkey")
|
||||
batch_op.create_foreign_key("user_portal_user_fkey", "user", ["user"], ["tgid"],
|
||||
onupdate="CASCADE", ondelete="CASCADE")
|
||||
batch_op.create_foreign_key("user_portal_portal_fkey", "portal",
|
||||
["portal", "portal_receiver"], ["tgid", "tg_receiver"],
|
||||
onupdate="CASCADE", ondelete="CASCADE")
|
||||
except ValueError:
|
||||
return
|
||||
|
||||
|
||||
def downgrade():
|
||||
try:
|
||||
with op.batch_alter_table("user_portal") as batch_op:
|
||||
batch_op.drop_constraint("user_portal_user_fkey", type_="foreignkey")
|
||||
batch_op.drop_constraint("user_portal_portal_fkey", type_="foreignkey")
|
||||
batch_op.create_foreign_key("user_portal_user_fkey", "portal",
|
||||
["portal", "portal_receiver"], ["tgid", "tg_receiver"])
|
||||
batch_op.create_foreign_key("user_portal_portal_fkey", "user", ["user"], ["tgid"])
|
||||
except ValueError:
|
||||
return
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Add encrypted field for portals
|
||||
|
||||
Revision ID: 24f31fc8a72b
|
||||
Revises: a7c04a56041b
|
||||
Create Date: 2020-03-28 20:14:29.046699
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "24f31fc8a72b"
|
||||
down_revision = "a7c04a56041b"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("portal") as batch_op:
|
||||
batch_op.add_column(sa.Column("encrypted", sa.Boolean(), nullable=False,
|
||||
server_default=sa.sql.expression.false()))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("portal") as batch_op:
|
||||
batch_op.drop_column("encrypted")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Add megagroup field to portals
|
||||
|
||||
Revision ID: 30eca60587f1
|
||||
Revises: cfc972368e50
|
||||
Create Date: 2018-04-29 15:51:04.656605
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '30eca60587f1'
|
||||
down_revision = 'cfc972368e50'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("portal") as batch_op:
|
||||
batch_op.add_column(sa.Column('megagroup', sa.Boolean()))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("portal") as batch_op:
|
||||
batch_op.drop_column('megagroup')
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Store Matrix avatar URL in database
|
||||
|
||||
Revision ID: 3e3745baa458
|
||||
Revises: dff56c93da8d
|
||||
Create Date: 2020-06-15 14:32:10.454033
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '3e3745baa458'
|
||||
down_revision = 'dff56c93da8d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('portal', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('avatar_url', sa.String(), nullable=True))
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('portal', schema=None) as batch_op:
|
||||
batch_op.drop_column('avatar_url')
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Switch mx_user_profile to native enum
|
||||
|
||||
Revision ID: 4f7d7ed5792a
|
||||
Revises: 9e9c89b0b877
|
||||
Create Date: 2019-08-04 17:47:36.568120
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '4f7d7ed5792a'
|
||||
down_revision = '9e9c89b0b877'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
conn = op.get_bind()
|
||||
conn.execute("UPDATE mx_user_profile SET membership=UPPER(membership)")
|
||||
conn.execute("UPDATE mx_user_profile SET membership='LEAVE' WHERE membership='LEFT'")
|
||||
|
||||
|
||||
def downgrade():
|
||||
conn = op.get_bind()
|
||||
conn.execute("UPDATE mx_user_profile SET membership=LOWER(membership)")
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Move sessions to main database
|
||||
|
||||
Revision ID: 501dad2868bc
|
||||
Revises: 7d47d84380b6
|
||||
Create Date: 2018-03-02 19:15:53.826985
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '501dad2868bc'
|
||||
down_revision = '7d47d84380b6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
Session = op.create_table('telethon_sessions',
|
||||
sa.Column('session_id', sa.String, nullable=False),
|
||||
sa.Column('dc_id', sa.Integer, nullable=False),
|
||||
sa.Column('server_address', sa.String, nullable=True),
|
||||
sa.Column('port', sa.Integer, nullable=True),
|
||||
sa.Column('auth_key', sa.LargeBinary, nullable=True),
|
||||
sa.PrimaryKeyConstraint('session_id', 'dc_id'))
|
||||
SentFile = op.create_table('telethon_sent_files',
|
||||
sa.Column('session_id', sa.String, nullable=False),
|
||||
sa.Column('md5_digest', sa.LargeBinary, nullable=False),
|
||||
sa.Column('file_size', sa.Integer, nullable=False),
|
||||
sa.Column('type', sa.Integer, nullable=False),
|
||||
sa.Column('id', sa.BigInteger, nullable=True),
|
||||
sa.Column('hash', sa.BigInteger, nullable=True),
|
||||
sa.PrimaryKeyConstraint('session_id', 'md5_digest', 'file_size',
|
||||
'type'))
|
||||
Entity = op.create_table('telethon_entities',
|
||||
sa.Column('session_id', sa.String, nullable=False),
|
||||
sa.Column('id', sa.Integer, nullable=False),
|
||||
sa.Column('hash', sa.Integer, nullable=False),
|
||||
sa.Column('username', sa.String, nullable=True),
|
||||
sa.Column('phone', sa.Integer, nullable=True),
|
||||
sa.Column('name', sa.String, nullable=True),
|
||||
sa.PrimaryKeyConstraint('session_id', 'id'))
|
||||
Version = op.create_table('telethon_version',
|
||||
sa.Column('version', sa.Integer, nullable=False),
|
||||
sa.PrimaryKeyConstraint('version'))
|
||||
conn = op.get_bind()
|
||||
sessions = [os.path.basename(f) for f in os.listdir(".") if f.endswith(".session")]
|
||||
for session in sessions:
|
||||
session_to_sqlalchemy(conn, session, Session, SentFile, Entity)
|
||||
|
||||
|
||||
def session_to_sqlalchemy(conn, path, Session, SentFile, Entity):
|
||||
session_conn = sqlite3.connect(path)
|
||||
session_id = os.path.splitext(path)[0]
|
||||
c = session_conn.cursor()
|
||||
|
||||
auth_data_tuples = c.execute("SELECT * FROM sessions").fetchall()
|
||||
auth_data_dicts = []
|
||||
for row in auth_data_tuples:
|
||||
dc_id, server_address, port, auth_key = row
|
||||
auth_data_dicts.append({
|
||||
"session_id": session_id,
|
||||
"dc_id": dc_id,
|
||||
"server_address": server_address,
|
||||
"port": port,
|
||||
"auth_key": auth_key,
|
||||
})
|
||||
if auth_data_dicts:
|
||||
conn.execute(Session.insert().values(auth_data_dicts))
|
||||
|
||||
sent_file_tuples = c.execute("SELECT * FROM sent_files").fetchall()
|
||||
sent_file_dicts = []
|
||||
for row in sent_file_tuples:
|
||||
md5_digest, file_size, type, id, hash = row
|
||||
sent_file_dicts.append({
|
||||
"session_id": session_id,
|
||||
"md5_digest": md5_digest,
|
||||
"file_size": file_size,
|
||||
"type": type,
|
||||
"id": id,
|
||||
"hash": hash,
|
||||
})
|
||||
if sent_file_dicts:
|
||||
conn.execute(SentFile.insert().values(sent_file_dicts))
|
||||
|
||||
entity_tuples = c.execute("SELECT * FROM entities").fetchall()
|
||||
entity_dicts = []
|
||||
for row in entity_tuples:
|
||||
id, hash, username, phone, name = row
|
||||
entity_dicts.append({
|
||||
"session_id": session_id,
|
||||
"id": id,
|
||||
"hash": hash,
|
||||
"username": username,
|
||||
"phone": phone,
|
||||
"name": name,
|
||||
})
|
||||
if entity_dicts:
|
||||
conn.execute(Entity.insert().values(entity_dicts))
|
||||
|
||||
c.close()
|
||||
session_conn.close()
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('telethon_version')
|
||||
op.drop_table('telethon_entities')
|
||||
op.drop_table('telethon_sent_files')
|
||||
op.drop_table('telethon_sessions')
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Move state store to main database
|
||||
|
||||
Revision ID: 6ca3d74d51e4
|
||||
Revises: 2228d49c383f
|
||||
Create Date: 2018-06-26 21:31:26.911307
|
||||
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
|
||||
from alembic import context, op
|
||||
import sqlalchemy.orm as orm
|
||||
import sqlalchemy as sa
|
||||
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from mautrix_telegram.config import Config
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "6ca3d74d51e4"
|
||||
down_revision = "2228d49c383f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
class RoomState(Base):
|
||||
__tablename__ = "mx_room_state"
|
||||
__table_args__ = {"extend_existing": True}
|
||||
|
||||
room_id = sa.Column(sa.String, primary_key=True)
|
||||
power_levels = sa.Column("power_levels", sa.Text, nullable=True)
|
||||
|
||||
|
||||
class UserProfile(Base):
|
||||
__tablename__ = "mx_user_profile"
|
||||
__table_args__ = {"extend_existing": True}
|
||||
|
||||
room_id = sa.Column(sa.String, primary_key=True)
|
||||
user_id = sa.Column(sa.String, primary_key=True)
|
||||
membership = sa.Column(sa.String, nullable=False, default="leave")
|
||||
displayname = sa.Column(sa.String, nullable=True)
|
||||
avatar_url = sa.Column(sa.String, nullable=True)
|
||||
|
||||
|
||||
class Puppet(Base):
|
||||
__tablename__ = "puppet"
|
||||
__table_args__ = {"extend_existing": True}
|
||||
|
||||
id = sa.Column(sa.Integer, primary_key=True)
|
||||
displayname = sa.Column(sa.String, nullable=True)
|
||||
displayname_source = sa.Column(sa.Integer, nullable=True)
|
||||
username = sa.Column(sa.String, nullable=True)
|
||||
photo_id = sa.Column(sa.String, nullable=True)
|
||||
is_bot = sa.Column(sa.Boolean, nullable=True)
|
||||
matrix_registered = sa.Column(sa.Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.add_column(sa.Column("matrix_registered", sa.Boolean(), nullable=False,
|
||||
server_default=sa.sql.expression.false()))
|
||||
op.create_table("mx_room_state",
|
||||
sa.Column("room_id", sa.String(), nullable=False),
|
||||
sa.Column("power_levels", sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("room_id"))
|
||||
op.create_table("mx_user_profile",
|
||||
sa.Column("room_id", sa.String(), nullable=False),
|
||||
sa.Column("user_id", sa.String(), nullable=False),
|
||||
sa.Column("membership", sa.String(), nullable=False,
|
||||
default="leave"),
|
||||
sa.Column("displayname", sa.String(), nullable=True),
|
||||
sa.Column("avatar_url", sa.String(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("room_id", "user_id"))
|
||||
|
||||
try:
|
||||
migrate_state_store()
|
||||
except Exception as e:
|
||||
print("Failed to migrate state store:", e)
|
||||
print("Migrating the state store isn't required, but you can retry by alembic downgrading "
|
||||
"to revision 2228d49c383f and upgrading again.")
|
||||
|
||||
|
||||
def migrate_state_store():
|
||||
conn = op.get_bind()
|
||||
session: orm.Session = orm.sessionmaker(bind=conn)()
|
||||
|
||||
try:
|
||||
with open("mx-state.json") as file:
|
||||
data = json.load(file)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
if not data:
|
||||
return
|
||||
registrations = data.get("registrations", [])
|
||||
|
||||
mxtg_config_path = context.get_x_argument(as_dictionary=True).get("config", "config.yaml")
|
||||
mxtg_config = Config(mxtg_config_path, None, None)
|
||||
mxtg_config.load()
|
||||
|
||||
username_template = mxtg_config.get("bridge.username_template", "telegram_{userid}")
|
||||
hs_domain = mxtg_config["homeserver.domain"]
|
||||
localpart = username_template.format(userid="(.+)")
|
||||
mxid_regex = re.compile("@{}:{}".format(localpart, hs_domain))
|
||||
for user in registrations:
|
||||
match = mxid_regex.match(user)
|
||||
if not match:
|
||||
continue
|
||||
|
||||
puppet = session.query(Puppet).get(match.group(1))
|
||||
if not puppet:
|
||||
continue
|
||||
|
||||
puppet.matrix_registered = True
|
||||
session.merge(puppet)
|
||||
session.commit()
|
||||
|
||||
user_profiles = [UserProfile(room_id=room, user_id=user,
|
||||
membership=member.get("membership", "leave"),
|
||||
displayname=member.get("displayname", None),
|
||||
avatar_url=member.get("avatar_url", None))
|
||||
for room, members in data.get("members", {}).items()
|
||||
for user, member in members.items()]
|
||||
session.add_all(user_profiles)
|
||||
session.commit()
|
||||
|
||||
room_state = [RoomState(room_id=room, power_levels=json.dumps(levels))
|
||||
for room, levels in data.get("power_levels", {}).items()]
|
||||
session.add_all(room_state)
|
||||
session.commit()
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table("mx_user_profile")
|
||||
op.drop_table("mx_room_state")
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.drop_column("matrix_registered")
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Add timestamp to TelegramFile
|
||||
|
||||
Revision ID: 7d47d84380b6
|
||||
Revises: 1b241f7e8530
|
||||
Create Date: 2018-02-19 23:53:18.050871
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '7d47d84380b6'
|
||||
down_revision = '1b241f7e8530'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('telegram_file',
|
||||
sa.Column('timestamp', sa.BigInteger(), nullable=True, default=0,
|
||||
server_default="0"))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("telegram_file") as batch_op:
|
||||
batch_op.drop_column('timestamp')
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Add Matrix redaction state to message table
|
||||
|
||||
Revision ID: 7de69cf5809e
|
||||
Revises: 888275d58e57
|
||||
Create Date: 2020-12-19 12:39:57.368568
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '7de69cf5809e'
|
||||
down_revision = '888275d58e57'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table('message', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('redacted', sa.Boolean(), server_default=sa.false(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('message', schema=None) as batch_op:
|
||||
batch_op.drop_column('redacted')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Add double puppet base URL to puppet table
|
||||
|
||||
Revision ID: 888275d58e57
|
||||
Revises: a328bf4f0932
|
||||
Create Date: 2020-10-14 18:52:00.730666
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '888275d58e57'
|
||||
down_revision = 'a328bf4f0932'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('puppet', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('base_url', sa.Text(), nullable=True))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('puppet', schema=None) as batch_op:
|
||||
batch_op.drop_column('base_url')
|
||||
# ### end Alembic commands ###
|
||||
@@ -1,14 +1,13 @@
|
||||
"""initial revision
|
||||
|
||||
Revision ID: 97d2a942bcf8
|
||||
Revises:
|
||||
Revises:
|
||||
Create Date: 2018-02-11 18:40:55.483842
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '97d2a942bcf8'
|
||||
down_revision = None
|
||||
@@ -17,12 +16,65 @@ depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
op.create_table('portal',
|
||||
sa.Column('tgid', sa.Integer),
|
||||
sa.Column('tg_receiver', sa.Integer),
|
||||
sa.Column('peer_type', sa.String, nullable=False, default=""),
|
||||
sa.Column('mxid', sa.String, nullable=True),
|
||||
sa.Column('username', sa.String, nullable=True),
|
||||
sa.Column('title', sa.String, nullable=True),
|
||||
sa.Column('about', sa.String, nullable=True),
|
||||
sa.Column('photo_id', sa.String, nullable=True),
|
||||
sa.PrimaryKeyConstraint('tgid', 'tg_receiver'),
|
||||
sa.UniqueConstraint('mxid'))
|
||||
op.create_table('user',
|
||||
sa.Column('mxid', sa.String),
|
||||
sa.Column('tgid', sa.Integer, nullable=True, unique=True),
|
||||
sa.Column('tg_username', sa.String, nullable=True),
|
||||
sa.Column('saved_contacts', sa.Integer, nullable=False, default=0),
|
||||
sa.PrimaryKeyConstraint('mxid'))
|
||||
op.create_table('puppet',
|
||||
sa.Column('id', sa.Integer),
|
||||
sa.Column('displayname', sa.String, nullable=True),
|
||||
sa.Column('username', sa.String, nullable=True),
|
||||
sa.Column('photo_id', sa.String, nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
op.create_table('contact',
|
||||
sa.Column('user', sa.Integer),
|
||||
sa.Column('contact', sa.Integer),
|
||||
sa.ForeignKeyConstraint(("user",), ("user.tgid",)),
|
||||
sa.ForeignKeyConstraint(("contact",), ("puppet.id",)),
|
||||
sa.PrimaryKeyConstraint('user', 'contact'))
|
||||
op.create_table('user_portal',
|
||||
sa.Column('user', sa.Integer),
|
||||
sa.Column('portal', sa.Integer),
|
||||
sa.Column('portal_receiver', sa.Integer),
|
||||
sa.PrimaryKeyConstraint('user', 'portal', 'portal_receiver'),
|
||||
sa.ForeignKeyConstraint(("user",), ("user.tgid",),
|
||||
name="user_portal_user_fkey",
|
||||
onupdate="CASCADE", ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(("portal", "portal_receiver"),
|
||||
("portal.tgid", "portal.tg_receiver"),
|
||||
name="user_portal_portal_fkey",
|
||||
onupdate="CASCADE", ondelete="CASCADE"))
|
||||
op.create_table('message',
|
||||
sa.Column('mxid', sa.String),
|
||||
sa.Column('mx_room', sa.String),
|
||||
sa.Column('tgid', sa.Integer),
|
||||
sa.Column('tg_space', sa.Integer),
|
||||
sa.PrimaryKeyConstraint('tgid', 'tg_space'),
|
||||
sa.UniqueConstraint("mxid", "mx_room", "tg_space", name="_mx_id_room"))
|
||||
op.create_table('bot_chat',
|
||||
sa.Column('id', sa.Integer),
|
||||
sa.Column('type', sa.String, nullable=False, default=""),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
op.drop_table('bot_chat')
|
||||
op.drop_table('message')
|
||||
op.drop_table('user_portal')
|
||||
op.drop_table('contact')
|
||||
op.drop_table('puppet')
|
||||
op.drop_table('user')
|
||||
op.drop_table('portal')
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Store displayname contact status in puppet table
|
||||
|
||||
Revision ID: 990f4395afc6
|
||||
Revises: 7de69cf5809e
|
||||
Create Date: 2021-01-01 11:56:54.610681
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '990f4395afc6'
|
||||
down_revision = '7de69cf5809e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('puppet', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('displayname_contact', sa.Boolean(), server_default=sa.true(), nullable=False))
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('puppet', schema=None) as batch_op:
|
||||
batch_op.drop_column('displayname_contact')
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Add edit index to messages
|
||||
|
||||
Revision ID: 9e9c89b0b877
|
||||
Revises: 17574c57f3f8
|
||||
Create Date: 2019-05-29 15:28:23.128377
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '9e9c89b0b877'
|
||||
down_revision = '17574c57f3f8'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('_message_temp',
|
||||
sa.Column('mxid', sa.String),
|
||||
sa.Column('mx_room', sa.String),
|
||||
sa.Column('tgid', sa.Integer),
|
||||
sa.Column('tg_space', sa.Integer),
|
||||
sa.Column('edit_index', sa.Integer),
|
||||
sa.PrimaryKeyConstraint('tgid', 'tg_space', 'edit_index'),
|
||||
sa.UniqueConstraint("mxid", "mx_room", "tg_space", name="_mx_id_room_2"))
|
||||
c = op.get_bind()
|
||||
c.execute("INSERT INTO _message_temp (mxid, mx_room, tgid, tg_space, edit_index) "
|
||||
"SELECT message.mxid, message.mx_room, message.tgid, message.tg_space, 0 "
|
||||
"FROM message")
|
||||
c.execute("DROP TABLE message")
|
||||
c.execute("ALTER TABLE _message_temp RENAME TO message")
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.create_table('_message_temp',
|
||||
sa.Column('mxid', sa.String),
|
||||
sa.Column('mx_room', sa.String),
|
||||
sa.Column('tgid', sa.Integer),
|
||||
sa.Column('tg_space', sa.Integer),
|
||||
sa.PrimaryKeyConstraint('tgid', 'tg_space'),
|
||||
sa.UniqueConstraint("mxid", "mx_room", "tg_space", name="_mx_id_room"))
|
||||
c = op.get_bind()
|
||||
c.execute("INSERT INTO _message_temp (mxid, mx_room, tgid, tg_space) "
|
||||
"SELECT message.mxid, message.mx_room, message.tgid, message.tg_space "
|
||||
"FROM message")
|
||||
c.execute("DROP TABLE message")
|
||||
c.execute("ALTER TABLE _message_temp RENAME TO message")
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Store encryption state event in db
|
||||
|
||||
Revision ID: a328bf4f0932
|
||||
Revises: ccbaff858240
|
||||
Create Date: 2020-07-11 21:31:27.059813
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from mautrix.client.state_store.sqlalchemy import SerializableType
|
||||
from mautrix.types import RoomEncryptionStateEventContent
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a328bf4f0932'
|
||||
down_revision = 'ccbaff858240'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('mx_room_state', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('encryption',
|
||||
SerializableType(RoomEncryptionStateEventContent),
|
||||
nullable=True))
|
||||
batch_op.add_column(sa.Column('has_full_member_list', sa.Boolean(), nullable=True))
|
||||
batch_op.add_column(sa.Column('is_encrypted', sa.Boolean(), nullable=True))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('mx_room_state', schema=None) as batch_op:
|
||||
batch_op.drop_column('is_encrypted')
|
||||
batch_op.drop_column('has_full_member_list')
|
||||
batch_op.drop_column('encryption')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Store custom puppet next_batch in database
|
||||
|
||||
Revision ID: a7c04a56041b
|
||||
Revises: 4f7d7ed5792a
|
||||
Create Date: 2019-08-06 23:08:51.087651
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "a7c04a56041b"
|
||||
down_revision = "4f7d7ed5792a"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.add_column(sa.Column("next_batch", sa.String(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.drop_column("next_batch")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Add phone number field to users
|
||||
|
||||
Revision ID: a9119be92164
|
||||
Revises: b54929c22c86
|
||||
Create Date: 2018-09-28 02:38:40.626282
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "a9119be92164"
|
||||
down_revision = "b54929c22c86"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("user", sa.Column("tg_phone", sa.String(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("user") as batch_op:
|
||||
batch_op.drop_column("tg_phone")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Add portal-specific config
|
||||
|
||||
Revision ID: b54929c22c86
|
||||
Revises: d5f7b8b4b456
|
||||
Create Date: 2018-09-24 23:40:33.528710
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "b54929c22c86"
|
||||
down_revision = "d5f7b8b4b456"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("portal", sa.Column("config", sa.Text(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("portal") as batch_op:
|
||||
batch_op.drop_column("config")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Add displayname source fields for puppets
|
||||
|
||||
Revision ID: bcfefa1f1299
|
||||
Revises: bdadd173ee02
|
||||
Create Date: 2018-05-19 17:00:21.078098
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'bcfefa1f1299'
|
||||
down_revision = 'bdadd173ee02'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('puppet', sa.Column('displayname_source', sa.Integer(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.drop_column('displayname_source')
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Update telethon update state table
|
||||
|
||||
Revision ID: bdadd173ee02
|
||||
Revises: eeaf0dae87ce
|
||||
Create Date: 2018-05-13 10:42:59.395597
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'bdadd173ee02'
|
||||
down_revision = 'eeaf0dae87ce'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("telethon_entities") as batch_op:
|
||||
batch_op.alter_column("id", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
batch_op.alter_column("hash", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
|
||||
with op.batch_alter_table("telethon_update_state") as batch_op:
|
||||
batch_op.alter_column("entity_id", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
batch_op.alter_column("pts", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
batch_op.alter_column("qts", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
batch_op.alter_column("date", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
batch_op.alter_column("seq", existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
batch_op.add_column(sa.Column("unread_count", sa.Integer))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("telethon_entities") as batch_op:
|
||||
batch_op.alter_column("id", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
batch_op.alter_column("hash", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
|
||||
with op.batch_alter_table("telethon_update_state") as batch_op:
|
||||
batch_op.alter_column("entity_id", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
batch_op.alter_column("pts", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
batch_op.alter_column("qts", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
batch_op.alter_column("date", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
batch_op.alter_column("seq", existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
batch_op.drop_column("unread_count")
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Store displayname quality in puppet table
|
||||
|
||||
Revision ID: bfc0a39bfe02
|
||||
Revises: ec1d3dcc77e9
|
||||
Create Date: 2021-03-23 20:03:08.825333
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'bfc0a39bfe02'
|
||||
down_revision = 'ec1d3dcc77e9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('puppet', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('displayname_quality', sa.Integer(), server_default='0', nullable=False))
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('puppet', schema=None) as batch_op:
|
||||
batch_op.drop_column('displayname_quality')
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Switch to mautrix-python crypto
|
||||
|
||||
Revision ID: ccbaff858240
|
||||
Revises: 3e3745baa458
|
||||
Create Date: 2020-07-08 19:06:12.588047
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ccbaff858240'
|
||||
down_revision = '3e3745baa458'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('nio_account')
|
||||
op.drop_table('nio_device_key')
|
||||
op.drop_table('nio_outgoing_key_request')
|
||||
op.drop_table('nio_olm_session')
|
||||
op.drop_table('nio_megolm_inbound_session')
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('nio_megolm_inbound_session',
|
||||
sa.Column('session_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('sender_key', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('fp_key', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('room_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('session', postgresql.BYTEA(), autoincrement=False, nullable=False),
|
||||
sa.Column('forwarded_chains', postgresql.BYTEA(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint('session_id', name='nio_megolm_inbound_session_pkey')
|
||||
)
|
||||
op.create_table('nio_olm_session',
|
||||
sa.Column('session_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('sender_key', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('session', postgresql.BYTEA(), autoincrement=False, nullable=False),
|
||||
sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
|
||||
sa.Column('last_used', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint('session_id', name='nio_olm_session_pkey')
|
||||
)
|
||||
op.create_table('nio_outgoing_key_request',
|
||||
sa.Column('request_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('session_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('room_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('algorithm', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint('request_id', name='nio_outgoing_key_request_pkey')
|
||||
)
|
||||
op.create_table('nio_device_key',
|
||||
sa.Column('user_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('device_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('display_name', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=False),
|
||||
sa.Column('keys', postgresql.BYTEA(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint('user_id', 'device_id', name='nio_device_key_pkey')
|
||||
)
|
||||
op.create_table('nio_account',
|
||||
sa.Column('user_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('device_id', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
|
||||
sa.Column('shared', sa.BOOLEAN(), autoincrement=False, nullable=False),
|
||||
sa.Column('sync_token', sa.TEXT(), autoincrement=False, nullable=False),
|
||||
sa.Column('account', postgresql.BYTEA(), autoincrement=False, nullable=False),
|
||||
sa.PrimaryKeyConstraint('user_id', 'device_id', name='nio_account_pkey')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Add metadata to TelegramFile
|
||||
|
||||
Revision ID: cfc972368e50
|
||||
Revises: 501dad2868bc
|
||||
Create Date: 2018-03-09 16:07:01.236712
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'cfc972368e50'
|
||||
down_revision = '501dad2868bc'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("telegram_file") as batch_op:
|
||||
batch_op.add_column(sa.Column('size', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('width', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('height', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('thumbnail', sa.String(), nullable=True))
|
||||
batch_op.create_foreign_key(constraint_name="fk_file_thumbnail",
|
||||
referent_table="telegram_file",
|
||||
local_cols=['thumbnail'],
|
||||
remote_cols=['id'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("telegram_file") as batch_op:
|
||||
batch_op.drop_column('size')
|
||||
batch_op.drop_column('width')
|
||||
batch_op.drop_column('height')
|
||||
batch_op.drop_column('thumbnail')
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Add decryption info field for reuploaded telegram files
|
||||
|
||||
Revision ID: d3c922a6acd2
|
||||
Revises: 24f31fc8a72b
|
||||
Create Date: 2020-03-30 20:07:17.340346
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd3c922a6acd2'
|
||||
down_revision = '24f31fc8a72b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("telegram_file") as batch_op:
|
||||
batch_op.add_column(sa.Column("decryption_info", sa.Text(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("telegram_file") as batch_op:
|
||||
batch_op.drop_column("decryption_info")
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Add access_token and custom_mxid fields for puppets
|
||||
|
||||
Revision ID: d5f7b8b4b456
|
||||
Revises: 6ca3d74d51e4
|
||||
Create Date: 2018-07-20 12:09:30.277960
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "d5f7b8b4b456"
|
||||
down_revision = "6ca3d74d51e4"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("puppet", sa.Column("access_token", sa.String(), nullable=True))
|
||||
op.add_column("puppet", sa.Column("custom_mxid", sa.String(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("puppet") as batch_op:
|
||||
batch_op.drop_column("custom_mxid")
|
||||
batch_op.drop_column("access_token")
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Add matrix-nio state store to main db
|
||||
|
||||
Revision ID: dff56c93da8d
|
||||
Revises: d3c922a6acd2
|
||||
Create Date: 2020-03-31 22:04:04.014048
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'dff56c93da8d'
|
||||
down_revision = 'd3c922a6acd2'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('nio_account',
|
||||
sa.Column('user_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('device_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('shared', sa.Boolean(), nullable=False),
|
||||
sa.Column('sync_token', sa.Text(), nullable=False),
|
||||
sa.Column('account', sa.LargeBinary(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('user_id', 'device_id')
|
||||
)
|
||||
op.create_table('nio_device_key',
|
||||
sa.Column('user_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('device_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('display_name', sa.String(length=255), nullable=False),
|
||||
sa.Column('deleted', sa.Boolean(), nullable=False),
|
||||
sa.Column('keys', sa.PickleType(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('user_id', 'device_id')
|
||||
)
|
||||
op.create_table('nio_megolm_inbound_session',
|
||||
sa.Column('session_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('sender_key', sa.String(length=255), nullable=False),
|
||||
sa.Column('fp_key', sa.String(length=255), nullable=False),
|
||||
sa.Column('room_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('session', sa.LargeBinary(), nullable=False),
|
||||
sa.Column('forwarded_chains', sa.PickleType(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('session_id')
|
||||
)
|
||||
op.create_table('nio_olm_session',
|
||||
sa.Column('session_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('sender_key', sa.String(length=255), nullable=False),
|
||||
sa.Column('session', sa.LargeBinary(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('last_used', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('session_id')
|
||||
)
|
||||
op.create_table('nio_outgoing_key_request',
|
||||
sa.Column('request_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('session_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('room_id', sa.String(length=255), nullable=False),
|
||||
sa.Column('algorithm', sa.String(length=255), nullable=False),
|
||||
sa.PrimaryKeyConstraint('request_id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('nio_outgoing_key_request')
|
||||
op.drop_table('nio_olm_session')
|
||||
op.drop_table('nio_megolm_inbound_session')
|
||||
op.drop_table('nio_device_key')
|
||||
op.drop_table('nio_account')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Switch Telegram IDs to bigints
|
||||
|
||||
Revision ID: ec1d3dcc77e9
|
||||
Revises: 990f4395afc6
|
||||
Create Date: 2021-03-09 21:36:58.443727
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ec1d3dcc77e9'
|
||||
down_revision = '990f4395afc6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
columns_to_upgrade = (
|
||||
("bot_chat", "id"),
|
||||
("message", "tgid"),
|
||||
("message", "tg_space"),
|
||||
("portal", "tgid"),
|
||||
("portal", "tg_receiver"),
|
||||
("puppet", "id"),
|
||||
("puppet", "displayname_source"),
|
||||
("user", "tgid"),
|
||||
("user_portal", "user"),
|
||||
("user_portal", "portal"),
|
||||
("user_portal", "portal_receiver"),
|
||||
("contact", "user"),
|
||||
("contact", "contact"),
|
||||
)
|
||||
|
||||
|
||||
def upgrade():
|
||||
if op.get_context().dialect.name == "postgresql":
|
||||
for table, column in columns_to_upgrade:
|
||||
op.alter_column(table, column, existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
|
||||
|
||||
def downgrade():
|
||||
if op.get_context().dialect.name == "postgresql":
|
||||
for table, column in columns_to_upgrade:
|
||||
op.alter_column(table, column, existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Add telethon update state table
|
||||
|
||||
Revision ID: eeaf0dae87ce
|
||||
Revises: 1fa46383a9d3
|
||||
Create Date: 2018-04-30 17:30:59.610885
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'eeaf0dae87ce'
|
||||
down_revision = '1fa46383a9d3'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("telethon_entities") as batch_op:
|
||||
batch_op.alter_column('phone', existing_type=sa.Integer, type_=sa.BigInteger)
|
||||
op.create_table('telethon_update_state',
|
||||
sa.Column('session_id', sa.String, nullable=False),
|
||||
sa.Column('entity_id', sa.Integer, nullable=False),
|
||||
sa.Column('pts', sa.Integer, nullable=True),
|
||||
sa.Column('qts', sa.Integer, nullable=True),
|
||||
sa.Column('date', sa.Integer, nullable=True),
|
||||
sa.Column('seq', sa.Integer, nullable=True),
|
||||
sa.PrimaryKeyConstraint('session_id', 'entity_id'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("telethon_entities") as batch_op:
|
||||
batch_op.alter_column('phone', existing_type=sa.BigInteger, type_=sa.Integer)
|
||||
op.drop_table('telethon_update_state')
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Define functions.
|
||||
function fixperms {
|
||||
chown -R $UID:$GID /data /opt/mautrix-telegram
|
||||
}
|
||||
|
||||
cd /opt/mautrix-telegram
|
||||
|
||||
# Replace database path in config.
|
||||
sed -i "s#sqlite:///mautrix-telegram.db#sqlite:////data/mautrix-telegram.db#" /data/config.yaml
|
||||
|
||||
if [ -f /data/mx-state.json ]; then
|
||||
ln -s /data/mx-state.json
|
||||
fi
|
||||
|
||||
if [ ! -f /data/config.yaml ]; then
|
||||
cp example-config.yaml /data/config.yaml
|
||||
echo "Didn't find a config file."
|
||||
echo "Copied default config file to /data/config.yaml"
|
||||
echo "Modify that config file to your liking."
|
||||
echo "Start the container again after that to generate the registration file."
|
||||
fixperms
|
||||
exit
|
||||
fi
|
||||
|
||||
if [ ! -f /data/registration.yaml ]; then
|
||||
python3 -m mautrix_telegram -g -c /data/config.yaml -r /data/registration.yaml
|
||||
fixperms
|
||||
exit
|
||||
fi
|
||||
|
||||
# Check that database is in the right state
|
||||
alembic -x config=/data/config.yaml upgrade head
|
||||
|
||||
fixperms
|
||||
exec su-exec $UID:$GID python3 -m mautrix_telegram -c /data/config.yaml
|
||||
@@ -1,89 +0,0 @@
|
||||
# Homeserver details
|
||||
homeserver:
|
||||
address: https://matrix.org
|
||||
domain: matrix.org
|
||||
|
||||
# Application service host/registration related details
|
||||
# Changing these values requires regeneration of the registration.
|
||||
appservice:
|
||||
# The protocol the homeserver should use when connecting to this appservice.
|
||||
# Usually "http" or "https".
|
||||
protocol: http
|
||||
|
||||
# The hostname and port where the homeserver can find this appservice.
|
||||
hostname: localhost
|
||||
port: 8080
|
||||
|
||||
# Whether or not to enable debug messages in the console.
|
||||
debug: false
|
||||
|
||||
# The unique ID of this appservice.
|
||||
id: telegram
|
||||
# Username of the appservice bot.
|
||||
bot_username: telegrambot
|
||||
bot_displayname: Telegram bridge bot
|
||||
|
||||
# Authentication tokens for AS <-> HS communication. Autogenerated; do not modify.
|
||||
as_token: "This value is generated when generating the registration"
|
||||
hs_token: "This value is generated when generating the registration"
|
||||
|
||||
# Bridge config
|
||||
bridge:
|
||||
# Localpart template of MXIDs for Telegram users.
|
||||
# {userid} is replaced with the user ID of the Telegram user.
|
||||
username_template: "telegram_{userid}"
|
||||
# Localpart template of room aliases for Telegram portal rooms.
|
||||
# {groupname} is replaced with the name part of the public channel/group invite link ( https://t.me/{} )
|
||||
alias_template: "telegram_{groupname}"
|
||||
# Displayname template for Telegram users.
|
||||
# {displayname} is replaced with the display name of the Telegram user.
|
||||
displayname_template: "{displayname} (Telegram)"
|
||||
|
||||
# Set the preferred order of user identifiers which to use in the Matrix puppet display name.
|
||||
# In the (hopefully unlikely) scenario that none of the given keys are found, the numeric user
|
||||
# ID is used.
|
||||
#
|
||||
# If the bridge is working properly, a phone number or an username should always be known, but
|
||||
# the other one can very well be empty.
|
||||
#
|
||||
# Valid keys:
|
||||
# "full name" (First and/or last name)
|
||||
# "full name reversed" (Last and/or first name)
|
||||
# "first name"
|
||||
# "last name"
|
||||
# "username"
|
||||
# "phone number"
|
||||
displayname_preference:
|
||||
- full name
|
||||
- username
|
||||
- phone number
|
||||
|
||||
# Whether or not to use native Matrix replies. At the time of writing, only riot-web supports
|
||||
# replies and the format of them is subject to change.
|
||||
native_replies: True
|
||||
# If native replies are disabled, should the custom replies contain a link to the message being
|
||||
# replied to?
|
||||
link_in_reply: False
|
||||
# Show message editing as a reply to the original message.
|
||||
# If this is false, message edits are not shown at all, as Matrix does not support editing yet.
|
||||
edits_as_replies: False
|
||||
|
||||
# The prefix for commands. Only required in non-management rooms.
|
||||
command_prefix: "!tg"
|
||||
|
||||
# Whitelist of user IDs that are allowed to use this bridge. Leave empty to disable.
|
||||
# You can enter a domain without the localpart to allow all users from that homeserver to use the bridge.
|
||||
whitelist:
|
||||
- "internal.example.com"
|
||||
- "@user:public.example.com"
|
||||
|
||||
# Admins can do things like delete portal rooms. Here you must specify the exact MXID, domains
|
||||
# are not accepted.
|
||||
admins:
|
||||
- "@admin:internal.example.com"
|
||||
|
||||
# Telegram config
|
||||
telegram:
|
||||
# Get your own API keys at https://my.telegram.org/apps
|
||||
api_id: 12345
|
||||
api_hash: tjyd5yge35lbodk1xwzw2jstp90k55qz
|
||||
@@ -0,0 +1,2 @@
|
||||
[*.{yaml,yml}]
|
||||
indent_size = 2
|
||||
@@ -0,0 +1 @@
|
||||
charts/*
|
||||
@@ -0,0 +1,22 @@
|
||||
# Patterns to ignore when building packages.
|
||||
# This supports shell glob matching, relative path matching, and
|
||||
# negation (prefixed with !). Only one pattern per line.
|
||||
.DS_Store
|
||||
# Common VCS dirs
|
||||
.git/
|
||||
.gitignore
|
||||
.bzr/
|
||||
.bzrignore
|
||||
.hg/
|
||||
.hgignore
|
||||
.svn/
|
||||
# Common backup files
|
||||
*.swp
|
||||
*.bak
|
||||
*.tmp
|
||||
*~
|
||||
# Various IDEs
|
||||
.project
|
||||
.idea/
|
||||
*.tmproj
|
||||
.vscode/
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
name: mautrix-telegram
|
||||
version: 0.1.0
|
||||
appVersion: "0.7.0"
|
||||
description: A Matrix-Telegram hybrid puppeting/relaybot bridge.
|
||||
keywords:
|
||||
- matrix
|
||||
- bridge
|
||||
- telegram
|
||||
maintainers:
|
||||
- name: Tulir Asokan
|
||||
email: tulir@maunium.net
|
||||
sources:
|
||||
- https://github.com/tulir/mautrix-telegram
|
||||
@@ -0,0 +1,6 @@
|
||||
dependencies:
|
||||
- name: postgresql
|
||||
repository: https://kubernetes-charts.storage.googleapis.com/
|
||||
version: 6.5.0
|
||||
digest: sha256:85139e9d4207e49c11c5f84d7920d0135cffd3d427f3f3638d4e51258990de2a
|
||||
generated: "2019-10-23T22:11:37.005827507+03:00"
|
||||
@@ -0,0 +1,5 @@
|
||||
dependencies:
|
||||
- name: postgresql
|
||||
version: 6.5.0
|
||||
repository: https://kubernetes-charts.storage.googleapis.com/
|
||||
condition: postgresql.enabled
|
||||
@@ -0,0 +1,21 @@
|
||||
Your registration file is below. Save it into a YAML file and give the path to that file to synapse:
|
||||
|
||||
id: {{ .Values.appservice.id }}
|
||||
as_token: {{ .Values.appservice.asToken }}
|
||||
hs_token: {{ .Values.appservice.hsToken }}
|
||||
namespaces:
|
||||
users:
|
||||
- exclusive: true
|
||||
regex: "@{{ .Values.bridge.username_template | replace "{userid}" ".+"}}:{{ .Values.homeserver.domain }}"
|
||||
{{- if .Values.appservice.communityID }}
|
||||
group_id: {{ .Values.appservice.communityID }}
|
||||
{{- end }}
|
||||
aliases:
|
||||
- exclusive: true
|
||||
regex: "@{{ .Values.bridge.alias_template | replace "{groupname}" ".+"}}:{{ .Values.homeserver.domain }}"
|
||||
{{- if .Values.appservice.communityID }}
|
||||
group_id: {{ .Values.appservice.communityID }}
|
||||
{{- end }}
|
||||
url: {{ .Values.appservice.address }}
|
||||
sender_localpart: {{ .Values.appservice.botUsername }}
|
||||
rate_limited: false
|
||||
@@ -0,0 +1,55 @@
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "mautrix-telegram.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
Create a default fully qualified app name.
|
||||
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
|
||||
If release name contains chart name it will be used as a full name.
|
||||
*/}}
|
||||
{{- define "mautrix-telegram.fullname" -}}
|
||||
{{- if .Values.fullnameOverride -}}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
|
||||
{{- else -}}
|
||||
{{- $name := default .Chart.Name .Values.nameOverride -}}
|
||||
{{- if contains $name .Release.Name -}}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
|
||||
{{- else -}}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
Create chart name and version as used by the chart label.
|
||||
*/}}
|
||||
{{- define "mautrix-telegram.chart" -}}
|
||||
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
Common labels
|
||||
*/}}
|
||||
{{- define "mautrix-telegram.labels" -}}
|
||||
app.kubernetes.io/name: {{ include "mautrix-telegram.name" . }}
|
||||
helm.sh/chart: {{ include "mautrix-telegram.chart" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- if .Chart.AppVersion }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
{{- end }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
Create the name of the service account to use
|
||||
*/}}
|
||||
{{- define "mautrix-telegram.serviceAccountName" -}}
|
||||
{{- if .Values.serviceAccount.create -}}
|
||||
{{ default (include "mautrix-telegram.fullname" .) .Values.serviceAccount.name }}
|
||||
{{- else -}}
|
||||
{{ default "default" .Values.serviceAccount.name }}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,57 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ template "mautrix-telegram.fullname" . }}
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version }}
|
||||
app.kubernetes.io/name: {{ template "mautrix-telegram.name" . }}
|
||||
data:
|
||||
config.yaml: |
|
||||
homeserver:
|
||||
address: {{ .Values.homeserver.address }}
|
||||
domain: {{ .Values.homeserver.domain }}
|
||||
verify_ssl: {{ .Values.homeserver.verifySSL }}
|
||||
|
||||
appservice:
|
||||
address: http://{{ include "mautrix-telegram.fullname" . }}:{{ .Values.service.port }}
|
||||
|
||||
hostname: 0.0.0.0
|
||||
port: {{ .Values.service.port }}
|
||||
max_body_size: {{ .Values.appservice.maxBodySize }}
|
||||
|
||||
{{- if .Values.postgresql.enabled }}
|
||||
database: "postgres://postgres:{{ .Values.postgresql.postgresqlPassword }}@{{ .Release.Name }}-postgresql/{{ .Values.postgresql.postgresqlDatabase }}"
|
||||
{{- else }}
|
||||
database: {{ .Values.appservice.database | quote }}
|
||||
{{- end }}
|
||||
|
||||
public:
|
||||
{{- toYaml .Values.appservice.public | nindent 8 }}
|
||||
|
||||
provisioning:
|
||||
{{- toYaml .Values.appservice.provisioning | nindent 8 }}
|
||||
|
||||
id: {{ .Values.appservice.id }}
|
||||
bot_username: {{ .Values.appservice.botUsername }}
|
||||
bot_displayname: {{ .Values.appservice.botDisplayname }}
|
||||
bot_avatar: {{ .Values.appservice.botAvatar }}
|
||||
|
||||
community_id: {{ .Values.appservice.communityID }}
|
||||
|
||||
as_token: {{ .Values.appservice.asToken }}
|
||||
hs_token: {{ .Values.appservice.hsToken }}
|
||||
|
||||
metrics:
|
||||
{{- toYaml .Values.metrics | nindent 6 }}
|
||||
|
||||
bridge:
|
||||
{{- toYaml .Values.bridge | nindent 6 }}
|
||||
|
||||
telegram:
|
||||
{{- toYaml .Values.telegram | nindent 6 }}
|
||||
|
||||
logging:
|
||||
{{- toYaml .Values.logging | nindent 6 }}
|
||||
registration.yaml: ""
|
||||
@@ -0,0 +1,69 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "mautrix-telegram.fullname" . }}
|
||||
labels:
|
||||
{{- include "mautrix-telegram.labels" . | nindent 4 }}
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/name: {{ include "mautrix-telegram.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
template:
|
||||
{{- if .Values.podAnnotations }}
|
||||
annotations:
|
||||
{{- toYaml .Values.podAnnotations | nindent 6 }}
|
||||
{{- end }}
|
||||
metadata:
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "mautrix-telegram.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
spec:
|
||||
serviceAccountName: {{ template "mautrix-telegram.serviceAccountName" . }}
|
||||
containers:
|
||||
- name: {{ .Chart.Name }}
|
||||
securityContext:
|
||||
{{- toYaml .Values.securityContext | nindent 12 }}
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
volumeMounts:
|
||||
- mountPath: /data
|
||||
name: config-volume
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: {{ .Values.service.port }}
|
||||
protocol: TCP
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /_matrix/mau/live
|
||||
port: http
|
||||
initialDelaySeconds: 60
|
||||
periodSeconds: 5
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /_matrix/mau/ready
|
||||
port: http
|
||||
initialDelaySeconds: 60
|
||||
periodSeconds: 5
|
||||
resources:
|
||||
{{- toYaml .Values.resources | nindent 12 }}
|
||||
volumes:
|
||||
- name: config-volume
|
||||
configMap:
|
||||
name: {{ template "mautrix-telegram.fullname" . }}
|
||||
|
||||
securityContext:
|
||||
{{- toYaml .Values.podSecurityContext | nindent 8 }}
|
||||
{{- with .Values.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.affinity }}
|
||||
affinity:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.tolerations }}
|
||||
tolerations:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,16 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "mautrix-telegram.fullname" . }}
|
||||
labels:
|
||||
{{ include "mautrix-telegram.labels" . | indent 4 }}
|
||||
spec:
|
||||
type: {{ .Values.service.type }}
|
||||
ports:
|
||||
- port: {{ .Values.service.port }}
|
||||
targetPort: http
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
app.kubernetes.io/name: {{ include "mautrix-telegram.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
@@ -0,0 +1,8 @@
|
||||
{{- if .Values.serviceAccount.create -}}
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: {{ template "mautrix-telegram.serviceAccountName" . }}
|
||||
labels:
|
||||
{{ include "mautrix-telegram.labels" . | indent 4 }}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,141 @@
|
||||
image:
|
||||
repository: dock.mau.dev/tulir/mautrix-telegram
|
||||
tag: latest
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
nameOverride: ""
|
||||
fullnameOverride: ""
|
||||
|
||||
serviceAccount:
|
||||
# Specifies whether a service account should be created
|
||||
create: true
|
||||
# The name of the service account to use.
|
||||
# If not set and create is true, a name is generated using the fullname template
|
||||
name:
|
||||
|
||||
service:
|
||||
type: ClusterIP
|
||||
port: 29317
|
||||
|
||||
resources: {}
|
||||
# limits:
|
||||
# cpu: 100m
|
||||
# memory: 128Mi
|
||||
# requests:
|
||||
# cpu: 100m
|
||||
# memory: 128Mi
|
||||
|
||||
nodeSelector: {}
|
||||
|
||||
tolerations: []
|
||||
|
||||
affinity: {}
|
||||
|
||||
# Postgres pod configs
|
||||
postgresql:
|
||||
enabled: true
|
||||
postgresqlDatabase: mxtg
|
||||
postgresqlPassword: SET TO RANDOM STRING
|
||||
persistence:
|
||||
size: 2Gi
|
||||
resources:
|
||||
requests:
|
||||
memory: 256Mi
|
||||
cpu: 100m
|
||||
|
||||
# Homeserver details
|
||||
homeserver:
|
||||
# The address that this appservice can use to connect to the homeserver.
|
||||
address: https://example.com
|
||||
# The domain of the homeserver (for MXIDs, etc).
|
||||
domain: example.com
|
||||
# Whether or not to verify the SSL certificate of the homeserver.
|
||||
# Only applies if address starts with https://
|
||||
verifySSL: true
|
||||
|
||||
# Application service host/registration related details
|
||||
# Changing these values requires regeneration of the registration.
|
||||
appservice:
|
||||
# The maximum body size of appservice API requests (from the homeserver) in mebibytes
|
||||
# Usually 1 is enough, but on high-traffic bridges you might need to increase this to avoid 413s
|
||||
maxBodySize: 1
|
||||
|
||||
# Public part of web server for out-of-Matrix interaction with the bridge.
|
||||
# Used for things like login if the user wants to make sure the 2FA password isn't stored in
|
||||
# the HS database.
|
||||
public:
|
||||
# Whether or not the public-facing endpoints should be enabled.
|
||||
enabled: true
|
||||
# The prefix to use in the public-facing endpoints.
|
||||
prefix: /public
|
||||
# The base URL where the public-facing endpoints are available. The prefix is not added
|
||||
# implicitly.
|
||||
external: https://example.com/public
|
||||
|
||||
# Provisioning API part of the web server for automated portal creation and fetching information.
|
||||
# Used by things like Dimension (https://dimension.t2bot.io/).
|
||||
provisioning:
|
||||
# Whether or not the provisioning API should be enabled.
|
||||
enabled: true
|
||||
# The prefix to use in the provisioning API endpoints.
|
||||
prefix: /_matrix/provision/v1
|
||||
# The shared secret to authorize users of the API.
|
||||
shared_secret: SET TO RANDOM STRING
|
||||
|
||||
id: telegram
|
||||
botUsername: telegrambot
|
||||
# Display name and avatar for bot. Set to "remove" to remove display name/avatar, leave empty
|
||||
# to leave display name/avatar as-is.
|
||||
botDisplayname: Telegram bridge bot
|
||||
botAvatar: mxc://maunium.net/tJCRmUyJDsgRNgqhOgoiHWbX
|
||||
|
||||
# Community ID for bridged users (changes registration file) and rooms.
|
||||
# Must be created manually.
|
||||
communityID: false
|
||||
|
||||
# Authentication tokens for AS <-> HS communication. Autogenerated; do not modify.
|
||||
asToken: SET TO RANDOM STRING
|
||||
hsToken: SET TO RANDOM STRING
|
||||
|
||||
# The keys below can be used to override the configs in the base config:
|
||||
# https://github.com/tulir/mautrix-telegram/blob/master/example-config.yaml
|
||||
# Note that the "appservice" and "homeserver" sections are above and slightly different than the base.
|
||||
|
||||
# Bridge config
|
||||
bridge:
|
||||
# Localpart template of MXIDs for Telegram users.
|
||||
# {userid} is replaced with the user ID of the Telegram user.
|
||||
username_template: "telegram_{userid}"
|
||||
# Localpart template of room aliases for Telegram portal rooms.
|
||||
# {groupname} is replaced with the name part of the public channel/group invite link ( https://t.me/{} )
|
||||
alias_template: "telegram_{groupname}"
|
||||
|
||||
# Permissions for using the bridge.
|
||||
# Permitted values:
|
||||
# relaybot - Only use the bridge via the relaybot, no access to commands.
|
||||
# user - Relaybot level + access to commands to create bridges.
|
||||
# puppeting - User level + logging in with a Telegram account.
|
||||
# full - Full access to use the bridge, i.e. previous levels + Matrix login.
|
||||
# admin - Full access to use the bridge and some extra administration commands.
|
||||
# Permitted keys:
|
||||
# * - All Matrix users
|
||||
# domain - All users on that homeserver
|
||||
# mxid - Specific user
|
||||
permissions:
|
||||
"*": "relaybot"
|
||||
"public.example.com": "user"
|
||||
"example.com": "full"
|
||||
"@admin:example.com": "admin"
|
||||
|
||||
# Prometheus telemetry config.
|
||||
metrics:
|
||||
enabled: false
|
||||
listen_port: 8000
|
||||
|
||||
# Telegram config
|
||||
telegram:
|
||||
# Get your own API keys at https://my.telegram.org/apps
|
||||
api_id: 12345
|
||||
api_hash: tjyd5yge35lbodk1xwzw2jstp90k55qz
|
||||
# (Optional) Create your own bot at https://t.me/BotFather
|
||||
# bot_token: 123456789:
|
||||
@@ -1,5 +0,0 @@
|
||||
from .appservice import AppService
|
||||
from .errors import MatrixError, MatrixRequestError, IntentError
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__author__ = "Tulir Asokan <tulir@maunium.net>"
|
||||
@@ -1,180 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# matrix-appservice-python - A Matrix Application Service framework written in Python.
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Partly based on github.com/Cadair/python-appservice-framework (MIT license)
|
||||
from functools import partial
|
||||
from contextlib import contextmanager
|
||||
from aiohttp import web
|
||||
import aiohttp
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from .intent_api import HTTPAPI
|
||||
from .state_store import StateStore
|
||||
|
||||
|
||||
class AppService:
|
||||
def __init__(self, server, domain, as_token, hs_token, bot_localpart, loop=None, log=None,
|
||||
query_user=None, query_alias=None):
|
||||
self.server = server
|
||||
self.domain = domain
|
||||
self.as_token = as_token
|
||||
self.hs_token = hs_token
|
||||
self.bot_mxid = f"@{bot_localpart}:{domain}"
|
||||
self.state_store = StateStore(autosave_file="mx-state.json")
|
||||
self.state_store.load("mx-state.json")
|
||||
|
||||
self.transactions = []
|
||||
|
||||
self._http_session = None
|
||||
self._intent = None
|
||||
|
||||
self.loop = loop or asyncio.get_event_loop()
|
||||
self.log = (logging.getLogger(log) if isinstance(log, str)
|
||||
else log or logging.getLogger("mautrix_appservice"))
|
||||
|
||||
def default_query_handler(_):
|
||||
return None
|
||||
|
||||
self.query_user = query_user or default_query_handler
|
||||
self.query_alias = query_alias or default_query_handler
|
||||
|
||||
self.event_handlers = []
|
||||
|
||||
self.app = web.Application(loop=self.loop)
|
||||
self.app.router.add_route("PUT", "/transactions/{transaction_id}",
|
||||
self._http_handle_transaction)
|
||||
self.app.router.add_route("GET", "/rooms/{alias}", self._http_query_alias)
|
||||
self.app.router.add_route("GET", "/users/{user_id}", self._http_query_user)
|
||||
|
||||
self.matrix_event_handler(self.update_state_store)
|
||||
|
||||
@property
|
||||
def http_session(self):
|
||||
if self._http_session is None:
|
||||
raise AttributeError("the http_session attribute can only be used "
|
||||
"from within the `AppService.run` context manager")
|
||||
else:
|
||||
return self._http_session
|
||||
|
||||
@property
|
||||
def intent(self):
|
||||
if self._intent is None:
|
||||
raise AttributeError("the intent attribute can only be used from "
|
||||
"within the `AppService.run` context manager")
|
||||
else:
|
||||
return self._intent
|
||||
|
||||
@contextmanager
|
||||
def run(self, host="127.0.0.1", port=8080):
|
||||
self._http_session = aiohttp.ClientSession(loop=self.loop)
|
||||
self._intent = HTTPAPI(base_url=self.server, domain=self.domain, bot_mxid=self.bot_mxid,
|
||||
token=self.as_token, log=self.log, state_store=self.state_store,
|
||||
client_session=self._http_session).bot_intent()
|
||||
|
||||
yield self.loop.create_server(self.app.make_handler(), host, port)
|
||||
|
||||
self._intent = None
|
||||
self._http_session.close()
|
||||
self._http_session = None
|
||||
|
||||
def _check_token(self, request):
|
||||
try:
|
||||
token = request.rel_url.query["access_token"]
|
||||
except KeyError:
|
||||
return False
|
||||
|
||||
if token != self.hs_token:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
async def _http_query_user(self, request):
|
||||
if not self._check_token(request):
|
||||
return web.Response(status=401)
|
||||
|
||||
user_id = request.match_info["userId"]
|
||||
|
||||
try:
|
||||
response = await self.query_user(user_id)
|
||||
except Exception:
|
||||
self.log.exception("Exception in user query handler")
|
||||
return web.Response(status=500)
|
||||
|
||||
if not response:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(response)
|
||||
|
||||
async def _http_query_alias(self, request):
|
||||
if not self._check_token(request):
|
||||
return web.Response(status=401)
|
||||
|
||||
alias = request.match_info["alias"]
|
||||
|
||||
try:
|
||||
response = await self.query_alias(alias)
|
||||
except Exception:
|
||||
self.log.exception("Exception in alias query handler")
|
||||
return web.Response(status=500)
|
||||
|
||||
if not response:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(response)
|
||||
|
||||
async def _http_handle_transaction(self, request):
|
||||
if not self._check_token(request):
|
||||
return web.Response(status=401)
|
||||
|
||||
transaction_id = request.match_info["transaction_id"]
|
||||
if transaction_id in self.transactions:
|
||||
return web.Response(status=200)
|
||||
|
||||
json = await request.json()
|
||||
|
||||
try:
|
||||
events = json["events"]
|
||||
except KeyError:
|
||||
return web.Response(status=400)
|
||||
|
||||
for event in events:
|
||||
self.handle_matrix_event(event)
|
||||
|
||||
self.transactions.append(transaction_id)
|
||||
|
||||
return web.json_response({})
|
||||
|
||||
async def update_state_store(self, event):
|
||||
event_type = event["type"]
|
||||
if event_type == "m.room.power_levels":
|
||||
self.state_store.set_power_levels(event["room_id"], event["content"])
|
||||
elif event_type == "m.room.member":
|
||||
self.state_store.set_membership(event["room_id"], event["state_key"],
|
||||
event["content"]["membership"])
|
||||
|
||||
def handle_matrix_event(self, event):
|
||||
async def try_handle(handler):
|
||||
try:
|
||||
await handler(event)
|
||||
except Exception:
|
||||
self.log.exception("Exception in Matrix event handler")
|
||||
|
||||
for handler in self.event_handlers:
|
||||
asyncio.ensure_future(try_handle(handler), loop=self.loop)
|
||||
|
||||
def matrix_event_handler(self, func):
|
||||
self.event_handlers.append(func)
|
||||
return func
|
||||
@@ -1,38 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
class MatrixError(Exception):
|
||||
"""A generic Matrix error. Specific errors will subclass this."""
|
||||
pass
|
||||
|
||||
|
||||
class IntentError(MatrixError):
|
||||
def __init__(self, message, source):
|
||||
super().__init__(message)
|
||||
self.source = source
|
||||
|
||||
|
||||
class MatrixRequestError(MatrixError):
|
||||
""" The home server returned an error response. """
|
||||
|
||||
def __init__(self, code=0, text="", errcode=None, message=None):
|
||||
super().__init__("%d: %s" % (code, text))
|
||||
self.code = code
|
||||
self.text = text
|
||||
self.errcode = errcode
|
||||
self.message = message
|
||||
@@ -1,521 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from urllib.parse import quote
|
||||
from time import time
|
||||
from json.decoder import JSONDecodeError
|
||||
from aiohttp.client_exceptions import ContentTypeError
|
||||
import re
|
||||
import json
|
||||
import magic
|
||||
import asyncio
|
||||
|
||||
from .errors import MatrixError, MatrixRequestError, IntentError
|
||||
|
||||
|
||||
class HTTPAPI:
|
||||
def __init__(self, base_url, domain=None, bot_mxid=None, token=None, identity=None, log=None,
|
||||
state_store=None, client_session=None, child=False):
|
||||
self.base_url = base_url
|
||||
self.token = token
|
||||
self.identity = identity
|
||||
self.validate_cert = True
|
||||
self.session = client_session
|
||||
|
||||
self.domain = domain
|
||||
self.bot_mxid = bot_mxid
|
||||
self._bot_intent = None
|
||||
self.state_store = state_store
|
||||
|
||||
if child:
|
||||
self.log = log
|
||||
else:
|
||||
self.intent_log = log.getChild("intent")
|
||||
self.log = log.getChild("api")
|
||||
self.txn_id = 0
|
||||
self.children = {}
|
||||
|
||||
def user(self, user):
|
||||
try:
|
||||
return self.children[user]
|
||||
except KeyError:
|
||||
child = ChildHTTPAPI(user, self)
|
||||
self.children[user] = child
|
||||
return child
|
||||
|
||||
def bot_intent(self):
|
||||
if self._bot_intent:
|
||||
return self._bot_intent
|
||||
return IntentAPI(self.bot_mxid, self, state_store=self.state_store, log=self.intent_log)
|
||||
|
||||
def intent(self, user):
|
||||
return IntentAPI(user, self.user(user), self.bot_intent(), self.state_store,
|
||||
self.intent_log)
|
||||
|
||||
async def _send(self, method, endpoint, content, query_params, headers):
|
||||
while True:
|
||||
query_params["access_token"] = self.token
|
||||
request = self.session.request(method, endpoint, params=query_params,
|
||||
data=content, headers=headers)
|
||||
async with request as response:
|
||||
if response.status < 200 or response.status >= 300:
|
||||
errcode = message = None
|
||||
try:
|
||||
response_data = await response.json()
|
||||
errcode = response_data["errcode"]
|
||||
message = response_data["error"]
|
||||
except (JSONDecodeError, ContentTypeError, KeyError):
|
||||
pass
|
||||
raise MatrixRequestError(code=response.status, text=await response.text(),
|
||||
errcode=errcode, message=message)
|
||||
|
||||
if response.status == 429:
|
||||
await asyncio.sleep(response.json()["retry_after_ms"] / 1000)
|
||||
else:
|
||||
return await response.json()
|
||||
|
||||
def _log_request(self, method, path, content, query_params):
|
||||
log_content = content if not isinstance(content, bytes) else f"<{len(content)} bytes>"
|
||||
log_content = log_content or "(No content)"
|
||||
query_identity = query_params["user_id"] if "user_id" in query_params else "No identity"
|
||||
self.log.debug("%s %s %s as user %s", method, path, log_content, query_identity)
|
||||
|
||||
def request(self, method, path, content=None, query_params=None, headers=None,
|
||||
api_path="/_matrix/client/r0"):
|
||||
content = content or {}
|
||||
query_params = query_params or {}
|
||||
headers = headers or {}
|
||||
|
||||
method = method.upper()
|
||||
if method not in ["GET", "PUT", "DELETE", "POST"]:
|
||||
raise MatrixError("Unsupported HTTP method: %s" % method)
|
||||
|
||||
if "Content-Type" not in headers:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if headers["Content-Type"] == "application/json":
|
||||
content = json.dumps(content)
|
||||
|
||||
if self.identity:
|
||||
query_params["user_id"] = self.identity
|
||||
|
||||
self._log_request(method, path, content, query_params)
|
||||
|
||||
endpoint = self.base_url + api_path + path
|
||||
return self._send(method, endpoint, content, query_params, headers or {})
|
||||
|
||||
def get_download_url(self, mxcurl):
|
||||
if mxcurl.startswith('mxc://'):
|
||||
return f"{self.base_url}/_matrix/media/r0/download/{mxcurl[6:]}"
|
||||
else:
|
||||
raise ValueError("MXC URL did not begin with 'mxc://'")
|
||||
|
||||
async def get_display_name(self, user_id):
|
||||
content = await self.request("GET", f"/profile/{user_id}/displayname")
|
||||
return content.get('displayname', None)
|
||||
|
||||
async def get_avatar_url(self, user_id):
|
||||
content = await self.request("GET", f"/profile/{user_id}/avatar_url")
|
||||
return content.get('avatar_url', None)
|
||||
|
||||
async def get_room_id(self, room_alias):
|
||||
content = await self.request("GET", f"/directory/room/{quote(room_alias)}")
|
||||
return content.get("room_id", None)
|
||||
|
||||
def set_typing(self, room_id, is_typing=True, timeout=5000, user=None):
|
||||
content = {
|
||||
"typing": is_typing
|
||||
}
|
||||
if is_typing:
|
||||
content["timeout"] = timeout
|
||||
user = user or self.identity
|
||||
return self.request("PUT", f"/rooms/{room_id}/typing/{user}", content)
|
||||
|
||||
|
||||
class ChildHTTPAPI(HTTPAPI):
|
||||
def __init__(self, user, parent):
|
||||
super().__init__(parent.base_url, parent.domain, parent.bot_mxid, parent.token, user,
|
||||
parent.log, parent.state_store, parent.session, child=True)
|
||||
self.parent = parent
|
||||
|
||||
@property
|
||||
def txn_id(self):
|
||||
return self.parent.txn_id
|
||||
|
||||
@txn_id.setter
|
||||
def txn_id(self, value):
|
||||
self.parent.txn_id = value
|
||||
|
||||
|
||||
class IntentAPI:
|
||||
mxid_regex = re.compile("@(.+):(.+)")
|
||||
|
||||
def __init__(self, mxid, client, bot=None, state_store=None, log=None):
|
||||
self.client = client
|
||||
self.bot = bot
|
||||
self.mxid = mxid
|
||||
self.log = log
|
||||
|
||||
results = self.mxid_regex.search(mxid)
|
||||
if not results:
|
||||
raise ValueError("invalid MXID")
|
||||
self.localpart = results.group(1)
|
||||
|
||||
self.state_store = state_store
|
||||
|
||||
def user(self, user):
|
||||
if not self.bot:
|
||||
return self.client.intent(user)
|
||||
else:
|
||||
self.log.warning("Called IntentAPI#user() of child intent object.")
|
||||
return self.bot.client.intent(user)
|
||||
|
||||
# region User actions
|
||||
|
||||
async def get_joined_rooms(self):
|
||||
await self.ensure_registered()
|
||||
response = await self.client.request("GET", "/joined_rooms")
|
||||
return response["joined_rooms"]
|
||||
|
||||
async def set_display_name(self, name):
|
||||
await self.ensure_registered()
|
||||
content = {"displayname": name}
|
||||
return await self.client.request("PUT", f"/profile/{self.mxid}/displayname", content)
|
||||
|
||||
async def set_presence(self, status="online"):
|
||||
await self.ensure_registered()
|
||||
content = {
|
||||
"presence": status
|
||||
}
|
||||
return await self.client.request("PUT", f"/presence/{self.mxid}/status", content)
|
||||
|
||||
async def set_avatar(self, url):
|
||||
await self.ensure_registered()
|
||||
content = {"avatar_url": url}
|
||||
return await self.client.request("PUT", f"/profile/{self.mxid}/avatar_url", content)
|
||||
|
||||
async def upload_file(self, data, mime_type=None):
|
||||
await self.ensure_registered()
|
||||
mime_type = mime_type or magic.from_buffer(data, mime=True)
|
||||
return await self.client.request("POST", "", content=data,
|
||||
headers={"Content-Type": mime_type},
|
||||
api_path="/_matrix/media/r0/upload")
|
||||
|
||||
async def download_file(self, url):
|
||||
await self.ensure_registered()
|
||||
url = self.client.get_download_url(url)
|
||||
async with self.client.session.get(url) as response:
|
||||
return await response.read()
|
||||
|
||||
# endregion
|
||||
# region Room actions
|
||||
|
||||
async def create_room(self, alias=None, is_public=False, name=None, topic=None,
|
||||
is_direct=False, invitees=None, initial_state=None):
|
||||
await self.ensure_registered()
|
||||
content = {
|
||||
"visibility": "public" if is_public else "private",
|
||||
"is_direct": is_direct,
|
||||
}
|
||||
if alias:
|
||||
content["room_alias_name"] = alias
|
||||
if invitees:
|
||||
content["invite"] = invitees
|
||||
if name:
|
||||
content["name"] = name
|
||||
if topic:
|
||||
content["topic"] = topic
|
||||
if initial_state:
|
||||
content["initial_state"] = initial_state
|
||||
|
||||
return await self.client.request("POST", "/createRoom", content)
|
||||
|
||||
def _invite_direct(self, room_id, user_id):
|
||||
content = {"user_id": user_id}
|
||||
return self.client.request("POST", "/rooms/" + room_id + "/invite", content)
|
||||
|
||||
async def invite(self, room_id, user_id, check_cache=False):
|
||||
await self.ensure_joined(room_id)
|
||||
try:
|
||||
ok_states = {"invite", "join"}
|
||||
do_invite = (not check_cache
|
||||
or self.state_store.get_membership(room_id, user_id) not in ok_states)
|
||||
if do_invite:
|
||||
response = await self._invite_direct(room_id, user_id)
|
||||
self.state_store.invited(room_id, user_id)
|
||||
return response
|
||||
except MatrixRequestError as e:
|
||||
if e.errcode != "M_FORBIDDEN":
|
||||
raise IntentError(f"Failed to invite {user_id} to {room_id}", e)
|
||||
if "is already in the room" in e.message:
|
||||
self.state_store.joined(room_id, user_id)
|
||||
|
||||
def set_room_avatar(self, room_id, avatar_url, info=None):
|
||||
content = {
|
||||
"url": avatar_url,
|
||||
}
|
||||
if info:
|
||||
content["info"] = info
|
||||
return self.send_state_event(room_id, "m.room.avatar", content)
|
||||
|
||||
async def add_room_alias(self, room_id, localpart):
|
||||
await self.ensure_registered()
|
||||
content = {"room_id": room_id}
|
||||
alias = f"#{localpart}:{self.client.domain}"
|
||||
return await self.client.request("PUT", f"/directory/room/{quote(alias)}", content)
|
||||
|
||||
async def remove_room_alias(self, localpart):
|
||||
await self.ensure_registered()
|
||||
alias = f"#{localpart}:{self.client.domain}"
|
||||
return await self.client.request("DELETE", f"/directory/room/{quote(alias)}")
|
||||
|
||||
def set_room_name(self, room_id, name):
|
||||
body = {"name": name}
|
||||
return self.send_state_event(room_id, "m.room.name", body)
|
||||
|
||||
async def get_power_levels(self, room_id, ignore_cache=False):
|
||||
await self.ensure_joined(room_id)
|
||||
if not ignore_cache:
|
||||
try:
|
||||
return self.state_store.get_power_levels(room_id)
|
||||
except KeyError:
|
||||
pass
|
||||
levels = await self.client.request("GET",
|
||||
f"/rooms/{quote(room_id)}/state/m.room.power_levels")
|
||||
self.state_store.set_power_levels(room_id, levels)
|
||||
return levels
|
||||
|
||||
async def set_power_levels(self, room_id, content):
|
||||
if "events" not in content:
|
||||
content["events"] = {}
|
||||
response = await self.send_state_event(room_id, "m.room.power_levels", content)
|
||||
self.state_store.set_power_levels(room_id, content)
|
||||
return response
|
||||
|
||||
async def get_pinned_messages(self, room_id):
|
||||
await self.ensure_joined(room_id)
|
||||
response = await self.client.request("GET", f"/rooms/{room_id}/state/m.room.pinned_events")
|
||||
return response["content"]["pinned"]
|
||||
|
||||
def set_pinned_messages(self, room_id, events):
|
||||
return self.send_state_event(room_id, "m.room.pinned_events", {
|
||||
"pinned": events
|
||||
})
|
||||
|
||||
async def pin_message(self, room_id, event_id):
|
||||
events = await self.get_pinned_messages(room_id)
|
||||
if event_id not in events:
|
||||
events.append(event_id)
|
||||
await self.set_pinned_messages(room_id, events)
|
||||
|
||||
async def unpin_message(self, room_id, event_id):
|
||||
events = await self.get_pinned_messages(room_id)
|
||||
if event_id in events:
|
||||
events.remove(event_id)
|
||||
await self.set_pinned_messages(room_id, events)
|
||||
|
||||
async def get_event(self, room_id, event_id):
|
||||
await self.ensure_joined(room_id)
|
||||
return await self.client.request("GET", f"/rooms/{room_id}/event/{event_id}")
|
||||
|
||||
async def set_typing(self, room_id, is_typing=True, timeout=5000):
|
||||
await self.ensure_joined(room_id)
|
||||
content = {
|
||||
"typing": is_typing
|
||||
}
|
||||
if is_typing:
|
||||
content["timeout"] = timeout
|
||||
return await self.client.request("PUT", f"/rooms/{room_id}/typing/{self.mxid}", content)
|
||||
|
||||
async def mark_read(self, room_id, event_id):
|
||||
await self.ensure_joined(room_id)
|
||||
return await self.client.request("POST", f"/rooms/{room_id}/receipt/m.read/{event_id}",
|
||||
content={})
|
||||
|
||||
def send_notice(self, room_id, text, html=None, relates_to=None):
|
||||
return self.send_text(room_id, text, html, "m.notice", relates_to)
|
||||
|
||||
def send_emote(self, room_id, text, html=None, relates_to=None):
|
||||
return self.send_text(room_id, text, html, "m.emote", relates_to)
|
||||
|
||||
def send_image(self, room_id, url, info=None, text=None, relates_to=None):
|
||||
return self.send_file(room_id, url, info or {}, text, "m.image", relates_to)
|
||||
|
||||
def send_file(self, room_id, url, info=None, text=None, file_type="m.file", relates_to=None):
|
||||
return self.send_message(room_id, {
|
||||
"msgtype": file_type,
|
||||
"url": url,
|
||||
"body": text or "Uploaded file",
|
||||
"info": info or {},
|
||||
"m.relates_to": relates_to or None,
|
||||
})
|
||||
|
||||
def send_text(self, room_id, text, html=None, msgtype="m.text", relates_to=None):
|
||||
if html:
|
||||
if not text:
|
||||
text = html
|
||||
return self.send_message(room_id, {
|
||||
"body": text,
|
||||
"msgtype": msgtype,
|
||||
"format": "org.matrix.custom.html",
|
||||
"formatted_body": html or text,
|
||||
"m.relates_to": relates_to or None,
|
||||
})
|
||||
else:
|
||||
return self.send_message(room_id, {
|
||||
"body": text,
|
||||
"msgtype": msgtype,
|
||||
"m.relates_to": relates_to or None,
|
||||
})
|
||||
|
||||
def send_message(self, room_id, body):
|
||||
return self.send_event(room_id, "m.room.message", body)
|
||||
|
||||
async def error_and_leave(self, room_id, text, html=None):
|
||||
await self.ensure_joined(room_id)
|
||||
await self.send_notice(room_id, text, html=html)
|
||||
await self.leave_room(room_id)
|
||||
|
||||
def kick(self, room_id, user_id, message):
|
||||
return self.set_membership(room_id, user_id, "leave", message)
|
||||
|
||||
def get_membership(self, room_id, user_id):
|
||||
return self.get_state_event(room_id, "m.room.member", state_key=user_id)
|
||||
|
||||
def set_membership(self, room_id, user_id, membership, reason="", profile=None):
|
||||
body = {
|
||||
"membership": membership,
|
||||
"reason": reason
|
||||
}
|
||||
profile = profile or {}
|
||||
if "displayname" in profile:
|
||||
body["displayname"] = profile["displayname"]
|
||||
if "avatar_url" in profile:
|
||||
body["avatar_url"] = profile["avatar_url"]
|
||||
|
||||
return self.send_state_event(room_id, "m.room.member", body, state_key=user_id)
|
||||
|
||||
@staticmethod
|
||||
def _get_event_url(room_id, event_type, txn_id):
|
||||
return f"/rooms/{quote(room_id)}/send/{quote(event_type)}/{quote(txn_id)}"
|
||||
|
||||
async def send_event(self, room_id, event_type, content, txn_id=None):
|
||||
await self.ensure_joined(room_id)
|
||||
await self._ensure_has_power_level_for(room_id, event_type)
|
||||
|
||||
txn_id = txn_id or str(self.client.txn_id) + str(int(time() * 1000))
|
||||
self.client.txn_id += 1
|
||||
|
||||
url = self._get_event_url(room_id, event_type, txn_id)
|
||||
|
||||
return await self.client.request("PUT", url, content)
|
||||
|
||||
@staticmethod
|
||||
def _get_state_url(room_id, event_type, state_key=""):
|
||||
url = f"/rooms/{quote(room_id)}/state/{quote(event_type)}"
|
||||
if state_key:
|
||||
url += f"/{quote(state_key)}"
|
||||
return url
|
||||
|
||||
async def send_state_event(self, room_id, event_type, content, state_key=""):
|
||||
await self.ensure_joined(room_id)
|
||||
await self._ensure_has_power_level_for(room_id, event_type)
|
||||
url = self._get_state_url(room_id, event_type, state_key)
|
||||
return await self.client.request("PUT", url, content)
|
||||
|
||||
async def get_state_event(self, room_id, event_type, state_key=""):
|
||||
await self.ensure_joined(room_id)
|
||||
url = self._get_state_url(room_id, event_type, state_key)
|
||||
return await self.client.request("GET", url)
|
||||
|
||||
def join_room(self, room_id):
|
||||
return self.ensure_joined(room_id, ignore_cache=True)
|
||||
|
||||
def _join_room_direct(self, room):
|
||||
return self.client.request("POST", f"/join/{quote(room)}")
|
||||
|
||||
def leave_room(self, room_id):
|
||||
try:
|
||||
self.state_store.left(room_id, self.mxid)
|
||||
return self.client.request("POST", f"/rooms/{quote(room_id)}/leave")
|
||||
except MatrixRequestError as e:
|
||||
if "not in room" not in e.message:
|
||||
raise
|
||||
|
||||
def get_room_memberships(self, room_id):
|
||||
return self.client.request("GET", f"/rooms/{quote(room_id)}/members")
|
||||
|
||||
async def get_room_members(self, room_id, allowed_memberships=("join",)):
|
||||
memberships = await self.get_room_memberships(room_id)
|
||||
return [membership["state_key"] for membership in memberships["chunk"] if
|
||||
membership["content"]["membership"] in allowed_memberships]
|
||||
|
||||
async def get_room_state(self, room_id):
|
||||
await self.ensure_joined(room_id)
|
||||
state = await self.client.request("GET", f"/rooms/{quote(room_id)}/state")
|
||||
# TODO update values based on state?
|
||||
return state
|
||||
|
||||
# endregion
|
||||
# region Ensure functions
|
||||
|
||||
async def ensure_joined(self, room_id, ignore_cache=False):
|
||||
if not ignore_cache and self.state_store.is_joined(room_id, self.mxid):
|
||||
return
|
||||
await self.ensure_registered()
|
||||
try:
|
||||
await self._join_room_direct(room_id)
|
||||
self.state_store.joined(room_id, self.mxid)
|
||||
except MatrixRequestError as e:
|
||||
if e.errcode != "M_FORBIDDEN" or not self.bot:
|
||||
raise IntentError(f"Failed to join room {room_id} as {self.mxid}", e)
|
||||
try:
|
||||
await self.bot.invite(room_id, self.mxid)
|
||||
await self._join_room_direct(room_id)
|
||||
self.state_store.joined(room_id, self.mxid)
|
||||
except MatrixRequestError as e2:
|
||||
raise IntentError(f"Failed to join room {room_id} as {self.mxid}", e2)
|
||||
|
||||
def _register(self):
|
||||
content = {"username": self.localpart}
|
||||
query_params = {"kind": "user"}
|
||||
return self.client.request("POST", "/register", content, query_params)
|
||||
|
||||
async def ensure_registered(self):
|
||||
if self.state_store.is_registered(self.mxid):
|
||||
return
|
||||
try:
|
||||
await self._register()
|
||||
except MatrixRequestError as e:
|
||||
if e.errcode != "M_USER_IN_USE":
|
||||
self.log.exception(f"Failed to register {self.mxid}!")
|
||||
# raise IntentError(f"Failed to register {self.mxid}", e)
|
||||
return
|
||||
self.state_store.registered(self.mxid)
|
||||
|
||||
async def _ensure_has_power_level_for(self, room_id, event_type):
|
||||
if not self.state_store.has_power_levels(room_id):
|
||||
await self.get_power_levels(room_id)
|
||||
if self.state_store.has_power_level(room_id, self.mxid, event_type):
|
||||
return
|
||||
elif not self.bot:
|
||||
self.log.warning(
|
||||
f"Power level of {self.mxid} is not enough for {event_type} in {room_id}")
|
||||
# raise IntentError(f"Power level of {self.mxid} is not enough"
|
||||
# + f"for {event_type} in {room_id}")
|
||||
return
|
||||
# TODO implement
|
||||
|
||||
# endregion
|
||||
@@ -1,123 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# matrix-appservice-python - A Matrix Application Service framework written in Python.
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import json
|
||||
|
||||
|
||||
class StateStore:
|
||||
def __init__(self, autosave_file=None):
|
||||
self.registrations = set()
|
||||
self.memberships = {}
|
||||
self.power_levels = {}
|
||||
self.autosave_file = autosave_file
|
||||
|
||||
def save(self, file):
|
||||
if isinstance(file, str):
|
||||
output = open(file, "w")
|
||||
else:
|
||||
output = file
|
||||
|
||||
json.dump({
|
||||
"registrations": list(self.registrations),
|
||||
"memberships": self.memberships,
|
||||
"power_levels": self.power_levels,
|
||||
}, output)
|
||||
|
||||
if isinstance(file, str):
|
||||
output.close()
|
||||
|
||||
def load(self, file):
|
||||
if isinstance(file, str):
|
||||
try:
|
||||
input_source = open(file, "r")
|
||||
except FileNotFoundError:
|
||||
return
|
||||
else:
|
||||
input_source = file
|
||||
|
||||
data = json.load(input_source)
|
||||
if "registrations" in data:
|
||||
self.registrations = set(data["registrations"])
|
||||
if "memberships" in data:
|
||||
self.memberships = data["memberships"]
|
||||
if "power_levels" in data:
|
||||
self.power_levels = data["power_levels"]
|
||||
|
||||
if isinstance(file, str):
|
||||
input_source.close()
|
||||
|
||||
def _autosave(self):
|
||||
if self.autosave_file:
|
||||
self.save(self.autosave_file)
|
||||
|
||||
def is_registered(self, user):
|
||||
return user in self.registrations
|
||||
|
||||
def registered(self, user):
|
||||
self.registrations.add(user)
|
||||
self._autosave()
|
||||
|
||||
def get_membership(self, room, user):
|
||||
return self.memberships.get(room, {}).get(user, "left")
|
||||
|
||||
def is_joined(self, room, user):
|
||||
return self.get_membership(room, user) == "join"
|
||||
|
||||
def set_membership(self, room, user, membership):
|
||||
if room not in self.memberships:
|
||||
self.memberships[room] = {}
|
||||
self.memberships[room][user] = membership
|
||||
self._autosave()
|
||||
|
||||
def joined(self, room, user):
|
||||
return self.set_membership(room, user, "join")
|
||||
|
||||
def invited(self, room, user):
|
||||
return self.set_membership(room, user, "invite")
|
||||
|
||||
def left(self, room, user):
|
||||
return self.set_membership(room, user, "left")
|
||||
|
||||
def has_power_levels(self, room):
|
||||
return room in self.power_levels
|
||||
|
||||
def get_power_levels(self, room):
|
||||
return self.power_levels[room]
|
||||
|
||||
def has_power_level(self, room, user, event):
|
||||
room_levels = self.power_levels.get(room, {})
|
||||
required = room_levels.get("events", {}).get(event, 95)
|
||||
has = room_levels.get("users", {}).get(user, 0)
|
||||
return has >= required
|
||||
|
||||
def set_power_level(self, room, user, level):
|
||||
if room not in self.power_levels:
|
||||
self.power_levels[room] = {
|
||||
"users": {},
|
||||
"events": {},
|
||||
}
|
||||
elif "users" not in self.power_levels[room]:
|
||||
self.power_levels[room]["users"] = {}
|
||||
self.power_levels[room]["users"][user] = level
|
||||
self._autosave()
|
||||
|
||||
def set_power_levels(self, room, content):
|
||||
if "events" not in content:
|
||||
content["events"] = {}
|
||||
if "users" not in content:
|
||||
content["users"] = {}
|
||||
self.power_levels[room] = content
|
||||
self._autosave()
|
||||
@@ -1,2 +1,2 @@
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.10.2"
|
||||
__author__ = "Tulir Asokan <tulir@maunium.net>"
|
||||
|
||||
+120
-70
@@ -1,93 +1,143 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import argparse
|
||||
import sys
|
||||
import logging
|
||||
import asyncio
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Dict, Any
|
||||
|
||||
import sqlalchemy as sql
|
||||
from sqlalchemy import orm
|
||||
from telethon import __version__ as __telethon_version__
|
||||
from alchemysession import AlchemySessionContainer
|
||||
|
||||
from mautrix_appservice import AppService
|
||||
from mautrix.types import UserID, RoomID
|
||||
from mautrix.bridge import Bridge
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from .base import Base
|
||||
from .web.provisioning import ProvisioningAPI
|
||||
from .web.public import PublicBridgeWebsite
|
||||
from .abstract_user import init as init_abstract_user
|
||||
from .bot import Bot, init as init_bot
|
||||
from .config import Config
|
||||
from .matrix import MatrixHandler
|
||||
|
||||
from .context import Context
|
||||
from .db import init as init_db
|
||||
from .user import init as init_user, User
|
||||
from .portal import init as init_portal
|
||||
from .puppet import init as init_puppet
|
||||
from .formatter import init as init_formatter
|
||||
from .matrix import MatrixHandler
|
||||
from .portal import Portal, init as init_portal
|
||||
from .puppet import Puppet, init as init_puppet
|
||||
from .user import User, init as init_user
|
||||
from .version import version, linkified_version
|
||||
|
||||
log = logging.getLogger("mau")
|
||||
time_formatter = logging.Formatter("[%(asctime)s] [%(levelname)s@%(name)s] %(message)s")
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(time_formatter)
|
||||
log.addHandler(handler)
|
||||
try:
|
||||
import prometheus_client as prometheus
|
||||
except ImportError:
|
||||
prometheus = None
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="A Matrix-Telegram puppeting bridge.",
|
||||
prog="python -m mautrix-telegram")
|
||||
parser.add_argument("-c", "--config", type=str, default="config.yaml",
|
||||
metavar="<path>", help="the path to your config file")
|
||||
parser.add_argument("-g", "--generate-registration", action="store_true",
|
||||
help="generate registration and quit")
|
||||
parser.add_argument("-r", "--registration", type=str, default="registration.yaml",
|
||||
metavar="<path>", help="the path to save the generated registration to")
|
||||
args = parser.parse_args()
|
||||
|
||||
config = Config(args.config, args.registration)
|
||||
config.load()
|
||||
class TelegramBridge(Bridge):
|
||||
module = "mautrix_telegram"
|
||||
name = "mautrix-telegram"
|
||||
command = "python -m mautrix-telegram"
|
||||
description = "A Matrix-Telegram puppeting bridge."
|
||||
repo_url = "https://github.com/mautrix/telegram"
|
||||
real_user_content_key = "net.maunium.telegram.puppet"
|
||||
version = version
|
||||
markdown_version = linkified_version
|
||||
config_class = Config
|
||||
matrix_class = MatrixHandler
|
||||
|
||||
if args.generate_registration:
|
||||
config.generate_registration()
|
||||
config.save()
|
||||
print(f"Registration generated and saved to {config.registration_path}")
|
||||
sys.exit(0)
|
||||
config: Config
|
||||
session_container: AlchemySessionContainer
|
||||
bot: Bot
|
||||
|
||||
if config["appservice.debug"]:
|
||||
telethon_log = logging.getLogger("telethon")
|
||||
telethon_log.addHandler(handler)
|
||||
telethon_log.setLevel(logging.DEBUG)
|
||||
log.setLevel(logging.DEBUG)
|
||||
log.debug("Debug messages enabled.")
|
||||
def prepare_db(self) -> None:
|
||||
super().prepare_db()
|
||||
init_db(self.db)
|
||||
self.session_container = AlchemySessionContainer(
|
||||
engine=self.db, table_base=Base, session=False,
|
||||
table_prefix="telethon_", manage_tables=False)
|
||||
|
||||
db_engine = sql.create_engine(config.get("appservice.database", "sqlite:///mautrix-telegram.db"))
|
||||
db_factory = orm.sessionmaker(bind=db_engine)
|
||||
db_session = orm.scoping.scoped_session(db_factory)
|
||||
Base.metadata.bind = db_engine
|
||||
Base.metadata.create_all()
|
||||
def _prepare_website(self, context: Context) -> None:
|
||||
if self.config["appservice.public.enabled"]:
|
||||
public_website = PublicBridgeWebsite(self.loop)
|
||||
self.az.app.add_subapp(self.config["appservice.public.prefix"], public_website.app)
|
||||
context.public_website = public_website
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
appserv = AppService(config["homeserver.address"], config["homeserver.domain"],
|
||||
config["appservice.as_token"], config["appservice.hs_token"],
|
||||
config["appservice.bot_username"], log="mau.as", loop=loop)
|
||||
context = (appserv, db_session, config, loop)
|
||||
if self.config["appservice.provisioning.enabled"]:
|
||||
provisioning_api = ProvisioningAPI(context)
|
||||
self.az.app.add_subapp(self.config["appservice.provisioning.prefix"],
|
||||
provisioning_api.app)
|
||||
context.provisioning_api = provisioning_api
|
||||
|
||||
with appserv.run(config["appservice.hostname"], config["appservice.port"]) as start:
|
||||
MatrixHandler(context)
|
||||
init_db(db_session)
|
||||
init_portal(context)
|
||||
init_puppet(context)
|
||||
startup_actions = init_user(context) + [start]
|
||||
try:
|
||||
loop.run_until_complete(asyncio.gather(*startup_actions, loop=loop))
|
||||
loop.run_forever()
|
||||
except KeyboardInterrupt:
|
||||
for user in User.by_tgid.values():
|
||||
user.stop()
|
||||
sys.exit(0)
|
||||
def prepare_bridge(self) -> None:
|
||||
self.bot = init_bot(self.config)
|
||||
context = Context(self.az, self.config, self.loop, self.session_container, self, self.bot)
|
||||
self._prepare_website(context)
|
||||
self.matrix = context.mx = MatrixHandler(context)
|
||||
|
||||
init_abstract_user(context)
|
||||
init_formatter(context)
|
||||
init_portal(context)
|
||||
self.add_startup_actions(init_puppet(context))
|
||||
self.add_startup_actions(init_user(context))
|
||||
if self.bot:
|
||||
self.add_startup_actions(self.bot.start())
|
||||
if self.config["bridge.resend_bridge_info"]:
|
||||
self.add_startup_actions(self.resend_bridge_info())
|
||||
|
||||
async def resend_bridge_info(self) -> None:
|
||||
self.config["bridge.resend_bridge_info"] = False
|
||||
self.config.save()
|
||||
self.log.info("Re-sending bridge info state event to all portals")
|
||||
for portal in Portal.all():
|
||||
await portal.update_bridge_info()
|
||||
self.log.info("Finished re-sending bridge info state events")
|
||||
|
||||
def prepare_stop(self) -> None:
|
||||
for puppet in Puppet.by_custom_mxid.values():
|
||||
puppet.stop()
|
||||
self.shutdown_actions = (user.stop() for user in User.by_tgid.values())
|
||||
|
||||
async def get_user(self, user_id: UserID, create: bool = True) -> User:
|
||||
user = User.get_by_mxid(user_id, create=create)
|
||||
if user:
|
||||
await user.ensure_started()
|
||||
return user
|
||||
|
||||
async def get_portal(self, room_id: RoomID) -> Portal:
|
||||
return Portal.get_by_mxid(room_id)
|
||||
|
||||
async def get_puppet(self, user_id: UserID, create: bool = False) -> Puppet:
|
||||
return await Puppet.get_by_mxid(user_id, create=create)
|
||||
|
||||
async def get_double_puppet(self, user_id: UserID) -> Puppet:
|
||||
return await Puppet.get_by_custom_mxid(user_id)
|
||||
|
||||
def is_bridge_ghost(self, user_id: UserID) -> bool:
|
||||
return bool(Puppet.get_id_from_mxid(user_id))
|
||||
|
||||
async def count_logged_in_users(self) -> int:
|
||||
return len([user for user in User.by_tgid.values() if user.tgid])
|
||||
|
||||
async def manhole_global_namespace(self, user_id: UserID) -> Dict[str, Any]:
|
||||
return {
|
||||
**await super().manhole_global_namespace(user_id),
|
||||
"User": User,
|
||||
"Portal": Portal,
|
||||
"Puppet": Puppet,
|
||||
}
|
||||
|
||||
@property
|
||||
def manhole_banner_program_version(self) -> str:
|
||||
return f"{super().manhole_banner_program_version} and Telethon {__telethon_version__}"
|
||||
|
||||
|
||||
TelegramBridge().run()
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2021 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Tuple, Optional, Union, Dict, Type, Any, TYPE_CHECKING
|
||||
from abc import ABC, abstractmethod
|
||||
import platform
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
|
||||
from telethon.sessions import Session
|
||||
from telethon.network import (ConnectionTcpMTProxyRandomizedIntermediate, ConnectionTcpFull,
|
||||
Connection)
|
||||
from telethon.tl.patched import MessageService, Message
|
||||
from telethon.tl.types import (
|
||||
Channel, Chat, MessageActionChannelMigrateFrom, PeerUser, TypeUpdate, UpdatePinnedMessages,
|
||||
UpdatePinnedChannelMessages, UpdateChatParticipantAdmin, UpdateChatParticipants, PeerChat,
|
||||
UpdateChatUserTyping, UpdateDeleteChannelMessages, UpdateNewMessage, UpdateDeleteMessages,
|
||||
UpdateEditChannelMessage, UpdateEditMessage, UpdateNewChannelMessage, UpdateReadHistoryOutbox,
|
||||
UpdateShortChatMessage, UpdateShortMessage, UpdateUserName, UpdateUserPhoto, UpdateUserStatus,
|
||||
UpdateUserTyping, User, UserStatusOffline, UserStatusOnline, UpdateReadHistoryInbox,
|
||||
UpdateReadChannelInbox, MessageEmpty, UpdateFolderPeers, UpdatePinnedDialogs,
|
||||
UpdateNotifySettings, UpdateChannelUserTyping)
|
||||
|
||||
from mautrix.types import UserID, PresenceState
|
||||
from mautrix.errors import MatrixError
|
||||
from mautrix.appservice import AppService
|
||||
from mautrix.util.logging import TraceLogger
|
||||
from mautrix.util.opt_prometheus import Histogram, Counter
|
||||
from alchemysession import AlchemySessionContainer
|
||||
|
||||
from . import portal as po, puppet as pu, __version__
|
||||
from .db import Message as DBMessage
|
||||
from .types import TelegramID
|
||||
from .tgclient import MautrixTelegramClient
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .context import Context
|
||||
from .config import Config
|
||||
from .bot import Bot
|
||||
from .__main__ import TelegramBridge
|
||||
|
||||
config: Optional['Config'] = None
|
||||
# Value updated from config in init()
|
||||
MAX_DELETIONS: int = 10
|
||||
|
||||
UpdateMessage = Union[UpdateShortChatMessage, UpdateShortMessage, UpdateNewChannelMessage,
|
||||
UpdateNewMessage, UpdateEditMessage, UpdateEditChannelMessage]
|
||||
UpdateMessageContent = Union[UpdateShortMessage, UpdateShortChatMessage, Message, MessageService]
|
||||
UpdateTyping = Union[UpdateUserTyping, UpdateChatUserTyping, UpdateChannelUserTyping]
|
||||
|
||||
UPDATE_TIME = Histogram("bridge_telegram_update", "Time spent processing Telegram updates",
|
||||
("update_type",))
|
||||
UPDATE_ERRORS = Counter("bridge_telegram_update_error",
|
||||
"Number of fatal errors while handling Telegram updates", ("update_type",))
|
||||
|
||||
|
||||
class AbstractUser(ABC):
|
||||
session_container: AlchemySessionContainer = None
|
||||
loop: asyncio.AbstractEventLoop = None
|
||||
log: TraceLogger
|
||||
az: AppService
|
||||
bridge: 'TelegramBridge'
|
||||
relaybot: Optional['Bot']
|
||||
ignore_incoming_bot_events: bool = True
|
||||
|
||||
client: Optional[MautrixTelegramClient]
|
||||
mxid: Optional[UserID]
|
||||
|
||||
tgid: Optional[TelegramID]
|
||||
username: Optional['str']
|
||||
is_bot: bool
|
||||
|
||||
is_relaybot: bool
|
||||
|
||||
puppet_whitelisted: bool
|
||||
whitelisted: bool
|
||||
relaybot_whitelisted: bool
|
||||
matrix_puppet_whitelisted: bool
|
||||
is_admin: bool
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.is_admin = False
|
||||
self.matrix_puppet_whitelisted = False
|
||||
self.puppet_whitelisted = False
|
||||
self.whitelisted = False
|
||||
self.relaybot_whitelisted = False
|
||||
self.client = None
|
||||
self.is_relaybot = False
|
||||
self.is_bot = False
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
return self.client and self.client.is_connected()
|
||||
|
||||
@property
|
||||
def _proxy_settings(self) -> Tuple[Type[Connection], Optional[Tuple[Any, ...]]]:
|
||||
proxy_type = config["telegram.proxy.type"].lower()
|
||||
connection = ConnectionTcpFull
|
||||
connection_data = (config["telegram.proxy.address"],
|
||||
config["telegram.proxy.port"],
|
||||
config["telegram.proxy.rdns"],
|
||||
config["telegram.proxy.username"],
|
||||
config["telegram.proxy.password"])
|
||||
if proxy_type == "disabled":
|
||||
connection_data = None
|
||||
elif proxy_type == "socks4":
|
||||
connection_data = (1,) + connection_data
|
||||
elif proxy_type == "socks5":
|
||||
connection_data = (2,) + connection_data
|
||||
elif proxy_type == "http":
|
||||
connection_data = (3,) + connection_data
|
||||
elif proxy_type == "mtproxy":
|
||||
connection = ConnectionTcpMTProxyRandomizedIntermediate
|
||||
connection_data = (connection_data[0], connection_data[1], connection_data[4])
|
||||
|
||||
return connection, connection_data
|
||||
|
||||
def _init_client(self) -> None:
|
||||
self.log.debug(f"Initializing client for {self.name}")
|
||||
|
||||
session = self.session_container.new_session(self.name)
|
||||
if config["telegram.server.enabled"]:
|
||||
session.set_dc(config["telegram.server.dc"],
|
||||
config["telegram.server.ip"],
|
||||
config["telegram.server.port"])
|
||||
|
||||
if self.is_relaybot:
|
||||
base_logger = logging.getLogger("telethon.relaybot")
|
||||
else:
|
||||
base_logger = logging.getLogger(f"telethon.{self.tgid or -hash(self.mxid)}")
|
||||
|
||||
device = config["telegram.device_info.device_model"]
|
||||
sysversion = config["telegram.device_info.system_version"]
|
||||
appversion = config["telegram.device_info.app_version"]
|
||||
connection, proxy = self._proxy_settings
|
||||
|
||||
assert isinstance(session, Session)
|
||||
|
||||
self.client = MautrixTelegramClient(
|
||||
session=session,
|
||||
|
||||
api_id=config["telegram.api_id"],
|
||||
api_hash=config["telegram.api_hash"],
|
||||
|
||||
app_version=__version__ if appversion == "auto" else appversion,
|
||||
system_version=(MautrixTelegramClient.__version__
|
||||
if sysversion == "auto" else sysversion),
|
||||
device_model=(f"{platform.system()} {platform.release()}"
|
||||
if device == "auto" else device),
|
||||
|
||||
timeout=config["telegram.connection.timeout"],
|
||||
connection_retries=config["telegram.connection.retries"],
|
||||
retry_delay=config["telegram.connection.retry_delay"],
|
||||
flood_sleep_threshold=config["telegram.connection.flood_sleep_threshold"],
|
||||
request_retries=config["telegram.connection.request_retries"],
|
||||
connection=connection,
|
||||
proxy=proxy,
|
||||
raise_last_call_error=True,
|
||||
|
||||
loop=self.loop,
|
||||
base_logger=base_logger
|
||||
)
|
||||
self.client.add_event_handler(self._update_catch)
|
||||
|
||||
@abstractmethod
|
||||
async def update(self, update: TypeUpdate) -> bool:
|
||||
return False
|
||||
|
||||
@abstractmethod
|
||||
async def post_login(self) -> None:
|
||||
raise NotImplementedError()
|
||||
|
||||
@abstractmethod
|
||||
async def register_portal(self, portal: po.Portal) -> None:
|
||||
raise NotImplementedError()
|
||||
|
||||
@abstractmethod
|
||||
async def unregister_portal(self, tgid: int, tg_receiver: int) -> None:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def _update_catch(self, update: TypeUpdate) -> None:
|
||||
start_time = time.time()
|
||||
update_type = type(update).__name__
|
||||
try:
|
||||
if not await self.update(update):
|
||||
await self._update(update)
|
||||
except Exception:
|
||||
self.log.exception("Failed to handle Telegram update")
|
||||
UPDATE_ERRORS.labels(update_type=update_type).inc()
|
||||
UPDATE_TIME.labels(update_type=update_type).observe(time.time() - start_time)
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def name(self) -> str:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def is_logged_in(self) -> bool:
|
||||
return (self.client and self.client.is_connected()
|
||||
and await self.client.is_user_authorized())
|
||||
|
||||
async def has_full_access(self, allow_bot: bool = False) -> bool:
|
||||
return (self.puppet_whitelisted
|
||||
and (not self.is_bot or allow_bot)
|
||||
and await self.is_logged_in())
|
||||
|
||||
async def start(self, delete_unless_authenticated: bool = False) -> 'AbstractUser':
|
||||
if not self.client:
|
||||
self._init_client()
|
||||
await self.client.connect()
|
||||
self.log.debug(f"{'Bot' if self.is_relaybot else self.mxid} connected: {self.connected}")
|
||||
return self
|
||||
|
||||
async def ensure_started(self, even_if_no_session=False) -> 'AbstractUser':
|
||||
if self.connected:
|
||||
return self
|
||||
if even_if_no_session or self.session_container.has_session(self.mxid):
|
||||
self.log.debug("Starting client due to ensure_started"
|
||||
f"(even_if_no_session={even_if_no_session})")
|
||||
await self.start(delete_unless_authenticated=not even_if_no_session)
|
||||
return self
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self.client.disconnect()
|
||||
self.client = None
|
||||
|
||||
# region Telegram update handling
|
||||
|
||||
async def _update(self, update: TypeUpdate) -> None:
|
||||
asyncio.create_task(self._handle_entity_updates(getattr(update, "_entities", {})))
|
||||
if isinstance(update, (UpdateShortChatMessage, UpdateShortMessage, UpdateNewChannelMessage,
|
||||
UpdateNewMessage, UpdateEditMessage, UpdateEditChannelMessage)):
|
||||
await self.update_message(update)
|
||||
elif isinstance(update, UpdateDeleteMessages):
|
||||
await self.delete_message(update)
|
||||
elif isinstance(update, UpdateDeleteChannelMessages):
|
||||
await self.delete_channel_message(update)
|
||||
elif isinstance(update, (UpdateChatUserTyping, UpdateChannelUserTyping, UpdateUserTyping)):
|
||||
await self.update_typing(update)
|
||||
elif isinstance(update, UpdateUserStatus):
|
||||
await self.update_status(update)
|
||||
elif isinstance(update, UpdateChatParticipantAdmin):
|
||||
await self.update_admin(update)
|
||||
elif isinstance(update, UpdateChatParticipants):
|
||||
await self.update_participants(update)
|
||||
elif isinstance(update, (UpdatePinnedMessages, UpdatePinnedChannelMessages)):
|
||||
await self.update_pinned_messages(update)
|
||||
elif isinstance(update, (UpdateUserName, UpdateUserPhoto)):
|
||||
await self.update_others_info(update)
|
||||
elif isinstance(update, UpdateReadHistoryOutbox):
|
||||
await self.update_read_receipt(update)
|
||||
elif isinstance(update, (UpdateReadHistoryInbox, UpdateReadChannelInbox)):
|
||||
await self.update_own_read_receipt(update)
|
||||
elif isinstance(update, UpdateFolderPeers):
|
||||
await self.update_folder_peers(update)
|
||||
elif isinstance(update, UpdatePinnedDialogs):
|
||||
await self.update_pinned_dialogs(update)
|
||||
elif isinstance(update, UpdateNotifySettings):
|
||||
await self.update_notify_settings(update)
|
||||
else:
|
||||
self.log.trace("Unhandled update: %s", update)
|
||||
|
||||
async def update_folder_peers(self, update: UpdateFolderPeers) -> None:
|
||||
pass
|
||||
|
||||
async def update_pinned_dialogs(self, update: UpdatePinnedDialogs) -> None:
|
||||
pass
|
||||
|
||||
async def update_notify_settings(self, update: UpdateNotifySettings) -> None:
|
||||
pass
|
||||
|
||||
async def update_pinned_messages(self, update: Union[UpdatePinnedMessages,
|
||||
UpdatePinnedChannelMessages]) -> None:
|
||||
if isinstance(update, UpdatePinnedMessages):
|
||||
portal = po.Portal.get_by_entity(update.peer, receiver_id=self.tgid)
|
||||
else:
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.channel_id))
|
||||
if portal and portal.mxid:
|
||||
await portal.receive_telegram_pin_ids(update.messages, self.tgid,
|
||||
remove=not update.pinned)
|
||||
|
||||
@staticmethod
|
||||
async def update_participants(update: UpdateChatParticipants) -> None:
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.participants.chat_id))
|
||||
if portal and portal.mxid:
|
||||
await portal.update_power_levels(update.participants.participants)
|
||||
|
||||
async def update_read_receipt(self, update: UpdateReadHistoryOutbox) -> None:
|
||||
if not isinstance(update.peer, PeerUser):
|
||||
self.log.debug("Unexpected read receipt peer: %s", update.peer)
|
||||
return
|
||||
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.peer.user_id), self.tgid)
|
||||
if not portal or not portal.mxid:
|
||||
return
|
||||
|
||||
# We check that these are user read receipts, so tg_space is always the user ID.
|
||||
message = DBMessage.get_one_by_tgid(TelegramID(update.max_id), self.tgid, edit_index=-1)
|
||||
if not message:
|
||||
return
|
||||
|
||||
puppet = pu.Puppet.get(TelegramID(update.peer.user_id))
|
||||
await puppet.intent.mark_read(portal.mxid, message.mxid)
|
||||
|
||||
async def update_own_read_receipt(self, update: Union[UpdateReadHistoryInbox,
|
||||
UpdateReadChannelInbox]) -> None:
|
||||
puppet = pu.Puppet.get(self.tgid)
|
||||
if not puppet.is_real_user:
|
||||
return
|
||||
|
||||
if isinstance(update, UpdateReadChannelInbox):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.channel_id))
|
||||
elif isinstance(update.peer, PeerChat):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.peer.chat_id))
|
||||
elif isinstance(update.peer, PeerUser):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.peer.user_id), self.tgid)
|
||||
else:
|
||||
self.log.debug("Unexpected own read receipt peer: %s", update.peer)
|
||||
return
|
||||
|
||||
if not portal or not portal.mxid:
|
||||
return
|
||||
|
||||
tg_space = portal.tgid if portal.peer_type == "channel" else self.tgid
|
||||
message = DBMessage.get_one_by_tgid(TelegramID(update.max_id), tg_space, edit_index=-1)
|
||||
if not message:
|
||||
return
|
||||
|
||||
await puppet.intent.mark_read(portal.mxid, message.mxid)
|
||||
|
||||
async def update_admin(self, update: UpdateChatParticipantAdmin) -> None:
|
||||
# TODO duplication not checked
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.chat_id))
|
||||
if not portal or not portal.mxid:
|
||||
return
|
||||
|
||||
await portal.set_telegram_admin(TelegramID(update.user_id))
|
||||
|
||||
async def update_typing(self, update: UpdateTyping) -> None:
|
||||
sender = None
|
||||
if isinstance(update, UpdateUserTyping):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.user_id), self.tgid, "user")
|
||||
sender = pu.Puppet.get(TelegramID(update.user_id))
|
||||
elif isinstance(update, UpdateChannelUserTyping):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.channel_id))
|
||||
elif isinstance(update, UpdateChatUserTyping):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.chat_id))
|
||||
else:
|
||||
return
|
||||
|
||||
if isinstance(update, (UpdateChannelUserTyping, UpdateChatUserTyping)):
|
||||
# Can typing notifications come from non-user peers?
|
||||
if not update.from_id.user_id:
|
||||
return
|
||||
sender = pu.Puppet.get(TelegramID(update.from_id.user_id))
|
||||
|
||||
if not sender or not portal or not portal.mxid:
|
||||
return
|
||||
|
||||
await portal.handle_telegram_typing(sender, update)
|
||||
|
||||
async def _handle_entity_updates(self, entities: Dict[int, Union[User, Chat, Channel]]
|
||||
) -> None:
|
||||
try:
|
||||
users = (entity for entity in entities.values() if isinstance(entity, User))
|
||||
puppets = ((pu.Puppet.get(TelegramID(user.id)), user) for user in users)
|
||||
await asyncio.gather(*[puppet.try_update_info(self, info)
|
||||
for puppet, info in puppets if puppet])
|
||||
except Exception:
|
||||
self.log.exception("Failed to handle entity updates")
|
||||
|
||||
async def update_others_info(self, update: Union[UpdateUserName, UpdateUserPhoto]) -> None:
|
||||
# TODO duplication not checked
|
||||
puppet = pu.Puppet.get(TelegramID(update.user_id))
|
||||
if isinstance(update, UpdateUserName):
|
||||
puppet.username = update.username
|
||||
if await puppet.update_displayname(self, update):
|
||||
await puppet.save()
|
||||
elif isinstance(update, UpdateUserPhoto):
|
||||
if await puppet.update_avatar(self, update.photo):
|
||||
await puppet.save()
|
||||
else:
|
||||
self.log.warning(f"Unexpected other user info update: {type(update)}")
|
||||
|
||||
async def update_status(self, update: UpdateUserStatus) -> None:
|
||||
puppet = pu.Puppet.get(TelegramID(update.user_id))
|
||||
if isinstance(update.status, UserStatusOnline):
|
||||
await puppet.default_mxid_intent.set_presence(PresenceState.ONLINE)
|
||||
elif isinstance(update.status, UserStatusOffline):
|
||||
await puppet.default_mxid_intent.set_presence(PresenceState.OFFLINE)
|
||||
else:
|
||||
self.log.warning(f"Unexpected user status update: type({update})")
|
||||
return
|
||||
|
||||
def get_message_details(self, update: UpdateMessage) -> Tuple[UpdateMessageContent,
|
||||
Optional[pu.Puppet],
|
||||
Optional[po.Portal]]:
|
||||
if isinstance(update, UpdateShortChatMessage):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.chat_id))
|
||||
if not portal:
|
||||
self.log.warning(f"Received message in chat with unknown type {update.chat_id}")
|
||||
sender = pu.Puppet.get(TelegramID(update.from_id))
|
||||
elif isinstance(update, UpdateShortMessage):
|
||||
portal = po.Portal.get_by_tgid(TelegramID(update.user_id), self.tgid, "user")
|
||||
sender = pu.Puppet.get(self.tgid if update.out else update.user_id)
|
||||
elif isinstance(update, (UpdateNewMessage, UpdateNewChannelMessage,
|
||||
UpdateEditMessage, UpdateEditChannelMessage)):
|
||||
update = update.message
|
||||
if isinstance(update, MessageEmpty):
|
||||
return update, None, None
|
||||
portal = po.Portal.get_by_entity(update.peer_id, receiver_id=self.tgid)
|
||||
if update.out:
|
||||
sender = pu.Puppet.get(self.tgid)
|
||||
elif isinstance(update.from_id, PeerUser):
|
||||
sender = pu.Puppet.get(TelegramID(update.from_id.user_id))
|
||||
else:
|
||||
sender = None
|
||||
else:
|
||||
self.log.warning("Unexpected message type in User#get_message_details: "
|
||||
f"{type(update)}")
|
||||
return update, None, None
|
||||
return update, sender, portal
|
||||
|
||||
@staticmethod
|
||||
async def _try_redact(message: DBMessage) -> None:
|
||||
portal = po.Portal.get_by_mxid(message.mx_room)
|
||||
if not portal:
|
||||
return
|
||||
try:
|
||||
await portal.main_intent.redact(message.mx_room, message.mxid)
|
||||
except MatrixError:
|
||||
pass
|
||||
|
||||
async def delete_message(self, update: UpdateDeleteMessages) -> None:
|
||||
if len(update.messages) > MAX_DELETIONS:
|
||||
return
|
||||
|
||||
for message_id in update.messages:
|
||||
for message in DBMessage.get_all_by_tgid(TelegramID(message_id), self.tgid):
|
||||
if message.redacted:
|
||||
continue
|
||||
message.delete()
|
||||
number_left = DBMessage.count_spaces_by_mxid(message.mxid, message.mx_room)
|
||||
if number_left == 0:
|
||||
await self._try_redact(message)
|
||||
|
||||
async def delete_channel_message(self, update: UpdateDeleteChannelMessages) -> None:
|
||||
if len(update.messages) > MAX_DELETIONS:
|
||||
return
|
||||
|
||||
channel_id = TelegramID(update.channel_id)
|
||||
|
||||
for message_id in update.messages:
|
||||
for message in DBMessage.get_all_by_tgid(TelegramID(message_id), channel_id):
|
||||
if message.redacted:
|
||||
continue
|
||||
message.delete()
|
||||
await self._try_redact(message)
|
||||
|
||||
async def update_message(self, original_update: UpdateMessage) -> None:
|
||||
update, sender, portal = self.get_message_details(original_update)
|
||||
if not portal:
|
||||
return
|
||||
elif portal and not portal.allow_bridging:
|
||||
self.log.debug(f"Ignoring message in portal {portal.tgid_log} (bridging disallowed)")
|
||||
return
|
||||
|
||||
if self.is_relaybot:
|
||||
if update.is_private:
|
||||
if not config["bridge.relaybot.private_chat.invite"]:
|
||||
self.log.debug(f"Ignoring private message to bot from {sender.id}")
|
||||
return
|
||||
elif not portal.mxid and config["bridge.relaybot.ignore_unbridged_group_chat"]:
|
||||
self.log.debug("Ignoring message received by bot"
|
||||
f" in unbridged chat {portal.tgid_log}")
|
||||
return
|
||||
|
||||
if ((self.ignore_incoming_bot_events and self.relaybot
|
||||
and sender and sender.id == self.relaybot.tgid)):
|
||||
self.log.debug(f"Ignoring relaybot-sent message %s to %s", update.id, portal.tgid_log)
|
||||
return
|
||||
|
||||
await portal.backfill_lock.wait(update.id)
|
||||
|
||||
if isinstance(update, MessageService):
|
||||
if isinstance(update.action, MessageActionChannelMigrateFrom):
|
||||
self.log.trace(f"Received %s in %s by %d, unregistering portal...",
|
||||
update.action, portal.tgid_log, sender.id)
|
||||
await self.unregister_portal(update.action.chat_id, update.action.chat_id)
|
||||
await self.register_portal(portal)
|
||||
return
|
||||
self.log.trace("Handling action %s to %s by %d", update.action, portal.tgid_log,
|
||||
(sender.id if sender else 0))
|
||||
return await portal.handle_telegram_action(self, sender, update)
|
||||
|
||||
if isinstance(original_update, (UpdateEditMessage, UpdateEditChannelMessage)):
|
||||
return await portal.handle_telegram_edit(self, sender, update)
|
||||
return await portal.handle_telegram_message(self, sender, update)
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
def init(context: 'Context') -> None:
|
||||
global config, MAX_DELETIONS
|
||||
AbstractUser.az, config, AbstractUser.loop, AbstractUser.relaybot = context.core
|
||||
AbstractUser.bridge = context.bridge
|
||||
AbstractUser.ignore_incoming_bot_events = config["bridge.relaybot.ignore_own_incoming_events"]
|
||||
AbstractUser.session_container = context.session_container
|
||||
MAX_DELETIONS = config.get("bridge.max_telegram_delete", 10)
|
||||
@@ -1,2 +0,0 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
Base = declarative_base()
|
||||
@@ -0,0 +1,311 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Awaitable, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING
|
||||
import logging
|
||||
|
||||
from telethon.tl.patched import Message, MessageService
|
||||
from telethon.tl.types import (
|
||||
ChannelParticipantAdmin, ChannelParticipantCreator, ChatForbidden, ChatParticipantAdmin,
|
||||
ChatParticipantCreator, InputChannel, InputUser, MessageActionChatAddUser, PeerUser,
|
||||
MessageActionChatDeleteUser, MessageEntityBotCommand, PeerChannel, PeerChat, TypePeer,
|
||||
UpdateNewChannelMessage, UpdateNewMessage, MessageActionChatMigrateTo, User)
|
||||
from telethon.tl.functions.messages import GetChatsRequest, GetFullChatRequest
|
||||
from telethon.tl.functions.channels import GetChannelsRequest, GetParticipantRequest
|
||||
from telethon.errors import ChannelInvalidError, ChannelPrivateError
|
||||
|
||||
from mautrix.types import UserID
|
||||
|
||||
from .abstract_user import AbstractUser
|
||||
from .db import BotChat
|
||||
from .types import TelegramID
|
||||
from . import puppet as pu, portal as po, user as u
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .config import Config
|
||||
|
||||
config: Optional['Config'] = None
|
||||
|
||||
ReplyFunc = Callable[[str], Awaitable[Message]]
|
||||
|
||||
|
||||
class Bot(AbstractUser):
|
||||
log: logging.Logger = logging.getLogger("mau.user.bot")
|
||||
|
||||
token: str
|
||||
chats: Dict[int, str]
|
||||
tg_whitelist: List[int]
|
||||
whitelist_group_admins: bool
|
||||
_me_info: Optional[User]
|
||||
_me_mxid: Optional[UserID]
|
||||
|
||||
def __init__(self, token: str) -> None:
|
||||
super().__init__()
|
||||
self.token = token
|
||||
self.tgid = None
|
||||
self.mxid = None
|
||||
self.puppet_whitelisted = True
|
||||
self.whitelisted = True
|
||||
self.relaybot_whitelisted = True
|
||||
self.username = None
|
||||
self.is_relaybot = True
|
||||
self.is_bot = True
|
||||
self.chats = {}
|
||||
self.tg_whitelist = []
|
||||
self.whitelist_group_admins = (config["bridge.relaybot.whitelist_group_admins"]
|
||||
or False)
|
||||
self._me_info = None
|
||||
self._me_mxid = None
|
||||
|
||||
async def get_me(self, use_cache: bool = True) -> Tuple[User, UserID]:
|
||||
if not use_cache or not self._me_mxid:
|
||||
self._me_info = await self.client.get_me()
|
||||
self._me_mxid = pu.Puppet.get_mxid_from_id(TelegramID(self._me_info.id))
|
||||
return self._me_info, self._me_mxid
|
||||
|
||||
async def init_permissions(self) -> None:
|
||||
whitelist = config["bridge.relaybot.whitelist"] or []
|
||||
for user_id in whitelist:
|
||||
if isinstance(user_id, str):
|
||||
entity = await self.client.get_input_entity(user_id)
|
||||
if isinstance(entity, InputUser):
|
||||
user_id = entity.user_id
|
||||
else:
|
||||
user_id = None
|
||||
if isinstance(user_id, int):
|
||||
self.tg_whitelist.append(user_id)
|
||||
|
||||
async def start(self, delete_unless_authenticated: bool = False) -> 'Bot':
|
||||
self.chats = {chat.id: chat.type for chat in BotChat.all()}
|
||||
await super().start(delete_unless_authenticated)
|
||||
if not await self.is_logged_in():
|
||||
await self.client.sign_in(bot_token=self.token)
|
||||
await self.post_login()
|
||||
return self
|
||||
|
||||
async def post_login(self) -> None:
|
||||
await self.init_permissions()
|
||||
info = await self.client.get_me()
|
||||
self.tgid = TelegramID(info.id)
|
||||
self.username = info.username
|
||||
self.mxid = pu.Puppet.get_mxid_from_id(self.tgid)
|
||||
|
||||
chat_ids = [chat_id for chat_id, chat_type in self.chats.items() if chat_type == "chat"]
|
||||
response = await self.client(GetChatsRequest(chat_ids))
|
||||
for chat in response.chats:
|
||||
if isinstance(chat, ChatForbidden) or chat.left or chat.deactivated:
|
||||
self.remove_chat(TelegramID(chat.id))
|
||||
|
||||
channel_ids = [InputChannel(chat_id, 0)
|
||||
for chat_id, chat_type in self.chats.items()
|
||||
if chat_type == "channel"]
|
||||
for channel_id in channel_ids:
|
||||
try:
|
||||
await self.client(GetChannelsRequest([channel_id]))
|
||||
except (ChannelPrivateError, ChannelInvalidError):
|
||||
self.remove_chat(TelegramID(channel_id.channel_id))
|
||||
|
||||
async def register_portal(self, portal: po.Portal) -> None:
|
||||
self.add_chat(portal.tgid, portal.peer_type)
|
||||
|
||||
async def unregister_portal(self, tgid: int, tg_receiver: int) -> None:
|
||||
self.remove_chat(tgid)
|
||||
|
||||
def add_chat(self, chat_id: TelegramID, chat_type: str) -> None:
|
||||
if chat_id not in self.chats:
|
||||
self.chats[chat_id] = chat_type
|
||||
BotChat(id=TelegramID(chat_id), type=chat_type).insert()
|
||||
|
||||
def remove_chat(self, chat_id: TelegramID) -> None:
|
||||
try:
|
||||
del self.chats[chat_id]
|
||||
except KeyError:
|
||||
pass
|
||||
BotChat.delete_by_id(chat_id)
|
||||
|
||||
async def _can_use_commands(self, chat: TypePeer, tgid: TelegramID) -> bool:
|
||||
if tgid in self.tg_whitelist:
|
||||
return True
|
||||
|
||||
user = u.User.get_by_tgid(tgid)
|
||||
if user and user.is_admin:
|
||||
self.tg_whitelist.append(user.tgid)
|
||||
return True
|
||||
|
||||
if self.whitelist_group_admins:
|
||||
if isinstance(chat, PeerChannel):
|
||||
p = await self.client(GetParticipantRequest(chat, tgid))
|
||||
return isinstance(p.participant, (ChannelParticipantCreator, ChannelParticipantAdmin))
|
||||
elif isinstance(chat, PeerChat):
|
||||
chat = await self.client(GetFullChatRequest(chat.chat_id))
|
||||
participants = chat.full_chat.participants.participants
|
||||
for p in participants:
|
||||
if p.user_id == tgid:
|
||||
return isinstance(p, (ChatParticipantCreator, ChatParticipantAdmin))
|
||||
return False
|
||||
|
||||
async def check_can_use_commands(self, event: Message, reply: ReplyFunc) -> bool:
|
||||
if not await self._can_use_commands(event.to_id, TelegramID(event.from_id)):
|
||||
await reply("You do not have the permission to use that command.")
|
||||
return False
|
||||
return True
|
||||
|
||||
async def handle_command_portal(self, portal: po.Portal, reply: ReplyFunc) -> Message:
|
||||
if not config["bridge.relaybot.authless_portals"]:
|
||||
return await reply("This bridge doesn't allow portal creation from Telegram.")
|
||||
|
||||
if not portal.allow_bridging:
|
||||
return await reply("This bridge doesn't allow bridging this chat.")
|
||||
|
||||
await portal.create_matrix_room(self)
|
||||
if portal.mxid:
|
||||
if portal.username:
|
||||
return await reply(
|
||||
f"Portal is public: [{portal.alias}](https://matrix.to/#/{portal.alias})")
|
||||
else:
|
||||
return await reply(
|
||||
"Portal is not public. Use `/invite <mxid>` to get an invite.")
|
||||
|
||||
async def handle_command_invite(self, portal: po.Portal, reply: ReplyFunc,
|
||||
mxid_input: UserID) -> Message:
|
||||
if len(mxid_input) == 0:
|
||||
return await reply("Usage: `/invite <mxid>`")
|
||||
elif not portal.mxid:
|
||||
return await reply("Portal does not have Matrix room. "
|
||||
"Create one with /portal first.")
|
||||
if mxid_input[0] != '@' or mxid_input.find(':') < 2:
|
||||
return await reply("That doesn't look like a Matrix ID.")
|
||||
user = await u.User.get_by_mxid(mxid_input).ensure_started()
|
||||
if not user.relaybot_whitelisted:
|
||||
return await reply("That user is not whitelisted to use the bridge.")
|
||||
elif await user.is_logged_in():
|
||||
displayname = f"@{user.username}" if user.username else user.displayname
|
||||
return await reply("That user seems to be logged in. "
|
||||
f"Just invite [{displayname}](tg://user?id={user.tgid})")
|
||||
else:
|
||||
await portal.invite_to_matrix(user.mxid)
|
||||
return await reply(f"Invited `{user.mxid}` to the portal.")
|
||||
|
||||
@staticmethod
|
||||
def handle_command_id(message: Message, reply: ReplyFunc) -> Awaitable[Message]:
|
||||
# Provide the prefixed ID to the user so that the user wouldn't need to specify whether the
|
||||
# chat is a normal group or a supergroup/channel when using the ID.
|
||||
if isinstance(message.to_id, PeerChannel):
|
||||
return reply(f"-100{message.to_id.channel_id}")
|
||||
elif isinstance(message.to_id, PeerChat):
|
||||
return reply(str(-message.to_id.chat_id))
|
||||
elif isinstance(message.to_id, PeerUser):
|
||||
return reply(f"Your user ID is {message.from_id}.")
|
||||
else:
|
||||
return reply("Failed to find chat ID.")
|
||||
|
||||
def match_command(self, text: str, command: str) -> bool:
|
||||
text = text.lower()
|
||||
command = f"/{command.lower()}"
|
||||
command_targeted = f"{command}@{self.username.lower()}"
|
||||
|
||||
is_plain_command = text == command or text == command_targeted
|
||||
if is_plain_command:
|
||||
return True
|
||||
|
||||
is_arg_command = text.startswith(command + " ") or text.startswith(command_targeted + " ")
|
||||
if is_arg_command:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
async def handle_command(self, message: Message) -> None:
|
||||
def reply(reply_text: str) -> Awaitable[Message]:
|
||||
return self.client.send_message(message.chat_id, reply_text, reply_to=message.id)
|
||||
|
||||
text = message.message
|
||||
|
||||
if self.match_command(text, "start"):
|
||||
pcm = config["bridge.relaybot.private_chat.message"]
|
||||
if pcm:
|
||||
await reply(pcm)
|
||||
return
|
||||
elif self.match_command(text, "id"):
|
||||
await self.handle_command_id(message, reply)
|
||||
return
|
||||
elif message.is_private:
|
||||
return
|
||||
|
||||
portal = po.Portal.get_by_entity(message.to_id)
|
||||
|
||||
is_portal_cmd = self.match_command(text, "portal")
|
||||
is_invite_cmd = self.match_command(text, "invite")
|
||||
if is_portal_cmd or is_invite_cmd:
|
||||
if not await self.check_can_use_commands(message, reply):
|
||||
return
|
||||
if is_portal_cmd:
|
||||
await self.handle_command_portal(portal, reply)
|
||||
elif is_invite_cmd:
|
||||
try:
|
||||
mxid = text[text.index(" ") + 1:]
|
||||
except ValueError:
|
||||
mxid = ""
|
||||
await self.handle_command_invite(portal, reply, mxid_input=UserID(mxid))
|
||||
|
||||
def handle_service_message(self, message: MessageService) -> None:
|
||||
to_peer = message.to_id
|
||||
if isinstance(to_peer, PeerChannel):
|
||||
to_id = TelegramID(to_peer.channel_id)
|
||||
chat_type = "channel"
|
||||
elif isinstance(to_peer, PeerChat):
|
||||
to_id = TelegramID(to_peer.chat_id)
|
||||
chat_type = "chat"
|
||||
else:
|
||||
return
|
||||
|
||||
action = message.action
|
||||
if isinstance(action, MessageActionChatAddUser) and self.tgid in action.users:
|
||||
self.add_chat(to_id, chat_type)
|
||||
elif isinstance(action, MessageActionChatDeleteUser) and action.user_id == self.tgid:
|
||||
self.remove_chat(to_id)
|
||||
elif isinstance(action, MessageActionChatMigrateTo):
|
||||
self.remove_chat(to_id)
|
||||
self.add_chat(TelegramID(action.channel_id), "channel")
|
||||
|
||||
async def update(self, update) -> bool:
|
||||
if not isinstance(update, (UpdateNewMessage, UpdateNewChannelMessage)):
|
||||
return False
|
||||
if isinstance(update.message, MessageService):
|
||||
self.handle_service_message(update.message)
|
||||
return False
|
||||
|
||||
is_command = (isinstance(update.message, Message)
|
||||
and update.message.entities and len(update.message.entities) > 0
|
||||
and isinstance(update.message.entities[0], MessageEntityBotCommand)
|
||||
and update.message.entities[0].offset == 0)
|
||||
if is_command:
|
||||
await self.handle_command(update.message)
|
||||
return False
|
||||
|
||||
def is_in_chat(self, peer_id) -> bool:
|
||||
return peer_id in self.chats
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "bot"
|
||||
|
||||
|
||||
def init(cfg: 'Config') -> Optional[Bot]:
|
||||
global config
|
||||
config = cfg
|
||||
token = config["telegram.bot_token"]
|
||||
if token and not token.lower().startswith("disable"):
|
||||
return Bot(token)
|
||||
return None
|
||||
@@ -1,2 +1,8 @@
|
||||
from .handler import command_handler, CommandHandler
|
||||
from . import clean_rooms, auth, meta, telegram
|
||||
from .handler import (command_handler, CommandHandler, CommandProcessor, CommandEvent,
|
||||
SECTION_AUTH, SECTION_CREATING_PORTALS, SECTION_PORTAL_MANAGEMENT,
|
||||
SECTION_MISC, SECTION_ADMIN)
|
||||
from . import portal, telegram, matrix_auth
|
||||
|
||||
__all__ = ["command_handler", "CommandHandler", "CommandProcessor", "CommandEvent",
|
||||
"SECTION_AUTH", "SECTION_MISC", "SECTION_ADMIN", "SECTION_CREATING_PORTALS",
|
||||
"SECTION_PORTAL_MANAGEMENT"]
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import asyncio
|
||||
|
||||
from telethon.errors import *
|
||||
|
||||
from . import command_handler
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def ping(evt):
|
||||
if not evt.sender.logged_in:
|
||||
return await evt.reply("You're not logged in.")
|
||||
me = await evt.sender.client.get_me()
|
||||
if me:
|
||||
return await evt.reply(f"You're logged in as @{me.username}")
|
||||
else:
|
||||
return await evt.reply("You're not logged in.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, management_only=True)
|
||||
def register(evt):
|
||||
return evt.reply("Not yet implemented.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, management_only=True)
|
||||
async def login(evt):
|
||||
if evt.sender.logged_in:
|
||||
return await evt.reply("You are already logged in.")
|
||||
elif len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp login <phone number>`")
|
||||
phone_number = evt.args[0]
|
||||
await evt.sender.client.sign_in(phone_number)
|
||||
evt.sender.command_status = {
|
||||
"next": enter_code,
|
||||
"action": "Login",
|
||||
}
|
||||
return await evt.reply(f"Login code sent to {phone_number}. Please send the code here.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def enter_code(evt):
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp enter-code <code>`")
|
||||
|
||||
try:
|
||||
user = await evt.sender.client.sign_in(code=evt.args[0])
|
||||
asyncio.ensure_future(evt.sender.post_login(user), loop=evt.loop)
|
||||
evt.sender.command_status = None
|
||||
return await evt.reply(f"Successfully logged in as @{user.username}")
|
||||
except PhoneNumberUnoccupiedError:
|
||||
return await evt.reply("That phone number has not been registered."
|
||||
"Please register with `$cmdprefix+sp register <phone>`.")
|
||||
except PhoneCodeExpiredError:
|
||||
return await evt.reply(
|
||||
"Phone code expired. Try again with `$cmdprefix+sp login <phone>`.")
|
||||
except PhoneCodeInvalidError:
|
||||
return await evt.reply("Invalid phone code.")
|
||||
except PhoneNumberAppSignupForbiddenError:
|
||||
return await evt.reply(
|
||||
"Your phone number does not allow 3rd party apps to sign in.")
|
||||
except PhoneNumberFloodError:
|
||||
return await evt.reply(
|
||||
"Your phone number has been temporarily blocked for flooding. "
|
||||
"The block is usually applied for around a day.")
|
||||
except PhoneNumberBannedError:
|
||||
return await evt.reply("Your phone number has been banned from Telegram.")
|
||||
except SessionPasswordNeededError:
|
||||
evt.sender.command_status = {
|
||||
"next": enter_password,
|
||||
"action": "Login (password entry)",
|
||||
}
|
||||
return await evt.reply("Your account has two-factor authentication."
|
||||
"Please send your password here.")
|
||||
except Exception:
|
||||
evt.log.exception("Error sending phone code")
|
||||
return await evt.reply("Unhandled exception while sending code."
|
||||
"Check console for more details.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def enter_password(evt):
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp enter-password <password>`")
|
||||
|
||||
try:
|
||||
user = await evt.sender.client.sign_in(password=evt.args[0])
|
||||
asyncio.ensure_future(evt.sender.post_login(user), loop=evt.loop)
|
||||
evt.sender.command_status = None
|
||||
return await evt.reply(f"Successfully logged in as @{user.username}")
|
||||
except PasswordHashInvalidError:
|
||||
return await evt.reply("Incorrect password.")
|
||||
except Exception:
|
||||
evt.log.exception("Error sending password")
|
||||
return await evt.reply("Unhandled exception while sending password. "
|
||||
"Check console for more details.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def logout(evt):
|
||||
if not evt.sender.logged_in:
|
||||
return await evt.reply("You're not logged in.")
|
||||
if await evt.sender.log_out():
|
||||
return await evt.reply("Logged out successfully.")
|
||||
return await evt.reply("Failed to log out.")
|
||||
@@ -1,170 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from mautrix_appservice import MatrixRequestError
|
||||
|
||||
from . import command_handler
|
||||
from .. import puppet as pu, portal as po
|
||||
|
||||
|
||||
async def _find_rooms(intent):
|
||||
management_rooms = []
|
||||
unidentified_rooms = []
|
||||
portals = []
|
||||
empty_portals = []
|
||||
|
||||
rooms = await intent.get_joined_rooms()
|
||||
for room in rooms:
|
||||
portal = po.Portal.get_by_mxid(room)
|
||||
if not portal:
|
||||
try:
|
||||
members = await intent.get_room_members(room)
|
||||
except MatrixRequestError:
|
||||
members = []
|
||||
if len(members) == 2:
|
||||
other_member = members[0] if members[0] != intent.mxid else members[1]
|
||||
if pu.Puppet.get_id_from_mxid(other_member):
|
||||
unidentified_rooms.append(room)
|
||||
else:
|
||||
management_rooms.append((room, other_member))
|
||||
else:
|
||||
unidentified_rooms.append(room)
|
||||
else:
|
||||
members = await portal.get_authenticated_matrix_users()
|
||||
if len(members) == 0:
|
||||
empty_portals.append(portal)
|
||||
else:
|
||||
portals.append(portal)
|
||||
|
||||
return management_rooms, unidentified_rooms, portals, empty_portals
|
||||
|
||||
|
||||
@command_handler(needs_admin=True, name="clean-rooms")
|
||||
async def clean_rooms(evt):
|
||||
if not evt.is_management:
|
||||
return await evt.reply("`clean-rooms` is a particularly spammy command. Please don't "
|
||||
"run it in non-management rooms.")
|
||||
|
||||
management_rooms, unidentified_rooms, portals, empty_portals = await _find_rooms(evt.az.intent)
|
||||
|
||||
reply = ["#### Management rooms (M)"]
|
||||
reply += ([f"{n+1}. [M{n+1}](https://matrix.to/#/{room}) (with {other_member}"
|
||||
for n, (room, other_member) in enumerate(management_rooms)]
|
||||
or ["No management rooms found."])
|
||||
reply.append("#### Active portal rooms (A)")
|
||||
reply += ([f"{n+1}. [P{n+1}](https://matrix.to/#/{portal.mxid}) "
|
||||
+ f"(to Telegram chat \"{portal.title}\")"
|
||||
for n, portal in enumerate(portals)]
|
||||
or ["No active portal rooms found."])
|
||||
reply.append("#### Unidentified rooms (U)")
|
||||
reply += ([f"{n+1}. [U{n+1}](https://matrix.to/#/{room})"
|
||||
for n, room in enumerate(unidentified_rooms)]
|
||||
or ["No unidentified rooms found."])
|
||||
reply.append("#### Inactive portal rooms (I)")
|
||||
reply += ([f"{n}. [E{n}](https://matrix.to/#/{portal.mxid}) "
|
||||
+ f"(to Telegram chat \"{portal.title}\")"
|
||||
for n, portal in enumerate(empty_portals)]
|
||||
or ["No inactive portal rooms found."])
|
||||
|
||||
reply += ["#### Usage",
|
||||
("To clean the recommended set of rooms (unidentified & inactive portals), "
|
||||
"type `$cmdprefix+sp clean-recommended`"),
|
||||
"",
|
||||
("To clean other groups of rooms, type `$cmdprefix+sp clean-groups <letters>` "
|
||||
"where `letters` are the first letters of the group names (M, A, U, I)"),
|
||||
"",
|
||||
("To clean specific rooms, type `$cmdprefix+sp clean-range <range>` "
|
||||
"where `range` is the range (e.g. `5-21`) prefixed with the first letter of"
|
||||
"the group name."),
|
||||
"",
|
||||
("Please note that you will have to re-run `$cmdprefix+sp cleanrooms` "
|
||||
"between each use of the commands above.")]
|
||||
|
||||
evt.sender.command_status = {
|
||||
"next": lambda clean_evt: set_rooms_to_clean(clean_evt, management_rooms,
|
||||
unidentified_rooms, portals, empty_portals),
|
||||
"action": "Room cleaning",
|
||||
}
|
||||
|
||||
return await evt.reply("\n".join(reply))
|
||||
|
||||
|
||||
async def set_rooms_to_clean(evt, management_rooms, unidentified_rooms, portals, empty_portals):
|
||||
command = evt.args[0]
|
||||
rooms_to_clean = []
|
||||
if command == "clean-recommended":
|
||||
rooms_to_clean = empty_portals + unidentified_rooms
|
||||
elif command == "clean-groups":
|
||||
if len(evt.args) < 2:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp clean-groups [M][A][U][I]")
|
||||
groups_to_clean = evt.args[1]
|
||||
if "M" in groups_to_clean:
|
||||
rooms_to_clean += management_rooms
|
||||
if "A" in groups_to_clean:
|
||||
rooms_to_clean += portals
|
||||
if "U" in groups_to_clean:
|
||||
rooms_to_clean += unidentified_rooms
|
||||
if "I" in groups_to_clean:
|
||||
rooms_to_clean += empty_portals
|
||||
elif command == "clean-range":
|
||||
try:
|
||||
range = evt.args[1]
|
||||
group, range = range[0], range[1:]
|
||||
start, end = range.split("-")
|
||||
start, end = int(start), int(end)
|
||||
if group == "M":
|
||||
group = management_rooms
|
||||
elif group == "A":
|
||||
group = portals
|
||||
elif group == "U":
|
||||
group = unidentified_rooms
|
||||
elif group == "I":
|
||||
group = empty_portals
|
||||
else:
|
||||
raise ValueError("Unknown group")
|
||||
rooms_to_clean = group[start - 1:end]
|
||||
except (KeyError, ValueError):
|
||||
return await evt.reply(
|
||||
"**Usage:** `$cmdprefix+sp clean-groups <_M|A|U|I_><range>")
|
||||
else:
|
||||
return await evt.reply(f"Unknown room cleaning action `{command}`. "
|
||||
+ "Use `$cmdprefix+sp cancel` to cancel room "
|
||||
+ "cleaning.")
|
||||
|
||||
evt.sender.command_status = {
|
||||
"next": lambda confirm: execute_room_cleanup(confirm, rooms_to_clean),
|
||||
"action": "Room cleaning",
|
||||
}
|
||||
await evt.reply(f"To confirm cleaning up {len(rooms_to_clean)} rooms, type"
|
||||
+ "`$cmdprefix+sp confirm-clean`.")
|
||||
|
||||
|
||||
async def execute_room_cleanup(evt, rooms_to_clean):
|
||||
if len(evt.args) > 0 and evt.args[0] == "confirm-clean":
|
||||
await evt.reply(f"Cleaning {len(rooms_to_clean)} rooms. "
|
||||
+ "This might take a while.")
|
||||
cleaned = 0
|
||||
for room in rooms_to_clean:
|
||||
if isinstance(room, po.Portal):
|
||||
await room.cleanup_and_delete()
|
||||
cleaned += 1
|
||||
elif isinstance(room, str):
|
||||
await po.Portal.cleanup_room(evt.az.intent, room, type="Room")
|
||||
cleaned += 1
|
||||
evt.sender.command_status = None
|
||||
await evt.reply(f"{cleaned} rooms cleaned up successfully.")
|
||||
else:
|
||||
await evt.reply("Room cleaning cancelled.")
|
||||
@@ -1,115 +1,123 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import markdown
|
||||
import logging
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
"""This module contains classes handling commands issued by Matrix users."""
|
||||
from typing import Awaitable, Callable, List, Optional, NamedTuple, Any
|
||||
|
||||
from telethon.errors import FloodWaitError
|
||||
|
||||
command_handlers = {}
|
||||
from mautrix.types import RoomID, EventID, MessageEventContent
|
||||
from mautrix.bridge.commands import (HelpSection, CommandEvent as BaseCommandEvent,
|
||||
CommandHandler as BaseCommandHandler,
|
||||
CommandProcessor as BaseCommandProcessor,
|
||||
CommandHandlerFunc, command_handler as base_command_handler)
|
||||
|
||||
from ..util import format_duration
|
||||
from .. import user as u, context as c, portal as po
|
||||
|
||||
|
||||
def command_handler(needs_auth=True, management_only=False, needs_admin=False, name=None):
|
||||
def decorator(func):
|
||||
def wrapper(evt):
|
||||
if management_only and not evt.is_management:
|
||||
return evt.reply(f"`{evt.command}` is a restricted command:"
|
||||
+ "you may only run it in management rooms.")
|
||||
elif needs_auth and not evt.sender.logged_in:
|
||||
return evt.reply("This command requires you to be logged in.")
|
||||
elif needs_admin and not evt.sender.is_admin:
|
||||
return evt.reply("This is command requires administrator privileges.")
|
||||
return func(evt)
|
||||
|
||||
command_handlers[name or func.__name__.replace("_", "-")] = wrapper
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
class HelpCacheKey(NamedTuple):
|
||||
is_management: bool
|
||||
is_portal: bool
|
||||
puppet_whitelisted: bool
|
||||
matrix_puppet_whitelisted: bool
|
||||
is_admin: bool
|
||||
is_logged_in: bool
|
||||
|
||||
|
||||
class CommandEvent:
|
||||
def __init__(self, handler, room, sender, command, args, is_management, is_portal):
|
||||
self.az = handler.az
|
||||
self.log = handler.log
|
||||
self.loop = handler.loop
|
||||
self.command_prefix = handler.command_prefix
|
||||
self.room_id = room
|
||||
self.sender = sender
|
||||
self.command = command
|
||||
self.args = args
|
||||
self.is_management = is_management
|
||||
self.is_portal = is_portal
|
||||
|
||||
def reply(self, message, allow_html=False, render_markdown=True):
|
||||
message = message.replace("$cmdprefix+sp ",
|
||||
"" if self.is_management else f"{self.command_prefix} ")
|
||||
message = message.replace("$cmdprefix", self.command_prefix)
|
||||
html = None
|
||||
if render_markdown:
|
||||
html = markdown.markdown(message, safe_mode="escape" if allow_html else False)
|
||||
elif allow_html:
|
||||
html = message
|
||||
return self.az.intent.send_notice(self.room_id, message, html=html)
|
||||
SECTION_AUTH = HelpSection("Authentication", 10, "")
|
||||
SECTION_CREATING_PORTALS = HelpSection("Creating portals", 20, "")
|
||||
SECTION_PORTAL_MANAGEMENT = HelpSection("Portal management", 30, "")
|
||||
SECTION_MISC = HelpSection("Miscellaneous", 40, "")
|
||||
SECTION_ADMIN = HelpSection("Administration", 50, "")
|
||||
|
||||
|
||||
def format_duration(seconds):
|
||||
def pluralize(count, singular): return singular if count == 1 else singular + "s"
|
||||
class CommandEvent(BaseCommandEvent):
|
||||
sender: u.User
|
||||
portal: po.Portal
|
||||
|
||||
def include(count, word): return f"{count} {pluralize(count, word)}" if count > 0 else ""
|
||||
def __init__(self, processor: 'CommandProcessor', room_id: RoomID, event_id: EventID,
|
||||
sender: u.User, command: str, args: List[str], content: MessageEventContent,
|
||||
portal: Optional['po.Portal'], is_management: bool, has_bridge_bot: bool) -> None:
|
||||
super().__init__(processor, room_id, event_id, sender, command, args, content,
|
||||
portal, is_management, has_bridge_bot)
|
||||
self.bridge = processor.bridge
|
||||
self.tgbot = processor.tgbot
|
||||
self.config = processor.config
|
||||
self.public_website = processor.public_website
|
||||
|
||||
minutes, seconds = divmod(seconds, 60)
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
days, hours = divmod(hours, 24)
|
||||
parts = [a for a in [
|
||||
include(days, "day"),
|
||||
include(hours, "hour"),
|
||||
include(minutes, "minute"),
|
||||
include(seconds, "second")] if a]
|
||||
if len(parts) > 2:
|
||||
return "{} and {}".format(", ".join(parts[:-1]), parts[-1])
|
||||
return " and ".join(parts)
|
||||
@property
|
||||
def print_error_traceback(self) -> bool:
|
||||
return self.sender.is_admin
|
||||
|
||||
async def get_help_key(self) -> HelpCacheKey:
|
||||
return HelpCacheKey(self.is_management, self.portal is not None,
|
||||
self.sender.puppet_whitelisted, self.sender.matrix_puppet_whitelisted,
|
||||
self.sender.is_admin, await self.sender.is_logged_in())
|
||||
|
||||
|
||||
class CommandHandler:
|
||||
log = logging.getLogger("mau.commands")
|
||||
class CommandHandler(BaseCommandHandler):
|
||||
name: str
|
||||
|
||||
def __init__(self, context):
|
||||
self.az, self.db, self.config, self.loop = context
|
||||
self.command_prefix = self.config["bridge.command_prefix"]
|
||||
needs_puppeting: bool
|
||||
needs_matrix_puppeting: bool
|
||||
|
||||
# region Utility functions for handling commands
|
||||
def __init__(self, handler: Callable[[CommandEvent], Awaitable[EventID]],
|
||||
management_only: bool, name: str, help_text: str, help_args: str,
|
||||
help_section: HelpSection, needs_auth: bool, needs_puppeting: bool,
|
||||
needs_matrix_puppeting: bool, needs_admin: bool) -> None:
|
||||
super().__init__(handler, management_only, name, help_text, help_args, help_section,
|
||||
needs_auth=needs_auth, needs_puppeting=needs_puppeting,
|
||||
needs_matrix_puppeting=needs_matrix_puppeting, needs_admin=needs_admin)
|
||||
|
||||
async def handle(self, room, sender, command, args, is_management, is_portal):
|
||||
evt = CommandEvent(self, room, sender, command, args,
|
||||
is_management, is_portal)
|
||||
command = command.lower()
|
||||
async def get_permission_error(self, evt: CommandEvent) -> Optional[str]:
|
||||
if self.needs_puppeting and not evt.sender.puppet_whitelisted:
|
||||
return "This command requires puppeting privileges."
|
||||
elif self.needs_matrix_puppeting and not evt.sender.matrix_puppet_whitelisted:
|
||||
return "This command requires Matrix puppeting privileges."
|
||||
return await super().get_permission_error(evt)
|
||||
|
||||
def has_permission(self, key: HelpCacheKey) -> bool:
|
||||
return (super().has_permission(key) and
|
||||
(not self.needs_puppeting or key.puppet_whitelisted) and
|
||||
(not self.needs_matrix_puppeting or key.matrix_puppet_whitelisted))
|
||||
|
||||
|
||||
def command_handler(_func: Optional[CommandHandlerFunc] = None, *, needs_auth: bool = True,
|
||||
needs_puppeting: bool = True, needs_matrix_puppeting: bool = False,
|
||||
needs_admin: bool = False, management_only: bool = False,
|
||||
name: Optional[str] = None, help_text: str = "", help_args: str = "",
|
||||
help_section: HelpSection = None) -> Callable[[CommandHandlerFunc],
|
||||
CommandHandler]:
|
||||
return base_command_handler(
|
||||
_func, _handler_class=CommandHandler, name=name, help_text=help_text, help_args=help_args,
|
||||
help_section=help_section, management_only=management_only, needs_auth=needs_auth,
|
||||
needs_admin=needs_admin, needs_puppeting=needs_puppeting,
|
||||
needs_matrix_puppeting=needs_matrix_puppeting)
|
||||
|
||||
|
||||
class CommandProcessor(BaseCommandProcessor):
|
||||
def __init__(self, context: c.Context) -> None:
|
||||
super().__init__(event_class=CommandEvent, bridge=context.bridge)
|
||||
self.tgbot = context.bot
|
||||
self.public_website = context.public_website
|
||||
|
||||
@staticmethod
|
||||
async def _run_handler(handler: Callable[[CommandEvent], Awaitable[Any]], evt: CommandEvent
|
||||
) -> Any:
|
||||
try:
|
||||
command = command_handlers[command]
|
||||
except KeyError:
|
||||
if sender.command_status and "next" in sender.command_status:
|
||||
args.insert(0, command)
|
||||
evt.command = ""
|
||||
command = sender.command_status["next"]
|
||||
else:
|
||||
command = command_handlers["unknown-command"]
|
||||
try:
|
||||
await command(evt)
|
||||
return await handler(evt)
|
||||
except FloodWaitError as e:
|
||||
return evt.reply(f"Flood error: Please wait {format_duration(e.seconds)}")
|
||||
except Exception:
|
||||
self.log.exception(f"Fatal error handling command "
|
||||
+ f"{evt.command} {' '.join(args)} from {sender.mxid}")
|
||||
return evt.reply("Fatal error while handling command. Check logs for more details.")
|
||||
return await evt.reply(f"Flood error: Please wait {format_duration(e.seconds)}")
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from mautrix.types import EventID
|
||||
from mautrix.bridge import InvalidAccessToken, OnlyLoginSelf
|
||||
|
||||
from . import command_handler, CommandEvent, SECTION_AUTH
|
||||
from .. import puppet as pu
|
||||
|
||||
|
||||
@command_handler(needs_auth=True, needs_matrix_puppeting=True,
|
||||
help_section=SECTION_AUTH, help_text="Revert your Telegram account's Matrix "
|
||||
"puppet to use the default Matrix account.")
|
||||
async def logout_matrix(evt: CommandEvent) -> EventID:
|
||||
puppet = pu.Puppet.get(evt.sender.tgid)
|
||||
if not puppet.is_real_user:
|
||||
return await evt.reply("You are not logged in with your Matrix account.")
|
||||
await puppet.switch_mxid(None, None)
|
||||
return await evt.reply("Reverted your Telegram account's Matrix puppet back to the default.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=True, management_only=True, needs_matrix_puppeting=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_text="Replace your Telegram account's Matrix puppet with your own Matrix "
|
||||
"account.")
|
||||
async def login_matrix(evt: CommandEvent) -> EventID:
|
||||
puppet = pu.Puppet.get(evt.sender.tgid)
|
||||
if puppet.is_real_user:
|
||||
return await evt.reply("You have already logged in with your Matrix account. "
|
||||
"Log out with `$cmdprefix+sp logout-matrix` first.")
|
||||
allow_matrix_login = evt.config.get("bridge.allow_matrix_login", True)
|
||||
if allow_matrix_login:
|
||||
evt.sender.command_status = {
|
||||
"next": enter_matrix_token,
|
||||
"action": "Matrix login",
|
||||
}
|
||||
if evt.config["appservice.public.enabled"]:
|
||||
prefix = evt.config["appservice.public.external"]
|
||||
token = evt.public_website.make_token(evt.sender.mxid, "/matrix-login")
|
||||
url = f"{prefix}/matrix-login?token={token}"
|
||||
if allow_matrix_login:
|
||||
return await evt.reply(
|
||||
"This bridge instance allows you to log in inside or outside Matrix.\n\n"
|
||||
"If you would like to log in within Matrix, please send your Matrix access token "
|
||||
"here.\n"
|
||||
f"If you would like to log in outside of Matrix, [click here]({url}).\n\n"
|
||||
"Logging in outside of Matrix is recommended, because in-Matrix login would save "
|
||||
"your access token in the message history.")
|
||||
return await evt.reply("This bridge instance does not allow logging in inside Matrix.\n\n"
|
||||
f"Please visit [the login page]({url}) to log in.")
|
||||
elif allow_matrix_login:
|
||||
return await evt.reply(
|
||||
"This bridge instance does not allow you to log in outside of Matrix.\n\n"
|
||||
"Please send your Matrix access token here to log in.")
|
||||
return await evt.reply("This bridge instance has been configured to not allow logging in.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=True, needs_matrix_puppeting=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_text="Pings the server with the stored matrix authentication.")
|
||||
async def ping_matrix(evt: CommandEvent) -> EventID:
|
||||
puppet = pu.Puppet.get(evt.sender.tgid)
|
||||
if not puppet.is_real_user:
|
||||
return await evt.reply("You are not logged in with your Matrix account.")
|
||||
try:
|
||||
await puppet.start()
|
||||
except InvalidAccessToken:
|
||||
return await evt.reply("Your access token is invalid.")
|
||||
return await evt.reply("Your Matrix login is working.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=True, needs_matrix_puppeting=True, help_section=SECTION_AUTH,
|
||||
help_text="Clear the Matrix sync token stored for your custom puppet.")
|
||||
async def clear_cache_matrix(evt: CommandEvent) -> EventID:
|
||||
puppet = pu.Puppet.get(evt.sender.tgid)
|
||||
if not puppet.is_real_user:
|
||||
return await evt.reply("You are not logged in with your Matrix account.")
|
||||
try:
|
||||
puppet.stop()
|
||||
puppet.next_batch = None
|
||||
await puppet.start()
|
||||
except InvalidAccessToken:
|
||||
return await evt.reply("Your access token is invalid.")
|
||||
return await evt.reply("Cleared cache successfully.")
|
||||
|
||||
|
||||
async def enter_matrix_token(evt: CommandEvent) -> EventID:
|
||||
evt.sender.command_status = None
|
||||
|
||||
puppet = pu.Puppet.get(evt.sender.tgid)
|
||||
if puppet.is_real_user:
|
||||
return await evt.reply("You have already logged in with your Matrix account. "
|
||||
"Log out with `$cmdprefix+sp logout-matrix` first.")
|
||||
try:
|
||||
await puppet.switch_mxid(" ".join(evt.args), evt.sender.mxid)
|
||||
except OnlyLoginSelf:
|
||||
return await evt.reply("You can only log in as your own Matrix user.")
|
||||
except InvalidAccessToken:
|
||||
return await evt.reply("Failed to verify access token.")
|
||||
return await evt.reply("Replaced your Telegram account's Matrix puppet "
|
||||
f"with {puppet.custom_mxid}.")
|
||||
@@ -1,76 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from . import command_handler
|
||||
|
||||
|
||||
@command_handler()
|
||||
def cancel(evt):
|
||||
if evt.sender.command_status:
|
||||
action = evt.sender.command_status["action"]
|
||||
evt.sender.command_status = None
|
||||
return evt.reply(f"{action} cancelled.")
|
||||
else:
|
||||
return evt.reply("No ongoing command.")
|
||||
|
||||
|
||||
@command_handler()
|
||||
def unknown_command(evt):
|
||||
return evt.reply("Unknown command. Try `$cmdprefix+sp help` for help.")
|
||||
|
||||
|
||||
@command_handler()
|
||||
def help(evt):
|
||||
if evt.is_management:
|
||||
management_status = ("This is a management room: prefixing commands "
|
||||
"with `$cmdprefix` is not required.\n")
|
||||
elif evt.is_portal:
|
||||
management_status = ("**This is a portal room**: you must always "
|
||||
"prefix commands with `$cmdprefix`.\n"
|
||||
"Management commands will not be sent to Telegram.")
|
||||
else:
|
||||
management_status = ("**This is not a management room**: you must "
|
||||
"prefix commands with `$cmdprefix`.\n")
|
||||
help = """\n
|
||||
#### Generic bridge commands
|
||||
**help** - Show this help message.
|
||||
**cancel** - Cancel an ongoing action (such as login).
|
||||
|
||||
#### Authentication
|
||||
**login** <_phone_> - Request an authentication code.
|
||||
**logout** - Log out from Telegram.
|
||||
**ping** - Check if you're logged into Telegram.
|
||||
|
||||
#### Initiating chats
|
||||
**search** [_-r|--remote_] <_query_> - Search your contacts or the Telegram servers for users.
|
||||
**pm** <_identifier_> - Open a private chat with the given Telegram user. The
|
||||
identifier is either the internal user ID, the username or
|
||||
the phone number.
|
||||
**join** <_link_> - Join a chat with an invite link.
|
||||
**create** [_type_] - Create a Telegram chat of the given type for the current
|
||||
Matrix room. The type is either `group`, `supergroup` or
|
||||
`channel` (defaults to `group`).
|
||||
|
||||
#### Portal management
|
||||
**upgrade** - Upgrade a normal Telegram group to a supergroup.
|
||||
**invite-link** - Get a Telegram invite link to the current chat.
|
||||
**delete-portal** - Forget the current portal room. Only works for group chats; to delete
|
||||
a private chat portal, simply leave the room.
|
||||
**group-name** <_name_|`-`> - Change the username of a supergroup/channel. To disable, use a dash
|
||||
(`-`) as the name.
|
||||
**clean-rooms** - Clean up unused portal/management rooms.
|
||||
"""
|
||||
return evt.reply(management_status + help)
|
||||
@@ -0,0 +1 @@
|
||||
from . import admin, bridge, config, create_chat, filter, misc, unbridge
|
||||
@@ -0,0 +1,76 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
import asyncio
|
||||
|
||||
from mautrix.types import EventID
|
||||
|
||||
from ... import portal as po, puppet as pu, user as u
|
||||
from .. import command_handler, CommandEvent, SECTION_ADMIN
|
||||
|
||||
|
||||
@command_handler(needs_admin=True, needs_auth=False,
|
||||
help_section=SECTION_ADMIN,
|
||||
help_args="<`portal`|`puppet`|`user`>",
|
||||
help_text="Clear internal bridge caches")
|
||||
async def clear_db_cache(evt: CommandEvent) -> EventID:
|
||||
try:
|
||||
section = evt.args[0].lower()
|
||||
except IndexError:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp clear-db-cache <section>`")
|
||||
if section == "portal":
|
||||
po.Portal.by_tgid = {}
|
||||
po.Portal.by_mxid = {}
|
||||
await evt.reply("Cleared portal cache")
|
||||
elif section == "puppet":
|
||||
pu.Puppet.cache = {}
|
||||
for puppet in pu.Puppet.by_custom_mxid.values():
|
||||
puppet.sync_task.cancel()
|
||||
pu.Puppet.by_custom_mxid = {}
|
||||
await asyncio.gather(*[puppet.try_start() for puppet in pu.Puppet.all_with_custom_mxid()],
|
||||
loop=evt.loop)
|
||||
await evt.reply("Cleared puppet cache and restarted custom puppet syncers")
|
||||
elif section == "user":
|
||||
u.User.by_mxid = {
|
||||
user.mxid: user
|
||||
for user in u.User.by_tgid.values()
|
||||
}
|
||||
await evt.reply("Cleared non-logged-in user cache")
|
||||
else:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp clear-db-cache <section>`")
|
||||
|
||||
|
||||
@command_handler(needs_admin=True, needs_auth=False,
|
||||
help_section=SECTION_ADMIN,
|
||||
help_args="[_mxid_]",
|
||||
help_text="Reload and reconnect a user")
|
||||
async def reload_user(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) > 0:
|
||||
mxid = evt.args[0]
|
||||
else:
|
||||
mxid = evt.sender.mxid
|
||||
user = u.User.get_by_mxid(mxid, create=False)
|
||||
if not user:
|
||||
return await evt.reply("User not found")
|
||||
puppet = await pu.Puppet.get_by_custom_mxid(mxid)
|
||||
if puppet:
|
||||
puppet.sync_task.cancel()
|
||||
await user.stop()
|
||||
user.delete(delete_db=False)
|
||||
user = u.User.get_by_mxid(mxid)
|
||||
await user.ensure_started()
|
||||
if puppet:
|
||||
await puppet.start()
|
||||
return await evt.reply(f"Reloaded and reconnected {user.mxid} (telegram: {user.human_tg_id})")
|
||||
@@ -0,0 +1,196 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, Tuple, Awaitable
|
||||
import asyncio
|
||||
|
||||
from telethon.tl.types import ChatForbidden, ChannelForbidden
|
||||
|
||||
from mautrix.types import EventID, RoomID
|
||||
|
||||
from ...types import TelegramID
|
||||
from ... import portal as po
|
||||
from .. import command_handler, CommandEvent, SECTION_CREATING_PORTALS
|
||||
from .util import user_has_power_level, get_initial_state, warn_missing_power
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, needs_puppeting=False,
|
||||
help_section=SECTION_CREATING_PORTALS,
|
||||
help_args="[_id_]",
|
||||
help_text="Bridge the current Matrix room to the Telegram chat with the given "
|
||||
"ID. The ID must be the prefixed version that you get with the `/id` "
|
||||
"command of the Telegram-side bot.")
|
||||
async def bridge(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** "
|
||||
"`$cmdprefix+sp bridge <Telegram chat ID> [Matrix room ID]`")
|
||||
force_use_bot = False
|
||||
if evt.args[0] == "--usebot" and evt.sender.is_admin:
|
||||
force_use_bot = True
|
||||
evt.args = evt.args[1:]
|
||||
room_id = RoomID(evt.args[1]) if len(evt.args) > 1 else evt.room_id
|
||||
that_this = "This" if room_id == evt.room_id else "That"
|
||||
|
||||
portal = po.Portal.get_by_mxid(room_id)
|
||||
if portal:
|
||||
return await evt.reply(f"{that_this} room is already a portal room.")
|
||||
|
||||
if not await user_has_power_level(room_id, evt.az.intent, evt.sender, "bridge"):
|
||||
return await evt.reply(f"You do not have the permissions to bridge {that_this} room.")
|
||||
|
||||
# The /id bot command provides the prefixed ID, so we assume
|
||||
tgid_str = evt.args[0]
|
||||
if tgid_str.startswith("-100"):
|
||||
tgid = TelegramID(int(tgid_str[4:]))
|
||||
peer_type = "channel"
|
||||
elif tgid_str.startswith("-"):
|
||||
tgid = TelegramID(-int(tgid_str))
|
||||
peer_type = "chat"
|
||||
else:
|
||||
return await evt.reply("That doesn't seem like a prefixed Telegram chat ID.\n\n"
|
||||
"If you did not get the ID using the `/id` bot command, please "
|
||||
"prefix channel IDs with `-100` and normal group IDs with `-`.\n\n"
|
||||
"Bridging private chats to existing rooms is not allowed.")
|
||||
|
||||
portal = po.Portal.get_by_tgid(tgid, peer_type=peer_type)
|
||||
if not portal.allow_bridging:
|
||||
return await evt.reply("This bridge doesn't allow bridging that Telegram chat.\n"
|
||||
"If you're the bridge admin, try "
|
||||
"`$cmdprefix+sp filter whitelist <Telegram chat ID>` first.")
|
||||
if portal.mxid:
|
||||
has_portal_message = (
|
||||
"That Telegram chat already has a portal at "
|
||||
f"[{portal.alias or portal.mxid}](https://matrix.to/#/{portal.mxid}). ")
|
||||
if not await user_has_power_level(portal.mxid, evt.az.intent, evt.sender, "unbridge"):
|
||||
return await evt.reply(f"{has_portal_message}"
|
||||
"Additionally, you do not have the permissions to unbridge "
|
||||
"that room.")
|
||||
evt.sender.command_status = {
|
||||
"next": confirm_bridge,
|
||||
"action": "Room bridging",
|
||||
"mxid": portal.mxid,
|
||||
"bridge_to_mxid": room_id,
|
||||
"tgid": portal.tgid,
|
||||
"peer_type": portal.peer_type,
|
||||
"force_use_bot": force_use_bot,
|
||||
}
|
||||
return await evt.reply(f"{has_portal_message}"
|
||||
"However, you have the permissions to unbridge that room.\n\n"
|
||||
"To delete that portal completely and continue bridging, use "
|
||||
"`$cmdprefix+sp delete-and-continue`. To unbridge the portal "
|
||||
"without kicking Matrix users, use `$cmdprefix+sp unbridge-and-"
|
||||
"continue`. To cancel, use `$cmdprefix+sp cancel`")
|
||||
evt.sender.command_status = {
|
||||
"next": confirm_bridge,
|
||||
"action": "Room bridging",
|
||||
"bridge_to_mxid": room_id,
|
||||
"tgid": portal.tgid,
|
||||
"peer_type": portal.peer_type,
|
||||
"force_use_bot": force_use_bot,
|
||||
}
|
||||
return await evt.reply("That Telegram chat has no existing portal. To confirm bridging the "
|
||||
"chat to this room, use `$cmdprefix+sp continue`")
|
||||
|
||||
|
||||
async def cleanup_old_portal_while_bridging(evt: CommandEvent, portal: "po.Portal"
|
||||
) -> Tuple[bool, Optional[Awaitable[None]]]:
|
||||
if not portal.mxid:
|
||||
await evt.reply("The portal seems to have lost its Matrix room between you"
|
||||
"calling `$cmdprefix+sp bridge` and this command.\n\n"
|
||||
"Continuing without touching previous Matrix room...")
|
||||
return True, None
|
||||
elif evt.args[0] == "delete-and-continue":
|
||||
return True, portal.cleanup_portal("Portal deleted (moving to another room)", delete=False)
|
||||
elif evt.args[0] == "unbridge-and-continue":
|
||||
return True, portal.cleanup_portal("Room unbridged (portal moving to another room)",
|
||||
puppets_only=True, delete=False)
|
||||
else:
|
||||
await evt.reply(
|
||||
"The chat you were trying to bridge already has a Matrix portal room.\n\n"
|
||||
"Please use `$cmdprefix+sp delete-and-continue` or `$cmdprefix+sp unbridge-and-"
|
||||
"continue` to either delete or unbridge the existing room (respectively) and "
|
||||
"continue with the bridging.\n\n"
|
||||
"If you changed your mind, use `$cmdprefix+sp cancel` to cancel.")
|
||||
return False, None
|
||||
|
||||
|
||||
async def confirm_bridge(evt: CommandEvent) -> Optional[EventID]:
|
||||
status = evt.sender.command_status
|
||||
try:
|
||||
portal = po.Portal.get_by_tgid(status["tgid"], peer_type=status["peer_type"])
|
||||
bridge_to_mxid = status["bridge_to_mxid"]
|
||||
except KeyError:
|
||||
evt.sender.command_status = None
|
||||
return await evt.reply("Fatal error: tgid or peer_type missing from command_status. "
|
||||
"This shouldn't happen unless you're messing with the command "
|
||||
"handler code.")
|
||||
|
||||
is_logged_in = await evt.sender.is_logged_in() and not status["force_use_bot"]
|
||||
|
||||
if "mxid" in status:
|
||||
ok, coro = await cleanup_old_portal_while_bridging(evt, portal)
|
||||
if not ok:
|
||||
return None
|
||||
elif coro:
|
||||
asyncio.ensure_future(coro, loop=evt.loop)
|
||||
await evt.reply("Cleaning up previous portal room...")
|
||||
elif portal.mxid:
|
||||
evt.sender.command_status = None
|
||||
return await evt.reply("The portal seems to have created a Matrix room between you "
|
||||
"calling `$cmdprefix+sp bridge` and this command.\n\n"
|
||||
"Please start over by calling the bridge command again.")
|
||||
elif evt.args[0] != "continue":
|
||||
return await evt.reply("Please use `$cmdprefix+sp continue` to confirm the bridging or "
|
||||
"`$cmdprefix+sp cancel` to cancel.")
|
||||
|
||||
evt.sender.command_status = None
|
||||
async with portal._room_create_lock:
|
||||
await _locked_confirm_bridge(evt, portal=portal, room_id=bridge_to_mxid,
|
||||
is_logged_in=is_logged_in)
|
||||
|
||||
|
||||
async def _locked_confirm_bridge(evt: CommandEvent, portal: 'po.Portal', room_id: RoomID,
|
||||
is_logged_in: bool) -> Optional[EventID]:
|
||||
user = evt.sender if is_logged_in else evt.tgbot
|
||||
try:
|
||||
entity = await user.client.get_entity(portal.peer)
|
||||
except Exception:
|
||||
evt.log.exception("Failed to get_entity(%s) for manual bridging.", portal.peer)
|
||||
if is_logged_in:
|
||||
return await evt.reply("Failed to get info of telegram chat. "
|
||||
"You are logged in, are you in that chat?")
|
||||
else:
|
||||
return await evt.reply("Failed to get info of telegram chat. "
|
||||
"You're not logged in, is the relay bot in the chat?")
|
||||
if isinstance(entity, (ChatForbidden, ChannelForbidden)):
|
||||
if is_logged_in:
|
||||
return await evt.reply("You don't seem to be in that chat.")
|
||||
else:
|
||||
return await evt.reply("The bot doesn't seem to be in that chat.")
|
||||
|
||||
portal.mxid = room_id
|
||||
portal.by_mxid[portal.mxid] = portal
|
||||
(portal.title, portal.about, levels,
|
||||
portal.encrypted) = await get_initial_state(evt.az.intent, evt.room_id)
|
||||
portal.photo_id = ""
|
||||
await portal.save()
|
||||
await portal.update_bridge_info()
|
||||
|
||||
asyncio.ensure_future(portal.update_matrix_room(user, entity, direct=False, levels=levels),
|
||||
loop=evt.loop)
|
||||
|
||||
await warn_missing_power(levels, evt)
|
||||
|
||||
return await evt.reply("Bridging complete. Portal synchronization should begin momentarily.")
|
||||
@@ -0,0 +1,151 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Awaitable, Any
|
||||
from io import StringIO
|
||||
|
||||
from ruamel.yaml import YAMLError
|
||||
|
||||
from mautrix.util.config import yaml
|
||||
from mautrix.types import EventID
|
||||
|
||||
from ... import portal as po, util
|
||||
from .. import command_handler, CommandEvent, SECTION_PORTAL_MANAGEMENT
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, help_section=SECTION_PORTAL_MANAGEMENT,
|
||||
help_text="View or change per-portal settings.",
|
||||
help_args="<`help`|_subcommand_> [...]")
|
||||
async def config(evt: CommandEvent) -> None:
|
||||
cmd = evt.args[0].lower() if len(evt.args) > 0 else "help"
|
||||
if cmd not in ("view", "defaults", "set", "unset", "add", "del"):
|
||||
await config_help(evt)
|
||||
return
|
||||
elif cmd == "defaults":
|
||||
await config_defaults(evt)
|
||||
return
|
||||
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
await evt.reply("This is not a portal room.")
|
||||
return
|
||||
elif cmd == "view":
|
||||
await config_view(evt, portal)
|
||||
return
|
||||
|
||||
if not await portal.can_user_perform(evt.sender, "config"):
|
||||
await evt.reply("You do not have the permissions to configure this room.")
|
||||
return
|
||||
|
||||
key = evt.args[1] if len(evt.args) > 1 else None
|
||||
try:
|
||||
value = yaml.load(" ".join(evt.args[2:])) if len(evt.args) > 2 else None
|
||||
except YAMLError as e:
|
||||
await evt.reply(f"Invalid value provided. Values must be valid YAML.\n{e}")
|
||||
return
|
||||
if cmd == "set":
|
||||
await config_set(evt, portal, key, value)
|
||||
elif cmd == "unset":
|
||||
await config_unset(evt, portal, key)
|
||||
elif cmd == "add" or cmd == "del":
|
||||
await config_add_del(evt, portal, key, value, cmd)
|
||||
else:
|
||||
return
|
||||
await portal.save()
|
||||
|
||||
|
||||
def config_help(evt: CommandEvent) -> Awaitable[EventID]:
|
||||
return evt.reply("""**Usage:** `$cmdprefix config <subcommand> [...]`. Subcommands:
|
||||
|
||||
* **help** - View this help text.
|
||||
* **view** - View the current config data.
|
||||
* **defaults** - View the default config values.
|
||||
* **set** <_key_> <_value_> - Set a config value.
|
||||
* **unset** <_key_> - Remove a config value.
|
||||
* **add** <_key_> <_value_> - Add a value to an array.
|
||||
* **del** <_key_> <_value_> - Remove a value from an array.
|
||||
""")
|
||||
|
||||
|
||||
def config_view(evt: CommandEvent, portal: po.Portal) -> Awaitable[EventID]:
|
||||
return evt.reply(f"Room-specific config:\n{_str_value(portal.local_config).rstrip()}")
|
||||
|
||||
|
||||
def config_defaults(evt: CommandEvent) -> Awaitable[EventID]:
|
||||
value = _str_value({
|
||||
"bridge_notices": {
|
||||
"default": evt.config["bridge.bridge_notices.default"],
|
||||
"exceptions": evt.config["bridge.bridge_notices.exceptions"],
|
||||
},
|
||||
"bot_messages_as_notices": evt.config["bridge.bot_messages_as_notices"],
|
||||
"inline_images": evt.config["bridge.inline_images"],
|
||||
"message_formats": evt.config["bridge.message_formats"],
|
||||
"emote_format": evt.config["bridge.emote_format"],
|
||||
"state_event_formats": evt.config["bridge.state_event_formats"],
|
||||
"telegram_link_preview": evt.config["bridge.telegram_link_preview"],
|
||||
})
|
||||
return evt.reply(f"Bridge instance wide config:\n{value.rstrip()}")
|
||||
|
||||
|
||||
def _str_value(value: Any) -> str:
|
||||
stream = StringIO()
|
||||
yaml.dump(value, stream)
|
||||
value_str = stream.getvalue()
|
||||
if "\n" in value_str:
|
||||
return f"\n```yaml\n{value_str}\n```\n"
|
||||
else:
|
||||
return f"`{value_str}`"
|
||||
|
||||
|
||||
def config_set(evt: CommandEvent, portal: po.Portal, key: str, value: Any) -> Awaitable[EventID]:
|
||||
if not key or value is None:
|
||||
return evt.reply(f"**Usage:** `$cmdprefix+sp config set <key> <value>`")
|
||||
elif util.recursive_set(portal.local_config, key, value):
|
||||
return evt.reply(f"Successfully set the value of `{key}` to {_str_value(value)}".rstrip())
|
||||
else:
|
||||
return evt.reply(f"Failed to set value of `{key}`. "
|
||||
"Does the path contain non-map types?")
|
||||
|
||||
|
||||
def config_unset(evt: CommandEvent, portal: po.Portal, key: str) -> Awaitable[EventID]:
|
||||
if not key:
|
||||
return evt.reply(f"**Usage:** `$cmdprefix+sp config unset <key>`")
|
||||
elif util.recursive_del(portal.local_config, key):
|
||||
return evt.reply(f"Successfully deleted `{key}` from config.")
|
||||
else:
|
||||
return evt.reply(f"`{key}` not found in config.")
|
||||
|
||||
|
||||
def config_add_del(evt: CommandEvent, portal: po.Portal, key: str, value: str, cmd: str
|
||||
) -> Awaitable[EventID]:
|
||||
if not key or value is None:
|
||||
return evt.reply(f"**Usage:** `$cmdprefix+sp config {cmd} <key> <value>`")
|
||||
|
||||
arr = util.recursive_get(portal.local_config, key)
|
||||
if not arr:
|
||||
return evt.reply(f"`{key}` not found in config. "
|
||||
f"Maybe do `$cmdprefix+sp config set {key} []` first?")
|
||||
elif not isinstance(arr, list):
|
||||
return evt.reply("`{key}` does not seem to be an array.")
|
||||
elif cmd == "add":
|
||||
if value in arr:
|
||||
return evt.reply(f"The array at `{key}` already contains {_str_value(value)}".rstrip())
|
||||
arr.append(value)
|
||||
return evt.reply(f"Successfully added {_str_value(value)} to the array at `{key}`")
|
||||
else:
|
||||
if value not in arr:
|
||||
return evt.reply(f"The array at `{key}` does not contain {_str_value(value)}")
|
||||
arr.remove(value)
|
||||
return evt.reply(f"Successfully removed {_str_value(value)} from the array at `{key}`")
|
||||
@@ -0,0 +1,69 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from mautrix.types import EventID
|
||||
|
||||
from ... import portal as po
|
||||
from ...types import TelegramID
|
||||
from .. import command_handler, CommandEvent, SECTION_CREATING_PORTALS
|
||||
from .util import user_has_power_level, get_initial_state, warn_missing_power
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_CREATING_PORTALS,
|
||||
help_args="[_type_]",
|
||||
help_text="Create a Telegram chat of the given type for the current Matrix room. "
|
||||
"The type is either `group`, `supergroup` or `channel` (defaults to "
|
||||
"`supergroup`).")
|
||||
async def create(evt: CommandEvent) -> EventID:
|
||||
type = evt.args[0] if len(evt.args) > 0 else "supergroup"
|
||||
if type not in ("chat", "group", "supergroup", "channel"):
|
||||
return await evt.reply(
|
||||
"**Usage:** `$cmdprefix+sp create ['group'/'supergroup'/'channel']`")
|
||||
|
||||
if po.Portal.get_by_mxid(evt.room_id):
|
||||
return await evt.reply("This is already a portal room.")
|
||||
|
||||
if not await user_has_power_level(evt.room_id, evt.az.intent, evt.sender, "bridge"):
|
||||
return await evt.reply("You do not have the permissions to bridge this room.")
|
||||
|
||||
title, about, levels, encrypted = await get_initial_state(evt.az.intent, evt.room_id)
|
||||
if not title:
|
||||
return await evt.reply("Please set a title before creating a Telegram chat.")
|
||||
|
||||
supergroup = type == "supergroup"
|
||||
type = {
|
||||
"supergroup": "channel",
|
||||
"channel": "channel",
|
||||
"chat": "chat",
|
||||
"group": "chat",
|
||||
}[type]
|
||||
|
||||
portal = po.Portal(tgid=TelegramID(0), peer_type=type, mxid=evt.room_id,
|
||||
title=title, about=about, encrypted=encrypted)
|
||||
invites, errors = await portal.get_telegram_users_in_matrix_room(evt.sender)
|
||||
if len(errors) > 0:
|
||||
error_list = "\n".join(f"* [{mxid}](https://matrix.to/#/{mxid})" for mxid in errors)
|
||||
await evt.reply(f"Failed to add the following users to the chat:\n\n{error_list}\n\n"
|
||||
"You can try `$cmdprefix+sp search -r <username>` to help the bridge find "
|
||||
"those users.")
|
||||
|
||||
await warn_missing_power(levels, evt)
|
||||
|
||||
try:
|
||||
await portal.create_telegram_chat(evt.sender, invites=invites, supergroup=supergroup)
|
||||
except ValueError as e:
|
||||
await portal.delete()
|
||||
return await evt.reply(e.args[0])
|
||||
return await evt.reply(f"Telegram chat created. ID: {portal.tgid}")
|
||||
@@ -0,0 +1,95 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from mautrix.types import EventID
|
||||
|
||||
from ... import portal as po
|
||||
from .. import command_handler, CommandEvent, SECTION_ADMIN
|
||||
|
||||
|
||||
@command_handler(needs_admin=True,
|
||||
help_section=SECTION_ADMIN,
|
||||
help_args="<`whitelist`|`blacklist`>",
|
||||
help_text="Change whether the bridge will allow or disallow bridging rooms by "
|
||||
"default.")
|
||||
async def filter_mode(evt: CommandEvent) -> EventID:
|
||||
try:
|
||||
mode = evt.args[0]
|
||||
if mode not in ("whitelist", "blacklist"):
|
||||
raise ValueError()
|
||||
except (IndexError, ValueError):
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp filter-mode <whitelist/blacklist>`")
|
||||
|
||||
evt.config["bridge.filter.mode"] = mode
|
||||
evt.config.save()
|
||||
po.Portal.filter_mode = mode
|
||||
if mode == "whitelist":
|
||||
return await evt.reply("The bridge will now disallow bridging chats by default.\n"
|
||||
"To allow bridging a specific chat, use"
|
||||
"`!filter whitelist <chat ID>`.")
|
||||
else:
|
||||
return await evt.reply("The bridge will now allow bridging chats by default.\n"
|
||||
"To disallow bridging a specific chat, use"
|
||||
"`!filter blacklist <chat ID>`.")
|
||||
|
||||
|
||||
@command_handler(name="filter", needs_admin=True,
|
||||
help_section=SECTION_ADMIN,
|
||||
help_args="<`whitelist`|`blacklist`> <_chat ID_>",
|
||||
help_text="Allow or disallow bridging a specific chat.")
|
||||
async def edit_filter(evt: CommandEvent) -> EventID:
|
||||
try:
|
||||
action = evt.args[0]
|
||||
if action not in ("whitelist", "blacklist", "add", "remove"):
|
||||
raise ValueError()
|
||||
|
||||
id_str = evt.args[1]
|
||||
if id_str.startswith("-100"):
|
||||
filter_id = int(id_str[4:])
|
||||
elif id_str.startswith("-"):
|
||||
filter_id = int(id_str[1:])
|
||||
else:
|
||||
filter_id = int(id_str)
|
||||
except (IndexError, ValueError):
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp filter <whitelist/blacklist> <chat ID>`")
|
||||
|
||||
mode = evt.config["bridge.filter.mode"]
|
||||
if mode not in ("blacklist", "whitelist"):
|
||||
return await evt.reply(f"Unknown filter mode \"{mode}\". Please fix the bridge config.")
|
||||
|
||||
filter_id_list = evt.config["bridge.filter.list"]
|
||||
|
||||
if action in ("blacklist", "whitelist"):
|
||||
action = "add" if mode == action else "remove"
|
||||
|
||||
def save() -> None:
|
||||
evt.config["bridge.filter.list"] = filter_id_list
|
||||
evt.config.save()
|
||||
po.Portal.filter_list = filter_id_list
|
||||
|
||||
if action == "add":
|
||||
if filter_id in filter_id_list:
|
||||
return await evt.reply(f"That chat is already {mode}ed.")
|
||||
filter_id_list.append(filter_id)
|
||||
save()
|
||||
return await evt.reply(f"Chat ID added to {mode}.")
|
||||
elif action == "remove":
|
||||
if filter_id not in filter_id_list:
|
||||
return await evt.reply(f"That chat is not {mode}ed.")
|
||||
filter_id_list.remove(filter_id)
|
||||
save()
|
||||
return await evt.reply(f"Chat ID removed from {mode}.")
|
||||
else:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp filter <whitelist/blacklist> <chat ID>`")
|
||||
@@ -0,0 +1,230 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, List, Tuple
|
||||
from datetime import timedelta, datetime
|
||||
import re
|
||||
|
||||
from telethon.tl.functions.channels import GetFullChannelRequest
|
||||
from telethon.tl.functions.messages import GetFullChatRequest
|
||||
from telethon.errors import (ChatAdminRequiredError, UsernameInvalidError,
|
||||
UsernameNotModifiedError, UsernameOccupiedError, RPCError)
|
||||
|
||||
from mautrix.types import EventID
|
||||
|
||||
from ... import portal as po
|
||||
from .. import command_handler, CommandEvent, SECTION_PORTAL_MANAGEMENT, SECTION_MISC
|
||||
from .util import user_has_power_level
|
||||
|
||||
|
||||
@command_handler(needs_admin=False, needs_puppeting=False, needs_auth=False,
|
||||
help_section=SECTION_MISC,
|
||||
help_text="Fetch Matrix room state to ensure the bridge has up-to-date info.")
|
||||
async def sync_state(evt: CommandEvent) -> EventID:
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
elif not await user_has_power_level(evt.room_id, evt.az.intent, evt.sender, "bridge"):
|
||||
return await evt.reply(f"You do not have the permissions to synchronize this room.")
|
||||
|
||||
await portal.main_intent.get_joined_members(portal.mxid)
|
||||
await evt.reply("Synchronization complete")
|
||||
|
||||
|
||||
@command_handler(needs_admin=False, needs_puppeting=False, needs_auth=False,
|
||||
help_section=SECTION_MISC)
|
||||
async def sync_full(evt: CommandEvent) -> EventID:
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
|
||||
if len(evt.args) > 0 and evt.args[0] == "--usebot" and evt.sender.is_admin:
|
||||
src = evt.tgbot
|
||||
else:
|
||||
src = evt.tgbot if await evt.sender.needs_relaybot(portal) else evt.sender
|
||||
|
||||
try:
|
||||
if portal.peer_type == "channel":
|
||||
res = await src.client(GetFullChannelRequest(portal.peer))
|
||||
elif portal.peer_type == "chat":
|
||||
res = await src.client(GetFullChatRequest(portal.tgid))
|
||||
else:
|
||||
return await evt.reply("This is not a channel or chat portal.")
|
||||
except (ValueError, RPCError):
|
||||
return await evt.reply("Failed to get portal info from Telegram.")
|
||||
|
||||
await portal.update_matrix_room(src, res.full_chat)
|
||||
return await evt.reply("Portal synced successfully.")
|
||||
|
||||
|
||||
@command_handler(name="id", needs_admin=False, needs_puppeting=False, needs_auth=False,
|
||||
help_section=SECTION_MISC,
|
||||
help_text="Get the ID of the Telegram chat where this room is bridged.")
|
||||
async def get_id(evt: CommandEvent) -> EventID:
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
tgid = portal.tgid
|
||||
if portal.peer_type == "chat":
|
||||
tgid = -tgid
|
||||
elif portal.peer_type == "channel":
|
||||
tgid = f"-100{tgid}"
|
||||
await evt.reply(f"This room is bridged to Telegram chat ID `{tgid}`.")
|
||||
|
||||
|
||||
invite_link_usage = ("**Usage:** `$cmdprefix+sp invite-link [--uses=<amount>] [--expire=<delta>]`"
|
||||
"\n\n"
|
||||
"* `--uses`: the number of times the invite link can be used."
|
||||
" Defaults to unlimited.\n"
|
||||
"* `--expire`: the duration after which the link will expire."
|
||||
" A number suffixed with d(ay), h(our), m(inute) or s(econd)")
|
||||
|
||||
|
||||
def _parse_flag(args: List[str]) -> Tuple[str, str]:
|
||||
arg = args.pop(0).lower()
|
||||
if arg.startswith("--"):
|
||||
value_start = arg.index("=")
|
||||
if value_start:
|
||||
flag = arg[2:value_start]
|
||||
value = arg[value_start+1:]
|
||||
else:
|
||||
flag = arg[2:]
|
||||
value = args.pop(0).lower()
|
||||
elif arg.startswith("-"):
|
||||
flag = arg[1]
|
||||
if len(arg) > 3 and arg[2] == "=":
|
||||
value = arg[3:]
|
||||
else:
|
||||
value = args.pop(0).lower()
|
||||
else:
|
||||
raise ValueError("invalid flag")
|
||||
return flag, value
|
||||
|
||||
|
||||
delta_regex = re.compile("([0-9]+)(w(?:eek)?|d(?:ay)?|h(?:our)?|m(?:in(?:ute)?)?|s(?:ec(?:ond)?)?)")
|
||||
|
||||
|
||||
def _parse_delta(value: str) -> Optional[timedelta]:
|
||||
match = delta_regex.fullmatch(value)
|
||||
if not match:
|
||||
return None
|
||||
number = int(match.group(1))
|
||||
unit = match.group(2)[0]
|
||||
if unit == "w":
|
||||
return timedelta(weeks=number)
|
||||
elif unit == "d":
|
||||
return timedelta(days=number)
|
||||
elif unit == "h":
|
||||
return timedelta(hours=number)
|
||||
elif unit == "m":
|
||||
return timedelta(minutes=number)
|
||||
elif unit == "s":
|
||||
return timedelta(seconds=number)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_PORTAL_MANAGEMENT,
|
||||
help_text="Get a Telegram invite link to the current chat.",
|
||||
help_args="[--uses=<amount>] [--expire=<time delta, e.g. 1d>]")
|
||||
async def invite_link(evt: CommandEvent) -> EventID:
|
||||
# TODO once we switch to Python 3.9 minimum, use argparse with exit_on_error=False
|
||||
uses = None
|
||||
expire = None
|
||||
while evt.args:
|
||||
try:
|
||||
flag, value = _parse_flag(evt.args)
|
||||
except (ValueError, IndexError):
|
||||
return await evt.reply(invite_link_usage)
|
||||
if flag in ("uses", "u"):
|
||||
try:
|
||||
uses = int(value)
|
||||
except ValueError:
|
||||
await evt.reply("The number of uses must be an integer")
|
||||
elif flag in ("expire", "e"):
|
||||
expire_delta = _parse_delta(value)
|
||||
if not expire_delta:
|
||||
await evt.reply("Invalid format for expiry time delta")
|
||||
expire = datetime.now() + expire_delta
|
||||
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
|
||||
if portal.peer_type == "user":
|
||||
return await evt.reply("You can't invite users to private chats.")
|
||||
|
||||
try:
|
||||
link = await portal.get_invite_link(evt.sender, uses=uses, expire=expire)
|
||||
return await evt.reply(f"Invite link to {portal.title}: {link}")
|
||||
except ValueError as e:
|
||||
return await evt.reply(e.args[0])
|
||||
except ChatAdminRequiredError:
|
||||
return await evt.reply("You don't have the permission to create an invite link.")
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_PORTAL_MANAGEMENT,
|
||||
help_text="Upgrade a normal Telegram group to a supergroup.")
|
||||
async def upgrade(evt: CommandEvent) -> EventID:
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
elif portal.peer_type == "channel":
|
||||
return await evt.reply("This is already a supergroup or a channel.")
|
||||
elif portal.peer_type == "user":
|
||||
return await evt.reply("You can't upgrade private chats.")
|
||||
|
||||
try:
|
||||
await portal.upgrade_telegram_chat(evt.sender)
|
||||
return await evt.reply(f"Group upgraded to supergroup. New ID: -100{portal.tgid}")
|
||||
except ChatAdminRequiredError:
|
||||
return await evt.reply("You don't have the permission to upgrade this group.")
|
||||
except ValueError as e:
|
||||
return await evt.reply(e.args[0])
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_PORTAL_MANAGEMENT,
|
||||
help_args="<_name_|`-`>",
|
||||
help_text="Change the username of a supergroup/channel. "
|
||||
"To disable, use a dash (`-`) as the name.")
|
||||
async def group_name(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp group-name <name/->`")
|
||||
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
elif portal.peer_type != "channel":
|
||||
return await evt.reply("Only channels and supergroups have usernames.")
|
||||
|
||||
try:
|
||||
await portal.set_telegram_username(evt.sender,
|
||||
evt.args[0] if evt.args[0] != "-" else "")
|
||||
if portal.username:
|
||||
return await evt.reply(f"Username of channel changed to {portal.username}.")
|
||||
else:
|
||||
return await evt.reply(f"Channel is now private.")
|
||||
except ChatAdminRequiredError:
|
||||
return await evt.reply(
|
||||
"You don't have the permission to set the username of this channel.")
|
||||
except UsernameNotModifiedError:
|
||||
if portal.username:
|
||||
return await evt.reply("That is already the username of this channel.")
|
||||
else:
|
||||
return await evt.reply("This channel is already private")
|
||||
except UsernameOccupiedError:
|
||||
return await evt.reply("That username is already in use.")
|
||||
except UsernameInvalidError:
|
||||
return await evt.reply("Invalid username")
|
||||
@@ -0,0 +1,100 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Dict, Callable, Optional
|
||||
|
||||
from mautrix.types import RoomID, EventID
|
||||
|
||||
from ... import portal as po
|
||||
from .. import command_handler, CommandEvent, SECTION_PORTAL_MANAGEMENT
|
||||
from .util import user_has_power_level
|
||||
|
||||
|
||||
async def _get_portal_and_check_permission(evt: CommandEvent) -> Optional[po.Portal]:
|
||||
room_id = RoomID(evt.args[0]) if len(evt.args) > 0 else evt.room_id
|
||||
|
||||
portal = po.Portal.get_by_mxid(room_id)
|
||||
if not portal:
|
||||
that_this = "This" if room_id == evt.room_id else "That"
|
||||
await evt.reply(f"{that_this} is not a portal room.")
|
||||
return None
|
||||
|
||||
if portal.peer_type == "user":
|
||||
if portal.tg_receiver != evt.sender.tgid:
|
||||
await evt.reply("You do not have the permissions to unbridge that portal.")
|
||||
return None
|
||||
return portal
|
||||
|
||||
if not await user_has_power_level(portal.mxid, evt.az.intent, evt.sender, "unbridge"):
|
||||
await evt.reply("You do not have the permissions to unbridge that portal.")
|
||||
return None
|
||||
return portal
|
||||
|
||||
|
||||
def _get_portal_murder_function(action: str, room_id: str, function: Callable, command: str,
|
||||
completed_message: str) -> Dict:
|
||||
async def post_confirm(confirm) -> Optional[EventID]:
|
||||
confirm.sender.command_status = None
|
||||
if len(confirm.args) > 0 and confirm.args[0] == f"confirm-{command}":
|
||||
await function()
|
||||
if confirm.room_id != room_id:
|
||||
return await confirm.reply(completed_message)
|
||||
else:
|
||||
return await confirm.reply(f"{action} cancelled.")
|
||||
return None
|
||||
|
||||
return {
|
||||
"next": post_confirm,
|
||||
"action": action,
|
||||
}
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, needs_puppeting=False,
|
||||
help_section=SECTION_PORTAL_MANAGEMENT,
|
||||
help_text="Remove all users from the current portal room and forget the portal. "
|
||||
"Only works for group chats; to delete a private chat portal, simply "
|
||||
"leave the room.")
|
||||
async def delete_portal(evt: CommandEvent) -> Optional[EventID]:
|
||||
portal = await _get_portal_and_check_permission(evt)
|
||||
if not portal:
|
||||
return None
|
||||
|
||||
evt.sender.command_status = _get_portal_murder_function("Portal deletion", portal.mxid,
|
||||
portal.cleanup_and_delete, "delete",
|
||||
"Portal successfully deleted.")
|
||||
return await evt.reply("Please confirm deletion of portal "
|
||||
f"[{portal.alias or portal.mxid}](https://matrix.to/#/{portal.mxid}) "
|
||||
f"to Telegram chat \"{portal.title}\" "
|
||||
"by typing `$cmdprefix+sp confirm-delete`"
|
||||
"\n\n"
|
||||
"**WARNING:** If the bridge bot has the power level to do so, **this "
|
||||
"will kick ALL users** in the room. If you just want to remove the "
|
||||
"bridge, use `$cmdprefix+sp unbridge` instead.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, needs_puppeting=False,
|
||||
help_section=SECTION_PORTAL_MANAGEMENT,
|
||||
help_text="Remove puppets from the current portal room and forget the portal.")
|
||||
async def unbridge(evt: CommandEvent) -> Optional[EventID]:
|
||||
portal = await _get_portal_and_check_permission(evt)
|
||||
if not portal:
|
||||
return None
|
||||
|
||||
evt.sender.command_status = _get_portal_murder_function("Room unbridging", portal.mxid,
|
||||
portal.unbridge, "unbridge",
|
||||
"Room successfully unbridged.")
|
||||
return await evt.reply(f"Please confirm unbridging chat \"{portal.title}\" from room "
|
||||
f"[{portal.alias or portal.mxid}](https://matrix.to/#/{portal.mxid}) "
|
||||
"by typing `$cmdprefix+sp confirm-unbridge`")
|
||||
@@ -0,0 +1,72 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Tuple, Optional
|
||||
|
||||
from mautrix.errors import MatrixRequestError
|
||||
from mautrix.appservice import IntentAPI
|
||||
from mautrix.types import RoomID, EventType, PowerLevelStateEventContent
|
||||
from .. import CommandEvent
|
||||
|
||||
from ... import user as u
|
||||
|
||||
OptStr = Optional[str]
|
||||
|
||||
|
||||
async def get_initial_state(
|
||||
intent: IntentAPI, room_id: RoomID
|
||||
) -> Tuple[OptStr, OptStr, Optional[PowerLevelStateEventContent], bool]:
|
||||
state = await intent.get_state(room_id)
|
||||
title: OptStr = None
|
||||
about: OptStr = None
|
||||
levels: Optional[PowerLevelStateEventContent] = None
|
||||
encrypted: bool = False
|
||||
for event in state:
|
||||
try:
|
||||
if event.type == EventType.ROOM_NAME:
|
||||
title = event.content.name
|
||||
elif event.type == EventType.ROOM_TOPIC:
|
||||
about = event.content.topic
|
||||
elif event.type == EventType.ROOM_POWER_LEVELS:
|
||||
levels = event.content
|
||||
elif event.type == EventType.ROOM_CANONICAL_ALIAS:
|
||||
title = title or event.content.canonical_alias
|
||||
elif event.type == EventType.ROOM_ENCRYPTION:
|
||||
encrypted = True
|
||||
except KeyError:
|
||||
# Some state event probably has empty content
|
||||
pass
|
||||
return title, about, levels, encrypted
|
||||
|
||||
|
||||
async def warn_missing_power(levels: PowerLevelStateEventContent, evt: CommandEvent) -> None:
|
||||
if levels.get_user_level(evt.az.bot_mxid) < levels.redact:
|
||||
await evt.reply("Warning: The bot does not have privileges to redact messages on Matrix. "
|
||||
"Message deletions from Telegram will not be bridged unless you give "
|
||||
"redaction permissions to "
|
||||
f"[{evt.az.bot_mxid}](https://matrix.to/#/{evt.az.bot_mxid})")
|
||||
|
||||
|
||||
async def user_has_power_level(room_id: RoomID, intent: IntentAPI, sender: u.User,
|
||||
event: str) -> bool:
|
||||
if sender.is_admin:
|
||||
return True
|
||||
# Make sure the state store contains the power levels.
|
||||
try:
|
||||
await intent.get_power_levels(room_id)
|
||||
except MatrixRequestError:
|
||||
return False
|
||||
event_type = EventType.find(f"net.maunium.telegram.{event}", t_class=EventType.Class.STATE)
|
||||
return await intent.state_store.has_power_level(room_id, sender.mxid, event_type)
|
||||
@@ -1,261 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from telethon.errors import *
|
||||
from telethon.tl.types import User as TLUser
|
||||
from telethon.tl.functions.messages import ImportChatInviteRequest, CheckChatInviteRequest
|
||||
from telethon.tl.functions.channels import JoinChannelRequest
|
||||
|
||||
from .. import puppet as pu, portal as po
|
||||
from . import command_handler
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def search(evt):
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp search [-r|--remote] <query>`")
|
||||
|
||||
force_remote = False
|
||||
if evt.args[0] in {"-r", "--remote"}:
|
||||
force_remote = True
|
||||
evt.args.pop(0)
|
||||
|
||||
query = " ".join(evt.args)
|
||||
if force_remote and len(query) < 5:
|
||||
return await evt.reply("Minimum length of query for remote search is 5 characters.")
|
||||
|
||||
results, remote = await evt.sender.search(query, force_remote)
|
||||
|
||||
if not results:
|
||||
if len(query) < 5 and remote:
|
||||
return await evt.reply("No local results. "
|
||||
"Minimum length of remote query is 5 characters.")
|
||||
return await evt.reply("No results 3:")
|
||||
|
||||
reply = []
|
||||
if remote:
|
||||
reply += ["**Results from Telegram server:**", ""]
|
||||
else:
|
||||
reply += ["**Results in contacts:**", ""]
|
||||
reply += [(f"* [{puppet.displayname}](https://matrix.to/#/{puppet.mxid}): "
|
||||
+ f"{puppet.id} ({similarity}% match)")
|
||||
for puppet, similarity in results]
|
||||
|
||||
# TODO somehow show remote channel results when joining by alias is possible?
|
||||
|
||||
return await evt.reply("\n".join(reply))
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def pm(evt):
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp pm <user identifier>`")
|
||||
|
||||
user = await evt.sender.client.get_entity(evt.args[0])
|
||||
if not user:
|
||||
return await evt.reply("User not found.")
|
||||
elif not isinstance(user, TLUser):
|
||||
return await evt.reply("That doesn't seem to be a user.")
|
||||
portal = po.Portal.get_by_entity(user, evt.sender.tgid)
|
||||
await portal.create_matrix_room(evt.sender, user, [evt.sender.mxid])
|
||||
return await evt.reply(
|
||||
f"Created private chat room with {pu.Puppet.get_displayname(user, False)}")
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def invite_link(evt):
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
|
||||
if portal.peer_type == "user":
|
||||
return await evt.reply("You can't invite users to private chats.")
|
||||
|
||||
try:
|
||||
link = await portal.get_invite_link(evt.sender)
|
||||
return await evt.reply(f"Invite link to {portal.title}: {link}")
|
||||
except ValueError as e:
|
||||
return await evt.reply(e.args[0])
|
||||
except ChatAdminRequiredError:
|
||||
return await evt.reply("You don't have the permission to create an invite link.")
|
||||
|
||||
|
||||
@command_handler(needs_admin=True)
|
||||
async def delete_portal(evt):
|
||||
room_id = evt.args[0] if len(evt.args) > 0 else evt.room_id
|
||||
|
||||
portal = po.Portal.get_by_mxid(room_id)
|
||||
if not portal:
|
||||
that_this = "This" if room_id == evt.room_id else "That"
|
||||
return await evt.reply(f"{that_this} is not a portal room.")
|
||||
|
||||
async def post_confirm(confirm):
|
||||
evt.sender.command_status = None
|
||||
if len(confirm.args) > 0 and confirm.args[0] == "confirm-delete":
|
||||
await portal.cleanup_and_delete()
|
||||
if confirm.room_id != room_id:
|
||||
return await confirm.reply("Portal successfully deleted.")
|
||||
else:
|
||||
return await confirm.reply("Portal deletion cancelled.")
|
||||
|
||||
evt.sender.command_status = {
|
||||
"next": post_confirm,
|
||||
"action": "Portal deletion",
|
||||
}
|
||||
return await evt.reply("Please confirm deletion of portal "
|
||||
+ f"[{room_id}](https://matrix.to/#/{room_id}) "
|
||||
+ f"to Telegram chat \"{portal.title}\" "
|
||||
+ "by typing `$cmdprefix+sp confirm-delete`")
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def join(evt):
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp join <invite link>`")
|
||||
|
||||
regex = re.compile(r"(?:https?://)?t(?:elegram)?\.(?:dog|me)(?:joinchat/)?/(.+)")
|
||||
arg = regex.match(evt.args[0])
|
||||
if not arg:
|
||||
return await evt.reply("That doesn't look like a Telegram invite link.")
|
||||
arg = arg.group(1)
|
||||
if arg.startswith("joinchat/"):
|
||||
invite_hash = arg[len("joinchat/"):]
|
||||
try:
|
||||
await evt.sender.client(CheckChatInviteRequest(invite_hash))
|
||||
except InviteHashInvalidError:
|
||||
return await evt.reply("Invalid invite link.")
|
||||
except InviteHashExpiredError:
|
||||
return await evt.reply("Invite link expired.")
|
||||
try:
|
||||
updates = evt.sender.client(ImportChatInviteRequest(invite_hash))
|
||||
except UserAlreadyParticipantError:
|
||||
return await evt.reply("You are already in that chat.")
|
||||
else:
|
||||
channel = await evt.sender.client.get_entity(arg)
|
||||
if not channel:
|
||||
return await evt.reply("Channel/supergroup not found.")
|
||||
updates = await evt.sender.client(JoinChannelRequest(channel))
|
||||
for chat in updates.chats:
|
||||
portal = po.Portal.get_by_entity(chat)
|
||||
if portal.mxid:
|
||||
await portal.create_matrix_room(evt.sender, chat, [evt.sender.mxid])
|
||||
return await evt.reply(f"Created room for {portal.title}")
|
||||
else:
|
||||
await portal.invite_matrix([evt.sender.mxid])
|
||||
return await evt.reply(f"Invited you to portal of {portal.title}")
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def create(evt):
|
||||
type = evt.args[0] if len(evt.args) > 0 else "group"
|
||||
if type not in {"chat", "group", "supergroup", "channel"}:
|
||||
return await evt.reply(
|
||||
"**Usage:** `$cmdprefix+sp create ['group'/'supergroup'/'channel']`")
|
||||
|
||||
if po.Portal.get_by_mxid(evt.room_id):
|
||||
return await evt.reply("This is already a portal room.")
|
||||
|
||||
state = await evt.az.intent.get_room_state(evt.room_id)
|
||||
title = None
|
||||
about = None
|
||||
levels = None
|
||||
for event in state:
|
||||
if event["type"] == "m.room.name":
|
||||
title = event["content"]["name"]
|
||||
elif event["type"] == "m.room.topic":
|
||||
about = event["content"]["topic"]
|
||||
elif event["type"] == "m.room.power_levels":
|
||||
levels = event["content"]
|
||||
if not title:
|
||||
return await evt.reply("Please set a title before creating a Telegram chat.")
|
||||
elif (not levels or not levels["users"] or evt.az.intent.mxid not in levels["users"] or
|
||||
levels["users"][evt.az.intent.mxid] < 100):
|
||||
return await evt.reply(f"Please give "
|
||||
+ f"[the bridge bot](https://matrix.to/#/{evt.az.intent.mxid})"
|
||||
+ f" a power level of 100 before creating a Telegram chat.")
|
||||
else:
|
||||
for user, level in levels["users"].items():
|
||||
if level >= 100 and user != evt.az.intent.mxid:
|
||||
return await evt.reply(
|
||||
f"Please make sure only the bridge bot has power level above"
|
||||
+ f"99 before creating a Telegram chat.\n\n"
|
||||
+ f"Use power level 95 instead of 100 for admins.")
|
||||
|
||||
supergroup = type == "supergroup"
|
||||
type = {
|
||||
"supergroup": "channel",
|
||||
"channel": "channel",
|
||||
"chat": "chat",
|
||||
"group": "chat",
|
||||
}[type]
|
||||
|
||||
portal = po.Portal(tgid=None, mxid=evt.room_id, title=title, about=about, peer_type=type)
|
||||
try:
|
||||
await portal.create_telegram_chat(evt.sender, supergroup=supergroup)
|
||||
except ValueError as e:
|
||||
return await evt.reply(e.args[0])
|
||||
return await evt.reply(f"Telegram chat created. ID: {portal.tgid}")
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def upgrade(evt):
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
elif portal.peer_type == "channel":
|
||||
return await evt.reply("This is already a supergroup or a channel.")
|
||||
elif portal.peer_type == "user":
|
||||
return await evt.reply("You can't upgrade private chats.")
|
||||
|
||||
try:
|
||||
await portal.upgrade_telegram_chat(evt.sender)
|
||||
return await evt.reply(f"Group upgraded to supergroup. New ID: {portal.tgid}")
|
||||
except ChatAdminRequiredError:
|
||||
return await evt.reply("You don't have the permission to upgrade this group.")
|
||||
except ValueError as e:
|
||||
return await evt.reply(e.args[0])
|
||||
|
||||
|
||||
@command_handler()
|
||||
async def group_name(evt):
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp group-name <name/->`")
|
||||
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not portal:
|
||||
return await evt.reply("This is not a portal room.")
|
||||
elif portal.peer_type != "channel":
|
||||
return await evt.reply("Only channels and supergroups have usernames.")
|
||||
|
||||
try:
|
||||
await portal.set_telegram_username(evt.sender,
|
||||
evt.args[0] if evt.args[0] != "-" else "")
|
||||
if portal.username:
|
||||
return await evt.reply(f"Username of channel changed to {portal.username}.")
|
||||
else:
|
||||
return await evt.reply(f"Channel is now private.")
|
||||
except ChatAdminRequiredError:
|
||||
return await evt.reply(
|
||||
"You don't have the permission to set the username of this channel.")
|
||||
except UsernameNotModifiedError:
|
||||
if portal.username:
|
||||
return await evt.reply("That is already the username of this channel.")
|
||||
else:
|
||||
return await evt.reply("This channel is already private")
|
||||
except UsernameOccupiedError:
|
||||
return await evt.reply("That username is already in use.")
|
||||
except UsernameInvalidError:
|
||||
return await evt.reply("Invalid username")
|
||||
@@ -0,0 +1 @@
|
||||
from . import account, auth, misc
|
||||
@@ -0,0 +1,142 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional
|
||||
|
||||
from telethon.errors import (UsernameInvalidError, UsernameNotModifiedError, UsernameOccupiedError,
|
||||
HashInvalidError, AuthKeyError, FirstNameInvalidError, AboutTooLongError)
|
||||
from telethon.tl.types import Authorization
|
||||
from telethon.tl.functions.account import (UpdateUsernameRequest, GetAuthorizationsRequest,
|
||||
ResetAuthorizationRequest, UpdateProfileRequest)
|
||||
|
||||
from mautrix.types import EventID
|
||||
|
||||
from .. import command_handler, CommandEvent, SECTION_AUTH
|
||||
|
||||
|
||||
@command_handler(needs_auth=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_args="<_new username_>",
|
||||
help_text="Change your Telegram username.")
|
||||
async def username(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp username <new username>`")
|
||||
if evt.sender.is_bot:
|
||||
return await evt.reply("Bots can't set their own username.")
|
||||
new_name = evt.args[0]
|
||||
if new_name == "-":
|
||||
new_name = ""
|
||||
try:
|
||||
await evt.sender.client(UpdateUsernameRequest(username=new_name))
|
||||
except UsernameInvalidError:
|
||||
return await evt.reply("Invalid username. Usernames must be between 5 and 30 alphanumeric "
|
||||
"characters.")
|
||||
except UsernameNotModifiedError:
|
||||
return await evt.reply("That is your current username.")
|
||||
except UsernameOccupiedError:
|
||||
return await evt.reply("That username is already in use.")
|
||||
await evt.sender.update_info()
|
||||
if not evt.sender.username:
|
||||
await evt.reply("Username removed")
|
||||
else:
|
||||
await evt.reply(f"Username changed to {evt.sender.username}")
|
||||
|
||||
@command_handler(needs_auth=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_args="<_new about_>",
|
||||
help_text="Change your Telegram about section.")
|
||||
async def about(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp about <new about>`")
|
||||
if evt.sender.is_bot:
|
||||
return await evt.reply("Bots can't set their own about section.")
|
||||
new_about = " ".join(evt.args)
|
||||
if new_about == "-":
|
||||
new_about = ""
|
||||
try:
|
||||
await evt.sender.client(UpdateProfileRequest(about=new_about))
|
||||
except AboutTooLongError:
|
||||
return await evt.reply("The provided about section is too long")
|
||||
return await evt.reply("About section updated")
|
||||
|
||||
@command_handler(needs_auth=True, help_section=SECTION_AUTH, help_args="<_new displayname_>",
|
||||
help_text="Change your Telegram displayname.")
|
||||
async def displayname(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp displayname <new displayname>`")
|
||||
if evt.sender.is_bot:
|
||||
return await evt.reply("Bots can't set their own displayname.")
|
||||
|
||||
first_name, last_name = ((evt.args[0], "")
|
||||
if len(evt.args) == 1
|
||||
else (" ".join(evt.args[:-1]), evt.args[-1]))
|
||||
try:
|
||||
await evt.sender.client(UpdateProfileRequest(first_name=first_name, last_name=last_name))
|
||||
except FirstNameInvalidError:
|
||||
return await evt.reply("Invalid first name")
|
||||
await evt.sender.update_info()
|
||||
return await evt.reply("Displayname updated")
|
||||
|
||||
|
||||
def _format_session(sess: Authorization) -> str:
|
||||
return (f"**{sess.app_name} {sess.app_version}** \n"
|
||||
f" **Platform:** {sess.device_model} {sess.platform} {sess.system_version} \n"
|
||||
f" **Active:** {sess.date_active} (created {sess.date_created}) \n"
|
||||
f" **From:** {sess.ip} - {sess.region}, {sess.country}")
|
||||
|
||||
|
||||
@command_handler(needs_auth=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_args="<`list`|`terminate`> [_hash_]",
|
||||
help_text="View or delete other Telegram sessions.")
|
||||
async def session(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp session <list|terminate> [hash]`")
|
||||
elif evt.sender.is_bot:
|
||||
return await evt.reply("Bots can't manage their sessions")
|
||||
cmd = evt.args[0].lower()
|
||||
if cmd == "list":
|
||||
res = await evt.sender.client(GetAuthorizationsRequest())
|
||||
session_list = res.authorizations
|
||||
current = [s for s in session_list if s.current][0]
|
||||
current_text = _format_session(current)
|
||||
other_text = "\n".join(f"* {_format_session(sess)} \n"
|
||||
f" **Hash:** {sess.hash}"
|
||||
for sess in session_list if not sess.current)
|
||||
return await evt.reply(f"### Current session\n"
|
||||
f"{current_text}\n"
|
||||
f"\n"
|
||||
f"### Other active sessions\n"
|
||||
f"{other_text}")
|
||||
elif cmd == "terminate" and len(evt.args) > 1:
|
||||
try:
|
||||
session_hash = int(evt.args[1])
|
||||
except ValueError:
|
||||
return await evt.reply("Hash must be an integer")
|
||||
try:
|
||||
ok = await evt.sender.client(ResetAuthorizationRequest(hash=session_hash))
|
||||
except HashInvalidError:
|
||||
return await evt.reply("Invalid session hash.")
|
||||
except AuthKeyError as e:
|
||||
if e.message == "FRESH_RESET_AUTHORISATION_FORBIDDEN":
|
||||
return await evt.reply("New sessions can't terminate other sessions. "
|
||||
"Please wait a while.")
|
||||
raise
|
||||
if ok:
|
||||
return await evt.reply("Session terminated successfully.")
|
||||
else:
|
||||
return await evt.reply("Session not found.")
|
||||
else:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp session <list|terminate> [hash]`")
|
||||
@@ -0,0 +1,360 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Any, Dict, Optional
|
||||
import asyncio
|
||||
import io
|
||||
|
||||
from telethon.errors import ( # isort: skip
|
||||
AccessTokenExpiredError, AccessTokenInvalidError, FirstNameInvalidError, FloodWaitError,
|
||||
PasswordHashInvalidError, PhoneCodeExpiredError, PhoneCodeInvalidError,
|
||||
PhoneNumberAppSignupForbiddenError, PhoneNumberBannedError, PhoneNumberFloodError,
|
||||
PhoneNumberOccupiedError, PhoneNumberUnoccupiedError, SessionPasswordNeededError,
|
||||
PhoneNumberInvalidError)
|
||||
from telethon.tl.types import User
|
||||
|
||||
from mautrix.types import (EventID, UserID, MediaMessageEventContent, ImageInfo, MessageType,
|
||||
TextMessageEventContent)
|
||||
|
||||
from ... import user as u
|
||||
from ...types import TelegramID
|
||||
from ...commands import command_handler, CommandEvent, SECTION_AUTH
|
||||
from ...util import format_duration as fmt_duration
|
||||
|
||||
try:
|
||||
import qrcode
|
||||
import PIL as _
|
||||
from telethon.tl.custom import QRLogin
|
||||
except ImportError:
|
||||
qrcode = None
|
||||
QRLogin = None
|
||||
|
||||
|
||||
@command_handler(needs_auth=False,
|
||||
help_section=SECTION_AUTH,
|
||||
help_text="Check if you're logged into Telegram.")
|
||||
async def ping(evt: CommandEvent) -> EventID:
|
||||
if await evt.sender.is_logged_in():
|
||||
me = await evt.sender.get_me()
|
||||
if me:
|
||||
human_tg_id = f"@{me.username}" if me.username else f"+{me.phone}"
|
||||
return await evt.reply(f"You're logged in as {human_tg_id}")
|
||||
else:
|
||||
return await evt.reply("You were logged in, but there appears to have been an error.")
|
||||
else:
|
||||
return await evt.reply("You're not logged in.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, needs_puppeting=False,
|
||||
help_section=SECTION_AUTH,
|
||||
help_text="Get the info of the message relay Telegram bot.")
|
||||
async def ping_bot(evt: CommandEvent) -> EventID:
|
||||
if not evt.tgbot:
|
||||
return await evt.reply("Telegram message relay bot not configured.")
|
||||
info, mxid = await evt.tgbot.get_me(use_cache=False)
|
||||
return await evt.reply("Telegram message relay bot is active: "
|
||||
f"[{info.first_name}](https://matrix.to/#/{mxid}) (ID {info.id})\n\n"
|
||||
"To use the bot, simply invite it to a portal room.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, management_only=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_args="<_phone_> <_full name_>",
|
||||
help_text="Register to Telegram")
|
||||
async def register(evt: CommandEvent) -> EventID:
|
||||
if await evt.sender.is_logged_in():
|
||||
return await evt.reply("You are already logged in.")
|
||||
elif len(evt.args) < 1:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp register <phone> <full name>`")
|
||||
|
||||
phone_number = evt.args[0]
|
||||
if len(evt.args) == 2:
|
||||
full_name = evt.args[1], ""
|
||||
else:
|
||||
full_name = " ".join(evt.args[1:-1]), evt.args[-1]
|
||||
|
||||
await _request_code(evt, phone_number, {
|
||||
"next": enter_code_register,
|
||||
"action": "Register",
|
||||
"full_name": full_name,
|
||||
})
|
||||
return await evt.reply("By signing up for Telegram, you agree to "
|
||||
"the terms of service: https://telegram.org/tos")
|
||||
|
||||
|
||||
async def enter_code_register(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp <code>`")
|
||||
try:
|
||||
await evt.sender.ensure_started(even_if_no_session=True)
|
||||
first_name, last_name = evt.sender.command_status["full_name"]
|
||||
user = await evt.sender.client.sign_up(evt.args[0], first_name, last_name)
|
||||
asyncio.ensure_future(evt.sender.post_login(user, first_login=True), loop=evt.loop)
|
||||
evt.sender.command_status = None
|
||||
return await evt.reply(f"Successfully registered to Telegram.")
|
||||
except PhoneNumberOccupiedError:
|
||||
return await evt.reply("That phone number has already been registered. "
|
||||
"You can log in with `$cmdprefix+sp login`.")
|
||||
except FirstNameInvalidError:
|
||||
return await evt.reply("Invalid name. Please set a Matrix displayname before registering.")
|
||||
except PhoneCodeExpiredError:
|
||||
return await evt.reply(
|
||||
"Phone code expired. Try again with `$cmdprefix+sp register <phone>`.")
|
||||
except PhoneCodeInvalidError:
|
||||
return await evt.reply("Invalid phone code.")
|
||||
except Exception:
|
||||
evt.log.exception("Error sending phone code")
|
||||
return await evt.reply("Unhandled exception while sending code. "
|
||||
"Check console for more details.")
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, management_only=True, help_section=SECTION_AUTH,
|
||||
help_text="Log in by scanning a QR code.")
|
||||
async def login_qr(evt: CommandEvent) -> EventID:
|
||||
login_as = evt.sender
|
||||
if len(evt.args) > 0 and evt.sender.is_admin:
|
||||
login_as = u.User.get_by_mxid(UserID(evt.args[0]))
|
||||
if not qrcode or not QRLogin:
|
||||
return await evt.reply("This bridge instance does not support logging in with a QR code.")
|
||||
if await login_as.is_logged_in():
|
||||
return await evt.reply(f"You are already logged in as {login_as.human_tg_id}.")
|
||||
|
||||
await login_as.ensure_started(even_if_no_session=True)
|
||||
qr_login = QRLogin(login_as.client, ignored_ids=[])
|
||||
qr_event_id: Optional[EventID] = None
|
||||
|
||||
async def upload_qr() -> None:
|
||||
nonlocal qr_event_id
|
||||
buffer = io.BytesIO()
|
||||
image = qrcode.make(qr_login.url)
|
||||
size = image.pixel_size
|
||||
image.save(buffer, "PNG")
|
||||
qr = buffer.getvalue()
|
||||
mxc = await evt.az.intent.upload_media(qr, "image/png", "login-qr.png", len(qr))
|
||||
content = MediaMessageEventContent(body=qr_login.url, url=mxc, msgtype=MessageType.IMAGE,
|
||||
info=ImageInfo(mimetype="image/png", size=len(qr),
|
||||
width=size, height=size))
|
||||
if qr_event_id:
|
||||
content.set_edit(qr_event_id)
|
||||
await evt.az.intent.send_message(evt.room_id, content)
|
||||
else:
|
||||
content.set_reply(evt.event_id)
|
||||
qr_event_id = await evt.az.intent.send_message(evt.room_id, content)
|
||||
|
||||
retries = 4
|
||||
while retries > 0:
|
||||
await qr_login.recreate()
|
||||
await upload_qr()
|
||||
try:
|
||||
user = await qr_login.wait()
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
retries -= 1
|
||||
except SessionPasswordNeededError:
|
||||
evt.sender.command_status = {
|
||||
"next": enter_password,
|
||||
"login_as": login_as if login_as != evt.sender else None,
|
||||
"action": "Login (password entry)",
|
||||
}
|
||||
return await evt.reply("Your account has two-factor authentication. "
|
||||
"Please send your password here.")
|
||||
else:
|
||||
timeout = TextMessageEventContent(body="Login timed out", msgtype=MessageType.TEXT)
|
||||
timeout.set_edit(qr_event_id)
|
||||
return await evt.az.intent.send_message(evt.room_id, timeout)
|
||||
|
||||
return await _finish_sign_in(evt, user, login_as=login_as)
|
||||
|
||||
|
||||
@command_handler(needs_auth=False, management_only=True,
|
||||
help_section=SECTION_AUTH,
|
||||
help_text="Get instructions on how to log in.")
|
||||
async def login(evt: CommandEvent) -> EventID:
|
||||
override_sender = False
|
||||
if len(evt.args) > 0 and evt.sender.is_admin:
|
||||
evt.sender = await u.User.get_by_mxid(UserID(evt.args[0])).ensure_started()
|
||||
override_sender = True
|
||||
if await evt.sender.is_logged_in():
|
||||
return await evt.reply(f"You are already logged in as {evt.sender.human_tg_id}.")
|
||||
|
||||
allow_matrix_login = evt.config["bridge.allow_matrix_login"]
|
||||
if allow_matrix_login and not override_sender:
|
||||
evt.sender.command_status = {
|
||||
"next": enter_phone_or_token,
|
||||
"action": "Login",
|
||||
}
|
||||
|
||||
nb = "**N.B. Logging in grants the bridge full access to your Telegram account.**"
|
||||
if evt.config["appservice.public.enabled"]:
|
||||
prefix = evt.config["appservice.public.external"]
|
||||
url = f"{prefix}/login?token={evt.public_website.make_token(evt.sender.mxid, '/login')}"
|
||||
if override_sender:
|
||||
return await evt.reply(f"[Click here to log in]({url}) as "
|
||||
f"[{evt.sender.mxid}](https://matrix.to/#/{evt.sender.mxid}).")
|
||||
elif allow_matrix_login:
|
||||
return await evt.reply(f"[Click here to log in]({url}). Alternatively, send your phone"
|
||||
f" number (or bot auth token) here to log in.\n\n{nb}")
|
||||
return await evt.reply(f"[Click here to log in]({url}).\n\n{nb}")
|
||||
elif allow_matrix_login:
|
||||
if override_sender:
|
||||
return await evt.reply(
|
||||
"This bridge instance does not allow you to log in outside of Matrix. "
|
||||
"Logging in as another user inside Matrix is not currently possible.")
|
||||
return await evt.reply("Please send your phone number (or bot auth token) here to start "
|
||||
f"the login process.\n\n{nb}")
|
||||
return await evt.reply("This bridge instance has been configured to not allow logging in.")
|
||||
|
||||
|
||||
async def _request_code(evt: CommandEvent, phone_number: str, next_status: Dict[str, Any]
|
||||
) -> EventID:
|
||||
ok = False
|
||||
try:
|
||||
await evt.sender.ensure_started(even_if_no_session=True)
|
||||
await evt.sender.client.sign_in(phone_number)
|
||||
ok = True
|
||||
return await evt.reply(f"Login code sent to {phone_number}. Please send the code here.")
|
||||
except PhoneNumberAppSignupForbiddenError:
|
||||
return await evt.reply("Your phone number does not allow 3rd party apps to sign in.")
|
||||
except PhoneNumberFloodError:
|
||||
return await evt.reply("Your phone number has been temporarily blocked for flooding. "
|
||||
"The ban is usually applied for around a day.")
|
||||
except FloodWaitError as e:
|
||||
return await evt.reply("Your phone number has been temporarily blocked for flooding. "
|
||||
f"Please wait for {fmt_duration(e.seconds)} before trying again.")
|
||||
except PhoneNumberBannedError:
|
||||
return await evt.reply("Your phone number has been banned from Telegram.")
|
||||
except PhoneNumberUnoccupiedError:
|
||||
return await evt.reply("That phone number has not been registered. "
|
||||
"Please register with `$cmdprefix+sp register <phone>`.")
|
||||
except PhoneNumberInvalidError:
|
||||
return await evt.reply("That phone number is not valid.")
|
||||
except Exception:
|
||||
evt.log.exception("Error requesting phone code")
|
||||
return await evt.reply("Unhandled exception while requesting code. "
|
||||
"Check console for more details.")
|
||||
finally:
|
||||
evt.sender.command_status = next_status if ok else None
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def enter_phone_or_token(evt: CommandEvent) -> Optional[EventID]:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp enter-phone-or-token <phone-or-token>`")
|
||||
elif not evt.config.get("bridge.allow_matrix_login", True):
|
||||
return await evt.reply("This bridge instance does not allow in-Matrix login. "
|
||||
"Please use `$cmdprefix+sp login` to get login instructions")
|
||||
|
||||
# phone numbers don't contain colons but telegram bot auth tokens do
|
||||
if evt.args[0].find(":") > 0:
|
||||
try:
|
||||
await _sign_in(evt, bot_token=evt.args[0])
|
||||
except Exception:
|
||||
evt.log.exception("Error sending auth token")
|
||||
return await evt.reply("Unhandled exception while sending auth token. "
|
||||
"Check console for more details.")
|
||||
else:
|
||||
await _request_code(evt, evt.args[0], {
|
||||
"next": enter_code,
|
||||
"action": "Login",
|
||||
})
|
||||
return None
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def enter_code(evt: CommandEvent) -> Optional[EventID]:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp enter-code <code>`")
|
||||
elif not evt.config.get("bridge.allow_matrix_login", True):
|
||||
return await evt.reply("This bridge instance does not allow in-Matrix login. "
|
||||
"Please use `$cmdprefix+sp login` to get login instructions")
|
||||
try:
|
||||
await _sign_in(evt, code=evt.args[0])
|
||||
except Exception:
|
||||
evt.log.exception("Error sending phone code")
|
||||
return await evt.reply("Unhandled exception while sending code. "
|
||||
"Check console for more details.")
|
||||
return None
|
||||
|
||||
|
||||
@command_handler(needs_auth=False)
|
||||
async def enter_password(evt: CommandEvent) -> Optional[EventID]:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp enter-password <password>`")
|
||||
elif not evt.config.get("bridge.allow_matrix_login", True):
|
||||
return await evt.reply("This bridge instance does not allow in-Matrix login. "
|
||||
"Please use `$cmdprefix+sp login` to get login instructions")
|
||||
try:
|
||||
await _sign_in(evt, login_as=evt.sender.command_status.get("login_as", None),
|
||||
password=" ".join(evt.args))
|
||||
except AccessTokenInvalidError:
|
||||
return await evt.reply("That bot token is not valid.")
|
||||
except AccessTokenExpiredError:
|
||||
return await evt.reply("That bot token has expired.")
|
||||
except Exception:
|
||||
evt.log.exception("Error sending password")
|
||||
return await evt.reply("Unhandled exception while sending password. "
|
||||
"Check console for more details.")
|
||||
return None
|
||||
|
||||
|
||||
async def _sign_in(evt: CommandEvent, login_as: 'u.User' = None, **sign_in_info) -> EventID:
|
||||
login_as = login_as or evt.sender
|
||||
try:
|
||||
await login_as.ensure_started(even_if_no_session=True)
|
||||
user = await login_as.client.sign_in(**sign_in_info)
|
||||
await _finish_sign_in(evt, user)
|
||||
except PhoneCodeExpiredError:
|
||||
return await evt.reply("Phone code expired. Try again with `$cmdprefix+sp login`.")
|
||||
except PhoneCodeInvalidError:
|
||||
return await evt.reply("Invalid phone code.")
|
||||
except PasswordHashInvalidError:
|
||||
return await evt.reply("Incorrect password.")
|
||||
except SessionPasswordNeededError:
|
||||
evt.sender.command_status = {
|
||||
"next": enter_password,
|
||||
"action": "Login (password entry)",
|
||||
}
|
||||
return await evt.reply("Your account has two-factor authentication. "
|
||||
"Please send your password here.")
|
||||
|
||||
|
||||
async def _finish_sign_in(evt: CommandEvent, user: User, login_as: 'u.User' = None) -> EventID:
|
||||
login_as = login_as or evt.sender
|
||||
existing_user = u.User.get_by_tgid(TelegramID(user.id))
|
||||
if existing_user and existing_user != login_as:
|
||||
await existing_user.log_out()
|
||||
await evt.reply(f"[{existing_user.displayname}]"
|
||||
f"(https://matrix.to/#/{existing_user.mxid})"
|
||||
" was logged out from the account.")
|
||||
asyncio.ensure_future(login_as.post_login(user, first_login=True), loop=evt.loop)
|
||||
evt.sender.command_status = None
|
||||
name = f"@{user.username}" if user.username else f"+{user.phone}"
|
||||
if login_as != evt.sender:
|
||||
msg = (f"Successfully logged in [{login_as.mxid}](https://matrix.to/#/{login_as.mxid})"
|
||||
f" as {name}")
|
||||
else:
|
||||
msg = f"Successfully logged in as {name}"
|
||||
return await evt.reply(msg)
|
||||
|
||||
|
||||
@command_handler(needs_auth=False,
|
||||
help_section=SECTION_AUTH,
|
||||
help_text="Log out from Telegram.")
|
||||
async def logout(evt: CommandEvent) -> EventID:
|
||||
if not evt.sender.tgid:
|
||||
return await evt.reply("You're not logged in")
|
||||
if await evt.sender.log_out():
|
||||
return await evt.reply("Logged out successfully.")
|
||||
return await evt.reply("Failed to log out.")
|
||||
@@ -0,0 +1,375 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import List, Optional, Tuple, cast
|
||||
import codecs
|
||||
import base64
|
||||
import re
|
||||
|
||||
from aiohttp import ClientSession, InvalidURL
|
||||
|
||||
from telethon.errors import (InviteHashInvalidError, InviteHashExpiredError, OptionsTooMuchError,
|
||||
UserAlreadyParticipantError, ChatIdInvalidError,
|
||||
TakeoutInitDelayError, EmoticonInvalidError)
|
||||
from telethon.tl.patched import Message
|
||||
from telethon.tl.types import (User as TLUser, TypeUpdates, MessageMediaGame, MessageMediaPoll,
|
||||
TypeInputPeer, InputMediaDice)
|
||||
from telethon.tl.types.messages import BotCallbackAnswer
|
||||
from telethon.tl.functions.messages import (ImportChatInviteRequest, CheckChatInviteRequest,
|
||||
GetBotCallbackAnswerRequest, SendVoteRequest)
|
||||
from telethon.tl.functions.channels import JoinChannelRequest
|
||||
|
||||
from mautrix.types import EventID, Format
|
||||
|
||||
from ... import puppet as pu, portal as po
|
||||
from ...abstract_user import AbstractUser
|
||||
from ...db import Message as DBMessage
|
||||
from ...types import TelegramID
|
||||
from ...commands import (command_handler, CommandEvent, SECTION_MISC, SECTION_CREATING_PORTALS,
|
||||
SECTION_PORTAL_MANAGEMENT)
|
||||
|
||||
|
||||
@command_handler(needs_auth=False,
|
||||
help_section=SECTION_MISC, help_args="<_caption_>",
|
||||
help_text="Set a caption for the next image you send")
|
||||
async def caption(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp caption <caption>`")
|
||||
|
||||
prefix = f"{evt.command_prefix} caption "
|
||||
if evt.content.format == Format.HTML:
|
||||
evt.content.formatted_body = evt.content.formatted_body.replace(prefix, "", 1)
|
||||
evt.content.body = evt.content.body.replace(prefix, "", 1)
|
||||
evt.sender.command_status = {"caption": evt.content, "action": "Caption"}
|
||||
return await evt.reply("Your next image or file will be sent with that caption. "
|
||||
"Use `$cmdprefix+sp cancel` to cancel the caption.")
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_MISC,
|
||||
help_args="[_-r|--remote_] <_query_>",
|
||||
help_text="Search your contacts or the Telegram servers for users.")
|
||||
async def search(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp search [-r|--remote] <query>`")
|
||||
|
||||
force_remote = False
|
||||
if evt.args[0] in {"-r", "--remote"}:
|
||||
force_remote = True
|
||||
evt.args.pop(0)
|
||||
|
||||
query = " ".join(evt.args)
|
||||
if force_remote and len(query) < 5:
|
||||
return await evt.reply("Minimum length of query for remote search is 5 characters.")
|
||||
|
||||
results, remote = await evt.sender.search(query, force_remote)
|
||||
|
||||
if not results:
|
||||
if len(query) < 5 and remote:
|
||||
return await evt.reply("No local results. "
|
||||
"Minimum length of remote query is 5 characters.")
|
||||
return await evt.reply("No results 3:")
|
||||
|
||||
reply: List[str] = []
|
||||
if remote:
|
||||
reply += ["**Results from Telegram server:**", ""]
|
||||
else:
|
||||
reply += ["**Results in contacts:**", ""]
|
||||
reply += [(f"* [{puppet.displayname}](https://matrix.to/#/{puppet.mxid}): "
|
||||
f"{puppet.id} ({similarity}% match)")
|
||||
for puppet, similarity in results]
|
||||
|
||||
# TODO somehow show remote channel results when joining by alias is possible?
|
||||
|
||||
return await evt.reply("\n".join(reply))
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_CREATING_PORTALS, help_args="<_identifier_>",
|
||||
help_text="Open a private chat with the given Telegram user. The identifier is "
|
||||
"either the internal user ID, the username or the phone number. "
|
||||
"**N.B.** The phone numbers you start chats with must already be in "
|
||||
"your contacts.")
|
||||
async def pm(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp pm <user identifier>`")
|
||||
|
||||
try:
|
||||
id = "".join(evt.args).translate({ord(c): None for c in "+()- "})
|
||||
user = await evt.sender.client.get_entity(id)
|
||||
except ValueError:
|
||||
return await evt.reply("Invalid user identifier or user not found.")
|
||||
|
||||
if not user:
|
||||
return await evt.reply("User not found.")
|
||||
elif not isinstance(user, TLUser):
|
||||
return await evt.reply("That doesn't seem to be a user.")
|
||||
portal = po.Portal.get_by_entity(user, evt.sender.tgid)
|
||||
await portal.create_matrix_room(evt.sender, user, [evt.sender.mxid])
|
||||
displayname, _ = pu.Puppet.get_displayname(user, False)
|
||||
return await evt.reply(f"Created private chat room with {displayname}")
|
||||
|
||||
|
||||
async def _join(evt: CommandEvent, identifier: str, link_type: str
|
||||
) -> Tuple[Optional[TypeUpdates], Optional[EventID]]:
|
||||
if link_type == "joinchat":
|
||||
try:
|
||||
await evt.sender.client(CheckChatInviteRequest(identifier))
|
||||
except InviteHashInvalidError:
|
||||
return None, await evt.reply("Invalid invite link.")
|
||||
except InviteHashExpiredError:
|
||||
return None, await evt.reply("Invite link expired.")
|
||||
try:
|
||||
return (await evt.sender.client(ImportChatInviteRequest(identifier))), None
|
||||
except UserAlreadyParticipantError:
|
||||
return None, await evt.reply("You are already in that chat.")
|
||||
else:
|
||||
channel = await evt.sender.client.get_entity(identifier)
|
||||
if not channel:
|
||||
return None, await evt.reply("Channel/supergroup not found.")
|
||||
return await evt.sender.client(JoinChannelRequest(channel)), None
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_CREATING_PORTALS,
|
||||
help_args="<_link_>",
|
||||
help_text="Join a chat with an invite link.")
|
||||
async def join(evt: CommandEvent) -> Optional[EventID]:
|
||||
if len(evt.args) == 0:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp join <invite link>`")
|
||||
|
||||
url = evt.args[0]
|
||||
if evt.config["bridge.invite_link_resolve"]:
|
||||
try:
|
||||
async with ClientSession() as sess, sess.get(url) as resp:
|
||||
url = str(resp.url)
|
||||
except InvalidURL:
|
||||
return await evt.reply("That doesn't look like a Telegram invite link.")
|
||||
|
||||
regex = re.compile(r"(?:https?://)?t(?:elegram)?\.(?:dog|me)"
|
||||
r"(?:/(?P<type>joinchat|s))?/(?P<id>[^/]+)/?", flags=re.IGNORECASE)
|
||||
arg = regex.match(url)
|
||||
if not arg:
|
||||
return await evt.reply("That doesn't look like a Telegram invite link.")
|
||||
|
||||
data = arg.groupdict()
|
||||
identifier = data["id"]
|
||||
link_type = data["type"]
|
||||
if link_type:
|
||||
link_type = link_type.lower()
|
||||
updates, _ = await _join(evt, identifier, link_type)
|
||||
if not updates:
|
||||
return None
|
||||
|
||||
for chat in updates.chats:
|
||||
portal = po.Portal.get_by_entity(chat)
|
||||
if portal.mxid:
|
||||
await portal.invite_to_matrix([evt.sender.mxid])
|
||||
return await evt.reply(f"Invited you to portal of {portal.title}")
|
||||
else:
|
||||
await evt.reply(f"Creating room for {chat.title}... This might take a while.")
|
||||
try:
|
||||
await portal.create_matrix_room(evt.sender, chat, [evt.sender.mxid])
|
||||
except ChatIdInvalidError as e:
|
||||
evt.log.trace("ChatIdInvalidError while creating portal from !tg join command: %s",
|
||||
updates.stringify())
|
||||
raise e
|
||||
return await evt.reply(f"Created room for {portal.title}")
|
||||
return None
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_MISC,
|
||||
help_args="[`chats`|`contacts`|`me`]",
|
||||
help_text="Synchronize your chat portals, contacts and/or own info.")
|
||||
async def sync(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) > 0:
|
||||
sync_only = evt.args[0]
|
||||
if sync_only not in ("chats", "contacts", "me"):
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp sync [chats|contacts|me]`")
|
||||
else:
|
||||
sync_only = None
|
||||
|
||||
if not sync_only or sync_only == "chats":
|
||||
await evt.reply("Synchronizing chats...")
|
||||
await evt.sender.sync_dialogs()
|
||||
if not sync_only or sync_only == "contacts":
|
||||
await evt.reply("Synchronizing contacts...")
|
||||
await evt.sender.sync_contacts()
|
||||
if not sync_only or sync_only == "me":
|
||||
await evt.sender.update_info()
|
||||
return await evt.reply("Synchronization complete.")
|
||||
|
||||
|
||||
PEER_TYPE_CHAT = b"g"
|
||||
|
||||
|
||||
class MessageIDError(ValueError):
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
async def _parse_encoded_msgid(user: AbstractUser, enc_id: str, type_name: str
|
||||
) -> Tuple[TypeInputPeer, Message]:
|
||||
try:
|
||||
enc_id += (4 - len(enc_id) % 4) * "="
|
||||
enc_id = base64.b64decode(enc_id)
|
||||
peer_type, enc_id = bytes([enc_id[0]]), enc_id[1:]
|
||||
tgid = TelegramID(int(codecs.encode(enc_id[0:5], "hex_codec"), 16))
|
||||
msg_id = TelegramID(int(codecs.encode(enc_id[5:10], "hex_codec"), 16))
|
||||
space = None
|
||||
if peer_type == PEER_TYPE_CHAT:
|
||||
space = TelegramID(int(codecs.encode(enc_id[10:15], "hex_codec"), 16))
|
||||
except ValueError as e:
|
||||
raise MessageIDError(f"Invalid {type_name} ID (format)") from e
|
||||
|
||||
if peer_type == PEER_TYPE_CHAT:
|
||||
orig_msg = DBMessage.get_one_by_tgid(msg_id, space)
|
||||
if not orig_msg:
|
||||
raise MessageIDError(f"Invalid {type_name} ID (original message not found in db)")
|
||||
new_msg = DBMessage.get_by_mxid(orig_msg.mxid, orig_msg.mx_room, user.tgid)
|
||||
if not new_msg:
|
||||
raise MessageIDError(f"Invalid {type_name} ID (your copy of message not found in db)")
|
||||
msg_id = new_msg.tgid
|
||||
try:
|
||||
peer = await user.client.get_input_entity(tgid)
|
||||
except ValueError as e:
|
||||
raise MessageIDError(f"Invalid {type_name} ID (chat not found)") from e
|
||||
|
||||
msg = await user.client.get_messages(entity=peer, ids=msg_id)
|
||||
if not msg:
|
||||
raise MessageIDError(f"Invalid {type_name} ID (message not found)")
|
||||
return peer, cast(Message, msg)
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_MISC,
|
||||
help_args="<_play ID_>",
|
||||
help_text="Play a Telegram game.")
|
||||
async def play(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) < 1:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp play <play ID>`")
|
||||
elif not await evt.sender.is_logged_in():
|
||||
return await evt.reply("You must be logged in with a real account to play games.")
|
||||
elif evt.sender.is_bot:
|
||||
return await evt.reply("Bots can't play games :(")
|
||||
|
||||
try:
|
||||
peer, msg = await _parse_encoded_msgid(evt.sender, evt.args[0], type_name="play")
|
||||
except MessageIDError as e:
|
||||
return await evt.reply(e.message)
|
||||
|
||||
if not isinstance(msg.media, MessageMediaGame):
|
||||
return await evt.reply("Invalid play ID (message doesn't look like a game)")
|
||||
|
||||
game = await evt.sender.client(
|
||||
GetBotCallbackAnswerRequest(peer=peer, msg_id=msg.id, game=True))
|
||||
if not isinstance(game, BotCallbackAnswer):
|
||||
return await evt.reply("Game request response invalid")
|
||||
|
||||
return await evt.reply(f"Click [here]({game.url}) to play {msg.media.game.title}:\n\n"
|
||||
f"{msg.media.game.description}")
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_MISC,
|
||||
help_args="<_poll ID_> <_choice number_>",
|
||||
help_text="Vote in a Telegram poll.")
|
||||
async def vote(evt: CommandEvent) -> EventID:
|
||||
if len(evt.args) < 1:
|
||||
return await evt.reply("**Usage:** `$cmdprefix+sp vote <poll ID> <choice number>`")
|
||||
elif not await evt.sender.is_logged_in():
|
||||
return await evt.reply("You must be logged in with a real account to vote in polls.")
|
||||
elif evt.sender.is_bot:
|
||||
return await evt.reply("Bots can't vote in polls :(")
|
||||
|
||||
try:
|
||||
peer, msg = await _parse_encoded_msgid(evt.sender, evt.args[0], type_name="poll")
|
||||
except MessageIDError as e:
|
||||
return await evt.reply(e.message)
|
||||
|
||||
if not isinstance(msg.media, MessageMediaPoll):
|
||||
return await evt.reply("Invalid poll ID (message doesn't look like a poll)")
|
||||
|
||||
options = []
|
||||
for option in evt.args[1:]:
|
||||
try:
|
||||
if len(option) > 10:
|
||||
raise ValueError("option index too long")
|
||||
option_index = int(option) - 1
|
||||
except ValueError:
|
||||
option_index = None
|
||||
if option_index is None:
|
||||
return await evt.reply(f"Invalid option number \"{option}\"",
|
||||
render_markdown=False, allow_html=False)
|
||||
elif option_index < 0:
|
||||
return await evt.reply(f"Invalid option number {option}. "
|
||||
f"Option numbers must be positive.")
|
||||
elif option_index >= len(msg.media.poll.answers):
|
||||
return await evt.reply(f"Invalid option number {option}. "
|
||||
f"The poll only has {len(msg.media.poll.answers)} options.")
|
||||
options.append(msg.media.poll.answers[option_index].option)
|
||||
options = [msg.media.poll.answers[int(option) - 1].option
|
||||
for option in evt.args[1:]]
|
||||
try:
|
||||
resp = await evt.sender.client(SendVoteRequest(peer=peer, msg_id=msg.id, options=options))
|
||||
except OptionsTooMuchError:
|
||||
return await evt.reply("You passed too many options.")
|
||||
# TODO use response
|
||||
return await evt.mark_read()
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_MISC, help_args="<_emoji_>",
|
||||
help_text="Roll a dice (\U0001F3B2), kick a football (\u26BD\uFE0F) or throw a "
|
||||
"dart (\U0001F3AF) or basketball (\U0001F3C0) on the Telegram servers.")
|
||||
async def random(evt: CommandEvent) -> EventID:
|
||||
if not evt.is_portal:
|
||||
return await evt.reply("You can only randomize values in portal rooms")
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
arg = evt.args[0] if len(evt.args) > 0 else "dice"
|
||||
emoticon = {
|
||||
"dart": "\U0001F3AF",
|
||||
"dice": "\U0001F3B2",
|
||||
"ball": "\U0001F3C0",
|
||||
"basketball": "\U0001F3C0",
|
||||
"football": "\u26BD",
|
||||
"soccer": "\u26BD",
|
||||
}.get(arg, arg)
|
||||
try:
|
||||
await evt.sender.client.send_media(await portal.get_input_entity(evt.sender),
|
||||
InputMediaDice(emoticon))
|
||||
except EmoticonInvalidError:
|
||||
return await evt.reply("Invalid emoji for randomization")
|
||||
|
||||
|
||||
@command_handler(help_section=SECTION_PORTAL_MANAGEMENT, help_args="[_limit_]",
|
||||
help_text="Backfill messages from Telegram history.")
|
||||
async def backfill(evt: CommandEvent) -> None:
|
||||
if not evt.is_portal:
|
||||
await evt.reply("You can only use backfill in portal rooms")
|
||||
return
|
||||
try:
|
||||
limit = int(evt.args[0])
|
||||
except (ValueError, IndexError):
|
||||
limit = -1
|
||||
portal = po.Portal.get_by_mxid(evt.room_id)
|
||||
if not evt.config["bridge.backfill.normal_groups"] and portal.peer_type == "chat":
|
||||
await evt.reply("Backfilling normal groups is disabled in the bridge config")
|
||||
return
|
||||
try:
|
||||
await portal.backfill(evt.sender, limit=limit)
|
||||
except TakeoutInitDelayError:
|
||||
msg = ("Please accept the data export request from a mobile device, "
|
||||
"then re-run the backfill command.")
|
||||
if portal.peer_type == "user":
|
||||
from mautrix.appservice import IntentAPI
|
||||
await portal.main_intent.send_notice(evt.room_id, msg)
|
||||
else:
|
||||
await evt.reply(msg)
|
||||
+215
-87
@@ -1,115 +1,243 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
# Copyright (C) 2020 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from ruamel.yaml import YAML
|
||||
import random
|
||||
import string
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Any, List, NamedTuple
|
||||
from ruamel.yaml.comments import CommentedMap
|
||||
import os
|
||||
|
||||
yaml = YAML()
|
||||
from mautrix.types import UserID
|
||||
from mautrix.client import Client
|
||||
from mautrix.bridge.config import BaseBridgeConfig
|
||||
from mautrix.util.config import ForbiddenKey, ForbiddenDefault, ConfigUpdateHelper
|
||||
|
||||
Permissions = NamedTuple("Permissions", relaybot=bool, user=bool, puppeting=bool,
|
||||
matrix_puppeting=bool, admin=bool, level=str)
|
||||
|
||||
|
||||
class DictWithRecursion:
|
||||
def __init__(self, data=None):
|
||||
self._data = data or {}
|
||||
class Config(BaseBridgeConfig):
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
try:
|
||||
return os.environ[f"MAUTRIX_TELEGRAM_{key.replace('.', '_').upper()}"]
|
||||
except KeyError:
|
||||
return super().__getitem__(key)
|
||||
|
||||
def _recursive_get(self, data, key, default_value):
|
||||
if '.' in key:
|
||||
key, next_key = key.split('.', 1)
|
||||
next_data = data.get(key, {})
|
||||
return self._recursive_get(next_data, next_key, default_value)
|
||||
return data.get(key, default_value)
|
||||
@property
|
||||
def forbidden_defaults(self) -> List[ForbiddenDefault]:
|
||||
return [
|
||||
*super().forbidden_defaults,
|
||||
ForbiddenDefault("appservice.public.external", "https://example.com/public",
|
||||
condition="appservice.public.enabled"),
|
||||
ForbiddenDefault("bridge.permissions", ForbiddenKey("example.com")),
|
||||
ForbiddenDefault("telegram.api_id", 12345),
|
||||
ForbiddenDefault("telegram.api_hash", "tjyd5yge35lbodk1xwzw2jstp90k55qz"),
|
||||
]
|
||||
|
||||
def get(self, key, default_value, allow_recursion=True):
|
||||
if allow_recursion and '.' in key:
|
||||
return self._recursive_get(self._data, key, default_value)
|
||||
return self._data.get(key, default_value)
|
||||
def do_update(self, helper: ConfigUpdateHelper) -> None:
|
||||
super().do_update(helper)
|
||||
copy, copy_dict, base = helper
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.get(key, None)
|
||||
copy("homeserver.asmux")
|
||||
|
||||
def _recursive_set(self, data, key, value):
|
||||
if '.' in key:
|
||||
key, next_key = key.split('.', 1)
|
||||
if key not in data:
|
||||
data[key] = {}
|
||||
next_data = data.get(key, {})
|
||||
self._recursive_set(next_data, next_key, value)
|
||||
return
|
||||
data[key] = value
|
||||
if "appservice.protocol" in self and "appservice.address" not in self:
|
||||
protocol, hostname, port = (self["appservice.protocol"], self["appservice.hostname"],
|
||||
self["appservice.port"])
|
||||
base["appservice.address"] = f"{protocol}://{hostname}:{port}"
|
||||
if "appservice.debug" in self and "logging" not in self:
|
||||
level = "DEBUG" if self["appservice.debug"] else "INFO"
|
||||
base["logging.root.level"] = level
|
||||
base["logging.loggers.mau.level"] = level
|
||||
base["logging.loggers.telethon.level"] = level
|
||||
|
||||
def set(self, key, value, allow_recursion=True):
|
||||
if allow_recursion and '.' in key:
|
||||
self._recursive_set(self._data, key, value)
|
||||
return
|
||||
self._data[key] = value
|
||||
copy("appservice.public.enabled")
|
||||
copy("appservice.public.prefix")
|
||||
copy("appservice.public.external")
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self.set(key, value)
|
||||
copy("appservice.provisioning.enabled")
|
||||
copy("appservice.provisioning.prefix")
|
||||
copy("appservice.provisioning.shared_secret")
|
||||
if base["appservice.provisioning.shared_secret"] == "generate":
|
||||
base["appservice.provisioning.shared_secret"] = self._new_token()
|
||||
|
||||
copy("appservice.community_id")
|
||||
|
||||
class Config(DictWithRecursion):
|
||||
def __init__(self, path, registration_path):
|
||||
super().__init__()
|
||||
self.path = path
|
||||
self.registration_path = registration_path
|
||||
self._registration = None
|
||||
copy("metrics.enabled")
|
||||
copy("metrics.listen_port")
|
||||
|
||||
def load(self):
|
||||
with open(self.path, 'r') as stream:
|
||||
self._data = yaml.load(stream)
|
||||
copy("bridge.username_template")
|
||||
copy("bridge.alias_template")
|
||||
copy("bridge.displayname_template")
|
||||
|
||||
def save(self):
|
||||
with open(self.path, 'w') as stream:
|
||||
yaml.dump(self._data, stream)
|
||||
if self._registration and self.registration_path:
|
||||
with open(self.registration_path, 'w') as stream:
|
||||
yaml.dump(self._registration, stream)
|
||||
copy("bridge.displayname_preference")
|
||||
copy("bridge.displayname_max_length")
|
||||
copy("bridge.allow_avatar_remove")
|
||||
|
||||
@staticmethod
|
||||
def _new_token():
|
||||
return "".join(random.choices(string.ascii_lowercase + string.digits, k=64))
|
||||
copy("bridge.max_initial_member_sync")
|
||||
copy("bridge.sync_channel_members")
|
||||
copy("bridge.skip_deleted_members")
|
||||
copy("bridge.startup_sync")
|
||||
if "bridge.sync_dialog_limit" in self:
|
||||
base["bridge.sync_create_limit"] = self["bridge.sync_dialog_limit"]
|
||||
base["bridge.sync_update_limit"] = self["bridge.sync_dialog_limit"]
|
||||
else:
|
||||
copy("bridge.sync_update_limit")
|
||||
copy("bridge.sync_create_limit")
|
||||
copy("bridge.sync_direct_chats")
|
||||
copy("bridge.max_telegram_delete")
|
||||
copy("bridge.sync_matrix_state")
|
||||
copy("bridge.allow_matrix_login")
|
||||
copy("bridge.plaintext_highlights")
|
||||
copy("bridge.public_portals")
|
||||
copy("bridge.sync_with_custom_puppets")
|
||||
copy("bridge.sync_direct_chat_list")
|
||||
copy("bridge.double_puppet_server_map")
|
||||
copy("bridge.double_puppet_allow_discovery")
|
||||
if "bridge.login_shared_secret" in self:
|
||||
base["bridge.login_shared_secret_map"] = {
|
||||
base["homeserver.domain"]: self["bridge.login_shared_secret"]
|
||||
}
|
||||
else:
|
||||
copy("bridge.login_shared_secret_map")
|
||||
copy("bridge.telegram_link_preview")
|
||||
copy("bridge.invite_link_resolve")
|
||||
copy("bridge.inline_images")
|
||||
copy("bridge.image_as_file_size")
|
||||
copy("bridge.max_document_size")
|
||||
copy("bridge.parallel_file_transfer")
|
||||
copy("bridge.federate_rooms")
|
||||
copy("bridge.animated_sticker.target")
|
||||
copy("bridge.animated_sticker.args")
|
||||
copy("bridge.encryption.allow")
|
||||
copy("bridge.encryption.default")
|
||||
copy("bridge.encryption.database")
|
||||
copy("bridge.encryption.key_sharing.allow")
|
||||
copy("bridge.encryption.key_sharing.require_cross_signing")
|
||||
copy("bridge.encryption.key_sharing.require_verification")
|
||||
copy("bridge.private_chat_portal_meta")
|
||||
copy("bridge.delivery_receipts")
|
||||
copy("bridge.delivery_error_reports")
|
||||
copy("bridge.resend_bridge_info")
|
||||
copy("bridge.mute_bridging")
|
||||
copy("bridge.pinned_tag")
|
||||
copy("bridge.archive_tag")
|
||||
copy("bridge.tag_only_on_create")
|
||||
copy("bridge.backfill.invite_own_puppet")
|
||||
copy("bridge.backfill.takeout_limit")
|
||||
copy("bridge.backfill.initial_limit")
|
||||
copy("bridge.backfill.missed_limit")
|
||||
copy("bridge.backfill.disable_notifications")
|
||||
copy("bridge.backfill.normal_groups")
|
||||
|
||||
def generate_registration(self):
|
||||
homeserver = self["homeserver.domain"]
|
||||
copy("bridge.initial_power_level_overrides.group")
|
||||
copy("bridge.initial_power_level_overrides.user")
|
||||
|
||||
username_format = self.get("bridge.username_template", "telegram_{userid}") \
|
||||
.format(userid=".+")
|
||||
alias_format = self.get("bridge.alias_template", "telegram_{groupname}") \
|
||||
.format(groupname=".+")
|
||||
copy("bridge.bot_messages_as_notices")
|
||||
if isinstance(self["bridge.bridge_notices"], bool):
|
||||
base["bridge.bridge_notices"] = {
|
||||
"default": self["bridge.bridge_notices"],
|
||||
"exceptions": ["@importantbot:example.com"],
|
||||
}
|
||||
else:
|
||||
copy("bridge.bridge_notices")
|
||||
|
||||
self.set("appservice.as_token", self._new_token())
|
||||
self.set("appservice.hs_token", self._new_token())
|
||||
copy("bridge.deduplication.pre_db_check")
|
||||
copy("bridge.deduplication.cache_queue_length")
|
||||
|
||||
url = (f"{self['appservice.protocol']}://"
|
||||
+ f"{self['appservice.hostname']}:{self['appservice.port']}")
|
||||
self._registration = {
|
||||
"id": self.get("appservice.id", "telegram"),
|
||||
"as_token": self["appservice.as_token"],
|
||||
"hs_token": self["appservice.hs_token"],
|
||||
"namespaces": {
|
||||
"users": [{
|
||||
"exclusive": True,
|
||||
"regex": f"@{username_format}:{homeserver}"
|
||||
}],
|
||||
"aliases": [{
|
||||
"exclusive": True,
|
||||
"regex": f"#{alias_format}:{homeserver}"
|
||||
}]
|
||||
},
|
||||
"url": url,
|
||||
"sender_localpart": self["appservice.bot_username"],
|
||||
"rate_limited": False
|
||||
}
|
||||
if "bridge.message_formats.m_text" in self:
|
||||
del self["bridge.message_formats"]
|
||||
copy_dict("bridge.message_formats", override_existing_map=False)
|
||||
copy("bridge.emote_format")
|
||||
|
||||
copy("bridge.state_event_formats.join")
|
||||
copy("bridge.state_event_formats.leave")
|
||||
copy("bridge.state_event_formats.name_change")
|
||||
|
||||
copy("bridge.filter.mode")
|
||||
copy("bridge.filter.list")
|
||||
|
||||
copy("bridge.command_prefix")
|
||||
|
||||
migrate_permissions = ("bridge.permissions" not in self
|
||||
or "bridge.whitelist" in self
|
||||
or "bridge.admins" in self)
|
||||
if migrate_permissions:
|
||||
permissions = self["bridge.permissions"] or CommentedMap()
|
||||
for entry in self["bridge.whitelist"] or []:
|
||||
permissions[entry] = "full"
|
||||
for entry in self["bridge.admins"] or []:
|
||||
permissions[entry] = "admin"
|
||||
base["bridge.permissions"] = permissions
|
||||
else:
|
||||
copy_dict("bridge.permissions")
|
||||
|
||||
if "bridge.relaybot" not in self:
|
||||
copy("bridge.authless_relaybot_portals", "bridge.relaybot.authless_portals")
|
||||
else:
|
||||
copy("bridge.relaybot.private_chat.invite")
|
||||
copy("bridge.relaybot.private_chat.state_changes")
|
||||
copy("bridge.relaybot.private_chat.message")
|
||||
copy("bridge.relaybot.group_chat_invite")
|
||||
copy("bridge.relaybot.ignore_unbridged_group_chat")
|
||||
copy("bridge.relaybot.authless_portals")
|
||||
copy("bridge.relaybot.whitelist_group_admins")
|
||||
copy("bridge.relaybot.whitelist")
|
||||
copy("bridge.relaybot.ignore_own_incoming_events")
|
||||
|
||||
copy("telegram.api_id")
|
||||
copy("telegram.api_hash")
|
||||
copy("telegram.bot_token")
|
||||
|
||||
copy("telegram.connection.timeout")
|
||||
copy("telegram.connection.retries")
|
||||
copy("telegram.connection.retry_delay")
|
||||
copy("telegram.connection.flood_sleep_threshold")
|
||||
copy("telegram.connection.request_retries")
|
||||
|
||||
copy("telegram.device_info.device_model")
|
||||
copy("telegram.device_info.system_version")
|
||||
copy("telegram.device_info.app_version")
|
||||
copy("telegram.device_info.lang_code")
|
||||
copy("telegram.device_info.system_lang_code")
|
||||
|
||||
copy("telegram.server.enabled")
|
||||
copy("telegram.server.dc")
|
||||
copy("telegram.server.ip")
|
||||
copy("telegram.server.port")
|
||||
|
||||
copy("telegram.proxy.type")
|
||||
copy("telegram.proxy.address")
|
||||
copy("telegram.proxy.port")
|
||||
copy("telegram.proxy.rdns")
|
||||
copy("telegram.proxy.username")
|
||||
copy("telegram.proxy.password")
|
||||
|
||||
def _get_permissions(self, key: str) -> Permissions:
|
||||
level = self["bridge.permissions"].get(key, "")
|
||||
admin = level == "admin"
|
||||
matrix_puppeting = level == "full" or admin
|
||||
puppeting = level == "puppeting" or matrix_puppeting
|
||||
user = level == "user" or puppeting
|
||||
relaybot = level == "relaybot" or user
|
||||
return Permissions(relaybot, user, puppeting, matrix_puppeting, admin, level)
|
||||
|
||||
def get_permissions(self, mxid: UserID) -> Permissions:
|
||||
permissions = self["bridge.permissions"]
|
||||
if mxid in permissions:
|
||||
return self._get_permissions(mxid)
|
||||
|
||||
_, homeserver = Client.parse_user_id(mxid)
|
||||
if homeserver in permissions:
|
||||
return self._get_permissions(homeserver)
|
||||
|
||||
return self._get_permissions("*")
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, Tuple, TYPE_CHECKING
|
||||
import asyncio
|
||||
|
||||
from alchemysession import AlchemySessionContainer
|
||||
|
||||
from mautrix.appservice import AppService
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .web import PublicBridgeWebsite, ProvisioningAPI
|
||||
from .config import Config
|
||||
from .bot import Bot
|
||||
from .matrix import MatrixHandler
|
||||
from .__main__ import TelegramBridge
|
||||
|
||||
|
||||
class Context:
|
||||
az: AppService
|
||||
config: 'Config'
|
||||
loop: asyncio.AbstractEventLoop
|
||||
bridge: 'TelegramBridge'
|
||||
bot: Optional['Bot']
|
||||
mx: Optional['MatrixHandler']
|
||||
session_container: AlchemySessionContainer
|
||||
public_website: Optional['PublicBridgeWebsite']
|
||||
provisioning_api: Optional['ProvisioningAPI']
|
||||
|
||||
def __init__(self, az: AppService, config: 'Config', loop: asyncio.AbstractEventLoop,
|
||||
session_container: AlchemySessionContainer, bridge: 'TelegramBridge',
|
||||
bot: Optional['Bot']) -> None:
|
||||
self.az = az
|
||||
self.config = config
|
||||
self.loop = loop
|
||||
self.bridge = bridge
|
||||
self.bot = bot
|
||||
self.mx = None
|
||||
self.session_container = session_container
|
||||
self.public_website = None
|
||||
self.provisioning_api = None
|
||||
|
||||
@property
|
||||
def core(self) -> Tuple[AppService, 'Config', asyncio.AbstractEventLoop, Optional['Bot']]:
|
||||
return self.az, self.config, self.loop, self.bot
|
||||
@@ -1,103 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from sqlalchemy import Column, UniqueConstraint, ForeignKey, ForeignKeyConstraint, Integer, String
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class Portal(Base):
|
||||
query = None
|
||||
__tablename__ = "portal"
|
||||
|
||||
# Telegram chat information
|
||||
tgid = Column(Integer, primary_key=True)
|
||||
tg_receiver = Column(Integer, primary_key=True)
|
||||
peer_type = Column(String)
|
||||
|
||||
# Matrix portal information
|
||||
mxid = Column(String, unique=True, nullable=True)
|
||||
|
||||
# Telegram chat metadata
|
||||
username = Column(String, nullable=True)
|
||||
title = Column(String, nullable=True)
|
||||
about = Column(String, nullable=True)
|
||||
photo_id = Column(String, nullable=True)
|
||||
|
||||
|
||||
class Message(Base):
|
||||
query = None
|
||||
__tablename__ = "message"
|
||||
|
||||
mxid = Column(String)
|
||||
mx_room = Column(String)
|
||||
tgid = Column(Integer, primary_key=True)
|
||||
tg_space = Column(Integer, primary_key=True)
|
||||
|
||||
__table_args__ = (UniqueConstraint('mxid', 'mx_room', 'tg_space', name='_mx_id_room'),)
|
||||
|
||||
|
||||
class UserPortal(Base):
|
||||
query = None
|
||||
__tablename__ = "user_portal"
|
||||
|
||||
user = Column(Integer, ForeignKey("user.tgid"), primary_key=True)
|
||||
portal = Column(Integer, primary_key=True)
|
||||
portal_receiver = Column(Integer, primary_key=True)
|
||||
|
||||
__table_args__ = (ForeignKeyConstraint(("portal", "portal_receiver"),
|
||||
("portal.tgid", "portal.tg_receiver")),)
|
||||
|
||||
|
||||
class User(Base):
|
||||
query = None
|
||||
__tablename__ = "user"
|
||||
|
||||
mxid = Column(String, primary_key=True)
|
||||
tgid = Column(Integer, nullable=True)
|
||||
tg_username = Column(String, nullable=True)
|
||||
saved_contacts = Column(Integer, default=0)
|
||||
contacts = relationship("Contact", uselist=True,
|
||||
cascade="save-update, merge, delete, delete-orphan")
|
||||
portals = relationship("Portal", secondary="user_portal", single_parent=True,
|
||||
cascade="save-update, merge, delete, delete-orphan")
|
||||
|
||||
|
||||
class Contact(Base):
|
||||
query = None
|
||||
__tablename__ = "contact"
|
||||
|
||||
user = Column("user", Integer, ForeignKey("user.tgid"), primary_key=True)
|
||||
contact = Column("contact", Integer, ForeignKey("puppet.id"), primary_key=True)
|
||||
|
||||
|
||||
class Puppet(Base):
|
||||
query = None
|
||||
__tablename__ = "puppet"
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
displayname = Column(String, nullable=True)
|
||||
username = Column(String, nullable=True)
|
||||
photo_id = Column(String, nullable=True)
|
||||
|
||||
|
||||
def init(db_session):
|
||||
Portal.query = db_session.query_property()
|
||||
Message.query = db_session.query_property()
|
||||
UserPortal.query = db_session.query_property()
|
||||
User.query = db_session.query_property()
|
||||
Puppet.query = db_session.query_property()
|
||||
@@ -0,0 +1,31 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from sqlalchemy.engine.base import Engine
|
||||
|
||||
from mautrix.client.state_store.sqlalchemy import UserProfile, RoomState
|
||||
|
||||
from .bot_chat import BotChat
|
||||
from .message import Message
|
||||
from .portal import Portal
|
||||
from .puppet import Puppet
|
||||
from .telegram_file import TelegramFile
|
||||
from .user import User, UserPortal, Contact
|
||||
|
||||
|
||||
def init(db_engine: Engine) -> None:
|
||||
for table in (Portal, Message, User, Contact, UserPortal, Puppet, TelegramFile, UserProfile,
|
||||
RoomState, BotChat):
|
||||
table.bind(db_engine)
|
||||
@@ -0,0 +1,38 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Iterable
|
||||
|
||||
from sqlalchemy import Column, BigInteger, String
|
||||
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from ..types import TelegramID
|
||||
|
||||
|
||||
# Fucking Telegram not telling bots what chats they are in 3:<
|
||||
class BotChat(Base):
|
||||
__tablename__ = "bot_chat"
|
||||
id: TelegramID = Column(BigInteger, primary_key=True)
|
||||
type: str = Column(String, nullable=False)
|
||||
|
||||
@classmethod
|
||||
def delete_by_id(cls, chat_id: TelegramID) -> None:
|
||||
with cls.db.begin() as conn:
|
||||
conn.execute(cls.t.delete().where(cls.c.id == chat_id))
|
||||
|
||||
@classmethod
|
||||
def all(cls) -> Iterable['BotChat']:
|
||||
return cls._select_all()
|
||||
@@ -0,0 +1,108 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, Iterator, List
|
||||
|
||||
from sqlalchemy import (Column, UniqueConstraint, BigInteger, Integer, String, Boolean, and_, func,
|
||||
desc, select, false)
|
||||
|
||||
from mautrix.types import RoomID, EventID
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from ..types import TelegramID
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "message"
|
||||
|
||||
mxid: EventID = Column(String)
|
||||
mx_room: RoomID = Column(String)
|
||||
tgid: TelegramID = Column(BigInteger, primary_key=True)
|
||||
tg_space: TelegramID = Column(BigInteger, primary_key=True)
|
||||
edit_index: int = Column(Integer, primary_key=True)
|
||||
redacted: bool = Column(Boolean, server_default=false())
|
||||
|
||||
__table_args__ = (UniqueConstraint("mxid", "mx_room", "tg_space", name="_mx_id_room_2"),)
|
||||
|
||||
@classmethod
|
||||
def get_all_by_tgid(cls, tgid: TelegramID, tg_space: TelegramID) -> Iterator['Message']:
|
||||
return cls._select_all(cls.c.tgid == tgid, cls.c.tg_space == tg_space)
|
||||
|
||||
@classmethod
|
||||
def get_one_by_tgid(cls, tgid: TelegramID, tg_space: TelegramID, edit_index: int = 0
|
||||
) -> Optional['Message']:
|
||||
if edit_index < 0:
|
||||
return cls._one_or_none(cls.db.execute(
|
||||
cls.t.select()
|
||||
.where(and_(cls.c.tgid == tgid, cls.c.tg_space == tg_space))
|
||||
.order_by(desc(cls.c.edit_index))
|
||||
.limit(1).offset(-edit_index - 1)))
|
||||
else:
|
||||
return cls._select_one_or_none(cls.c.tgid == tgid, cls.c.tg_space == tg_space,
|
||||
cls.c.edit_index == edit_index)
|
||||
|
||||
@classmethod
|
||||
def get_first_by_tgids(cls, tgids: List[TelegramID], tg_space: TelegramID
|
||||
) -> Iterator['Message']:
|
||||
return cls._select_all(cls.c.tgid.in_(tgids), cls.c.tg_space == tg_space,
|
||||
cls.c.edit_index == 0)
|
||||
|
||||
@classmethod
|
||||
def count_spaces_by_mxid(cls, mxid: EventID, mx_room: RoomID) -> int:
|
||||
rows = cls.db.execute(select([func.count(cls.c.tg_space)])
|
||||
.where(and_(cls.c.mxid == mxid, cls.c.mx_room == mx_room)))
|
||||
try:
|
||||
count, = next(rows)
|
||||
return count
|
||||
except StopIteration:
|
||||
return 0
|
||||
|
||||
@classmethod
|
||||
def find_last(cls, mx_room: RoomID, tg_space: TelegramID) -> Optional['Message']:
|
||||
return cls._one_or_none(cls.db.execute(
|
||||
cls._make_simple_select(cls.c.mx_room == mx_room, cls.c.tg_space == tg_space)
|
||||
.order_by(desc(cls.c.tgid)).limit(1)))
|
||||
|
||||
@classmethod
|
||||
def delete_all(cls, mx_room: RoomID) -> None:
|
||||
cls.db.execute(cls.t.delete().where(cls.c.mx_room == mx_room))
|
||||
|
||||
@classmethod
|
||||
def get_by_mxid(cls, mxid: EventID, mx_room: RoomID, tg_space: TelegramID
|
||||
) -> Optional['Message']:
|
||||
return cls._select_one_or_none(cls.c.mxid == mxid, cls.c.mx_room == mx_room,
|
||||
cls.c.tg_space == tg_space)
|
||||
|
||||
@classmethod
|
||||
def get_by_mxids(cls, mxids: List[EventID], mx_room: RoomID, tg_space: TelegramID
|
||||
) -> Iterator['Message']:
|
||||
return cls._select_all(cls.c.mxid.in_(mxids), cls.c.mx_room == mx_room,
|
||||
cls.c.tg_space == tg_space)
|
||||
|
||||
@classmethod
|
||||
def update_by_tgid(cls, s_tgid: TelegramID, s_tg_space: TelegramID, s_edit_index: int,
|
||||
**values) -> None:
|
||||
with cls.db.begin() as conn:
|
||||
conn.execute(cls.t.update()
|
||||
.where(and_(cls.c.tgid == s_tgid, cls.c.tg_space == s_tg_space,
|
||||
cls.c.edit_index == s_edit_index))
|
||||
.values(**values))
|
||||
|
||||
@classmethod
|
||||
def update_by_mxid(cls, s_mxid: EventID, s_mx_room: RoomID, **values) -> None:
|
||||
with cls.db.begin() as conn:
|
||||
conn.execute(cls.t.update()
|
||||
.where(and_(cls.c.mxid == s_mxid, cls.c.mx_room == s_mx_room))
|
||||
.values(**values))
|
||||
@@ -0,0 +1,66 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, Iterable
|
||||
|
||||
from sqlalchemy import Column, BigInteger, String, Boolean, Text, func, sql
|
||||
|
||||
from mautrix.types import RoomID, ContentURI
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from ..types import TelegramID
|
||||
|
||||
|
||||
class Portal(Base):
|
||||
__tablename__ = "portal"
|
||||
|
||||
# Telegram chat information
|
||||
tgid: TelegramID = Column(BigInteger, primary_key=True)
|
||||
tg_receiver: TelegramID = Column(BigInteger, primary_key=True)
|
||||
peer_type: str = Column(String, nullable=False)
|
||||
megagroup: bool = Column(Boolean)
|
||||
|
||||
# Matrix portal information
|
||||
mxid: Optional[RoomID] = Column(String, unique=True, nullable=True)
|
||||
avatar_url: Optional[ContentURI] = Column(String, nullable=True)
|
||||
encrypted: bool = Column(Boolean, nullable=False, server_default=sql.expression.false())
|
||||
|
||||
config: str = Column(Text, nullable=True)
|
||||
|
||||
# Telegram chat metadata
|
||||
username: str = Column(String, nullable=True)
|
||||
title: str = Column(String, nullable=True)
|
||||
about: str = Column(String, nullable=True)
|
||||
photo_id: str = Column(String, nullable=True)
|
||||
|
||||
@classmethod
|
||||
def get_by_tgid(cls, tgid: TelegramID, tg_receiver: TelegramID) -> Optional['Portal']:
|
||||
return cls._select_one_or_none(cls.c.tgid == tgid, cls.c.tg_receiver == tg_receiver)
|
||||
|
||||
@classmethod
|
||||
def find_private_chats(cls, tg_receiver: TelegramID) -> Iterable['Portal']:
|
||||
yield from cls._select_all(cls.c.tg_receiver == tg_receiver, cls.c.peer_type == "user")
|
||||
|
||||
@classmethod
|
||||
def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
|
||||
return cls._select_one_or_none(cls.c.mxid == mxid)
|
||||
|
||||
@classmethod
|
||||
def get_by_username(cls, username: str) -> Optional['Portal']:
|
||||
return cls._select_one_or_none(func.lower(cls.c.username) == username)
|
||||
|
||||
@classmethod
|
||||
def all(cls) -> Iterable['Portal']:
|
||||
yield from cls._select_all()
|
||||
@@ -0,0 +1,63 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, Iterable
|
||||
|
||||
from sqlalchemy import Column, Integer, BigInteger, String, Text, Boolean
|
||||
from sqlalchemy.sql import expression, func
|
||||
|
||||
from mautrix.types import UserID, SyncToken
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from ..types import TelegramID
|
||||
|
||||
|
||||
class Puppet(Base):
|
||||
__tablename__ = "puppet"
|
||||
|
||||
id: TelegramID = Column(BigInteger, primary_key=True)
|
||||
custom_mxid: UserID = Column(String, nullable=True)
|
||||
access_token: str = Column(String, nullable=True)
|
||||
next_batch: SyncToken = Column(String, nullable=True)
|
||||
base_url: str = Column(Text, nullable=True)
|
||||
displayname: str = Column(String, nullable=True)
|
||||
displayname_source: TelegramID = Column(BigInteger, nullable=True)
|
||||
displayname_contact: bool = Column(Boolean, nullable=False, server_default=expression.true())
|
||||
displayname_quality: int = Column(Integer, nullable=False, server_default="0")
|
||||
username: str = Column(String, nullable=True)
|
||||
photo_id: str = Column(String, nullable=True)
|
||||
is_bot: bool = Column(Boolean, nullable=True)
|
||||
matrix_registered: bool = Column(Boolean, nullable=False, server_default=expression.false())
|
||||
disable_updates: bool = Column(Boolean, nullable=False, server_default=expression.false())
|
||||
|
||||
@classmethod
|
||||
def all_with_custom_mxid(cls) -> Iterable['Puppet']:
|
||||
yield from cls._select_all(cls.c.custom_mxid != None)
|
||||
|
||||
@classmethod
|
||||
def get_by_tgid(cls, tgid: TelegramID) -> Optional['Puppet']:
|
||||
return cls._select_one_or_none(cls.c.id == tgid)
|
||||
|
||||
@classmethod
|
||||
def get_by_custom_mxid(cls, mxid: UserID) -> Optional['Puppet']:
|
||||
return cls._select_one_or_none(cls.c.custom_mxid == mxid)
|
||||
|
||||
@classmethod
|
||||
def get_by_username(cls, username: str) -> Optional['Puppet']:
|
||||
return cls._select_one_or_none(func.lower(cls.c.username) == username)
|
||||
|
||||
@classmethod
|
||||
def get_by_displayname(cls, displayname: str) -> Optional['Puppet']:
|
||||
return cls._select_one_or_none(cls.c.displayname == displayname)
|
||||
@@ -0,0 +1,81 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, cast, Dict, Any, TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import (Column, ForeignKey, Integer, BigInteger, String, Boolean, Text,
|
||||
TypeDecorator)
|
||||
|
||||
from mautrix.types import ContentURI, EncryptedFile
|
||||
from mautrix.util.db import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.engine.result import RowProxy
|
||||
|
||||
|
||||
class DBEncryptedFile(TypeDecorator):
|
||||
impl = Text
|
||||
|
||||
@property
|
||||
def python_type(self):
|
||||
return EncryptedFile
|
||||
|
||||
def process_bind_param(self, value: EncryptedFile, dialect) -> Optional[str]:
|
||||
if value is not None:
|
||||
return value.json()
|
||||
return None
|
||||
|
||||
def process_result_value(self, value: str, dialect) -> Optional[EncryptedFile]:
|
||||
if value is not None:
|
||||
return EncryptedFile.parse_json(value)
|
||||
return None
|
||||
|
||||
def process_literal_param(self, value, dialect):
|
||||
return value
|
||||
|
||||
|
||||
class TelegramFile(Base):
|
||||
__tablename__ = "telegram_file"
|
||||
|
||||
id: str = Column(String, primary_key=True)
|
||||
mxc: ContentURI = Column(String)
|
||||
mime_type: str = Column(String)
|
||||
was_converted: bool = Column(Boolean)
|
||||
timestamp: int = Column(BigInteger)
|
||||
size: Optional[int] = Column(Integer, nullable=True)
|
||||
width: Optional[int] = Column(Integer, nullable=True)
|
||||
height: Optional[int] = Column(Integer, nullable=True)
|
||||
decryption_info: Optional[Dict[str, Any]] = Column(DBEncryptedFile, nullable=True)
|
||||
thumbnail_id: str = Column("thumbnail", String, ForeignKey("telegram_file.id"), nullable=True)
|
||||
thumbnail: Optional['TelegramFile'] = None
|
||||
|
||||
@classmethod
|
||||
def scan(cls, row: 'RowProxy') -> 'TelegramFile':
|
||||
telegram_file = cast(TelegramFile, super().scan(row))
|
||||
if isinstance(telegram_file.thumbnail, str):
|
||||
telegram_file.thumbnail = cls.get(telegram_file.thumbnail)
|
||||
return telegram_file
|
||||
|
||||
@classmethod
|
||||
def get(cls, loc_id: str) -> Optional['TelegramFile']:
|
||||
return cls._select_one_or_none(cls.c.id == loc_id)
|
||||
|
||||
def insert(self) -> None:
|
||||
with self.db.begin() as conn:
|
||||
conn.execute(self.t.insert().values(
|
||||
id=self.id, mxc=self.mxc, mime_type=self.mime_type,
|
||||
was_converted=self.was_converted, timestamp=self.timestamp, size=self.size,
|
||||
width=self.width, height=self.height, decryption_info=self.decryption_info,
|
||||
thumbnail=self.thumbnail.id if self.thumbnail else self.thumbnail_id))
|
||||
@@ -0,0 +1,108 @@
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2019 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
from typing import Optional, Iterable, Tuple
|
||||
|
||||
from sqlalchemy import Column, ForeignKey, ForeignKeyConstraint, BigInteger, Integer, String, func
|
||||
|
||||
from mautrix.types import UserID
|
||||
from mautrix.util.db import Base
|
||||
|
||||
from ..types import TelegramID
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "user"
|
||||
|
||||
mxid: UserID = Column(String, primary_key=True)
|
||||
tgid: Optional[TelegramID] = Column(BigInteger, nullable=True, unique=True)
|
||||
tg_username: str = Column(String, nullable=True)
|
||||
tg_phone: str = Column(String, nullable=True)
|
||||
saved_contacts: int = Column(Integer, default=0, nullable=False)
|
||||
|
||||
@classmethod
|
||||
def all_with_tgid(cls) -> Iterable['User']:
|
||||
return cls._select_all(cls.c.tgid != None)
|
||||
|
||||
@classmethod
|
||||
def get_by_tgid(cls, tgid: TelegramID) -> Optional['User']:
|
||||
return cls._select_one_or_none(cls.c.tgid == tgid)
|
||||
|
||||
@classmethod
|
||||
def get_by_mxid(cls, mxid: UserID) -> Optional['User']:
|
||||
return cls._select_one_or_none(cls.c.mxid == mxid)
|
||||
|
||||
@classmethod
|
||||
def get_by_username(cls, username: str) -> Optional['User']:
|
||||
return cls._select_one_or_none(func.lower(cls.c.tg_username) == username)
|
||||
|
||||
@property
|
||||
def contacts(self) -> Iterable[TelegramID]:
|
||||
rows = self.db.execute(Contact.t.select().where(Contact.c.user == self.tgid))
|
||||
for row in rows:
|
||||
user, contact = row
|
||||
yield contact
|
||||
|
||||
@contacts.setter
|
||||
def contacts(self, puppets: Iterable[TelegramID]) -> None:
|
||||
with self.db.begin() as conn:
|
||||
conn.execute(Contact.t.delete().where(Contact.c.user == self.tgid))
|
||||
insert_puppets = [{"user": self.tgid, "contact": tgid} for tgid in puppets]
|
||||
if insert_puppets:
|
||||
conn.execute(Contact.t.insert(), insert_puppets)
|
||||
|
||||
@property
|
||||
def portals(self) -> Iterable[Tuple[TelegramID, TelegramID]]:
|
||||
rows = self.db.execute(UserPortal.t.select().where(UserPortal.c.user == self.tgid))
|
||||
for row in rows:
|
||||
user, portal, portal_receiver = row
|
||||
yield (portal, portal_receiver)
|
||||
|
||||
@portals.setter
|
||||
def portals(self, portals: Iterable[Tuple[TelegramID, TelegramID]]) -> None:
|
||||
with self.db.begin() as conn:
|
||||
conn.execute(UserPortal.t.delete().where(UserPortal.c.user == self.tgid))
|
||||
insert_portals = [{
|
||||
"user": self.tgid,
|
||||
"portal": tgid,
|
||||
"portal_receiver": tg_receiver
|
||||
} for tgid, tg_receiver in portals]
|
||||
if insert_portals:
|
||||
conn.execute(UserPortal.t.insert(), insert_portals)
|
||||
|
||||
def delete(self) -> None:
|
||||
super().delete()
|
||||
self.portals = []
|
||||
self.contacts = []
|
||||
|
||||
|
||||
class UserPortal(Base):
|
||||
__tablename__ = "user_portal"
|
||||
|
||||
user: TelegramID = Column(BigInteger, ForeignKey("user.tgid", onupdate="CASCADE",
|
||||
ondelete="CASCADE"), primary_key=True)
|
||||
portal: TelegramID = Column(BigInteger, primary_key=True)
|
||||
portal_receiver: TelegramID = Column(BigInteger, primary_key=True)
|
||||
|
||||
__table_args__ = (ForeignKeyConstraint(("portal", "portal_receiver"),
|
||||
("portal.tgid", "portal.tg_receiver"),
|
||||
onupdate="CASCADE", ondelete="CASCADE"),)
|
||||
|
||||
|
||||
class Contact(Base):
|
||||
__tablename__ = "contact"
|
||||
|
||||
user: TelegramID = Column(BigInteger, ForeignKey("user.tgid"), primary_key=True)
|
||||
contact: TelegramID = Column(BigInteger, ForeignKey("puppet.id"), primary_key=True)
|
||||
@@ -0,0 +1,549 @@
|
||||
# Homeserver details
|
||||
homeserver:
|
||||
# The address that this appservice can use to connect to the homeserver.
|
||||
address: https://example.com
|
||||
# The domain of the homeserver (for MXIDs, etc).
|
||||
domain: example.com
|
||||
# Whether or not to verify the SSL certificate of the homeserver.
|
||||
# Only applies if address starts with https://
|
||||
verify_ssl: true
|
||||
asmux: false
|
||||
# Number of retries for all HTTP requests if the homeserver isn't reachable.
|
||||
http_retry_count: 4
|
||||
# The URL to push real-time bridge status to.
|
||||
# If set, the bridge will make POST requests to this URL whenever a user's Telegram connection state changes.
|
||||
# The bridge will use the appservice as_token to authorize requests.
|
||||
status_endpoint: null
|
||||
|
||||
# Application service host/registration related details
|
||||
# Changing these values requires regeneration of the registration.
|
||||
appservice:
|
||||
# The address that the homeserver can use to connect to this appservice.
|
||||
address: http://localhost:29317
|
||||
# When using https:// the TLS certificate and key files for the address.
|
||||
tls_cert: false
|
||||
tls_key: false
|
||||
|
||||
# The hostname and port where this appservice should listen.
|
||||
hostname: 0.0.0.0
|
||||
port: 29317
|
||||
# The maximum body size of appservice API requests (from the homeserver) in mebibytes
|
||||
# Usually 1 is enough, but on high-traffic bridges you might need to increase this to avoid 413s
|
||||
max_body_size: 1
|
||||
|
||||
# The full URI to the database. SQLite and Postgres are fully supported.
|
||||
# Other DBMSes supported by SQLAlchemy may or may not work.
|
||||
# Format examples:
|
||||
# SQLite: sqlite:///filename.db
|
||||
# Postgres: postgres://username:password@hostname/dbname
|
||||
database: sqlite:///mautrix-telegram.db
|
||||
# Optional extra arguments for SQLAlchemy's create_engine
|
||||
database_opts: {}
|
||||
|
||||
# Public part of web server for out-of-Matrix interaction with the bridge.
|
||||
# Used for things like login if the user wants to make sure the 2FA password isn't stored in
|
||||
# the HS database.
|
||||
public:
|
||||
# Whether or not the public-facing endpoints should be enabled.
|
||||
enabled: false
|
||||
# The prefix to use in the public-facing endpoints.
|
||||
prefix: /public
|
||||
# The base URL where the public-facing endpoints are available. The prefix is not added
|
||||
# implicitly.
|
||||
external: https://example.com/public
|
||||
|
||||
# Provisioning API part of the web server for automated portal creation and fetching information.
|
||||
# Used by things like mautrix-manager (https://github.com/tulir/mautrix-manager).
|
||||
provisioning:
|
||||
# Whether or not the provisioning API should be enabled.
|
||||
enabled: true
|
||||
# The prefix to use in the provisioning API endpoints.
|
||||
prefix: /_matrix/provision/v1
|
||||
# The shared secret to authorize users of the API.
|
||||
# Set to "generate" to generate and save a new token.
|
||||
shared_secret: generate
|
||||
|
||||
# The unique ID of this appservice.
|
||||
id: telegram
|
||||
# Username of the appservice bot.
|
||||
bot_username: telegrambot
|
||||
# Display name and avatar for bot. Set to "remove" to remove display name/avatar, leave empty
|
||||
# to leave display name/avatar as-is.
|
||||
bot_displayname: Telegram bridge bot
|
||||
bot_avatar: mxc://maunium.net/tJCRmUyJDsgRNgqhOgoiHWbX
|
||||
|
||||
# Community ID for bridged users (changes registration file) and rooms.
|
||||
# Must be created manually.
|
||||
#
|
||||
# Example: "+telegram:example.com". Set to false to disable.
|
||||
community_id: false
|
||||
|
||||
# Whether or not to receive ephemeral events via appservice transactions.
|
||||
# Requires MSC2409 support (i.e. Synapse 1.22+).
|
||||
# You should disable bridge -> sync_with_custom_puppets when this is enabled.
|
||||
ephemeral_events: false
|
||||
|
||||
# Authentication tokens for AS <-> HS communication. Autogenerated; do not modify.
|
||||
as_token: "This value is generated when generating the registration"
|
||||
hs_token: "This value is generated when generating the registration"
|
||||
|
||||
# Prometheus telemetry config. Requires prometheus-client to be installed.
|
||||
metrics:
|
||||
enabled: false
|
||||
listen_port: 8000
|
||||
|
||||
# Manhole config.
|
||||
manhole:
|
||||
# Whether or not opening the manhole is allowed.
|
||||
enabled: false
|
||||
# The path for the unix socket.
|
||||
path: /var/tmp/mautrix-telegram.manhole
|
||||
# The list of UIDs who can be added to the whitelist.
|
||||
# If empty, any UIDs can be specified in the open-manhole command.
|
||||
whitelist:
|
||||
- 0
|
||||
|
||||
# Bridge config
|
||||
bridge:
|
||||
# Localpart template of MXIDs for Telegram users.
|
||||
# {userid} is replaced with the user ID of the Telegram user.
|
||||
username_template: "telegram_{userid}"
|
||||
# Localpart template of room aliases for Telegram portal rooms.
|
||||
# {groupname} is replaced with the name part of the public channel/group invite link ( https://t.me/{} )
|
||||
alias_template: "telegram_{groupname}"
|
||||
# Displayname template for Telegram users.
|
||||
# {displayname} is replaced with the display name of the Telegram user.
|
||||
displayname_template: "{displayname} (Telegram)"
|
||||
|
||||
# Set the preferred order of user identifiers which to use in the Matrix puppet display name.
|
||||
# In the (hopefully unlikely) scenario that none of the given keys are found, the numeric user
|
||||
# ID is used.
|
||||
#
|
||||
# If the bridge is working properly, a phone number or an username should always be known, but
|
||||
# the other one can very well be empty.
|
||||
#
|
||||
# Valid keys:
|
||||
# "full name" (First and/or last name)
|
||||
# "full name reversed" (Last and/or first name)
|
||||
# "first name"
|
||||
# "last name"
|
||||
# "username"
|
||||
# "phone number"
|
||||
displayname_preference:
|
||||
- full name
|
||||
- username
|
||||
- phone number
|
||||
# Maximum length of displayname
|
||||
displayname_max_length: 100
|
||||
# Remove avatars from Telegram ghost users when removed on Telegram. This is disabled by default
|
||||
# as there's no way to determine whether an avatar is removed or just hidden from some users. If
|
||||
# you're on a single-user instance, this should be safe to enable.
|
||||
allow_avatar_remove: false
|
||||
|
||||
# Maximum number of members to sync per portal when starting up. Other members will be
|
||||
# synced when they send messages. The maximum is 10000, after which the Telegram server
|
||||
# will not send any more members.
|
||||
# -1 means no limit (which means it's limited to 10000 by the server)
|
||||
max_initial_member_sync: 100
|
||||
# Whether or not to sync the member list in channels.
|
||||
# If no channel admins have logged into the bridge, the bridge won't be able to sync the member
|
||||
# list regardless of this setting.
|
||||
sync_channel_members: true
|
||||
# Whether or not to skip deleted members when syncing members.
|
||||
skip_deleted_members: true
|
||||
# Whether or not to automatically synchronize contacts and chats of Matrix users logged into
|
||||
# their Telegram account at startup.
|
||||
startup_sync: true
|
||||
# Number of most recently active dialogs to check when syncing chats.
|
||||
# Set to 0 to remove limit.
|
||||
sync_update_limit: 0
|
||||
# Number of most recently active dialogs to create portals for when syncing chats.
|
||||
# Set to 0 to remove limit.
|
||||
sync_create_limit: 30
|
||||
# Whether or not to sync and create portals for direct chats at startup.
|
||||
sync_direct_chats: false
|
||||
# The maximum number of simultaneous Telegram deletions to handle.
|
||||
# A large number of simultaneous redactions could put strain on your homeserver.
|
||||
max_telegram_delete: 10
|
||||
# Whether or not to automatically sync the Matrix room state (mostly unpuppeted displaynames)
|
||||
# at startup and when creating a bridge.
|
||||
sync_matrix_state: true
|
||||
# Allow logging in within Matrix. If false, users can only log in using login-qr or the
|
||||
# out-of-Matrix login website (see appservice.public config section)
|
||||
allow_matrix_login: true
|
||||
# Whether or not to bridge plaintext highlights.
|
||||
# Only enable this if your displayname_template has some static part that the bridge can use to
|
||||
# reliably identify what is a plaintext highlight.
|
||||
plaintext_highlights: false
|
||||
# Whether or not to make portals of publicly joinable channels/supergroups publicly joinable on Matrix.
|
||||
public_portals: true
|
||||
# Whether or not to use /sync to get presence, read receipts and typing notifications
|
||||
# when double puppeting is enabled
|
||||
sync_with_custom_puppets: true
|
||||
# Whether or not to update the m.direct account data event when double puppeting is enabled.
|
||||
# Note that updating the m.direct event is not atomic (except with mautrix-asmux)
|
||||
# and is therefore prone to race conditions.
|
||||
sync_direct_chat_list: false
|
||||
# Servers to always allow double puppeting from
|
||||
double_puppet_server_map:
|
||||
example.com: https://example.com
|
||||
# Allow using double puppeting from any server with a valid client .well-known file.
|
||||
double_puppet_allow_discovery: false
|
||||
# Shared secrets for https://github.com/devture/matrix-synapse-shared-secret-auth
|
||||
#
|
||||
# If set, custom puppets will be enabled automatically for local users
|
||||
# instead of users having to find an access token and run `login-matrix`
|
||||
# manually.
|
||||
# If using this for other servers than the bridge's server,
|
||||
# you must also set the URL in the double_puppet_server_map.
|
||||
login_shared_secret_map:
|
||||
example.com: foobar
|
||||
# Set to false to disable link previews in messages sent to Telegram.
|
||||
telegram_link_preview: true
|
||||
# Whether or not the !tg join command should do a HTTP request
|
||||
# to resolve redirects in invite links.
|
||||
invite_link_resolve: false
|
||||
# Use inline images instead of a separate message for the caption.
|
||||
# N.B. Inline images are not supported on all clients (e.g. Element iOS/Android).
|
||||
inline_images: false
|
||||
# Maximum size of image in megabytes before sending to Telegram as a document.
|
||||
image_as_file_size: 10
|
||||
# Maximum size of Telegram documents in megabytes to bridge.
|
||||
max_document_size: 100
|
||||
# Enable experimental parallel file transfer, which makes uploads/downloads much faster by
|
||||
# streaming from/to Matrix and using many connections for Telegram.
|
||||
# Note that generating HQ thumbnails for videos is not possible with streamed transfers.
|
||||
# This option uses internal Telethon implementation details and may break with minor updates.
|
||||
parallel_file_transfer: false
|
||||
# Whether or not created rooms should have federation enabled.
|
||||
# If false, created portal rooms will never be federated.
|
||||
federate_rooms: true
|
||||
# Settings for converting animated stickers.
|
||||
animated_sticker:
|
||||
# Format to which animated stickers should be converted.
|
||||
# disable - No conversion, send as-is (gzipped lottie)
|
||||
# png - converts to non-animated png (fastest),
|
||||
# gif - converts to animated gif, but loses transparency
|
||||
# webm - converts to webm video, requires ffmpeg executable with vp9 codec and webm container support
|
||||
target: gif
|
||||
# Arguments for converter. All converters take width and height.
|
||||
# GIF converter takes background as a hex color.
|
||||
args:
|
||||
width: 256
|
||||
height: 256
|
||||
background: "020202" # only for gif
|
||||
fps: 30 # only for webm
|
||||
# End-to-bridge encryption support options. These require matrix-nio to be installed with pip
|
||||
# and login_shared_secret to be configured in order to get a device for the bridge bot.
|
||||
#
|
||||
# Additionally, https://github.com/matrix-org/synapse/pull/5758 is required if using a normal
|
||||
# application service.
|
||||
encryption:
|
||||
# Allow encryption, work in group chat rooms with e2ee enabled
|
||||
allow: false
|
||||
# Default to encryption, force-enable encryption in all portals the bridge creates
|
||||
# This will cause the bridge bot to be in private chats for the encryption to work properly.
|
||||
default: false
|
||||
# Database for the encryption data. If set to `default`, will use the appservice database.
|
||||
database: default
|
||||
# Options for automatic key sharing.
|
||||
key_sharing:
|
||||
# Enable key sharing? If enabled, key requests for rooms where users are in will be fulfilled.
|
||||
# You must use a client that supports requesting keys from other users to use this feature.
|
||||
allow: false
|
||||
# Require the requesting device to have a valid cross-signing signature?
|
||||
# This doesn't require that the bridge has verified the device, only that the user has verified it.
|
||||
# Not yet implemented.
|
||||
require_cross_signing: false
|
||||
# Require devices to be verified by the bridge?
|
||||
# Verification by the bridge is not yet implemented.
|
||||
require_verification: true
|
||||
# Whether or not to explicitly set the avatar and room name for private
|
||||
# chat portal rooms. This will be implicitly enabled if encryption.default is true.
|
||||
private_chat_portal_meta: false
|
||||
# Whether or not the bridge should send a read receipt from the bridge bot when a message has
|
||||
# been sent to Telegram.
|
||||
delivery_receipts: false
|
||||
# Whether or not delivery errors should be reported as messages in the Matrix room.
|
||||
delivery_error_reports: false
|
||||
# Set this to true to tell the bridge to re-send m.bridge events to all rooms on the next run.
|
||||
# This field will automatically be changed back to false after it,
|
||||
# except if the config file is not writable.
|
||||
resend_bridge_info: false
|
||||
# When using double puppeting, should muted chats be muted in Matrix?
|
||||
mute_bridging: false
|
||||
# When using double puppeting, should pinned chats be moved to a specific tag in Matrix?
|
||||
# The favorites tag is `m.favourite`.
|
||||
pinned_tag: null
|
||||
# Same as above for archived chats, the low priority tag is `m.lowpriority`.
|
||||
archive_tag: null
|
||||
# Whether or not mute status and tags should only be bridged when the portal room is created.
|
||||
tag_only_on_create: true
|
||||
# Settings for backfilling messages from Telegram.
|
||||
backfill:
|
||||
# Whether or not the Telegram ghosts of logged in Matrix users should be
|
||||
# invited to private chats when backfilling history from Telegram. This is
|
||||
# usually needed to prevent rate limits and to allow timestamp massaging.
|
||||
invite_own_puppet: true
|
||||
# Maximum number of messages to backfill without using a takeout.
|
||||
# The first time a takeout is used, the user has to manually approve it from a different
|
||||
# device. If initial_limit or missed_limit are higher than this value, the bridge will ask
|
||||
# the user to accept the takeout after logging in before syncing any chats.
|
||||
takeout_limit: 100
|
||||
# Maximum number of messages to backfill initially.
|
||||
# Set to 0 to disable backfilling when creating portal, or -1 to disable the limit.
|
||||
#
|
||||
# N.B. Initial backfill will only start after member sync. Make sure your
|
||||
# max_initial_member_sync is set to a low enough value so it doesn't take forever.
|
||||
initial_limit: 0
|
||||
# Maximum number of messages to backfill if messages were missed while the bridge was
|
||||
# disconnected. Note that this only works for logged in users and only if the chat isn't
|
||||
# older than sync_update_limit
|
||||
# Set to 0 to disable backfilling missed messages.
|
||||
missed_limit: 50
|
||||
# If using double puppeting, should notifications be disabled
|
||||
# while the initial backfill is in progress?
|
||||
disable_notifications: false
|
||||
# Whether or not to enable backfilling in normal groups.
|
||||
# Normal groups have numerous technical problems in Telegram, and backfilling normal groups
|
||||
# will likely cause problems if there are multiple Matrix users in the group.
|
||||
normal_groups: false
|
||||
|
||||
# Overrides for base power levels.
|
||||
initial_power_level_overrides:
|
||||
user: {}
|
||||
group: {}
|
||||
|
||||
# Whether to bridge Telegram bot messages as m.notices or m.texts.
|
||||
bot_messages_as_notices: true
|
||||
bridge_notices:
|
||||
# Whether or not Matrix bot messages (type m.notice) should be bridged.
|
||||
default: false
|
||||
# List of user IDs for whom the previous flag is flipped.
|
||||
# e.g. if bridge_notices.default is false, notices from other users will not be bridged, but
|
||||
# notices from users listed here will be bridged.
|
||||
exceptions:
|
||||
- "@importantbot:example.com"
|
||||
|
||||
# Some config options related to Telegram message deduplication.
|
||||
# The default values are usually fine, but some debug messages/warnings might recommend you
|
||||
# change these.
|
||||
deduplication:
|
||||
# Whether or not to check the database if the message about to be sent is a duplicate.
|
||||
pre_db_check: false
|
||||
# The number of latest events to keep when checking for duplicates.
|
||||
# You might need to increase this on high-traffic bridge instances.
|
||||
cache_queue_length: 20
|
||||
|
||||
# The formats to use when sending messages to Telegram via the relay bot.
|
||||
# Text msgtypes (m.text, m.notice and m.emote) support HTML, media msgtypes don't.
|
||||
#
|
||||
# Available variables:
|
||||
# $sender_displayname - The display name of the sender (e.g. Example User)
|
||||
# $sender_username - The username (Matrix ID localpart) of the sender (e.g. exampleuser)
|
||||
# $sender_mxid - The Matrix ID of the sender (e.g. @exampleuser:example.com)
|
||||
# $message - The message content
|
||||
message_formats:
|
||||
m.text: "<b>$sender_displayname</b>: $message"
|
||||
m.notice: "<b>$sender_displayname</b>: $message"
|
||||
m.emote: "* <b>$sender_displayname</b> $message"
|
||||
m.file: "<b>$sender_displayname</b> sent a file: $message"
|
||||
m.image: "<b>$sender_displayname</b> sent an image: $message"
|
||||
m.audio: "<b>$sender_displayname</b> sent an audio file: $message"
|
||||
m.video: "<b>$sender_displayname</b> sent a video: $message"
|
||||
m.location: "<b>$sender_displayname</b> sent a location: $message"
|
||||
# Telegram doesn't have built-in emotes, this field specifies how m.emote's from authenticated
|
||||
# users are sent to telegram. All fields in message_formats are supported. Additionally, the
|
||||
# Telegram user info is available in the following variables:
|
||||
# $displayname - Telegram displayname
|
||||
# $username - Telegram username (may not exist)
|
||||
# $mention - Telegram @username or displayname mention (depending on which exists)
|
||||
emote_format: "* $mention $formatted_body"
|
||||
|
||||
# The formats to use when sending state events to Telegram via the relay bot.
|
||||
#
|
||||
# Variables from `message_formats` that have the `sender_` prefix are available without the prefix.
|
||||
# In name_change events, `$prev_displayname` is the previous displayname.
|
||||
#
|
||||
# Set format to an empty string to disable the messages for that event.
|
||||
state_event_formats:
|
||||
join: "<b>$displayname</b> joined the room."
|
||||
leave: "<b>$displayname</b> left the room."
|
||||
name_change: "<b>$prev_displayname</b> changed their name to <b>$displayname</b>"
|
||||
|
||||
# Filter rooms that can/can't be bridged. Can also be managed using the `filter` and
|
||||
# `filter-mode` management commands.
|
||||
#
|
||||
# Filters do not affect direct chats.
|
||||
# An empty blacklist will essentially disable the filter.
|
||||
filter:
|
||||
# Filter mode to use. Either "blacklist" or "whitelist".
|
||||
# If the mode is "blacklist", the listed chats will never be bridged.
|
||||
# If the mode is "whitelist", only the listed chats can be bridged.
|
||||
mode: blacklist
|
||||
# The list of group/channel IDs to filter.
|
||||
list: []
|
||||
|
||||
# The prefix for commands. Only required in non-management rooms.
|
||||
command_prefix: "!tg"
|
||||
|
||||
# Messages sent upon joining a management room.
|
||||
# Markdown is supported. The defaults are listed below.
|
||||
management_room_text:
|
||||
# Sent when joining a room.
|
||||
welcome: "Hello, I'm a Telegram bridge bot."
|
||||
# Sent when joining a management room and the user is already logged in.
|
||||
welcome_connected: "Use `help` for help."
|
||||
# Sent when joining a management room and the user is not logged in.
|
||||
welcome_unconnected: "Use `help` for help or `login` to log in."
|
||||
# Optional extra text sent when joining a management room.
|
||||
additional_help: ""
|
||||
|
||||
# Send each message separately (for readability in some clients)
|
||||
management_room_multiple_messages: false
|
||||
|
||||
# Permissions for using the bridge.
|
||||
# Permitted values:
|
||||
# relaybot - Only use the bridge via the relaybot, no access to commands.
|
||||
# user - Relaybot level + access to commands to create bridges.
|
||||
# puppeting - User level + logging in with a Telegram account.
|
||||
# full - Full access to use the bridge, i.e. previous levels + Matrix login.
|
||||
# admin - Full access to use the bridge and some extra administration commands.
|
||||
# Permitted keys:
|
||||
# * - All Matrix users
|
||||
# domain - All users on that homeserver
|
||||
# mxid - Specific user
|
||||
permissions:
|
||||
"*": "relaybot"
|
||||
"public.example.com": "user"
|
||||
"example.com": "full"
|
||||
"@admin:example.com": "admin"
|
||||
|
||||
# Options related to the message relay Telegram bot.
|
||||
relaybot:
|
||||
private_chat:
|
||||
# List of users to invite to the portal when someone starts a private chat with the bot.
|
||||
# If empty, private chats with the bot won't create a portal.
|
||||
invite: []
|
||||
# Whether or not to bridge state change messages in relaybot private chats.
|
||||
state_changes: true
|
||||
# When private_chat_invite is empty, this message is sent to users /starting the
|
||||
# relaybot. Telegram's "markdown" is supported.
|
||||
message: This is a Matrix bridge relaybot and does not support direct chats
|
||||
# List of users to invite to all group chat portals created by the bridge.
|
||||
group_chat_invite: []
|
||||
# Whether or not the relaybot should not bridge events in unbridged group chats.
|
||||
# If false, portals will be created when the relaybot receives messages, just like normal
|
||||
# users. This behavior is usually not desirable, as it interferes with manually bridging
|
||||
# the chat to another room.
|
||||
ignore_unbridged_group_chat: true
|
||||
# Whether or not to allow creating portals from Telegram.
|
||||
authless_portals: true
|
||||
# Whether or not to allow Telegram group admins to use the bot commands.
|
||||
whitelist_group_admins: true
|
||||
# Whether or not to ignore incoming events sent by the relay bot.
|
||||
ignore_own_incoming_events: true
|
||||
# List of usernames/user IDs who are also allowed to use the bot commands.
|
||||
whitelist:
|
||||
- myusername
|
||||
- 12345678
|
||||
|
||||
# Telegram config
|
||||
telegram:
|
||||
# Get your own API keys at https://my.telegram.org/apps
|
||||
api_id: 12345
|
||||
api_hash: tjyd5yge35lbodk1xwzw2jstp90k55qz
|
||||
# (Optional) Create your own bot at https://t.me/BotFather
|
||||
bot_token: disabled
|
||||
|
||||
# Telethon connection options.
|
||||
connection:
|
||||
# The timeout in seconds to be used when connecting.
|
||||
timeout: 120
|
||||
# How many times the reconnection should retry, either on the initial connection or when
|
||||
# Telegram disconnects us. May be set to a negative or null value for infinite retries, but
|
||||
# this is not recommended, since the program can get stuck in an infinite loop.
|
||||
retries: 5
|
||||
# The delay in seconds to sleep between automatic reconnections.
|
||||
retry_delay: 1
|
||||
# The threshold below which the library should automatically sleep on flood wait errors
|
||||
# (inclusive). For instance, if a FloodWaitError for 17s occurs and flood_sleep_threshold
|
||||
# is 20s, the library will sleep automatically. If the error was for 21s, it would raise
|
||||
# the error instead. Values larger than a day (86400) will be changed to a day.
|
||||
flood_sleep_threshold: 60
|
||||
# How many times a request should be retried. Request are retried when Telegram is having
|
||||
# internal issues, when there is a FloodWaitError less than flood_sleep_threshold, or when
|
||||
# there's a migrate error. May take a negative or null value for infinite retries, but this
|
||||
# is not recommended, since some requests can always trigger a call fail (such as searching
|
||||
# for messages).
|
||||
request_retries: 5
|
||||
|
||||
# Device info sent to Telegram.
|
||||
device_info:
|
||||
# "auto" = OS name+version.
|
||||
device_model: auto
|
||||
# "auto" = Telethon version.
|
||||
system_version: auto
|
||||
# "auto" = mautrix-telegram version.
|
||||
app_version: auto
|
||||
lang_code: en
|
||||
system_lang_code: en
|
||||
|
||||
# Custom server to connect to.
|
||||
server:
|
||||
# Set to true to use these server settings. If false, will automatically
|
||||
# use production server assigned by Telegram. Set to false in production.
|
||||
enabled: false
|
||||
# The DC ID to connect to.
|
||||
dc: 2
|
||||
# The IP to connect to.
|
||||
ip: 149.154.167.40
|
||||
# The port to connect to. 443 may not work, 80 is better and both are equally secure.
|
||||
port: 80
|
||||
|
||||
# Telethon proxy configuration.
|
||||
# You must install PySocks from pip for proxies to work.
|
||||
proxy:
|
||||
# Allowed types: disabled, socks4, socks5, http, mtproxy
|
||||
type: disabled
|
||||
# Proxy IP address and port.
|
||||
address: 127.0.0.1
|
||||
port: 1080
|
||||
# Whether or not to perform DNS resolving remotely. Only for socks/http proxies.
|
||||
rdns: true
|
||||
# Proxy authentication (optional). Put MTProxy secret in password field.
|
||||
username: ""
|
||||
password: ""
|
||||
|
||||
# Python logging configuration.
|
||||
#
|
||||
# See section 16.7.2 of the Python documentation for more info:
|
||||
# https://docs.python.org/3.6/library/logging.config.html#configuration-dictionary-schema
|
||||
logging:
|
||||
version: 1
|
||||
formatters:
|
||||
colored:
|
||||
(): mautrix_telegram.util.ColorFormatter
|
||||
format: "[%(asctime)s] [%(levelname)s@%(name)s] %(message)s"
|
||||
normal:
|
||||
format: "[%(asctime)s] [%(levelname)s@%(name)s] %(message)s"
|
||||
handlers:
|
||||
file:
|
||||
class: logging.handlers.RotatingFileHandler
|
||||
formatter: normal
|
||||
filename: ./mautrix-telegram.log
|
||||
maxBytes: 10485760
|
||||
backupCount: 10
|
||||
console:
|
||||
class: logging.StreamHandler
|
||||
formatter: colored
|
||||
loggers:
|
||||
mau:
|
||||
level: DEBUG
|
||||
telethon:
|
||||
level: INFO
|
||||
aiohttp:
|
||||
level: INFO
|
||||
root:
|
||||
level: DEBUG
|
||||
handlers: [file, console]
|
||||
@@ -1,380 +0,0 @@
|
||||
# -*- coding: future_fstrings -*-
|
||||
# mautrix-telegram - A Matrix-Telegram puppeting bridge
|
||||
# Copyright (C) 2018 Tulir Asokan
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from html import escape, unescape
|
||||
from html.parser import HTMLParser
|
||||
from collections import deque
|
||||
import re
|
||||
import logging
|
||||
|
||||
from mautrix_appservice import MatrixRequestError
|
||||
|
||||
from telethon.tl.types import *
|
||||
|
||||
from . import user as u, puppet as p
|
||||
from .db import Message as DBMessage
|
||||
|
||||
log = logging.getLogger("mau.formatter")
|
||||
|
||||
# TEXT LEN EXPLANATION:
|
||||
# Telegram formatting counts two bytes in an UTF-16 string as one character.
|
||||
#
|
||||
# For Telegram -> Matrix formatting, we get the same counting mechanism by encoding the input
|
||||
# text as UTF-16 Little Endian and doubling all the offsets and lengths given by Telegram. With
|
||||
# those doubled values, we process the input entities and text. The text is converted back to
|
||||
# native str format before it's inserted into the output HTML.
|
||||
#
|
||||
# For Matrix -> Telegram formatting, do the same input encoding, but divide the length by two
|
||||
# instead of multiplying when generating the lengths and offsets of Telegram entities.
|
||||
#
|
||||
# The endianness doesn't matter, but it has to be specified to avoid the two BOM bits messing
|
||||
# everything up.
|
||||
TEMP_ENC = "utf-16-le"
|
||||
|
||||
|
||||
# region Matrix to Telegram
|
||||
|
||||
|
||||
class MatrixParser(HTMLParser):
|
||||
mention_regex = re.compile("https://matrix.to/#/(@.+)")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.text = ""
|
||||
self.entities = []
|
||||
self._building_entities = {}
|
||||
self._list_counter = 0
|
||||
self._open_tags = deque()
|
||||
self._open_tags_meta = deque()
|
||||
self._previous_ended_line = True
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
self._open_tags.appendleft(tag)
|
||||
self._open_tags_meta.appendleft(0)
|
||||
attrs = dict(attrs)
|
||||
entity_type = None
|
||||
args = {}
|
||||
if tag == "strong" or tag == "b":
|
||||
entity_type = MessageEntityBold
|
||||
elif tag == "em" or tag == "i":
|
||||
entity_type = MessageEntityItalic
|
||||
elif tag == "code":
|
||||
try:
|
||||
pre = self._building_entities["pre"]
|
||||
try:
|
||||
pre.language = attrs["class"][len("language-"):]
|
||||
except KeyError:
|
||||
pass
|
||||
except KeyError:
|
||||
entity_type = MessageEntityCode
|
||||
elif tag == "pre":
|
||||
entity_type = MessageEntityPre
|
||||
args["language"] = ""
|
||||
elif tag == "a":
|
||||
try:
|
||||
url = attrs["href"]
|
||||
except KeyError:
|
||||
return
|
||||
mention = self.mention_regex.search(url)
|
||||
if mention:
|
||||
mxid = mention.group(1)
|
||||
user = p.Puppet.get_by_mxid(mxid, create=False)
|
||||
if not user:
|
||||
user = u.User.get_by_mxid(mxid, create=False)
|
||||
if not user:
|
||||
return
|
||||
if user.username:
|
||||
entity_type = MessageEntityMention
|
||||
url = f"@{user.username}"
|
||||
else:
|
||||
entity_type = MessageEntityMentionName
|
||||
args["user_id"] = user.tgid
|
||||
elif url.startswith("mailto:"):
|
||||
url = url[len("mailto:"):]
|
||||
entity_type = MessageEntityEmail
|
||||
else:
|
||||
if self.get_starttag_text() == url:
|
||||
entity_type = MessageEntityUrl
|
||||
else:
|
||||
entity_type = MessageEntityTextUrl
|
||||
args["url"] = url
|
||||
url = None
|
||||
self._open_tags_meta.popleft()
|
||||
self._open_tags_meta.appendleft(url)
|
||||
|
||||
if entity_type and tag not in self._building_entities:
|
||||
# See "TEXT LEN EXPLANATION" near start of file
|
||||
offset = int(len(self.text.encode(TEMP_ENC)) / 2)
|
||||
self._building_entities[tag] = entity_type(offset=offset, length=0, **args)
|
||||
|
||||
def _list_depth(self):
|
||||
depth = 0
|
||||
for tag in self._open_tags:
|
||||
if tag == "ol" or tag == "ul":
|
||||
depth += 1
|
||||
return depth
|
||||
|
||||
def handle_data(self, text):
|
||||
text = unescape(text)
|
||||
previous_tag = self._open_tags[0] if len(self._open_tags) > 0 else ""
|
||||
list_format_offset = 0
|
||||
if previous_tag == "a":
|
||||
url = self._open_tags_meta[0]
|
||||
if url:
|
||||
text = url
|
||||
elif len(self._open_tags) > 1 and self._previous_ended_line and previous_tag == "li":
|
||||
list_type = self._open_tags[1]
|
||||
indent = (self._list_depth() - 1) * 4 * " "
|
||||
text = text.strip("\n")
|
||||
if len(text) == 0:
|
||||
return
|
||||
elif list_type == "ul":
|
||||
text = f"{indent}* {text}"
|
||||
list_format_offset = len(indent) + 2
|
||||
elif list_type == "ol":
|
||||
n = self._open_tags_meta[1]
|
||||
n += 1
|
||||
self._open_tags_meta[1] = n
|
||||
text = f"{indent}{n}. {text}"
|
||||
list_format_offset = len(indent) + 3
|
||||
for tag, entity in self._building_entities.items():
|
||||
# See "TEXT LEN EXPLANATION" near start of file
|
||||
entity.length += int(len(text.strip("\n").encode(TEMP_ENC)) / 2)
|
||||
entity.offset += list_format_offset
|
||||
|
||||
if text.endswith("\n"):
|
||||
self._previous_ended_line = True
|
||||
else:
|
||||
self._previous_ended_line = False
|
||||
|
||||
self.text += text
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
try:
|
||||
self._open_tags.popleft()
|
||||
self._open_tags_meta.popleft()
|
||||
except IndexError:
|
||||
pass
|
||||
if (tag == "ul" or tag == "ol") and self.text.endswith("\n"):
|
||||
self.text = self.text[:-1]
|
||||
entity = self._building_entities.pop(tag, None)
|
||||
if entity:
|
||||
self.entities.append(entity)
|
||||
|
||||
|
||||
def matrix_to_telegram(html):
|
||||
try:
|
||||
parser = MatrixParser()
|
||||
parser.feed(html)
|
||||
return parser.text, parser.entities
|
||||
except Exception:
|
||||
log.exception("Failed to convert Matrix format:\nhtml=%s", html)
|
||||
|
||||
|
||||
def matrix_reply_to_telegram(content, tg_space, room_id=None):
|
||||
try:
|
||||
reply = content["m.relates_to"]["m.in_reply_to"]
|
||||
room_id = room_id or reply["room_id"]
|
||||
event_id = reply["event_id"]
|
||||
message = DBMessage.query.filter(DBMessage.mxid == event_id and
|
||||
DBMessage.tg_space == tg_space and
|
||||
DBMessage.mx_room == room_id).one_or_none()
|
||||
if message:
|
||||
return message.tgid
|
||||
except KeyError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
# endregion
|
||||
# region Telegram to Matrix
|
||||
|
||||
def telegram_reply_to_matrix(evt, source):
|
||||
if evt.reply_to_msg_id:
|
||||
space = (evt.to_id.channel_id
|
||||
if isinstance(evt, Message) and isinstance(evt.to_id, PeerChannel)
|
||||
else source.tgid)
|
||||
msg = DBMessage.query.get((evt.reply_to_msg_id, space))
|
||||
if msg:
|
||||
return {
|
||||
"m.in_reply_to": {
|
||||
"event_id": msg.mxid,
|
||||
"room_id": msg.mx_room,
|
||||
}
|
||||
}
|
||||
return {}
|
||||
|
||||
|
||||
async def telegram_event_to_matrix(evt, source, native_replies=False, message_link_in_reply=False,
|
||||
main_intent=None, reply_text="Reply"):
|
||||
text = evt.message
|
||||
html = telegram_to_matrix(evt.message, evt.entities) if evt.entities else None
|
||||
relates_to = {}
|
||||
|
||||
if evt.fwd_from:
|
||||
if not html:
|
||||
html = escape(text)
|
||||
from_id = evt.fwd_from.from_id
|
||||
user = u.User.get_by_tgid(from_id)
|
||||
if user:
|
||||
fwd_from = f"<a href='https://matrix.to/#/{user.mxid}'>{user.mxid}</a>"
|
||||
else:
|
||||
puppet = p.Puppet.get(from_id, create=False)
|
||||
if puppet and puppet.displayname:
|
||||
fwd_from = f"<a href='https://matrix.to/#/{puppet.mxid}'>{puppet.displayname}</a>"
|
||||
else:
|
||||
user = await source.client.get_entity(from_id)
|
||||
if user:
|
||||
fwd_from = p.Puppet.get_displayname(user, format=False)
|
||||
else:
|
||||
fwd_from = None
|
||||
if not fwd_from:
|
||||
fwd_from = "Unknown user"
|
||||
html = (f"Forwarded message from <b>{fwd_from}</b><br/>"
|
||||
+ f"<blockquote>{html}</blockquote>")
|
||||
|
||||
if evt.reply_to_msg_id:
|
||||
space = (evt.to_id.channel_id
|
||||
if isinstance(evt, Message) and isinstance(evt.to_id, PeerChannel)
|
||||
else source.tgid)
|
||||
msg = DBMessage.query.get((evt.reply_to_msg_id, space))
|
||||
if msg:
|
||||
if native_replies:
|
||||
relates_to["m.in_reply_to"] = {
|
||||
"event_id": msg.mxid,
|
||||
"room_id": msg.mx_room,
|
||||
}
|
||||
if reply_text == "Edit":
|
||||
html = "<u>Edit:</u> " + (html or escape(text))
|
||||
else:
|
||||
try:
|
||||
event = await main_intent.get_event(msg.mx_room, msg.mxid)
|
||||
content = event["content"]
|
||||
body = (content["formatted_body"]
|
||||
if "formatted_body" in content
|
||||
else content["body"])
|
||||
sender = event['sender']
|
||||
puppet = p.Puppet.get_by_mxid(sender, create=False)
|
||||
displayname = puppet.displayname if puppet else sender
|
||||
reply_to_user = f"<a href='https://matrix.to/#/{sender}'>{displayname}</a>"
|
||||
reply_to_msg = (("<a href='https://matrix.to/#/"
|
||||
+ f"{msg.mx_room}/{msg.mxid}'>{reply_text}</a>")
|
||||
if message_link_in_reply else "Reply")
|
||||
quote = f"{reply_to_msg} to {reply_to_user}<blockquote>{body}</blockquote>"
|
||||
except (ValueError, KeyError, MatrixRequestError):
|
||||
quote = "{reply_text} to unknown user <em>(Failed to fetch message)</em>:<br/>"
|
||||
if html:
|
||||
html = quote + html
|
||||
else:
|
||||
html = quote + escape(text)
|
||||
|
||||
if isinstance(evt, Message) and evt.post and evt.post_author:
|
||||
if not html:
|
||||
html = escape(text)
|
||||
text += f"\n- {evt.post_author}"
|
||||
html += f"<br/><i>- <u>{evt.post_author}</u></i>"
|
||||
|
||||
if html:
|
||||
html = html.replace("\n", "<br/>")
|
||||
|
||||
return text, html, relates_to
|
||||
|
||||
|
||||
def telegram_to_matrix(text, entities):
|
||||
try:
|
||||
return _telegram_to_matrix(text, entities)
|
||||
except Exception:
|
||||
log.exception("Failed to convert Telegram format:\n"
|
||||
"message=%s\n"
|
||||
"entities=%s",
|
||||
text, entities)
|
||||
|
||||
|
||||
def _telegram_to_matrix(text, entities):
|
||||
if not entities:
|
||||
return text
|
||||
# See "TEXT LEN EXPLANATION" near start of file
|
||||
text = text.encode(TEMP_ENC)
|
||||
html = []
|
||||
last_offset = 0
|
||||
for entity in entities:
|
||||
entity.offset *= 2
|
||||
entity.length *= 2
|
||||
if entity.offset > last_offset:
|
||||
html.append(escape(text[last_offset:entity.offset].decode(TEMP_ENC)))
|
||||
elif entity.offset < last_offset:
|
||||
continue
|
||||
|
||||
skip_entity = False
|
||||
entity_text = escape(text[entity.offset:entity.offset + entity.length].decode(TEMP_ENC))
|
||||
entity_type = type(entity)
|
||||
|
||||
if entity_type == MessageEntityBold:
|
||||
html.append(f"<strong>{entity_text}</strong>")
|
||||
elif entity_type == MessageEntityItalic:
|
||||
html.append(f"<em>{entity_text}</em>")
|
||||
elif entity_type == MessageEntityCode:
|
||||
html.append(f"<code>{entity_text}</code>")
|
||||
elif entity_type == MessageEntityPre:
|
||||
if entity.language:
|
||||
html.append("<pre>"
|
||||
+ f"<code class='language-{entity.language}'>{entity_text}</code>"
|
||||
+ "</pre>")
|
||||
else:
|
||||
html.append(f"<pre><code>{entity_text}</code></pre>")
|
||||
elif entity_type == MessageEntityMention:
|
||||
username = entity_text[1:]
|
||||
|
||||
user = u.User.find_by_username(username)
|
||||
if user:
|
||||
mxid = user.mxid
|
||||
else:
|
||||
puppet = p.Puppet.find_by_username(username)
|
||||
mxid = puppet.mxid if puppet else None
|
||||
if mxid:
|
||||
html.append(f"<a href='https://matrix.to/#/{mxid}'>{entity_text}</a>")
|
||||
else:
|
||||
skip_entity = True
|
||||
elif entity_type == MessageEntityMentionName:
|
||||
user = u.User.get_by_tgid(entity.user_id)
|
||||
if user:
|
||||
mxid = user.mxid
|
||||
else:
|
||||
puppet = p.Puppet.get(entity.user_id, create=False)
|
||||
mxid = puppet.mxid if puppet else None
|
||||
if mxid:
|
||||
html.append(f"<a href='https://matrix.to/#/{mxid}'>{entity_text}</a>")
|
||||
else:
|
||||
skip_entity = True
|
||||
elif entity_type == MessageEntityEmail:
|
||||
html.append(f"<a href='mailto:{entity_text}'>{entity_text}</a>")
|
||||
elif entity_type in {MessageEntityTextUrl, MessageEntityUrl}:
|
||||
url = escape(entity.url) if entity_type == MessageEntityTextUrl else entity_text
|
||||
if not url.startswith(("https://", "http://", "ftp://", "magnet://")):
|
||||
url = "http://" + url
|
||||
html.append(f"<a href='{url}'>{entity_text}</a>")
|
||||
elif entity_type == MessageEntityBotCommand:
|
||||
html.append(f"<font color='blue'>!{entity_text[1:]}")
|
||||
elif entity_type == MessageEntityHashtag:
|
||||
html.append(f"<font color='blue'>{entity_text}</font>")
|
||||
else:
|
||||
skip_entity = True
|
||||
last_offset = entity.offset + (0 if skip_entity else entity.length)
|
||||
html.append(text[last_offset:].decode(TEMP_ENC))
|
||||
|
||||
return "".join(html)
|
||||
|
||||
# endregion
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user