Compare commits
951 Commits
Author | SHA1 | Date |
---|---|---|
Alexei Stukov | 835cc3134c | |
Jiiks | 02b30153ee | |
Alexei Stukov | d09dc5a2a5 | |
Mega-Mewthree | 98d9a30027 | |
Alexei Stukov | 5cb4bc15bd | |
Alexei Stukov | bb2aba04d5 | |
Samuel Elliott | 82e9b0bd6a | |
Samuel Elliott | 47575d3449 | |
Samuel Elliott | 32e2582ded | |
Samuel Elliott | d58dda6f50 | |
Samuel Elliott | 648954d533 | |
Samuel Elliott | 4aa38f4582 | |
Samuel Elliott | b3ba1aef13 | |
Samuel Elliott | 2a6cbd39b7 | |
Samuel Elliott | ce5bcb9b85 | |
Samuel Elliott | 5a3821ad3e | |
Samuel Elliott | fd0032b24c | |
Samuel Elliott | 226719b36e | |
Samuel Elliott | fcfee53928 | |
Samuel Elliott | 285ae34b50 | |
Alexei Stukov | a170a97688 | |
Samuel Elliott | a770f57b28 | |
Samuel Elliott | 5757fc20c9 | |
Samuel Elliott | 421289f63b | |
Samuel Elliott | ac85316578 | |
Samuel Elliott | 08af9be061 | |
Samuel Elliott | ead0fbbd1e | |
Samuel Elliott | dc85a808f8 | |
Samuel Elliott | aecfa814f9 | |
Samuel Elliott | 436f3d3c36 | |
Alexei Stukov | 68a8187964 | |
Alexei Stukov | f30e4c12fe | |
Alexei Stukov | 686514ed1d | |
Alexei Stukov | d795da1750 | |
Alexei Stukov | 3219ff7c6e | |
Alexei Stukov | 33567a2cfd | |
Jiiks | 85310bfbff | |
Jiiks | d1d79a37b7 | |
Jiiks | d95592acc9 | |
Jiiks | f6a3fb65da | |
Alexei Stukov | 6788cca363 | |
Lars van der Zande | 1fb442e096 | |
Jiiks | 6e64ff61c5 | |
Jiiks | dd8fe68a11 | |
Jiiks | a3829089f9 | |
Jiiks | 174c1ee791 | |
Jiiks | b8793fd2b6 | |
Jiiks | 31986ca3a0 | |
Jiiks | 10ff740f75 | |
Jiiks | 83fbab63c0 | |
Jiiks | c4670946e6 | |
Jiiks | e5239d952e | |
Jiiks | a57783a9d8 | |
Jiiks | 001a6e4fda | |
Jiiks | dd621038f9 | |
Jiiks | 288c233447 | |
Jiiks | 399c6e792b | |
Jiiks | 0be6facba4 | |
Jiiks | dc7247a12d | |
Jiiks | 377c4fd104 | |
Jiiks | 252d496dc2 | |
Jiiks | 83e334c3f8 | |
Jiiks | e72ad10dfc | |
Jiiks | 9ef392c575 | |
Jiiks | 76057efbb7 | |
Jiiks | dcb121750a | |
Jiiks | 13fa769e9e | |
Jiiks | 3143991239 | |
Jiiks | 1ae0c5aa4d | |
Jiiks | 5ea39f86f7 | |
Jiiks | d6a946e096 | |
Jiiks | b68c1fbd04 | |
Jiiks | 07d3629622 | |
Jiiks | 15daa9acef | |
Jiiks | 817a4a03b6 | |
Jiiks | e63386e9eb | |
Jiiks | 402acdfea9 | |
Jiiks | b440206d07 | |
Jiiks | c7bea4a743 | |
Jiiks | 2528d87b8f | |
Alexei Stukov | 405d74fada | |
Alexei Stukov | b311220132 | |
Alexei Stukov | 66b47457b1 | |
Alexei Stukov | 6e9f9f8bf8 | |
Alexei Stukov | 88a113dc8f | |
Alexei Stukov | a61f860466 | |
Jiiks | 729a4607bd | |
Jiiks | d81dcc9aa2 | |
Jiiks | 1e4f3fa82b | |
Alexei Stukov | 150a1d63c4 | |
Jiiks | 6b481733b9 | |
Jiiks | e07b9b1550 | |
Jiiks | 99c2b53ec6 | |
Jiiks | 2a93e5d2a3 | |
Jiiks | 3661207602 | |
Jiiks | 92845728cc | |
Jiiks | c99753fc8c | |
Jiiks | 688e6022a0 | |
Jiiks | 5408d994be | |
Zack Rauen | 003c9766bc | |
Zack Rauen | 82e9c257ce | |
Jiiks | 6167cc7c4b | |
Jiiks | 1bacecf8d4 | |
Jiiks | d102686379 | |
Jiiks | 1160955629 | |
Jiiks | e60f765a50 | |
Alexei Stukov | d3db696616 | |
Jiiks | b8d16c6e4d | |
Jiiks | b22923d12f | |
Jiiks | 1ea307efdd | |
Jiiks | d98cff878f | |
Jiiks | dd11708f9f | |
Jiiks | 665a7818c9 | |
Jiiks | d75b907ae4 | |
Alexei Stukov | f051bc4812 | |
Jiiks | 9773f78506 | |
Alexei Stukov | f4b7c99c31 | |
Jiiks | 97519b2307 | |
Jiiks | 806ca5028a | |
Jiiks | db89e3a1a0 | |
Jiiks | 6030a78b91 | |
Jiiks | 99ec82795c | |
Jiiks | b1e8b591ba | |
Jiiks | ac9e16632d | |
Jiiks | d8f977b57a | |
Jiiks | c3283c47f6 | |
Jiiks | 2b86f2d741 | |
Jiiks | 9f6389845a | |
Jiiks | 7489fd0aaf | |
Jiiks | 7e1c379fd3 | |
Jiiks | c0765120e8 | |
Jiiks | 7e10de32cb | |
Jiiks | 145d61fe5e | |
Jiiks | 72b278de6e | |
Jiiks | 5e977e8dc4 | |
Jiiks | 109eb31aa5 | |
Jiiks | 1b6f3005f5 | |
Jiiks | d02f894d4a | |
Jiiks | 20561e2938 | |
Jiiks | a3724d739b | |
Jiiks | cf1da34e16 | |
Jiiks | 5454950838 | |
Jiiks | ed7abe3571 | |
Jiiks | b14bf93ef9 | |
Jiiks | 3436bbe52b | |
Jiiks | 1a26e77dd9 | |
Jiiks | da1fc0a2f0 | |
Jiiks | d1fd5ae881 | |
Jiiks | 8c04e7d2d3 | |
Jiiks | 3fc1adc503 | |
Jiiks | 691c9f378a | |
Jiiks | a769385219 | |
Jiiks | f1f23fa220 | |
Jiiks | 99ef0d9f81 | |
Jiiks | 5597c485d1 | |
Jiiks | 7f08ba27e6 | |
Jiiks | 99614aecdc | |
Alexei Stukov | 726db7f0c9 | |
Zack Rauen | 67c39fd9d9 | |
Jiiks | 23d4eb77b2 | |
Jiiks | 124ec078aa | |
Jiiks | e6c9bc447e | |
Jiiks | 7bc4b652fa | |
Alexei Stukov | 6ab1f5c844 | |
Alexei Stukov | 816ff2ed08 | |
Jiiks | 6ca36ebbb5 | |
Jiiks | f511e4556e | |
Alexei Stukov | 36515432c7 | |
Alexei Stukov | 47782c0168 | |
Jiiks | 3a370f2827 | |
Jiiks | 90f5596cb2 | |
Jiiks | 75439a600e | |
Alexei Stukov | f46960fdd0 | |
Alexei Stukov | f684780842 | |
Jiiks | 6c8631f1cd | |
Jiiks | 0311602539 | |
Jiiks | b5e8098d20 | |
Jiiks | 111be57b59 | |
Jiiks | 76e19c8469 | |
Jiiks | ccff016820 | |
Jiiks | 021e282b1c | |
Jiiks | 6699fcc1e7 | |
Jiiks | f3ea192974 | |
Jiiks | 9c1a93f4c1 | |
Jiiks | 2c23f18e89 | |
Jiiks | c88d2cdae9 | |
Alexei Stukov | 8235e55357 | |
Alexei Stukov | 754e6bbd72 | |
Alexei Stukov | e27d8874ef | |
Alexei Stukov | c310cc52d5 | |
Jiiks | 073cce825d | |
Alexei Stukov | a04fb59db7 | |
Alexei Stukov | f8ed871f8e | |
Alexei Stukov | fae97613d1 | |
Jiiks | 27df24f369 | |
Jiiks | 5bb95f59c0 | |
Alexei Stukov | bcabaab14c | |
Alexei Stukov | 033f3472cb | |
Alexei Stukov | 8fbd75ce94 | |
Alexei Stukov | 3a38b59a4d | |
Alexei Stukov | c29b659afb | |
Alexei Stukov | ece161fac0 | |
Lilian Tedone | b57ab92269 | |
Alexei Stukov | 5a3aa553cd | |
Jiiks | a2f48dd007 | |
Jiiks | 4f10f38581 | |
Jiiks | ea0dc0c6f1 | |
Jiiks | 93f536bf21 | |
Jiiks | 497ab62ee6 | |
Jiiks | 784a14f853 | |
Jiiks | 95447dd3f0 | |
Jiiks | 2cff8edb59 | |
Jiiks | e4c0796e5e | |
Jiiks | e3010fcd43 | |
Jiiks | 08b66d5e5a | |
Jiiks | c618956639 | |
Jiiks | c6ddb75630 | |
Jiiks | 1fd7b97ce6 | |
Jiiks | fa5be193ad | |
Jiiks | 63874c8b4e | |
Jiiks | b4dbfcd808 | |
Jiiks | 7a9b72a33a | |
Jiiks | 6db34b9cee | |
Alexei Stukov | ead51ae676 | |
Jiiks | 9a77aae56b | |
Jiiks | 3182f28359 | |
Jiiks | a274b0c839 | |
Jiiks | 199b9249e4 | |
Jiiks | 08ba649a91 | |
Jiiks | a0eb43188f | |
Jiiks | b1bd5190c1 | |
Jiiks | 7fb5c8a378 | |
Jiiks | 26b1fad5a4 | |
Jiiks | f028aefab8 | |
Jiiks | f0d66300c4 | |
Jiiks | 12b291cf0b | |
Jiiks | a8f686eb61 | |
Jiiks | 98bf4d21ac | |
Jiiks | d5a82ab2b3 | |
Jiiks | d5d7709c9f | |
Jiiks | cfc197cdc0 | |
Jiiks | e8cfb840fe | |
Jiiks | f01f4926eb | |
Jiiks | 83a4e0a114 | |
Jiiks | 4b8a905d2a | |
Alexei Stukov | 08ae8dceb5 | |
Jiiks | ad28e7c638 | |
Jiiks | 9ba8047066 | |
Alexei Stukov | 9ba9ec1556 | |
Jiiks | ce2658b6e2 | |
Jiiks | f3cc033182 | |
Jiiks | 7b44d163ca | |
Alexei Stukov | 72d24a1cb0 | |
Alexei Stukov | c2c520fe27 | |
Samuel Elliott | ad55459649 | |
Samuel Elliott | dfac3f1825 | |
Samuel Elliott | adecbf8945 | |
Samuel Elliott | a371fabc70 | |
Samuel Elliott | c04ffdfc24 | |
Samuel Elliott | 572721c57f | |
Samuel Elliott | 4af09224d7 | |
Samuel Elliott | 7f1ac9bea0 | |
Samuel Elliott | ce93b2b4c6 | |
Samuel Elliott | d98ed6649e | |
Zack Rauen | 468422084a | |
Alexei Stukov | 395167aafa | |
Alexei Stukov | 803cf59f11 | |
Alexei Stukov | 133511aeec | |
Zack Rauen | be024c1bbe | |
Zack Rauen | 6f10c71623 | |
Zack Rauen | adb2430d71 | |
Alexei Stukov | 990453cdad | |
Jiiks | 7cf69f6993 | |
Jiiks | 5822110c87 | |
Jiiks | 669a88c1ff | |
Jiiks | 6a8c77b578 | |
Jiiks | a93d12df03 | |
Jiiks | 80096c5e71 | |
Jiiks | 307b084214 | |
Jiiks | 1e0f3b69fb | |
Jiiks | 550d0d3c40 | |
Jiiks | 96f8fe680f | |
Jiiks | b48adc7a62 | |
Jiiks | 6db016060b | |
Jiiks | ecb0b3e9d0 | |
Jiiks | 8c060314da | |
Jiiks | a040a605d4 | |
Jiiks | 09fb76d148 | |
Jiiks | ddda5b3cc1 | |
Jiiks | cff425f916 | |
Jiiks | 76d54f0a95 | |
Jiiks | 2093c472b5 | |
Jiiks | 1009c62ea0 | |
Jiiks | 2cd94fcd5f | |
Jiiks | cb35b14311 | |
Jiiks | 6b3cb712c7 | |
Jiiks | cfbafffe46 | |
Jiiks | 2913a85368 | |
Jiiks | 5c160d75a6 | |
Jiiks | f14b1b71e7 | |
Jiiks | 4e3a56e466 | |
Alexei Stukov | 30716b57e6 | |
Jiiks | b18559aa5e | |
Jiiks | 6d8ef35bd6 | |
Jiiks | 8146e0e7f2 | |
Jiiks | 23b8e2dd76 | |
Jiiks | e12dc28052 | |
Jiiks | 6538442b0b | |
Jiiks | 4a9cc603d2 | |
Jiiks | d4aa8fb377 | |
Jiiks | 977fd80d0c | |
Alexei Stukov | ad64743874 | |
Jiiks | 436c469b1d | |
Alexei Stukov | 7d05d0c884 | |
Jiiks | 1afbcacec3 | |
Jiiks | 9b5464b9a5 | |
Jiiks | da8e912a95 | |
Jiiks | a4cbfd9235 | |
Jiiks | 5e0c5e39f6 | |
Jiiks | e798e3d6e2 | |
Jiiks | 937ab55456 | |
Jiiks | aa0882c449 | |
Jiiks | f5b70d5a23 | |
Jiiks | 6d818f40d2 | |
Jiiks | 6a5f185c80 | |
Jiiks | 62b7679408 | |
Jiiks | c11aa205a3 | |
Jiiks | 47af7a5da6 | |
Jiiks | 89b645b334 | |
Alexei Stukov | 62c9fe6011 | |
Alexei Stukov | a45c39ed91 | |
Alexei Stukov | f35d206044 | |
Jiiks | f46694f2d0 | |
Jiiks | 5c493d413b | |
Jiiks | 32fc655326 | |
Jiiks | 9cf63c2cfa | |
Jiiks | b59c919733 | |
Jiiks | e66af1e1d2 | |
Jiiks | f1cf802746 | |
Jiiks | d1387f5183 | |
Jiiks | 9190b208eb | |
Jiiks | fdd934ae0c | |
Jiiks | b1c8070fc3 | |
Jiiks | 56753d3614 | |
Alexei Stukov | 66966e6729 | |
Aphypnise | 0f7639da6d | |
Samuel Elliott | 2a81054f64 | |
Alexei Stukov | 22ea3ff2ad | |
Jiiks | d3e76a1c2d | |
Jiiks | 72326d220e | |
Samuel Elliott | 52dfaf18c1 | |
Samuel Elliott | 40acb33bbd | |
Samuel Elliott | 74d5d3540f | |
Alexei Stukov | 3ba90705ff | |
Samuel Elliott | 6c14f80791 | |
Samuel Elliott | 5fa964ed50 | |
Alexei Stukov | da28828880 | |
Samuel Elliott | 21c8c6d267 | |
Samuel Elliott | 5868b4f0f9 | |
Samuel Elliott | d53afe2538 | |
Samuel Elliott | 96b7e8d859 | |
Samuel Elliott | 60e42cea07 | |
Samuel Elliott | 43ec860bfe | |
Samuel Elliott | 1f971c7490 | |
Samuel Elliott | 5e7de49999 | |
Samuel Elliott | 35c1ab93a0 | |
Samuel Elliott | a85107cc51 | |
Samuel Elliott | 46dae11085 | |
Samuel Elliott | c885e4ceda | |
Samuel Elliott | 26bce739d7 | |
Samuel Elliott | 3747417865 | |
Samuel Elliott | 4c0248ca00 | |
Samuel Elliott | fd9c03ac2f | |
Samuel Elliott | d11e8d4fe2 | |
Samuel Elliott | 56a807f294 | |
Samuel Elliott | cf71f89077 | |
Samuel Elliott | 3ff077ea04 | |
Samuel Elliott | 697df8a7fe | |
Samuel Elliott | c2ccfd02da | |
Alexei Stukov | 1e9b1618f1 | |
Jiiks | d92da4b6e4 | |
Samuel Elliott | 67debca9d9 | |
Samuel Elliott | a0bee1846e | |
Samuel Elliott | 73192f5762 | |
Alexei Stukov | a1e32f8b89 | |
Jiiks | 2002db7807 | |
Jiiks | 07374ceeee | |
Samuel Elliott | d02be1521d | |
Jiiks | 5c92f3e3e0 | |
Jiiks | 41a5a3a791 | |
Samuel Elliott | 42a89129d4 | |
Jiiks | 2617925cd8 | |
Jiiks | 7a0b6e9262 | |
Jiiks | 3f5c168ffc | |
Jiiks | 09d9f50160 | |
Jiiks | d274fda428 | |
Jiiks | 58a2b6714e | |
Jiiks | 4c3659f857 | |
Jiiks | b8dc9c0d25 | |
Jiiks | c4f28a6ac5 | |
Jiiks | 1ab52cb174 | |
Jiiks | f315c8b134 | |
Jiiks | 8bfac0f6ff | |
Samuel Elliott | 4bed9f726c | |
Jiiks | 0145492773 | |
Samuel Elliott | 2188c22425 | |
Jiiks | e9c419529d | |
Samuel Elliott | 6ee647b249 | |
Samuel Elliott | 5676435473 | |
Samuel Elliott | 8cf28fcaba | |
Samuel Elliott | 237899c91a | |
Samuel Elliott | 73e4e83ced | |
Alexei Stukov | 5b63667bc2 | |
Alexei Stukov | 00ce5d70c9 | |
Alexei Stukov | b3d14d853c | |
Alexei Stukov | c1af0c6115 | |
Alexei Stukov | f3bb7aac96 | |
Jiiks | cd84f6329a | |
Jiiks | b4fa9c2934 | |
Jiiks | 9db6ddaf98 | |
Jiiks | ed55e060aa | |
Jiiks | bb37b89d35 | |
Jiiks | 07fc98670c | |
Jiiks | 25aecf82a6 | |
Jiiks | 242fbfaaa7 | |
Jiiks | ef5a1c223c | |
Jiiks | 8637f176c1 | |
Jiiks | 4c5300be12 | |
Zack Rauen | 1ccd7766bc | |
Maks-s | 9711c99217 | |
Maks | 10f45b6b4c | |
Maks | 7c44b92bce | |
Zack Rauen | 4784b13c86 | |
Zack Rauen | a8c8c017f6 | |
Zack Rauen | c98e4430b1 | |
Zack Rauen | adf94990c2 | |
Maks-s | e78021a538 | |
Alexei Stukov | 3c38ecdd97 | |
Jiiks | 12021fcf15 | |
Jiiks | 1031ab3a18 | |
Jiiks | e75c575a32 | |
Jiiks | 9c91222fff | |
Jiiks | d0eb2a441a | |
Jiiks | 5c6d544562 | |
Jiiks | ceca53a75d | |
Jiiks | 6eaed063ec | |
Jiiks | bc5eb1b5f0 | |
Jiiks | 1a11eb6a6b | |
Jiiks | cff67a3b1d | |
Jiiks | 3518ac7cb2 | |
Jiiks | f2d7ef41da | |
Jiiks | 87e0f132d1 | |
Alexei Stukov | 9306018111 | |
Zack Rauen | 19d33a44ea | |
Alexei Stukov | e755b60807 | |
Jiiks | f50bcd0785 | |
Jiiks | fc6481acae | |
Jiiks | de0651bb47 | |
Alexei Stukov | 358b1e8bf3 | |
Jiiks | 84b94c614e | |
Jiiks | 3fa848bb5a | |
Jiiks | 533566fde8 | |
Jiiks | 6ab1adfe5b | |
Jiiks | 205dcf6ff1 | |
Jiiks | beaee8764c | |
Alexei Stukov | d22188ea2a | |
Jiiks | 53ef0be7b8 | |
Jiiks | e3edb09f38 | |
Jiiks | 316f3c1bb0 | |
Jiiks | 6948335ea7 | |
Jiiks | 25decd0514 | |
Jiiks | a35c75717e | |
Jiiks | 8d6d3c9e18 | |
Jiiks | 91df5350ad | |
Jiiks | 22740fb16c | |
Jiiks | 0316bbc1cd | |
Jiiks | 8bac53e9be | |
Alexei Stukov | 42e2569569 | |
Alexei Stukov | dd81201a95 | |
Jiiks | 805e1ce771 | |
Zack Rauen | 322badd209 | |
Alexei Stukov | 8438d32ce9 | |
Jiiks | 3446ed2d6b | |
Jiiks | 6a51834f82 | |
Jiiks | 89461244bd | |
Jiiks | b1847b8c41 | |
Jiiks | 11eed2c89d | |
Jiiks | b971b716bf | |
Jiiks | 9f8a1f08be | |
Jiiks | c1ac349211 | |
Jiiks | 1804fcfbe1 | |
Jiiks | 303addae42 | |
Jiiks | 9e80f7b051 | |
Jiiks | 0e32d835ef | |
Alexei Stukov | 462b198895 | |
Jiiks | 34e2833555 | |
Alexei Stukov | 8b180ea423 | |
Jiiks | a90400c280 | |
Jiiks | e49a1932f3 | |
Jiiks | abf83821d9 | |
Jiiks | 6ed50c4206 | |
Jiiks | edab8dd93b | |
Jiiks | ab03633431 | |
Jiiks | 67b554c68f | |
Jiiks | 68f3a280a5 | |
Jiiks | 5db4f8cf26 | |
Jiiks | 3e57d0092a | |
Jiiks | 36408d74ad | |
Jiiks | 9aa9305755 | |
Jiiks | 6f9cdb9dda | |
Jiiks | 0aa370aeb9 | |
Jiiks | 27fee8e10c | |
Jiiks | ac1e4ad9a2 | |
Jiiks | 73f2fe4fd0 | |
Jiiks | 8b4318c06e | |
Jiiks | 7636ea480d | |
Jiiks | 54e5f2149b | |
Jiiks | b1f0a4247a | |
Jiiks | 8d6cdafc23 | |
Jiiks | 5711576a0d | |
Jiiks | 6df9b1e019 | |
Jiiks | c2e7abcfca | |
Jiiks | b6c58f16e7 | |
Jiiks | b47a3c65aa | |
Alexei Stukov | 0315d610e0 | |
Zack Rauen | 3714e71297 | |
Mega-Mewthree | 9f4b0aec6b | |
Mega-Mewthree | 0ea5bc2dcc | |
Mega-Mewthree | 64608c7e62 | |
Mega-Mewthree | 2d8c0a5306 | |
Mega-Mewthree | 81c451d31f | |
Jiiks | d04aa313fc | |
Jiiks | 45ab822fba | |
Alexei Stukov | c893216874 | |
Alexei Stukov | a1a869181b | |
Alexei Stukov | f5cbd8d491 | |
Alexei Stukov | 17917f3257 | |
Jiiks | 19be33b17d | |
Jiiks | cfcca0d782 | |
Jiiks | 5592a8d376 | |
Jiiks | 0c0ebb2ebb | |
Jiiks | d6d78d1e99 | |
Jiiks | b6da7019d0 | |
Jiiks | a123e20b05 | |
Jiiks | 856334cf30 | |
Jiiks | 3f5b2afbd5 | |
Jiiks | ad35c89d7d | |
Jiiks | 71a0ce8fb0 | |
Jiiks | d53a3b4d64 | |
Jiiks | bd0c66466f | |
Jiiks | 0a751919aa | |
Jiiks | cae68947df | |
Jiiks | 2b833b5141 | |
Jiiks | b24c0ba2f3 | |
Jiiks | 3b8126781d | |
Jiiks | a1a63f2c35 | |
Jiiks | 334c9f852a | |
Jiiks | 17128a889b | |
Jiiks | d2b99f200b | |
Jiiks | 5f4a77f2d8 | |
Jiiks | 3614997fa9 | |
Jiiks | 5f76d304f6 | |
Jiiks | e8688c0ce4 | |
Jiiks | 641a12d640 | |
Jiiks | 169741d5a1 | |
Alexei Stukov | 4aec2a7ade | |
Mega-Mewthree | ee9cba328f | |
Mega-Mewthree | c421be9e91 | |
Mega-Mewthree | 7a1768ca87 | |
Mega-Mewthree | b9e9ab89f7 | |
Mega-Mewthree | b9f3c3f4e2 | |
Mega-Mewthree | dc842b479b | |
Mega-Mewthree | 02e6fb88aa | |
Mega-Mewthree | c10310af3a | |
Mega-Mewthree | 7e41fe73e7 | |
Mega-Mewthree | c122457565 | |
Mega-Mewthree | 0ea0acfaa5 | |
Jiiks | 866ad8b13b | |
Mega-Mewthree | c5d4e199fc | |
Mega-Mewthree | 1a8946b151 | |
Zack Rauen | 9c0e19e198 | |
Alexei Stukov | 816f809ca7 | |
Samuel Elliott | 32a995f678 | |
Samuel Elliott | dac3187866 | |
Jiiks | 60cdec3ae4 | |
Jiiks | ed4adf21f4 | |
Jiiks | a8f0e239cf | |
Jiiks | be1a183e62 | |
Jiiks | d88cedb614 | |
Jiiks | 9880152290 | |
Jiiks | 0a1bd46ca9 | |
Jiiks | 83ef17d302 | |
Mega-Mewthree | cb6473920f | |
Mega-Mewthree | d8c769433a | |
Mega-Mewthree | fd7a0f4051 | |
Mega-Mewthree | 7899312e73 | |
Samuel Elliott | 784d8223e8 | |
Samuel Elliott | 344a9e6fe5 | |
Samuel Elliott | 22e78c03e1 | |
Jiiks | b67ca5c42d | |
Jiiks | bdec8b842e | |
Jiiks | 3bc7c28a97 | |
Samuel Elliott | a4992e905c | |
Samuel Elliott | c8381eb808 | |
Samuel Elliott | 0aabc72652 | |
Jiiks | 3d4204f080 | |
Samuel Elliott | dc3fed3408 | |
Samuel Elliott | a12a3c74f4 | |
Jiiks | 3c83dbe0ff | |
Samuel Elliott | 4970214324 | |
Jiiks | a5ae5ad8e9 | |
Jiiks | 54808f32ea | |
Jiiks | 4e4c532813 | |
Jiiks | aac4dba641 | |
Jiiks | 17f1b60a9b | |
Jiiks | 2a10191926 | |
Alexei Stukov | 87ec7d8773 | |
Jiiks | e518d4c117 | |
Jiiks | c4dfc7b11d | |
Jiiks | 0c04c04590 | |
Alexei Stukov | 11b2b16233 | |
Alexei Stukov | 4c6805510d | |
Samuel Elliott | cb01d32e19 | |
Samuel Elliott | 89a5bfba20 | |
Alexei Stukov | 87a2db1745 | |
Samuel Elliott | 387227cc1f | |
Zack Rauen | fdb3b308e1 | |
Alexei Stukov | b33aff51c1 | |
Alexei Stukov | be09fbb5ac | |
Jiiks | 2b4a804934 | |
Jiiks | fcfba41805 | |
Jiiks | d14a06528c | |
Alexei Stukov | c336c8cb0d | |
Samuel Elliott | 755d870a10 | |
Jiiks | 4ed301f531 | |
Jiiks | 263fcbe001 | |
Samuel Elliott | 883f760292 | |
Zack Rauen | 5af8a2168d | |
Jiiks | 50badaef2b | |
Alexei Stukov | 4c20115705 | |
Jiiks | e21583eafd | |
Jiiks | 983763c48d | |
Jiiks | 75ceee5449 | |
Jiiks | 572c57d3a7 | |
Jiiks | 4f98eaf85b | |
Jiiks | 44a1c87484 | |
Jiiks | b18dd7c01a | |
Jiiks | 356e8f0934 | |
Alexei Stukov | 1288e0361a | |
Alexei Stukov | 8f95ba290a | |
Zack Rauen | 5a603a084f | |
Zack Rauen | f144934cd7 | |
Zack Rauen | 9473e419b4 | |
Zack Rauen | a081a8fdf9 | |
Zack Rauen | e660ce6a31 | |
Zack Rauen | 5c7b10299b | |
Jiiks | 42957dbb16 | |
Alexei Stukov | c3df892f1c | |
Jiiks | 26f386ad31 | |
Jiiks | b861280548 | |
Jiiks | 9d22293927 | |
Jiiks | c3d8f4090e | |
Jiiks | 3f00dba937 | |
Alexei Stukov | 9f00aed4fa | |
Jiiks | 685d0f4bac | |
Alexei Stukov | a805c8f75a | |
Alexei Stukov | ce23a39f83 | |
Samuel Elliott | c0a971a27b | |
Jiiks | 7f567f6e9d | |
Jiiks | 865fcee12d | |
Jiiks | 6b3fc39a1d | |
Jiiks | 7b1f36cb9c | |
Jiiks | f6f308baa2 | |
Jiiks | e170ed608e | |
Jiiks | a432d78953 | |
Jiiks | b369dc31f2 | |
Jiiks | 778eb0474f | |
Jiiks | 8c1f196675 | |
Jiiks | e25ac66abf | |
Alexei Stukov | a2a334bdac | |
Jiiks | 8331b30d73 | |
Jiiks | 7083577db2 | |
Jiiks | 1b91c97c24 | |
Alexei Stukov | cca6cdf95d | |
Jiiks | 7c02a51a46 | |
Samuel Elliott | 0e34fdaa8d | |
Samuel Elliott | e2f05d9a64 | |
Samuel Elliott | 13437c56d4 | |
Samuel Elliott | 4b4b3c341f | |
Samuel Elliott | c2f8f5cfab | |
Samuel Elliott | d4c883a5d7 | |
Zack | 520366c4ac | |
Samuel Elliott | 342b4cddc4 | |
Samuel Elliott | 6ea85341b9 | |
Samuel Elliott | 9af8a71e17 | |
Samuel Elliott | 33488d716d | |
Samuel Elliott | a5ff8bbdb6 | |
Samuel Elliott | 16bb32b86c | |
Samuel Elliott | 8826a7b984 | |
Samuel Elliott | 5b419cb8ab | |
Samuel Elliott | db21f4eb13 | |
Samuel Elliott | 3a7ac06ce3 | |
Samuel Elliott | 0c8279311e | |
Samuel Elliott | 331b2b396a | |
Samuel Elliott | a20473d718 | |
Samuel Elliott | 1a12430322 | |
Samuel Elliott | 7a416c0ff7 | |
Samuel Elliott | 81e392c0f6 | |
Samuel Elliott | 71c2d3aaad | |
Samuel Elliott | 19bbd4215c | |
Samuel Elliott | 5301498978 | |
Samuel Elliott | 1d887967d9 | |
Samuel Elliott | a95b97b3c0 | |
Samuel Elliott | 007637a557 | |
Samuel Elliott | 6ded1c62e5 | |
Samuel Elliott | 27f1eec967 | |
Samuel Elliott | 821f46481e | |
Samuel Elliott | 6b97505f66 | |
Samuel Elliott | df471161a7 | |
Samuel Elliott | da627f71e5 | |
Samuel Elliott | 78079588ea | |
Samuel Elliott | b4ebd6c08a | |
Samuel Elliott | e6f2f518e6 | |
Samuel Elliott | aff89371e6 | |
Samuel Elliott | 98a7a71b87 | |
Samuel Elliott | 98a0717bba | |
Samuel Elliott | 7c8c8a754f | |
Samuel Elliott | ab13e716ad | |
Samuel Elliott | f2c31d866d | |
Samuel Elliott | e169206821 | |
Samuel Elliott | cd77d659a5 | |
Samuel Elliott | b6f38a73dc | |
Samuel Elliott | c384920275 | |
Samuel Elliott | 097fc9b3e9 | |
Samuel Elliott | b8fbfdee55 | |
Samuel Elliott | 8c0b73625d | |
Samuel Elliott | 55cd75b5f4 | |
Samuel Elliott | f8f519e882 | |
Samuel Elliott | 799dca7e1b | |
Samuel Elliott | eae1bdf3a6 | |
Samuel Elliott | ea27259a67 | |
Samuel Elliott | ebe195f078 | |
Samuel Elliott | e2b68788bd | |
Samuel Elliott | c8ca4fcfce | |
Samuel Elliott | 2c38433a2b | |
Samuel Elliott | ee0b13dab2 | |
Samuel Elliott | 4d2347cf84 | |
Samuel Elliott | 7cf40a9ee4 | |
Samuel Elliott | 70f678119a | |
Samuel Elliott | 0a2b967e36 | |
Samuel Elliott | a2367299b7 | |
Samuel Elliott | bbcc36647d | |
Samuel Elliott | 906140686f | |
Samuel Elliott | cecaf314f9 | |
Samuel Elliott | 4a3bb89259 | |
Samuel Elliott | d7db836e30 | |
Samuel Elliott | 1eca4bcec7 | |
Samuel Elliott | c02052a982 | |
Samuel Elliott | be841f0426 | |
Zack Rauen | 6c4743d7ed | |
Zack Rauen | 726d6cf4b0 | |
Samuel Elliott | 35cedbdbb3 | |
Samuel Elliott | 17597e2c30 | |
Zack Rauen | 1bb705014f | |
Samuel Elliott | 204dd76e7b | |
Samuel Elliott | 3e41a11197 | |
Samuel Elliott | 68d4617e46 | |
Samuel Elliott | 4654025423 | |
Samuel Elliott | 231afa8ed6 | |
Samuel Elliott | c3ff71ff85 | |
Samuel Elliott | 0e99b219c1 | |
Samuel Elliott | 13508b449d | |
Samuel Elliott | e57e1f51ea | |
Samuel Elliott | c345ab1419 | |
Samuel Elliott | bee869340d | |
Samuel Elliott | 1de4680ded | |
Samuel Elliott | bba1165c77 | |
Samuel Elliott | a5c7aaab3b | |
Samuel Elliott | 93cd1fd07d | |
Samuel Elliott | cfaf581ae1 | |
Samuel Elliott | 665c1d5fe4 | |
Samuel Elliott | 8d8c1a8080 | |
Samuel Elliott | 8827bdb8b0 | |
Samuel Elliott | cd81f925cb | |
Samuel Elliott | d7f4c651b6 | |
Samuel Elliott | f2159f1031 | |
Samuel Elliott | 581c94f6b3 | |
Samuel Elliott | 9eb8eaa906 | |
Samuel Elliott | 9915ef8b19 | |
Zack Rauen | 2d784b48f4 | |
Samuel Elliott | cee2a6ec34 | |
Samuel Elliott | 64e855ab2d | |
Samuel Elliott | 5aa921ae4b | |
Samuel Elliott | 40a72458e2 | |
Samuel Elliott | dc2be5c410 | |
Samuel Elliott | 640ec66abc | |
Samuel Elliott | 3aedcfdd06 | |
Samuel Elliott | 71fe549ee6 | |
Samuel Elliott | cbe1de98a5 | |
Samuel Elliott | 5a58c1c6ce | |
Samuel Elliott | 591d44dee4 | |
Samuel Elliott | 6da58ef6bb | |
Samuel Elliott | 85d5de9791 | |
Samuel Elliott | 5ce78f4b32 | |
Samuel Elliott | 2499f8c0ab | |
Samuel Elliott | 3f2eb1047e | |
Samuel Elliott | ac79bbb99b | |
Samuel Elliott | 1c4fb0b5ea | |
Samuel Elliott | 2e2d0dd6f6 | |
Samuel Elliott | a6c91d5e27 | |
Samuel Elliott | 949206738b | |
Samuel Elliott | 4dc715a39a | |
Samuel Elliott | 36d7554b46 | |
Samuel Elliott | d42e8f66ca | |
Samuel Elliott | 244b7e5bd1 | |
Samuel Elliott | ca7a7c1f91 | |
Samuel Elliott | 504221ce28 | |
Samuel Elliott | 1e643b8164 | |
Samuel Elliott | 0944c0708f | |
Samuel Elliott | 17575fc6a1 | |
Samuel Elliott | 1354b884b4 | |
Samuel Elliott | 1ace26b67f | |
Samuel Elliott | 117336a6b4 | |
Samuel Elliott | d1cce95abe | |
Samuel Elliott | 22fbb7b5bd | |
Samuel Elliott | 34ebab7c21 | |
Samuel Elliott | 5e8579e4dc | |
Samuel Elliott | 4721f66dab | |
Samuel Elliott | 02b313f2e6 | |
Samuel Elliott | b0ae424adb | |
Samuel Elliott | 5a6fb990c7 | |
Samuel Elliott | c294df6b26 | |
Samuel Elliott | c3e4563aeb | |
Samuel Elliott | 525fd3145d | |
Samuel Elliott | 32452d918a | |
Samuel Elliott | e524c50b65 | |
Samuel Elliott | 96952c3fef | |
Samuel Elliott | ad710de008 | |
Samuel Elliott | 21ff9d200c | |
Samuel Elliott | a1c6f5d5fd | |
Samuel Elliott | 6d64d17b7d | |
Samuel Elliott | 695d088f60 | |
Samuel Elliott | bcb888100c | |
Samuel Elliott | 146e108874 | |
Samuel Elliott | 4837a01812 | |
Samuel Elliott | 48f4837a24 | |
Samuel Elliott | 8b320d2f09 | |
Samuel Elliott | ac22b14358 | |
Samuel Elliott | 4d5a403d6d | |
Samuel Elliott | 9dc424cc75 | |
Samuel Elliott | 1b75753a3d | |
Samuel Elliott | a7b300d233 | |
Samuel Elliott | 68e42b8b36 | |
Samuel Elliott | e061d95ae6 | |
Alexei Stukov | 6b517adbe8 | |
Samuel Elliott | 33c0732c08 | |
Samuel Elliott | f1e0350433 | |
Samuel Elliott | d5f486d1ad | |
Samuel Elliott | 7fb8337095 | |
Samuel Elliott | 7adf63dfa8 | |
Samuel Elliott | d2f7e6142f | |
Samuel Elliott | b62727b046 | |
Samuel Elliott | f0a337e0ed | |
Samuel Elliott | 5c755bc121 | |
Samuel Elliott | 4d0631ba38 | |
Samuel Elliott | d4962bb2ab | |
Samuel Elliott | cf319a2604 | |
Samuel Elliott | 256db71aa4 | |
Samuel Elliott | de8601ded4 | |
Samuel Elliott | a96f3b1eb7 | |
Samuel Elliott | a7aa1fa5ec | |
Alexei Stukov | bbd12a0381 | |
Samuel Elliott | 027ca8d639 | |
Samuel Elliott | a0f60dddb2 | |
Samuel Elliott | a3038c46fd | |
Samuel Elliott | d98f152009 | |
Samuel Elliott | 68beee12d3 | |
Samuel Elliott | 4b59b9f65d | |
Samuel Elliott | 85d390e18d | |
Samuel Elliott | 3f89286946 | |
Samuel Elliott | 554b8d195b | |
Samuel Elliott | 7f5fa44fd3 | |
Samuel Elliott | c95d60ab0f | |
Samuel Elliott | 60a82a3ad9 | |
Samuel Elliott | 2f9af2e2d0 | |
Samuel Elliott | 858fdcec59 | |
Samuel Elliott | 3eb1782a64 | |
Samuel Elliott | 0e14d167dc | |
Samuel Elliott | c701a2b5f9 | |
Samuel Elliott | b3442ee108 | |
Samuel Elliott | 1bde3b4ec9 | |
Samuel Elliott | e83c6f92cb | |
Samuel Elliott | 06cca44376 | |
Samuel Elliott | 3f3898c774 | |
Samuel Elliott | f8a380fd59 | |
Samuel Elliott | f28525129e | |
Samuel Elliott | d2cbbd309b | |
Samuel Elliott | 74d78f4bca | |
Samuel Elliott | 68af931128 | |
Samuel Elliott | 5331afb763 | |
Samuel Elliott | 069b1ff689 | |
Samuel Elliott | 009d6be057 | |
Samuel Elliott | da4b592e54 | |
Samuel Elliott | 81f3519408 | |
Samuel Elliott | 8c09112cff | |
Samuel Elliott | 8983256ade | |
Samuel Elliott | d323292162 | |
Samuel Elliott | 1714a0225e | |
Samuel Elliott | fd3b0a92ce | |
Samuel Elliott | 9b1dd771ad | |
Samuel Elliott | 441e80e0e8 | |
Samuel Elliott | 4634266e14 | |
Samuel Elliott | 10fd25607d | |
Samuel Elliott | 946f68e4ef | |
Alexei Stukov | a4ceb8bd2c | |
Samuel Elliott | 545b72cc3e | |
Samuel Elliott | 9e229a1c0f | |
Samuel Elliott | ddfd0653ac | |
Samuel Elliott | 6bb8c18857 | |
Samuel Elliott | 66eee86eb3 | |
Samuel Elliott | eaeae7ad98 | |
Samuel Elliott | a3eeee9b57 | |
Samuel Elliott | 6d46ac67de | |
Samuel Elliott | db6be20864 | |
Samuel Elliott | 5e8e9fa19f | |
Samuel Elliott | ebff286c31 | |
Samuel Elliott | 0f805d57e3 | |
Samuel Elliott | 33adb92902 | |
Samuel Elliott | a85422f29e | |
Samuel Elliott | aa933d9a09 | |
Samuel Elliott | 8a9c8edf39 | |
Samuel Elliott | 74e3605ec6 | |
Samuel Elliott | dc44af6968 | |
Samuel Elliott | a4a130bfc6 | |
Samuel Elliott | 2fb5d8fe11 | |
Samuel Elliott | 1772edd37c | |
Samuel Elliott | b4bd9e9c7b | |
Samuel Elliott | 994faf94d6 | |
Alexei Stukov | 048abaeeed | |
Jiiks | f3fa3c2ae2 | |
Jiiks | ee87cbc25c | |
Jiiks | 4ce32c415e | |
Jiiks | c60411c901 | |
Jiiks | 9f24d0d1ce | |
Jiiks | 684f85b45e | |
Jiiks | 83d9419131 | |
Alexei Stukov | 1fe233bc91 | |
Jiiks | 70ae8365fe | |
Jiiks | 038d15ecf3 | |
Alexei Stukov | 86fc492af4 | |
Jiiks | eed634217e |
|
@ -2,6 +2,7 @@ root = true
|
|||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
indent_style = space
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
{
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 8,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true
|
||||
},
|
||||
"plugins": [
|
||||
"vue"
|
||||
],
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:vue/recommended"
|
||||
],
|
||||
"rules": {
|
||||
"no-unused-vars": "off",
|
||||
"no-console": "off",
|
||||
"no-empty": "off",
|
||||
"quotes": [
|
||||
"error",
|
||||
"single",
|
||||
{ "allowTemplateLiterals": true }
|
||||
],
|
||||
"prefer-template": "warn",
|
||||
"no-return-await": "error",
|
||||
"indent": [ "warn", 4 ],
|
||||
"no-lonely-if": "error",
|
||||
"no-multiple-empty-lines": [
|
||||
"warn",
|
||||
{ "max": 1 }
|
||||
],
|
||||
"no-tabs": "warn",
|
||||
"no-trailing-spaces": "warn",
|
||||
"no-unneeded-ternary": "warn",
|
||||
"no-useless-constructor": "warn",
|
||||
"no-var": "error",
|
||||
"prefer-const": "error",
|
||||
"no-else-return": "error"
|
||||
}
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
---
|
||||
|
||||
parserOptions:
|
||||
ecmaVersion: 8
|
||||
sourceType: module
|
||||
|
||||
env:
|
||||
browser: true
|
||||
node: true
|
||||
|
||||
plugins:
|
||||
- vue
|
||||
|
||||
extends:
|
||||
- eslint:recommended
|
||||
- plugin:vue/recommended
|
||||
|
||||
rules:
|
||||
no-unused-vars: 'off'
|
||||
no-console: 'off'
|
||||
no-empty: 'off'
|
|
@ -0,0 +1,33 @@
|
|||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: "[Bug]"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
- [ ] Used appropriate template for the issue type
|
||||
- [ ] Searched both open and closed issues for duplicates of this issue
|
||||
- [ ] Title adequately and _concisely_ reflects the feature or the bug
|
||||
|
||||
**Describe the bug**
|
||||
<!-- A clear and concise description of what the bug is. -->
|
||||
|
||||
**To Reproduce**
|
||||
<!-- Steps to reproduce the behavior -->
|
||||
|
||||
**Expected behavior**
|
||||
<!-- A clear and concise description of what you expected to happen. -->
|
||||
|
||||
**Screenshots**
|
||||
<!-- If applicable, add screenshots to help explain your problem. -->
|
||||
|
||||
**System information**
|
||||
<!-- os, discord branch etc -->
|
||||
|
||||
**Additional context**
|
||||
<!-- Add any other context about the problem here. -->
|
||||
|
||||
**Are you willing and able to fix this?**
|
||||
<!-- "Yes" or, if "no", what can current contributors do to help you create a PR? -->
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
name: Custom issue template
|
||||
about: Describe this issue template's purpose here.
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
- [ ] Used appropriate template for the issue type
|
||||
- [ ] Searched both open and closed issues for duplicates of this issue
|
||||
- [ ] Title adequately and _concisely_ reflects the feature or the bug
|
|
@ -0,0 +1,27 @@
|
|||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: "[Feature]"
|
||||
labels: feature
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
- [ ] Used appropriate template for the issue type
|
||||
- [ ] Searched both open and closed issues for duplicates of this issue
|
||||
- [ ] Title adequately and _concisely_ reflects the feature or the bug
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
|
||||
|
||||
**Describe the solution you'd like**
|
||||
<!-- A clear and concise description of what you want to happen. -->
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
|
||||
|
||||
**Additional context**
|
||||
<!-- Add any other context or screenshots about the feature request here. -->
|
||||
|
||||
**Are you willing and able to implement this?**
|
||||
<!-- "Yes" or, if "no", what can current contributors do to help you create a PR? -->
|
|
@ -1,26 +1,16 @@
|
|||
.idea/*
|
||||
*.name
|
||||
devjs/.idea/devjs.iml
|
||||
*.bak
|
||||
*.bak.*
|
||||
*.xpi
|
||||
Firefox/data/js/jquery-2.1.4.min.js
|
||||
*.dev.*
|
||||
/nbproject/private/
|
||||
# Generated files
|
||||
node_modules
|
||||
.sass-cache
|
||||
/*.jiiks
|
||||
Installers/dotNet/bin/
|
||||
Installers/dotNet/packages/
|
||||
Installers/dotNet/dlls/
|
||||
v2/dist/vendor/
|
||||
v2/lib/static.js
|
||||
**/*.suo
|
||||
Installers/**/*/bin
|
||||
Installers/**/*/obj
|
||||
Installers/**/*/packages
|
||||
.vs
|
||||
dist/
|
||||
user.config.json
|
||||
dist
|
||||
etc
|
||||
release
|
||||
|
||||
tests/tmp
|
||||
tests/log.txt
|
||||
|
||||
# User data
|
||||
tests/data
|
||||
/tests/themes/SimplerFlat
|
||||
user.config.json
|
||||
/.vs
|
||||
/npm-debug.log
|
||||
/tests/ext/extensions
|
||||
/tests/userdata
|
||||
|
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"rules": {
|
||||
"no-transition-all": [ 0 ],
|
||||
"nesting-depth": [
|
||||
1,
|
||||
{ "max-depth": 5 }
|
||||
],
|
||||
"no-vendor-prefixes": [ 0 ],
|
||||
"property-sort-order": [ 0 ],
|
||||
"indentation": [
|
||||
1,
|
||||
{ "size": 4 }
|
||||
],
|
||||
"no-color-literals": [ 0 ],
|
||||
"class-name-format": [
|
||||
1,
|
||||
{
|
||||
"convention": "^bd-[a-z]"
|
||||
}
|
||||
],
|
||||
"variable-name-format": [
|
||||
2,
|
||||
{
|
||||
"convention": "camelcase"
|
||||
}
|
||||
],
|
||||
"url-quotes": [ 0 ]
|
||||
}
|
||||
}
|
|
@ -1,6 +1,13 @@
|
|||
language: node_js
|
||||
|
||||
node_js:
|
||||
- stable
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- libsecret-1-dev
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
# BetterDiscordApp [![Travis][build-badge]][build]
|
||||
[build-badge]: https://img.shields.io/travis/JsSucks/BetterDiscordApp/master.svg
|
||||
[build]: https://travis-ci.org/JsSucks/BetterDiscordApp
|
|
@ -0,0 +1,12 @@
|
|||
# BetterDiscordApp [![Travis][build-badge]][build] [![Snyk][snyk-badge]][snyk-url] [![deps][deps-badge]][deps-url] [![devdeps][devdeps-badge]][devdeps-url]
|
||||
|
||||
[build-badge]: https://img.shields.io/travis/JsSucks/BetterDiscordApp/master.svg
|
||||
[build]: https://travis-ci.org/JsSucks/BetterDiscordApp
|
||||
|
||||
[snyk-badge]: https://snyk.io/test/github/JsSucks/BetterDiscordApp/badge.svg
|
||||
[snyk-url]: https://snyk.io/test/github/JsSucks/BetterDiscordApp
|
||||
|
||||
[deps-badge]: https://david-dm.org/JsSucks/BetterDiscordApp.svg
|
||||
[deps-url]: https://david-dm.org/JsSucks/BetterDiscordApp
|
||||
[devdeps-badge]: https://david-dm.org/JsSucks/BetterDiscordApp/dev-status.svg
|
||||
[devdeps-url]: https://david-dm.org/JsSucks/BetterDiscordApp?type=dev
|
|
@ -0,0 +1,17 @@
|
|||
module.exports = function(api) {
|
||||
|
||||
api.cache(true);
|
||||
|
||||
const presets = [['@babel/env', {
|
||||
targets: {
|
||||
'node': '8.6.0'
|
||||
}
|
||||
}]];
|
||||
|
||||
const plugins = [];
|
||||
|
||||
return {
|
||||
presets,
|
||||
plugins
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
module.exports = function(api) {
|
||||
|
||||
api.cache(true);
|
||||
|
||||
const presets = [['@babel/env', {
|
||||
targets: {
|
||||
'node': '8.6.0',
|
||||
'chrome': '60'
|
||||
}
|
||||
}], '@babel/react'];
|
||||
|
||||
const plugins = [];
|
||||
|
||||
return {
|
||||
presets,
|
||||
plugins
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2017",
|
||||
"allowSyntheticDefaultImports": false,
|
||||
"baseUrl": "./",
|
||||
"paths": {
|
||||
"modules": ["./src/modules/modules.js"],
|
||||
"structs": ["./src/structs/structs.js"],
|
||||
"common": ["../common/modules/common.js"],
|
||||
"ui": ["./src/ui/ui.js"],
|
||||
"builtin": ["./src/builtin/builtin.js"],
|
||||
"vue$": ["../node_modules/vue/dist/vue.esm.js"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
|
@ -2,24 +2,22 @@
|
|||
"name": "bdclient",
|
||||
"description": "BetterDiscord client package",
|
||||
"author": "Jiiks",
|
||||
"version": "0.4.0",
|
||||
"version": "2.0.0-beta.6",
|
||||
"homepage": "https://betterdiscord.net",
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"main": "dist/betterdiscord.client.js",
|
||||
"contributors": [
|
||||
"Jiiks",
|
||||
"Pohky"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Jiiks/BetterDiscordApp.git"
|
||||
"url": "https://github.com/JsSucks/BetterDiscordApp.git"
|
||||
},
|
||||
"private": false,
|
||||
"devDependencies": {
|
||||
|
||||
},
|
||||
"scripts": {
|
||||
"build": "webpack --progress --colors",
|
||||
"watch": "webpack --progress --colors --watch"
|
||||
"watch": "webpack --progress --colors --watch",
|
||||
"release": "webpack --progress --colors --config=webpack.production.config.js"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,40 @@
|
|||
/**
|
||||
* BetterDiscord 24 Hour Timestamps Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
import { Reflection } from 'modules';
|
||||
|
||||
const twelveHour = new RegExp(`([0-9]{1,2}):([0-9]{1,2})\\s(AM|PM)`);
|
||||
|
||||
export default new class TwentyFourHour extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'TwentyFourHour' }
|
||||
|
||||
get settingPath() { return ['ui', 'default', '24-hour'] }
|
||||
|
||||
/* Patches */
|
||||
applyPatches() {
|
||||
if (this.patches.length) return;
|
||||
const { TimeFormatter } = Reflection.modules;
|
||||
this.patch(TimeFormatter, 'calendarFormat', this.convertTimeStamps);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert 12 hours timestamps to 24 hour timestamps
|
||||
*/
|
||||
convertTimeStamps(that, args, returnValue) {
|
||||
const matched = returnValue.match(twelveHour);
|
||||
if (!matched || matched.length !== 4) return;
|
||||
if (matched[3] === 'AM') return returnValue.replace(matched[0], `${matched[1] === '12' ? '00' : matched[1].padStart(2, '0')}:${matched[2]}`)
|
||||
return returnValue.replace(matched[0], `${parseInt(matched[1]) + 12}:${matched[2]}`)
|
||||
}
|
||||
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
/**
|
||||
* BetterDiscord Autocomplete Component
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
<template>
|
||||
<div class="bd-autocomplete">
|
||||
<div class="bd-autocomplete-inner">
|
||||
<div class="bd-autocompleteRow">
|
||||
<div class="bd-autocompleteSelector">
|
||||
<div class="bd-autocompleteTitle">
|
||||
Emotes Matching:
|
||||
<strong>Kappa</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script>
|
||||
import EmoteModule from '../../../builtin/Emotemodule.js';
|
||||
export default {
|
||||
props: ['title', 'emotes'],
|
||||
beforeMount() {
|
||||
console.log(EmoteModule);
|
||||
}
|
||||
}
|
||||
</script>
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* BetterDiscord Blocked Messages Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
import { Reflection } from 'modules';
|
||||
|
||||
export default new class BlockedMessages extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'BlockedMessages' }
|
||||
|
||||
get settingPath() { return ['ui', 'default', 'blocked-messages'] }
|
||||
|
||||
async enabled(e) {
|
||||
const MessageListComponents = Reflection.module.byProps('BlockedMessageGroup');
|
||||
MessageListComponents.OriginalBlockedMessageGroup = MessageListComponents.BlockedMessageGroup;
|
||||
MessageListComponents.BlockedMessageGroup = () => null;
|
||||
this.cancelBlockedMessages = () => {
|
||||
MessageListComponents.BlockedMessageGroup = MessageListComponents.OriginalBlockedMessageGroup;
|
||||
delete MessageListComponents.OriginalBlockedMessageGroup;
|
||||
}
|
||||
}
|
||||
|
||||
disabled(e) {
|
||||
if (this.cancelBlockedMessages) this.cancelBlockedMessages();
|
||||
}
|
||||
|
||||
/* Methods */
|
||||
static isBlocked(id) {
|
||||
const { RelationshipStore } = Reflection.modules;
|
||||
return RelationshipStore.isBlocked(id);
|
||||
}
|
||||
|
||||
/* Patches */
|
||||
applyPatches() {
|
||||
if (this.patches.length) return;
|
||||
const { MessageActions } = Reflection.modules;
|
||||
this.patch(MessageActions, 'receiveMessage', this.processMessage, 'instead');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ignore blocked messages completely
|
||||
*/
|
||||
processMessage(that, args, originalFunction) {
|
||||
if (args[1] && args[1].author && args[1].author.id && BlockedMessages.isBlocked(args[1].author.id)) return;
|
||||
return originalFunction(...args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
/**
|
||||
* BetterDiscord Builtin Module Base
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Settings } from 'modules';
|
||||
import { Patcher, MonkeyPatch as Patch, Cache } from 'modules';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
|
||||
export default class BuiltinModule {
|
||||
|
||||
constructor() {
|
||||
this._settingUpdated = this._settingUpdated.bind(this);
|
||||
if (this.enabled) this.enabled = this.enabled.bind(this);
|
||||
if (this.disabled) this.disabled = this.disabled.bind(this);
|
||||
if (this.applyPatches) this.applyPatches = this.applyPatches.bind(this);
|
||||
this.patch = this.patch.bind(this);
|
||||
}
|
||||
|
||||
async init() {
|
||||
this.setting.on('setting-updated', this._settingUpdated);
|
||||
if (this.setting.value) {
|
||||
if (this.enabled) await this.enabled();
|
||||
if (this.applyPatches) this.applyPatches();
|
||||
}
|
||||
}
|
||||
|
||||
get setting() {
|
||||
return Settings.getSetting(...this.settingPath);
|
||||
}
|
||||
|
||||
get patches() {
|
||||
return Patcher.getPatchesByCaller(`BD:${this.moduleName}`);
|
||||
}
|
||||
|
||||
async _settingUpdated(e) {
|
||||
if (e.value) {
|
||||
if (this.enabled) await this.enabled(e);
|
||||
if (this.applyPatches) await this.applyPatches();
|
||||
if (this.rerenderPatchedComponents) this.rerenderPatchedComponents();
|
||||
} else {
|
||||
if (this.disabled) await this.disabled(e);
|
||||
this.unpatch();
|
||||
if (this.rerenderPatchedComponents) this.rerenderPatchedComponents();
|
||||
}
|
||||
}
|
||||
|
||||
get cache() {
|
||||
return {
|
||||
push: data => Cache.push(this.moduleName, data),
|
||||
find: filter => Cache.find(this.moduleName, filter)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* By default unpatch everything.
|
||||
* Override to do something else.
|
||||
*/
|
||||
unpatch() {
|
||||
Patcher.unpatchAll(`BD:${this.moduleName}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch a function in a module
|
||||
* @param {any} module Module to patch
|
||||
* @param {String} fnName Name of the function to patch
|
||||
* @param {Function} cb Callback
|
||||
* @param {String} [when=after] before|after|instead
|
||||
*/
|
||||
patch(module, fnName, cb, when = 'after') {
|
||||
if (!['before', 'after', 'instead'].includes(when)) when = 'after';
|
||||
return Patch(`BD:${this.moduleName}`, module)[when](fnName, cb.bind(this));
|
||||
}
|
||||
|
||||
childPatch(module, fnName, child, cb, when = 'after') {
|
||||
const last = child.pop();
|
||||
|
||||
this.patch(module, fnName, (component, args, retVal) => {
|
||||
const unpatch = this.patch(child.reduce((obj, key) => obj[key], retVal), last, function(...args) {unpatch(); return cb.call(this, component, ...args);}, when);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Logger wraps
|
||||
*/
|
||||
log(message) {
|
||||
Logger.log(this.moduleName, message);
|
||||
}
|
||||
|
||||
warn(message) {
|
||||
Logger.warn(this.moduleName, message);
|
||||
}
|
||||
|
||||
info(message) {
|
||||
Logger.warn(this.moduleName, message);
|
||||
}
|
||||
|
||||
debug(message) {
|
||||
Logger.dbg(this.moduleName, message);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
/**
|
||||
* BetterDiscord Colored Text Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
|
||||
import { Utils } from 'common';
|
||||
import { Settings, Reflection, ReactComponents, DiscordApi } from 'modules';
|
||||
|
||||
export default new class ColoredText extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'ColoredText' }
|
||||
|
||||
get settingPath() { return ['ui', 'default', 'colored-text'] }
|
||||
|
||||
get intensityPath() { return ['ui', 'advanced', 'colored-text-intensity'] }
|
||||
|
||||
get intensitySetting() { return Settings.getSetting(...this.intensityPath) }
|
||||
|
||||
get intensity() { return 100 - this.intensitySetting.value }
|
||||
|
||||
get defaultColor() { return DiscordApi.UserSettings.theme == 'light' ? '#747f8d' : '#dcddde' }
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._intensityUpdated = this._intensityUpdated.bind(this);
|
||||
}
|
||||
|
||||
async enabled(e) {
|
||||
this.intensitySetting.off('setting-updated', this._intensityUpdated);
|
||||
this.intensitySetting.on('setting-updated', this._intensityUpdated);
|
||||
}
|
||||
|
||||
disabled(e) {
|
||||
this.intensitySetting.off('setting-updated', this._intensityUpdated);
|
||||
}
|
||||
|
||||
rerenderPatchedComponents() {
|
||||
if (this.MessageContent) this.MessageContent.forceUpdateAll();
|
||||
}
|
||||
|
||||
/* Methods */
|
||||
_intensityUpdated() {
|
||||
this.MessageContent.forceUpdateAll();
|
||||
}
|
||||
|
||||
/* Patches */
|
||||
async applyPatches() {
|
||||
if (this.patches.length) return;
|
||||
this.MessageContent = await ReactComponents.getComponent('MessageContent');
|
||||
this.patch(this.MessageContent.component.prototype, 'render', this.injectColoredText);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set markup text colour to match role colour
|
||||
*/
|
||||
injectColoredText(thisObject, args, originalReturn) {
|
||||
const unpatch = this.patch(originalReturn.props, 'children', (obj, args, returnValue) => {
|
||||
unpatch();
|
||||
const { TinyColor } = Reflection.modules;
|
||||
const markup = Utils.findInReactTree(returnValue, m => m && m.props && m.props.className && m.props.className.includes('da-markup'));
|
||||
const roleColor = thisObject.props.message.colorString;
|
||||
if (markup && roleColor) markup.props.style = {color: TinyColor.mix(roleColor, this.defaultColor, this.intensity)};
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,396 @@
|
|||
/**
|
||||
* BetterDiscord E2EE Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Settings, Cache, Events } from 'modules';
|
||||
import BuiltinModule from '../BuiltinModule';
|
||||
import { Reflection, ReactComponents, DiscordApi, Security } from 'modules';
|
||||
import { VueInjector, Modals, Toasts } from 'ui';
|
||||
import { ClientLogger as Logger, ClientIPC } from 'common';
|
||||
import { request } from 'vendor';
|
||||
import { Utils } from 'common';
|
||||
import E2EEComponent from './E2EEComponent.vue';
|
||||
import E2EEMessageButton from './E2EEMessageButton.vue';
|
||||
import nodecrypto from 'node-crypto';
|
||||
|
||||
const userMentionPattern = new RegExp(`<@!?([0-9]{10,})>`, 'g');
|
||||
const roleMentionPattern = new RegExp(`<@&([0-9]{10,})>`, 'g');
|
||||
const everyoneMentionPattern = new RegExp(`(?:\\s+|^)@everyone(?:\\s+|$)`);
|
||||
|
||||
const START_DATE = new Date();
|
||||
const TEMP_KEY = 'temporarymasterkey';
|
||||
const ECDH_STORAGE = {};
|
||||
let seed;
|
||||
|
||||
export default new class E2EE extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
|
||||
get moduleName() { return 'E2EE' }
|
||||
|
||||
get settingPath() { return ['security', 'default', 'e2ee'] }
|
||||
|
||||
get database() { return Settings.getSetting('security', 'e2eedb', 'e2ekvps').value }
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.encryptNewMessages = true;
|
||||
this.ecdhDate = START_DATE;
|
||||
this.handlePublicKey = this.handlePublicKey.bind(this);
|
||||
this.fetchMasterKey = this.fetchMasterKey.bind(this);
|
||||
}
|
||||
|
||||
async enabled(e) {
|
||||
await this.fetchMasterKey();
|
||||
Events.on('discord:MESSAGE_CREATE', this.handlePublicKey);
|
||||
Settings.getSetting('security', 'default', 'use-keytar').on('setting-updated', this.fetchMasterKey);
|
||||
}
|
||||
|
||||
async disabled(e) {
|
||||
Settings.getSetting('security', 'default', 'use-keytar').off('setting-updated', this.fetchMasterKey);
|
||||
Events.off('discord:MESSAGE_CREATE', this.handlePublicKey);
|
||||
const ctaComponent = await ReactComponents.getComponent('ChannelTextArea');
|
||||
ctaComponent.forceUpdateAll();
|
||||
}
|
||||
|
||||
/* Methods */
|
||||
async fetchMasterKey() {
|
||||
try {
|
||||
if (Settings.get('security', 'default', 'use-keytar')) {
|
||||
const master = await ClientIPC.getPassword('betterdiscord', 'master');
|
||||
if (master) return this.setMaster(master);
|
||||
|
||||
if (Settings.getSetting('security', 'e2eedb', 'e2ekvps').items.length) {
|
||||
// Ask the user for their current password to save to the system keychain
|
||||
const currentMaster = await Modals.input('Save to System Keychain', 'Master Password', true).promise;
|
||||
await ClientIPC.setPassword('betterdiscord', 'master', currentMaster);
|
||||
return this.setMaster(currentMaster);
|
||||
}
|
||||
|
||||
// Generate a new master password and save it to the system keychain
|
||||
const newMaster = Security.randomBytes();
|
||||
await ClientIPC.setPassword('betterdiscord', 'master', newMaster);
|
||||
return this.setMaster(newMaster);
|
||||
}
|
||||
|
||||
const newMaster = await Modals.input('Open Database', 'Master Password', true).promise;
|
||||
return this.setMaster(newMaster);
|
||||
} catch (err) {
|
||||
Settings.getSetting(...this.settingPath).value = false;
|
||||
Toasts.error('Invalid master password! E2EE Disabled');
|
||||
Logger.err('E2EE', ['Error fetching master password', err]);
|
||||
}
|
||||
}
|
||||
|
||||
setMaster(key) {
|
||||
seed = Security.randomBytes();
|
||||
const newMaster = Security.encrypt(seed, key);
|
||||
// TODO re-encrypt everything with new master
|
||||
return (this.master = newMaster);
|
||||
}
|
||||
|
||||
encrypt(key, content, prefix = '') {
|
||||
if (!key) {
|
||||
// Encrypt something with master
|
||||
return Security.encrypt(Security.decrypt(seed, this.master), content);
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
// Get key for current channel and encrypt
|
||||
const haveKey = this.getKey(DiscordApi.currentChannel.id);
|
||||
if (!haveKey) return 'nokey';
|
||||
return Security.encrypt(Security.decrypt(seed, [this.master, haveKey]), key);
|
||||
}
|
||||
return prefix + Security.encrypt(key, content);
|
||||
}
|
||||
|
||||
decrypt(key, content, prefix = '') {
|
||||
return Security.decrypt(key, content, prefix);
|
||||
}
|
||||
|
||||
async createHmac(data) {
|
||||
const haveKey = this.getKey(DiscordApi.currentChannel.id);
|
||||
if (!haveKey) return null;
|
||||
return Security.createHmac(Security.decrypt(seed, [this.master, haveKey]), data);
|
||||
}
|
||||
|
||||
getKey(channelId) {
|
||||
const haveKey = this.database.find(kvp => kvp.value.key === channelId);
|
||||
if (!haveKey) return null;
|
||||
return haveKey.value.value;
|
||||
}
|
||||
|
||||
setKey(channelId, key) {
|
||||
const items = Settings.getSetting('security', 'e2eedb', 'e2ekvps').items;
|
||||
const index = items.findIndex(kvp => kvp.value.key === channelId);
|
||||
if (index > -1) {
|
||||
items[index].value = { key: channelId, value: key };
|
||||
return;
|
||||
}
|
||||
Settings.getSetting('security', 'e2eedb', 'e2ekvps').addItem({ value: { key: channelId, value: key } });
|
||||
}
|
||||
|
||||
createKeyExchange(dmChannelID) {
|
||||
if (ECDH_STORAGE.hasOwnProperty(dmChannelID)) return null;
|
||||
ECDH_STORAGE[dmChannelID] = Security.createECDH();
|
||||
setTimeout(() => {
|
||||
if (ECDH_STORAGE.hasOwnProperty(dmChannelID)) {
|
||||
delete ECDH_STORAGE[dmChannelID];
|
||||
Toasts.error('Key exchange expired!');
|
||||
if (this.preExchangeState) this.encryptNewMessages = this.preExchangeState;
|
||||
this.preExchangeState = null;
|
||||
}
|
||||
}, 30000);
|
||||
return Security.generateECDHKeys(ECDH_STORAGE[dmChannelID]);
|
||||
}
|
||||
|
||||
publicKeyFor(dmChannelID) {
|
||||
return Security.getECDHPublicKey(ECDH_STORAGE[dmChannelID]);
|
||||
}
|
||||
|
||||
computeSecret(dmChannelID, otherKey) {
|
||||
try {
|
||||
const secret = Security.computeECDHSecret(ECDH_STORAGE[dmChannelID], otherKey);
|
||||
delete ECDH_STORAGE[dmChannelID];
|
||||
return Security.hash('sha384', secret, 'hex');
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/* Patches */
|
||||
async applyPatches() {
|
||||
if (this.patches.length) return;
|
||||
|
||||
const { Dispatcher } = Reflection.modules;
|
||||
this.patch(Dispatcher, 'dispatch', this.dispatcherPatch, 'before');
|
||||
this.patchMessageContent();
|
||||
|
||||
const ChannelTextArea = await ReactComponents.getComponent('ChannelTextArea');
|
||||
this.patchChannelTextArea(ChannelTextArea);
|
||||
this.patchChannelTextAreaSubmit(ChannelTextArea);
|
||||
ChannelTextArea.forceUpdateAll();
|
||||
}
|
||||
|
||||
dispatcherPatch(_, [event]) {
|
||||
if (!event || event.type !== 'MESSAGE_CREATE') return;
|
||||
|
||||
const key = this.getKey(event.message.channel_id);
|
||||
if (!key) return; // We don't have a key for this channel
|
||||
|
||||
if (typeof event.message.content !== 'string') return; // Ignore any non string content
|
||||
if (!event.message.content.startsWith('$:')) return; // Not an encrypted string
|
||||
let decrypt;
|
||||
try {
|
||||
decrypt = this.decrypt(this.decrypt(this.decrypt(seed, this.master), key), event.message.content);
|
||||
} catch (err) { return } // Ignore errors such as non empty
|
||||
|
||||
const { MessageParser, Permissions, DiscordConstants } = Reflection.modules;
|
||||
|
||||
const currentChannel = DiscordApi.Channel.fromId(event.message.channel_id).discordObject;
|
||||
|
||||
// Create a generic message object to parse mentions with
|
||||
const parsed = MessageParser.parse(currentChannel, decrypt).content;
|
||||
|
||||
if (userMentionPattern.test(parsed))
|
||||
event.message.mentions = parsed.match(userMentionPattern).map(m => { return { id: m.replace(/[^0-9]/g, '') } });
|
||||
if (roleMentionPattern.test(parsed))
|
||||
event.message.mention_roles = parsed.match(roleMentionPattern).map(m => m.replace(/[^0-9]/g, ''));
|
||||
if (everyoneMentionPattern.test(parsed))
|
||||
event.message.mention_everyone = Permissions.can(DiscordConstants.Permissions.MENTION_EVERYONE, currentChannel);
|
||||
}
|
||||
|
||||
// TODO Received exchange should also expire if not accepted in time
|
||||
async handlePublicKey(e) {
|
||||
if (!DiscordApi.currentChannel) return;
|
||||
if (DiscordApi.currentChannel.type !== 'DM') return;
|
||||
const { id, content, author, channelId } = e.args;
|
||||
if (author.id === DiscordApi.currentUser.id || channelId !== DiscordApi.currentChannel.id) return;
|
||||
|
||||
const [tagstart, begin, key, end, tagend] = content.split('\n');
|
||||
if (begin !== '-----BEGIN PUBLIC KEY-----' || end !== '-----END PUBLIC KEY-----') return;
|
||||
|
||||
try {
|
||||
await Modals.confirm('Key Exchange', `Key exchange request from: ${author.username}#${author.discriminator}`, 'Accept', 'Reject').promise;
|
||||
// We already sent our key
|
||||
if (!ECDH_STORAGE.hasOwnProperty(channelId)) {
|
||||
const publicKeyMessage = `\`\`\`\n-----BEGIN PUBLIC KEY-----\n${this.createKeyExchange(channelId)}\n-----END PUBLIC KEY-----\n\`\`\``;
|
||||
if (this.encryptNewMessages) this.encryptNewMessages = false;
|
||||
Reflection.modules.DraftActions.saveDraft(channelId, publicKeyMessage);
|
||||
}
|
||||
const secret = this.computeSecret(channelId, key);
|
||||
this.setKey(channelId, secret);
|
||||
Toasts.success('Key exchange complete!');
|
||||
if (this.preExchangeState) this.encryptNewMessages = this.preExchangeState;
|
||||
this.preExchangeState = null;
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
async patchMessageContent() {
|
||||
const MessageContent = await ReactComponents.getComponent('MessageContent');
|
||||
this.patch(MessageContent.component.prototype, 'render', this.beforeRenderMessageContent, 'before');
|
||||
this.childPatch(MessageContent.component.prototype, 'render', ['props', 'children'], this.afterRenderMessageContent);
|
||||
MessageContent.forceUpdateAll();
|
||||
|
||||
const ImageWrapper = await ReactComponents.getComponent('ImageWrapper');
|
||||
this.patch(ImageWrapper.component.prototype, 'render', this.beforeRenderImageWrapper, 'before');
|
||||
ImageWrapper.forceUpdateAll();
|
||||
}
|
||||
|
||||
beforeRenderMessageContent(component) {
|
||||
if (!component.props || !component.props.message) return;
|
||||
|
||||
const key = this.getKey(component.props.message.channel_id);
|
||||
if (!key) return; // We don't have a key for this channel
|
||||
|
||||
const Message = Reflection.module.byPrototypes('isMentioned');
|
||||
const { MessageParser, Permissions, DiscordConstants } = Reflection.modules;
|
||||
const currentChannel = DiscordApi.Channel.fromId(component.props.message.channel_id).discordObject;
|
||||
|
||||
if (typeof component.props.message.content !== 'string') return; // Ignore any non string content
|
||||
if (!component.props.message.content.startsWith('$:')) return; // Not an encrypted string
|
||||
let decrypt;
|
||||
try {
|
||||
decrypt = Security.decrypt(seed, [this.master, key, component.props.message.content]);
|
||||
} catch (err) { return } // Ignore errors such as non empty
|
||||
|
||||
component.props.message.bd_encrypted = true; // signal as encrypted
|
||||
|
||||
// Create a generic message object to parse mentions with
|
||||
const message = MessageParser.createMessage(currentChannel.id, MessageParser.parse(currentChannel, decrypt).content);
|
||||
|
||||
if (userMentionPattern.test(message.content))
|
||||
message.mentions = message.content.match(userMentionPattern).map(m => { return { id: m.replace(/[^0-9]/g, '') } });
|
||||
if (roleMentionPattern.test(message.content))
|
||||
message.mention_roles = message.content.match(roleMentionPattern).map(m => m.replace(/[^0-9]/g, ''));
|
||||
if (everyoneMentionPattern.test(message.content))
|
||||
message.mention_everyone = Permissions.can(DiscordConstants.Permissions.MENTION_EVERYONE, currentChannel);
|
||||
|
||||
// Create a new message to parse it properly
|
||||
const create = Message.create(message);
|
||||
if (!create.content || !create.contentParsed) return;
|
||||
|
||||
component.props.message.mentions = create.mentions;
|
||||
component.props.message.mentionRoles = create.mentionRoles;
|
||||
component.props.message.mentionEveryone = create.mentionEveryone;
|
||||
component.props.message.mentioned = create.mentioned;
|
||||
component.props.message.content = create.content;
|
||||
component.props.message.contentParsed = create.contentParsed;
|
||||
}
|
||||
|
||||
afterRenderMessageContent(component, _childrenObject, args, retVal) {
|
||||
if (!component.props.message.bd_encrypted) return;
|
||||
|
||||
const { className } = Reflection.resolve('buttonContainer', 'avatar', 'username');
|
||||
const buttonContainer = Utils.findInReactTree(retVal, m => m && m.className && m.className.indexOf(className) !== -1);
|
||||
if (!buttonContainer) return;
|
||||
|
||||
const buttons = buttonContainer.children.props.children;
|
||||
if (!buttons) return;
|
||||
|
||||
try {
|
||||
buttons.unshift(VueInjector.createReactElement(E2EEMessageButton));
|
||||
} catch (err) {
|
||||
Logger.err('E2EE', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
beforeRenderImageWrapper(component, args, retVal) {
|
||||
if (!component.props || !component.props.src) return;
|
||||
if (component.props.decrypting) return;
|
||||
component.props.decrypting = true;
|
||||
|
||||
const src = component.props.original || component.props.src.split('?')[0];
|
||||
if (!src.includes('bde2ee')) return;
|
||||
component.props.className = 'bd-encryptedImage';
|
||||
|
||||
const haveKey = this.getKey(DiscordApi.currentChannel.id);
|
||||
if (!haveKey) return;
|
||||
|
||||
const cached = Cache.find('e2ee:images', item => item.src === src);
|
||||
if (cached) {
|
||||
if (cached.invalidKey) { // TODO If key has changed we should recheck all with invalid key
|
||||
component.props.className = 'bd-encryptedImage bd-encryptedImageBadKey';
|
||||
component.props.readyState = 'READY';
|
||||
return;
|
||||
}
|
||||
Logger.info('E2EE', 'Returning encrypted image from cache');
|
||||
try {
|
||||
const decrypt = Security.decrypt(seed, [this.master, haveKey, cached.image]);
|
||||
component.props.className = 'bd-decryptedImage';
|
||||
component.props.src = component.props.original = `data:;base64,${decrypt}`;
|
||||
} catch (err) { return } finally { component.props.readyState = 'READY' }
|
||||
return;
|
||||
}
|
||||
|
||||
component.props.readyState = 'LOADING';
|
||||
Logger.info('E2EE', `Decrypting image: ${src}`);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const res = await request.get(src, { encoding: 'binary' });
|
||||
|
||||
const arr = new Uint8Array(new ArrayBuffer(res.length));
|
||||
for (let i = 0; i < res.length; i++) arr[i] = res.charCodeAt(i);
|
||||
|
||||
const aobindex = Utils.aobscan(arr, [73, 69, 78, 68]) + 8;
|
||||
const sliced = arr.slice(aobindex);
|
||||
const image = new TextDecoder().decode(sliced);
|
||||
|
||||
const hmac = image.slice(-64);
|
||||
const data = image.slice(0, -64);
|
||||
const validateHmac = await this.createHmac(data);
|
||||
if (hmac !== validateHmac) {
|
||||
Cache.push('e2ee:images', { src, invalidKey: true });
|
||||
if (component && component.props) {
|
||||
component.props.decrypting = false;
|
||||
component.forceUpdate();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Cache.push('e2ee:images', { src, image: data });
|
||||
|
||||
if (!component || !component.props) {
|
||||
Logger.warn('E2EE', 'Component seems to be gone');
|
||||
return;
|
||||
}
|
||||
|
||||
component.props.decrypting = false;
|
||||
component.forceUpdate();
|
||||
} catch (err) {
|
||||
console.log('request error', err);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
patchChannelTextArea(cta) {
|
||||
this.patch(cta.component.prototype, 'render', this.renderChannelTextArea);
|
||||
}
|
||||
|
||||
renderChannelTextArea(component, args, retVal) {
|
||||
if (!(retVal.props.children instanceof Array)) retVal.props.children = [retVal.props.children];
|
||||
const inner = retVal.props.children.find(child => child.props.className && child.props.className.includes('inner'));
|
||||
inner.props.children.splice(0, 0, VueInjector.createReactElement(E2EEComponent));
|
||||
}
|
||||
|
||||
patchChannelTextAreaSubmit(cta) {
|
||||
this.patch(cta.component.prototype, 'handleSubmit', this.handleChannelTextAreaSubmit, 'before');
|
||||
}
|
||||
|
||||
handleChannelTextAreaSubmit(component, args, retVal) {
|
||||
const key = this.getKey(DiscordApi.currentChannel.id);
|
||||
if (!this.encryptNewMessages || !key) return;
|
||||
component.props.value = Security.encrypt(Security.decrypt(seed, [this.master, key]), component.props.value, '$:');
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
/**
|
||||
* BetterDiscord E2EE Component
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
<template>
|
||||
<div class="bd-e2eeTaContainer">
|
||||
<v-popover :popoverClass="['bd-popover', 'bd-e2eePopover', {'bd-e2eePopoverOver': popoutPositionSetting.value === 'over'}]"
|
||||
:trigger="popoutPositionSetting.value === 'over' && popoutTriggerSetting.value === 'hover' ? 'hover' : 'click'"
|
||||
:placement="popoutPositionSetting.value === 'over' ? 'top-start' : 'top'"
|
||||
:disabled="error && DiscordApi.currentChannel.type !== 'DM'">
|
||||
|
||||
<div v-if="error" class="bd-e2eeTaBtn bd-e2eeLock bd-error">
|
||||
<MiLock v-tooltip="error" />
|
||||
</div>
|
||||
<div v-else-if="state === 'loading'" class="bd-e2eeTaBtn bd-e2eeLock bd-loading bd-warn">
|
||||
<MiLock v-tooltip="'Loading'" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!E2EE.encryptNewMessages" class="bd-e2eeTaBtn bd-e2eeLock bd-warn">
|
||||
<MiLock v-tooltip="'New messages will not be encrypted.'" />
|
||||
</div>
|
||||
|
||||
<div v-else class="bd-e2eeTaBtn bd-e2eeLock bd-ok">
|
||||
<MiLock v-tooltip="'Ready!'" />
|
||||
</div>
|
||||
|
||||
<template slot="popover">
|
||||
<div @click="toggleEncrypt" :class="{'bd-warn': !E2EE.encryptNewMessages, 'bd-ok': E2EE.encryptNewMessages}"><MiLock v-tooltip="'Toggle Encryption'" /></div>
|
||||
<div v-close-popover @click="showUploadDialog" v-if="!error"><MiImagePlus v-tooltip="'Upload Encrypted Image'" /></div>
|
||||
<div v-close-popover @click="generatePublicKey" v-if="DiscordApi.currentChannel.type === 'DM'"><MiIcVpnKey v-tooltip="'Begin Key Exchange'" /></div>
|
||||
</template>
|
||||
</v-popover>
|
||||
<div class="bd-taDivider"></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { Utils, FileUtils, ClientIPC } from 'common';
|
||||
import { E2EE } from 'builtin';
|
||||
import { Settings, DiscordApi, Reflection } from 'modules';
|
||||
import { Toasts } from 'ui';
|
||||
import { MiLock, MiImagePlus, MiIcVpnKey } from 'commoncomponents';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
MiLock, MiImagePlus, MiIcVpnKey
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
E2EE,
|
||||
DiscordApi,
|
||||
state: 'loading',
|
||||
error: null,
|
||||
popoutPositionSetting: Settings.getSetting('security', 'e2ee-popout', 'position'),
|
||||
popoutTriggerSetting: Settings.getSetting('security', 'e2ee-popout', 'trigger')
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
async showUploadDialog() {
|
||||
const dialogResult = await ClientIPC.send('bd-native-open', {properties: ['openFile']});
|
||||
if (!dialogResult || !dialogResult.length) return;
|
||||
|
||||
const readFile = await FileUtils.readFileBuffer(dialogResult[0]);
|
||||
const FileActions = Reflection.module.byProps('makeFile');
|
||||
const Uploader = Reflection.module.byProps('instantBatchUpload');
|
||||
|
||||
const img = await Utils.getImageFromBuffer(readFile);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.height = img.height;
|
||||
canvas.width = img.width;
|
||||
const arrBuffer = await Utils.canvasToArrayBuffer(canvas);
|
||||
const encrypted = E2EE.encrypt(img.src.replace('data:;base64,', ''));
|
||||
const hmac = await E2EE.createHmac(encrypted);
|
||||
const encodedBytes = new TextEncoder().encode(encrypted + hmac);
|
||||
Uploader.upload(DiscordApi.currentChannel.id, FileActions.makeFile(new Uint8Array([...new Uint8Array(arrBuffer), ...encodedBytes]), 'bde2ee.png'));
|
||||
},
|
||||
toggleEncrypt() {
|
||||
const newState = !E2EE.encryptNewMessages;
|
||||
E2EE.encryptNewMessages = newState;
|
||||
if (!newState) {
|
||||
Toasts.warning('New messages will not be encrypted');
|
||||
return;
|
||||
}
|
||||
Toasts.success('New messages will be encrypted');
|
||||
},
|
||||
generatePublicKey() {
|
||||
const keyExchange = E2EE.createKeyExchange(DiscordApi.currentChannel.id);
|
||||
if (keyExchange === null) {
|
||||
Toasts.warning('Key exchange for channel already in progress!');
|
||||
return;
|
||||
}
|
||||
E2EE.preExchangeState = E2EE.encryptNewMessages;
|
||||
E2EE.encryptNewMessages = false; // Disable encrypting new messages so we won't encrypt public keys
|
||||
const publicKeyMessage = `\`\`\`\n-----BEGIN PUBLIC KEY-----\n${keyExchange}\n-----END PUBLIC KEY-----\n\`\`\``;
|
||||
Reflection.modules.DraftActions.saveDraft(DiscordApi.currentChannel.id, publicKeyMessage);
|
||||
Toasts.info('Key exchange started. Expires in 30 seconds');
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
if (!E2EE.master) {
|
||||
this.error = 'No master key set!';
|
||||
return;
|
||||
}
|
||||
const haveKey = E2EE.getKey(DiscordApi.currentChannel.id);
|
||||
if (!haveKey) {
|
||||
this.error = 'No key for channel!';
|
||||
return;
|
||||
}
|
||||
this.state = 'OK';
|
||||
this.error = null;
|
||||
}
|
||||
}
|
||||
</script>
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
* BetterDiscord E2EE Component
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
<template>
|
||||
<div class="bd-e2eeMessageButtonWrap">
|
||||
<div class="bd-e2eeMessageButton">
|
||||
<MiLock v-tooltip="'Encrypted'" :size="16" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { MiLock } from 'commoncomponents';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
MiLock
|
||||
},
|
||||
props: ['message']
|
||||
}
|
||||
</script>
|
|
@ -0,0 +1,3 @@
|
|||
export { default as default } from './E2EE';
|
||||
export { default as E2EEComponent } from './E2EEComponent.vue';
|
||||
export { default as E2EEMessageButton } from './E2EEMessageButton.vue';
|
|
@ -1,8 +0,0 @@
|
|||
<template>
|
||||
<span class="edited" v-tooltip="ets">(edited)</span>
|
||||
</template>
|
||||
<script>
|
||||
export default {
|
||||
props: ['ets']
|
||||
}
|
||||
</script>
|
|
@ -1,21 +0,0 @@
|
|||
<template>
|
||||
<span class="bd-emotewrapper" v-tooltip="name">
|
||||
<img class="bd-emote" :src="src" :alt="`;${name};`"/>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
favourite: false
|
||||
}
|
||||
},
|
||||
props: ['src', 'name'],
|
||||
methods: {
|
||||
},
|
||||
beforeMount() {
|
||||
// Check favourite state
|
||||
}
|
||||
}
|
||||
</script>
|
|
@ -1,182 +0,0 @@
|
|||
/**
|
||||
* BetterDiscord Emote Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
import { FileUtils, ClientLogger as Logger } from 'common';
|
||||
import { Events, Globals, WebpackModules, ReactComponents, MonkeyPatch } from 'modules';
|
||||
import { DOM, VueInjector, Reflection } from 'ui';
|
||||
import EmoteComponent from './EmoteComponent.vue';
|
||||
let emotes = null;
|
||||
const emotesEnabled = true;
|
||||
|
||||
export default class {
|
||||
static get searchCache() {
|
||||
return this._searchCache || (this._searchCache = {});
|
||||
}
|
||||
static get emoteDb() {
|
||||
return emotes;
|
||||
}
|
||||
static get React() {
|
||||
return WebpackModules.getModuleByName('React');
|
||||
}
|
||||
static get ReactDOM() {
|
||||
return WebpackModules.getModuleByName('ReactDOM');
|
||||
}
|
||||
static processMarkup(markup) {
|
||||
if (!emotesEnabled) return markup; // TODO Get it from setttings
|
||||
const newMarkup = [];
|
||||
for (const child of markup) {
|
||||
if ('string' !== typeof child) {
|
||||
newMarkup.push(child);
|
||||
continue;
|
||||
}
|
||||
if (!this.testWord(child)) {
|
||||
newMarkup.push(child);
|
||||
continue;
|
||||
}
|
||||
const words = child.split(/([^\s]+)([\s]|$)/g);
|
||||
if (!words) continue;
|
||||
let text = null;
|
||||
for (const [wordIndex, word] of words.entries()) {
|
||||
const isEmote = this.isEmote(word);
|
||||
if (isEmote) {
|
||||
if (text !== null) {
|
||||
newMarkup.push(text);
|
||||
text = null;
|
||||
}
|
||||
newMarkup.push(this.React.createElement('span', { className: 'bd-emote-outer', 'data-bdemote-name': isEmote.name, 'data-bdemote-src': isEmote.src }));
|
||||
continue;
|
||||
}
|
||||
if (text === null) {
|
||||
text = word;
|
||||
} else {
|
||||
text += word;
|
||||
}
|
||||
if (wordIndex === words.length - 1) {
|
||||
newMarkup.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
return newMarkup;
|
||||
}
|
||||
|
||||
static testWord(word) {
|
||||
if (!/;[\w]+;/gmi.test(word)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static injectAll() {
|
||||
if (!emotesEnabled) return;
|
||||
const all = document.getElementsByClassName('bd-emote-outer');
|
||||
for (const ec of all) {
|
||||
if (ec.children.length) continue;
|
||||
this.injectEmote(ec);
|
||||
}
|
||||
}
|
||||
|
||||
static findByProp(obj, what, value) {
|
||||
if (obj.hasOwnProperty(what) && obj[what] === value) return obj;
|
||||
if (obj.props && !obj.children) return this.findByProp(obj.props, what, value);
|
||||
if (!obj.children || !obj.children.length) return null;
|
||||
for (const child of obj.children) {
|
||||
if (!child) continue;
|
||||
const findInChild = this.findByProp(child, what, value);
|
||||
if (findInChild) return findInChild;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static async observe() {
|
||||
const dataPath = Globals.getObject('paths').find(path => path.id === 'data').path;
|
||||
try {
|
||||
emotes = await FileUtils.readJsonFromFile(dataPath + '/emotes.json');
|
||||
const Message = await ReactComponents.getComponent('Message');
|
||||
this.unpatchRender = MonkeyPatch('BD:EmoteModule', Message.component.prototype).after('render', (component, args, retVal) => {
|
||||
try {
|
||||
const markup = this.findByProp(retVal, 'className', 'markup'); // First child has all the actual text content, second is the edited timestamp
|
||||
if (!markup) return;
|
||||
markup.children[0] = this.processMarkup(markup.children[0]);
|
||||
} catch (err) {
|
||||
Logger.err('EmoteModule', err);
|
||||
}
|
||||
});
|
||||
for (const message of document.querySelectorAll('.message')) {
|
||||
Reflection(message).forceUpdate();
|
||||
}
|
||||
this.injectAll();
|
||||
this.unpatchMount = MonkeyPatch('BD:EmoteModule', Message.component.prototype).after('componentDidMount', component => {
|
||||
const element = this.ReactDOM.findDOMNode(component);
|
||||
if (!element) return;
|
||||
this.injectEmotes(element);
|
||||
});
|
||||
this.unpatchUpdate = MonkeyPatch('BD:EmoteModule', Message.component.prototype).after('componentDidUpdate', component => {
|
||||
const element = this.ReactDOM.findDOMNode(component);
|
||||
if (!element) return;
|
||||
this.injectEmotes(element);
|
||||
});
|
||||
} catch (err) {
|
||||
Logger.err('EmoteModule', err);
|
||||
}
|
||||
}
|
||||
|
||||
static injectEmote(root) {
|
||||
if (!emotesEnabled) return;
|
||||
while (root.firstChild) {
|
||||
root.removeChild(root.firstChild);
|
||||
}
|
||||
const { bdemoteName, bdemoteSrc } = root.dataset;
|
||||
if (!bdemoteName || !bdemoteSrc) return;
|
||||
VueInjector.inject(
|
||||
root,
|
||||
DOM.createElement('span'),
|
||||
{ EmoteComponent },
|
||||
`<EmoteComponent src="${bdemoteSrc}" name="${bdemoteName}"/>`
|
||||
);
|
||||
root.classList.add('bd-is-emote');
|
||||
}
|
||||
|
||||
static injectEmotes(element) {
|
||||
if (!emotesEnabled || !element) return;
|
||||
for (const beo of element.getElementsByClassName('bd-emote-outer')) this.injectEmote(beo);
|
||||
}
|
||||
|
||||
static isEmote(word) {
|
||||
if (!emotes) return null;
|
||||
const name = word.replace(/;/g, '');
|
||||
const emote = emotes.find(emote => emote.id === name);
|
||||
if (!emote) return null;
|
||||
let { id, value } = emote;
|
||||
if (value.id) value = value.id;
|
||||
const uri = emote.type === 2 ? 'https://cdn.betterttv.net/emote/:id/1x' : emote.type === 1 ? 'https://cdn.frankerfacez.com/emoticon/:id/1' : 'https://static-cdn.jtvnw.net/emoticons/v1/:id/1.0';
|
||||
return { name, src: uri.replace(':id', value) };
|
||||
}
|
||||
|
||||
static filterTest() {
|
||||
const re = new RegExp('Kappa', 'i');
|
||||
const filtered = emotes.filter(emote => re.test(emote.id));
|
||||
return filtered.slice(0, 10);
|
||||
}
|
||||
|
||||
static filter(regex, limit, start = 0) {
|
||||
const key = `${regex}:${limit}:${start}`;
|
||||
if (this.searchCache.hasOwnProperty(key)) return this.searchCache[key];
|
||||
let index = 0;
|
||||
let startIndex = 0;
|
||||
return this.searchCache[key] = emotes.filter(emote => {
|
||||
if (index >= limit) return false;
|
||||
if (regex.test(emote.id)) {
|
||||
if (startIndex < start) {
|
||||
startIndex++;
|
||||
return false;
|
||||
}
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
/**
|
||||
* BetterDiscord Emote Autocomplete Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Settings } from 'modules';
|
||||
import BuiltinModule from '../BuiltinModule';
|
||||
import EmoteModule, { EMOTE_SOURCES } from './EmoteModule';
|
||||
import GlobalAc from 'autocomplete';
|
||||
import { BdContextMenu } from 'ui';
|
||||
|
||||
export default new class EmoteAc extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'EmoteAC' }
|
||||
get settingPath() { return ['emotes', 'default', 'emoteac'] }
|
||||
|
||||
async enabled(e) {
|
||||
GlobalAc.add(';', this);
|
||||
window.removeEventListener('contextmenu', this.acCm);
|
||||
window.addEventListener('contextmenu', this.acCm);
|
||||
}
|
||||
|
||||
disabled(e) {
|
||||
GlobalAc.remove(';');
|
||||
window.removeEventListener('contextmenu', this.acCm);
|
||||
}
|
||||
|
||||
/* Methods */
|
||||
acCm(e) {
|
||||
const row = e.target.closest('.bd-emotAc');
|
||||
if (!row) return;
|
||||
const img = row.querySelector('img');
|
||||
if (!img || !img.alt) return;
|
||||
|
||||
BdContextMenu.show(e, [
|
||||
{
|
||||
text: 'Test',
|
||||
items: [
|
||||
{
|
||||
text: 'Favourite',
|
||||
type: 'toggle',
|
||||
checked: EmoteModule.isFavourite(img.alt.replace(/;/g, '')),
|
||||
onChange: checked => {
|
||||
if (!img || !img.alt) return;
|
||||
const emote = img.alt.replace(/;/g, '');
|
||||
if (!checked) return EmoteModule.removeFavourite(emote), false;
|
||||
return EmoteModule.addFavourite(emote), true;
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for autocomplete
|
||||
* @param {any} regex
|
||||
*/
|
||||
acsearch(regex) {
|
||||
const acType = Settings.getSetting('emotes', 'default', 'emoteactype').value;
|
||||
if (regex.length <= 0) {
|
||||
return {
|
||||
type: 'imagetext',
|
||||
title: [`Your ${acType ? 'most used' : 'favourite'} emotes`, '', `⬅ ${acType ? 'Favourites' : 'Most Used'} ⮕`],
|
||||
items: EmoteModule[acType ? 'mostUsed' : 'favourites'].sort((a, b) => b.useCount - a.useCount).map(mu => {
|
||||
return {
|
||||
key: acType ? mu.key : mu.name,
|
||||
value: {
|
||||
src: EMOTE_SOURCES[mu.type].replace(':id', mu.id),
|
||||
replaceWith: `;${acType ? mu.key : mu.name};`,
|
||||
hint: mu.useCount ? `Used ${mu.useCount} times` : null
|
||||
}
|
||||
}
|
||||
}),
|
||||
extraClasses: ['bd-emotAc']
|
||||
}
|
||||
}
|
||||
|
||||
const results = EmoteModule.search(regex);
|
||||
return {
|
||||
type: 'imagetext',
|
||||
title: ['Matching', regex.length],
|
||||
items: results.map(result => {
|
||||
result.value.src = EMOTE_SOURCES[result.value.type].replace(':id', result.value.id);
|
||||
result.value.replaceWith = `;${result.key};`;
|
||||
return result;
|
||||
}),
|
||||
extraClasses: ['bd-emotAc']
|
||||
}
|
||||
}
|
||||
|
||||
toggle(sterm) {
|
||||
if (sterm.length > 1) return false;
|
||||
Settings.getSetting('emotes', 'default', 'emoteactype').value = !Settings.getSetting('emotes', 'default', 'emoteactype').value;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
* BetterDiscord Emote Component
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import VrWrapper from '../../ui/vrwrapper';
|
||||
import { EMOTE_SOURCES } from '.';
|
||||
import EmoteComponent from './EmoteComponent.vue';
|
||||
|
||||
export default class Emote extends VrWrapper {
|
||||
|
||||
constructor(type, id, name) {
|
||||
super();
|
||||
this.jumboable = false;
|
||||
this.type = type;
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
get component() { return EmoteComponent }
|
||||
|
||||
get props() {
|
||||
return {
|
||||
src: this.parseSrc(),
|
||||
name: this.name,
|
||||
jumboable: this.jumboable
|
||||
}
|
||||
}
|
||||
|
||||
parseSrc() {
|
||||
const { type, id } = this;
|
||||
if (type > 2 || type < 0) return '';
|
||||
return EMOTE_SOURCES[type].replace(':id', id);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
<template>
|
||||
<img class="bd-emote emoji" :class="{jumboable}" :src="src" :alt="`;${name};`" v-tooltip="{ content: `;${name};`, delay: { show: 750, hide: 0 } }" />
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import EmoteModule from './EmoteModule';
|
||||
import { MiStar } from 'commoncomponents';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
MiStar
|
||||
},
|
||||
props: ['src', 'name', 'hasWrapper', 'jumboable'],
|
||||
data() {
|
||||
return {
|
||||
EmoteModule
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
favourite() {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async toggleFavourite() {
|
||||
await EmoteModule.setFavourite(this.name, !this.favourite);
|
||||
Logger.log('EmoteComponent', `Set emote ${this.name} as ${this.favourite ? '' : 'un'}favourite`);
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
|
@ -0,0 +1,406 @@
|
|||
/**
|
||||
* BetterDiscord Emote Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from '../BuiltinModule';
|
||||
import path from 'path';
|
||||
import { request } from 'vendor';
|
||||
|
||||
import { Utils, FileUtils, ClientLogger as Logger } from 'common';
|
||||
import { DiscordApi, Settings, Globals, Reflection, ReactComponents, Database } from 'modules';
|
||||
import { DiscordContextMenu } from 'ui';
|
||||
|
||||
import Emote from './EmoteComponent.js';
|
||||
|
||||
export const EMOTE_SOURCES = [
|
||||
'https://static-cdn.jtvnw.net/emoticons/v1/:id/1.0',
|
||||
'https://cdn.frankerfacez.com/emoticon/:id/1',
|
||||
'https://cdn.betterttv.net/emote/:id/1x'
|
||||
];
|
||||
|
||||
export default new class EmoteModule extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
|
||||
get moduleName() { return 'EmoteModule' }
|
||||
|
||||
/**
|
||||
* @returns {String} Path to local emote database
|
||||
*/
|
||||
get dbpath() { return path.join(Globals.getPath('data'), 'emotes.json') }
|
||||
|
||||
/**
|
||||
* @returns {Map} Cached raw emote database
|
||||
*/
|
||||
get database() { return this._db || (this._db = new Map()) }
|
||||
|
||||
/**
|
||||
* @returns {Array} Favourite emotes
|
||||
*/
|
||||
get favourites() { return this._favourites || (this._favourites = []) }
|
||||
|
||||
/**
|
||||
* @returns {Array} Most used emotes
|
||||
*/
|
||||
get mostUsed() { return this._mostUsed || (this._mostUsed = []) }
|
||||
|
||||
get settingPath() { return ['emotes', 'default', 'enable'] }
|
||||
|
||||
async enabled() {
|
||||
// Add favourite button to context menu
|
||||
this.favCm = DiscordContextMenu.add(target => [
|
||||
{
|
||||
text: 'Favourite',
|
||||
type: 'toggle',
|
||||
checked: target && target.alt && this.isFavourite(target.alt.replace(/;/g, '')),
|
||||
onChange: (checked, target) => {
|
||||
const { alt } = target;
|
||||
if (!alt) return false;
|
||||
|
||||
const emote = alt.replace(/;/g, '');
|
||||
|
||||
if (!checked) return this.removeFavourite(emote), false;
|
||||
return this.addFavourite(emote), true;
|
||||
}
|
||||
}
|
||||
], target => target.closest('.bd-emote'));
|
||||
|
||||
if (!this.database.size) {
|
||||
await this.loadLocalDb();
|
||||
}
|
||||
|
||||
// Read favourites and most used from database
|
||||
await this.loadUserData();
|
||||
}
|
||||
|
||||
async disabled() {
|
||||
DiscordContextMenu.remove(this.favCm);
|
||||
}
|
||||
|
||||
/* Methods */
|
||||
|
||||
/**
|
||||
* Adds an emote to favourites.
|
||||
* @param {Object|String} emote
|
||||
* @return {Promise}
|
||||
*/
|
||||
addFavourite(emote) {
|
||||
if (this.isFavourite(emote)) return;
|
||||
if (typeof emote === 'string') emote = this.findByName(emote, true);
|
||||
this.favourites.push(emote);
|
||||
return this.saveUserData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an emote from favourites.
|
||||
* @param {Object|String} emote
|
||||
* @return {Promise}
|
||||
*/
|
||||
removeFavourite(emote) {
|
||||
if (!this.isFavourite(emote)) return;
|
||||
Utils.removeFromArray(this.favourites, e => e.name === emote || e.name === emote.name, true);
|
||||
return this.saveUserData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an emote is in favourites.
|
||||
* @param {Object|String} emote
|
||||
* @return {Boolean}
|
||||
*/
|
||||
isFavourite(emote) {
|
||||
return !!this.favourites.find(e => e.name === emote || e.name === emote.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load emotes from local database
|
||||
*/
|
||||
async loadLocalDb() {
|
||||
const emotes = await FileUtils.readJsonFromFile(this.dbpath);
|
||||
for (const [index, emote] of emotes.entries()) {
|
||||
const { type, id, src, value } = emote;
|
||||
if (index % 10000 === 0) await Utils.wait();
|
||||
|
||||
this.database.set(id, { id: emote.value.id || value, type });
|
||||
}
|
||||
|
||||
Logger.log('EmoteModule', ['Loaded emote database']);
|
||||
}
|
||||
|
||||
async loadUserData() {
|
||||
const userData = await Database.findOne({ type: 'builtin', id: 'EmoteModule' });
|
||||
if (!userData) return;
|
||||
|
||||
if (userData.hasOwnProperty('favourites')) this._favourites = userData.favourites;
|
||||
if (userData.hasOwnProperty('mostused')) this._mostUsed = userData.mostused;
|
||||
}
|
||||
|
||||
async saveUserData() {
|
||||
await Database.insertOrUpdate({ type: 'builtin', id: 'EmoteModule' }, {
|
||||
type: 'builtin',
|
||||
id: 'EmoteModule',
|
||||
favourites: this.favourites,
|
||||
mostused: this.mostUsed
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add/update emote to most used
|
||||
* @param {Object} emote emote to add/update
|
||||
* @return {Promise}
|
||||
*/
|
||||
addToMostUsed(emote) {
|
||||
const isMostUsed = this.mostUsed.find(mu => mu.key === emote.name);
|
||||
if (isMostUsed) {
|
||||
isMostUsed.useCount += 1;
|
||||
} else {
|
||||
this.mostUsed.push({
|
||||
key: emote.name,
|
||||
id: emote.id,
|
||||
type: emote.type,
|
||||
useCount: 1
|
||||
});
|
||||
}
|
||||
// Save most used to database
|
||||
// TODO only save first n
|
||||
return this.saveUserData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an emote by name
|
||||
* @param {String} name Emote name
|
||||
* @param {Boolean} simple Simple object or Emote instance
|
||||
* @returns {Object|Emote}
|
||||
*/
|
||||
findByName(name, simple = false) {
|
||||
const emote = this.database.get(name);
|
||||
if (!emote) return null;
|
||||
return this.parseEmote(name, emote, simple);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse emote object
|
||||
* @param {String} name Emote name
|
||||
* @param {Object} emote Emote object
|
||||
* @param {Boolean} simple Simple object or Emote instance
|
||||
* @returns {Object|Emote}
|
||||
*/
|
||||
parseEmote(name, emote, simple = false) {
|
||||
const { type, id } = emote;
|
||||
if (type < 0 || type > 2) return null;
|
||||
return simple ? { type, id, name } : new Emote(type, id, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for anything else
|
||||
* @param {any} regex
|
||||
* @param {any} limit
|
||||
*/
|
||||
search(regex, limit = 10) {
|
||||
if (typeof regex === 'string') regex = new RegExp(regex, 'i');
|
||||
const matching = [];
|
||||
|
||||
for (const [key, value] of this.database.entries()) {
|
||||
if (matching.length >= limit) break;
|
||||
if (regex.test(key)) matching.push({ key, value })
|
||||
}
|
||||
|
||||
return matching;
|
||||
}
|
||||
|
||||
/* Patches */
|
||||
async applyPatches() {
|
||||
this.patchMessageContent();
|
||||
this.patchSendAndEdit();
|
||||
this.patchSpoiler();
|
||||
|
||||
const MessageAccessories = await ReactComponents.getComponent('MessageAccessories');
|
||||
this.patch(MessageAccessories.component.prototype, 'render', this.afterRenderMessageAccessories, 'after');
|
||||
MessageAccessories.forceUpdateAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Patches MessageContent render method
|
||||
*/
|
||||
async patchMessageContent() {
|
||||
const MessageContent = await ReactComponents.getComponent('MessageContent');
|
||||
this.childPatch(MessageContent.component.prototype, 'render', ['props', 'children'], this.afterRenderMessageContent);
|
||||
MessageContent.forceUpdateAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Patches MessageActions send and edit
|
||||
*/
|
||||
patchSendAndEdit() {
|
||||
const { MessageActions } = Reflection.modules;
|
||||
this.patch(MessageActions, 'sendMessage', this.handleSendMessage, 'instead');
|
||||
this.patch(MessageActions, 'editMessage', this.handleEditMessage, 'instead');
|
||||
}
|
||||
|
||||
async patchSpoiler() {
|
||||
const Spoiler = await ReactComponents.getComponent('Spoiler');
|
||||
this.childPatch(Spoiler.component.prototype, 'render', ['props', 'children', 'props', 'children'], this.afterRenderSpoiler);
|
||||
Spoiler.forceUpdateAll();
|
||||
}
|
||||
|
||||
afterRenderSpoiler(component, _childrenObject, args, retVal) {
|
||||
const markup = Utils.findInReactTree(retVal, filter =>
|
||||
filter &&
|
||||
filter.className &&
|
||||
filter.className.includes('inlineContent'));
|
||||
if (!markup) return;
|
||||
|
||||
markup.children = this.processMarkup(markup.children);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle message render
|
||||
*/
|
||||
afterRenderMessageContent(component, _childrenObject, args, retVal) {
|
||||
const markup = Utils.findInReactTree(retVal, filter =>
|
||||
filter &&
|
||||
filter.className &&
|
||||
filter.className.includes('markup') &&
|
||||
filter.children.length >= 2);
|
||||
if (!markup) return;
|
||||
markup.children[1] = this.processMarkup(markup.children[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle send message
|
||||
*/
|
||||
async handleSendMessage(MessageActions, args, orig) {
|
||||
if (!args.length) return orig(...args);
|
||||
const { content } = args[1];
|
||||
if (!content) return orig(...args);
|
||||
|
||||
Logger.log('EmoteModule', ['Sending message', MessageActions, args, orig]);
|
||||
|
||||
const emoteAsImage = Settings.getSetting('emotes', 'default', 'emoteasimage').value &&
|
||||
(DiscordApi.currentChannel.type === 'DM' || DiscordApi.currentChannel.type === 'GROUP_DM' || DiscordApi.currentChannel.checkPermissions(DiscordApi.modules.DiscordPermissions.ATTACH_FILES));
|
||||
|
||||
if (!emoteAsImage || content.split(' ').length > 1) {
|
||||
args[1].content = args[1].content.split(' ').map(word => {
|
||||
const isEmote = /;(.*?);/g.exec(word);
|
||||
if (isEmote) {
|
||||
const emote = this.findByName(isEmote[1], true);
|
||||
if (!emote) return word;
|
||||
this.addToMostUsed(emote);
|
||||
return emote ? `;${isEmote[1]};` : word;
|
||||
}
|
||||
return word;
|
||||
}).join(' ');
|
||||
return orig(...args);
|
||||
}
|
||||
|
||||
const isEmote = /;(.*?);/g.exec(content);
|
||||
if (!isEmote) return orig(...args);
|
||||
|
||||
const emote = this.findByName(isEmote[1]);
|
||||
if (!emote) return orig(...args);
|
||||
this.addToMostUsed(emote);
|
||||
|
||||
const FileActions = Reflection.module.byProps('makeFile');
|
||||
const Uploader = Reflection.module.byProps('instantBatchUpload');
|
||||
|
||||
request.get(emote.props.src, { encoding: 'binary' }).then(res => {
|
||||
const arr = new Uint8Array(new ArrayBuffer(res.length));
|
||||
for (let i = 0; i < res.length; i++) arr[i] = res.charCodeAt(i);
|
||||
const suffix = arr[0] === 71 && arr[1] === 73 && arr[2] === 70 ? '.gif' : '.png';
|
||||
Uploader.upload(args[0], FileActions.makeFile(arr, `${emote.name}.bdemote${suffix}`));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle edit message
|
||||
*/
|
||||
handleEditMessage(component, args, orig) {
|
||||
if (!args.length) return orig(...args);
|
||||
const { content } = args[2];
|
||||
if (!content) return orig(...args);
|
||||
args[2].content = args[2].content.split(' ').map(word => {
|
||||
const isEmote = /;(.*?);/g.exec(word);
|
||||
return isEmote ? `;${isEmote[1]};` : word;
|
||||
}).join(' ');
|
||||
return orig(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle MessageAccessories render
|
||||
*/
|
||||
afterRenderMessageAccessories(component, args, retVal) {
|
||||
if (!component.props || !component.props.message) return;
|
||||
if (!component.props.message.attachments || component.props.message.attachments.length !== 1) return;
|
||||
|
||||
const filename = component.props.message.attachments[0].filename;
|
||||
const match = filename.match(/([^/]*)\.bdemote\.(gif|png)$/i);
|
||||
if (!match) return;
|
||||
|
||||
const emote = this.findByName(match[1]);
|
||||
if (!emote) return;
|
||||
|
||||
emote.jumboable = true;
|
||||
retVal.props.children[2] = emote.render();
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject emotes into markup
|
||||
*/
|
||||
processMarkup(markup) {
|
||||
const newMarkup = [];
|
||||
if (!(markup instanceof Array)) return markup;
|
||||
|
||||
const jumboable = !markup.some(child => {
|
||||
if (typeof child !== 'string') return false;
|
||||
return / \w+/g.test(child);
|
||||
});
|
||||
|
||||
for (const child of markup) {
|
||||
if (typeof child !== 'string') {
|
||||
if (typeof child === 'object') {
|
||||
const isEmoji = Utils.findInReactTree(child, filter => filter && filter.emojiName);
|
||||
if (isEmoji) isEmoji.jumboable = jumboable;
|
||||
}
|
||||
newMarkup.push(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!/;(\w+);/g.test(child)) {
|
||||
newMarkup.push(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
const words = child.split(/([^\s]+)([\s]|$)/g).filter(f => f !== '');
|
||||
|
||||
let s = '';
|
||||
for (const word of words) {
|
||||
const isemote = /;(.*?);/g.exec(word);
|
||||
if (!isemote) {
|
||||
s += word;
|
||||
continue;
|
||||
}
|
||||
|
||||
const emote = this.findByName(isemote[1]);
|
||||
if (!emote) {
|
||||
s += word;
|
||||
continue;
|
||||
}
|
||||
|
||||
newMarkup.push(s);
|
||||
s = '';
|
||||
|
||||
emote.jumboable = jumboable;
|
||||
newMarkup.push(emote.render());
|
||||
}
|
||||
if (s !== '') newMarkup.push(s);
|
||||
}
|
||||
if (newMarkup.length === 1) return newMarkup[0];
|
||||
return newMarkup;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
export { default as EmoteModule, EMOTE_SOURCES } from './EmoteModule';
|
||||
export { default as Emote } from './EmoteComponent';
|
||||
export { default as EmoteComponent } from './EmoteComponent.vue';
|
||||
export { default as EmoteAc } from './EmoteAc';
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
* BetterDiscord Kill Clyde Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
import { Reflection } from 'modules';
|
||||
|
||||
export default new class KillClyde extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'KillClyde' }
|
||||
|
||||
get settingPath() { return ['ui', 'default', 'kill-clyde'] }
|
||||
|
||||
/* Patches */
|
||||
applyPatches() {
|
||||
if (this.patches.length) return;
|
||||
const { MessageActions } = Reflection.modules;
|
||||
this.patch(MessageActions, 'sendBotMessage', () => void 0, 'instead');
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
import { EmoteModule, EmoteAc } from './Emotes';
|
||||
import ReactDevtoolsModule from './ReactDevtoolsModule';
|
||||
import VueDevtoolsModule from './VueDevToolsModule';
|
||||
import TrackingProtection from './TrackingProtection';
|
||||
import E2EE from './E2EE';
|
||||
import ColoredText from './ColoredText';
|
||||
import TwentyFourHour from './24Hour';
|
||||
import KillClyde from './KillClyde';
|
||||
import BlockedMessages from './BlockedMessages';
|
||||
import VoiceDisconnect from './VoiceDisconnect';
|
||||
|
||||
export default class {
|
||||
static get modules() {
|
||||
return require('./builtin');
|
||||
}
|
||||
|
||||
static initAll() {
|
||||
EmoteModule.init();
|
||||
ReactDevtoolsModule.init();
|
||||
VueDevtoolsModule.init();
|
||||
TrackingProtection.init();
|
||||
E2EE.init();
|
||||
ColoredText.init();
|
||||
TwentyFourHour.init();
|
||||
KillClyde.init();
|
||||
BlockedMessages.init();
|
||||
VoiceDisconnect.init();
|
||||
EmoteAc.init();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/**
|
||||
* BetterDiscord React Devtools Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import electron from 'electron';
|
||||
import path from 'path';
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
|
||||
import { Globals } from 'modules';
|
||||
import { Toasts } from 'ui';
|
||||
|
||||
export default new class ReactDevtoolsModule extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'ReactDevTools' }
|
||||
|
||||
get settingPath() { return ['core', 'advanced', 'react-devtools'] }
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.devToolsOpened = this.devToolsOpened.bind(this);
|
||||
}
|
||||
|
||||
enabled(e) {
|
||||
electron.remote.getCurrentWindow().webContents.on('devtools-opened', this.devToolsOpened);
|
||||
if (electron.remote.getCurrentWindow().isDevToolsOpened) this.devToolsOpened();
|
||||
}
|
||||
|
||||
disabled(e) {
|
||||
electron.remote.BrowserWindow.removeDevToolsExtension('React Developer Tools');
|
||||
electron.remote.getCurrentWindow().webContents.removeListener('devtools-opened', this.devToolsOpened);
|
||||
}
|
||||
|
||||
devToolsOpened() {
|
||||
electron.remote.BrowserWindow.removeDevToolsExtension('React Developer Tools');
|
||||
|
||||
try {
|
||||
const res = electron.remote.BrowserWindow.addDevToolsExtension(path.join(Globals.getPath('ext'), 'extensions', 'rdt'));
|
||||
if (res !== undefined) {
|
||||
Toasts.success(`${res} Installed`);
|
||||
return;
|
||||
}
|
||||
Toasts.error('React Developer Tools install failed');
|
||||
} catch (err) {
|
||||
Toasts.error('React Developer Tools install failed');
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
/**
|
||||
* BetterDiscord Tracking Protection Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
|
||||
import { Reflection } from 'modules';
|
||||
|
||||
export default new class TrackingProtection extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'TrackingProtection' }
|
||||
|
||||
get settingPath() { return ['security', 'default', 'tracking-protection'] }
|
||||
|
||||
/* Patches */
|
||||
applyPatches() {
|
||||
if (this.patches.length) return;
|
||||
const TrackingModule = Reflection.module.byProps('track');
|
||||
if (!TrackingModule) {
|
||||
this.warn('Tracking module not found!');
|
||||
return;
|
||||
}
|
||||
this.patch(TrackingModule, 'track', this.track, 'instead');
|
||||
}
|
||||
|
||||
track(e) {
|
||||
this.debug('Tracking blocked');
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
/**
|
||||
* BetterDiscord Voice Disconnect Timestamps Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
import { Reflection } from 'modules';
|
||||
|
||||
export default new class VoiceDisconnect extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'VoiceDisconnect' }
|
||||
|
||||
get settingPath() { return ['core', 'default', 'voice-disconnect'] }
|
||||
|
||||
async enabled(e) {
|
||||
window.addEventListener('beforeunload', this.listener);
|
||||
}
|
||||
|
||||
disabled(e) {
|
||||
window.removeEventListener('beforeunload', this.listener);
|
||||
}
|
||||
|
||||
/* Methods */
|
||||
listener() {
|
||||
const { VoiceChannelActions } = Reflection.modules;
|
||||
VoiceChannelActions.selectVoiceChannel(null, null);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/**
|
||||
* BetterDiscord Vue Devtools Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import electron from 'electron';
|
||||
import path from 'path';
|
||||
|
||||
import BuiltinModule from './BuiltinModule';
|
||||
|
||||
import { Globals } from 'modules';
|
||||
import { Toasts } from 'ui';
|
||||
|
||||
export default new class VueDevtoolsModule extends BuiltinModule {
|
||||
|
||||
/* Getters */
|
||||
get moduleName() { return 'VueDevTools' }
|
||||
|
||||
get settingPath() { return ['core', 'advanced', 'vue-devtools'] }
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.devToolsOpened = this.devToolsOpened.bind(this);
|
||||
}
|
||||
|
||||
enabled(e) {
|
||||
electron.remote.getCurrentWindow().webContents.on('devtools-opened', this.devToolsOpened);
|
||||
if (electron.remote.getCurrentWindow().isDevToolsOpened) this.devToolsOpened();
|
||||
}
|
||||
|
||||
disabled(e) {
|
||||
electron.remote.BrowserWindow.removeDevToolsExtension('Vue.js devtools');
|
||||
electron.remote.getCurrentWindow().webContents.removeListener('devtools-opened', this.devToolsOpened);
|
||||
}
|
||||
|
||||
devToolsOpened() {
|
||||
electron.remote.BrowserWindow.removeDevToolsExtension('Vue.js devtools');
|
||||
|
||||
try {
|
||||
const res = electron.remote.BrowserWindow.addDevToolsExtension(path.join(Globals.getPath('ext'), 'extensions', 'vdt'));
|
||||
if (res !== undefined) {
|
||||
Toasts.success(`${res} Installed`);
|
||||
return;
|
||||
}
|
||||
Toasts.error('Vue.js devtools install failed');
|
||||
} catch (err) {
|
||||
Toasts.error('Vue.js devtools install failed');
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1 +1,11 @@
|
|||
export { default as EmoteModule } from './EmoteModule';
|
||||
export { EmoteModule, EmoteAc } from './Emotes';
|
||||
export { default as ReactDevtoolsModule } from './ReactDevtoolsModule';
|
||||
export { default as VueDevtoolsModule } from './VueDevToolsModule';
|
||||
export { default as TrackingProtection } from './TrackingProtection';
|
||||
export { default as BuiltinManager } from './Manager';
|
||||
export { default as E2EE } from './E2EE';
|
||||
export { default as ColoredText } from './ColoredText';
|
||||
export { default as TwentyFourHour } from './24Hour';
|
||||
export { default as KillClyde } from './KillClyde';
|
||||
export { default as BlockedMessages } from './BlockedMessages';
|
||||
export { default as VoiceDisconnect } from './VoiceDisconnect';
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
[
|
||||
{
|
||||
"__user": "Jiiks#5000",
|
||||
"id": "81388395867156480",
|
||||
"developer": true,
|
||||
"webdev": true,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Pohky#0156",
|
||||
"id": "98003542823944192",
|
||||
"developer": true,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Hammock#3110",
|
||||
"id": "138850472541814784",
|
||||
"developer": false,
|
||||
"webdev": true,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Zerebos#7790",
|
||||
"id": "249746236008169473",
|
||||
"developer": true,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Pierce#1337",
|
||||
"id": "125367412370440192",
|
||||
"developer": true,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Samuel Elliott#2764",
|
||||
"id": "284056145272766465",
|
||||
"developer": true,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Lilian Tedone#6223",
|
||||
"id": "184021060562321419",
|
||||
"developer": false,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "samfun123#8972",
|
||||
"id": "76052829285916672",
|
||||
"developer": false,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "samogot#4379",
|
||||
"id": "171005991272316937",
|
||||
"developer": false,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Lucario 🌌 V5.0.0#7902",
|
||||
"id": "438469378418409483",
|
||||
"developer": false,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
},
|
||||
{
|
||||
"__user": "Maks#3712",
|
||||
"id": "340975736037048332",
|
||||
"developer": false,
|
||||
"webdev": false,
|
||||
"contributor": true
|
||||
}
|
||||
]
|
|
@ -5,31 +5,14 @@
|
|||
"headertext": "Core Settings",
|
||||
"settings": [
|
||||
{
|
||||
"category": "default",
|
||||
"id": "default",
|
||||
"settings": [
|
||||
{
|
||||
"id": "test-setting",
|
||||
"type": "bool",
|
||||
"text": "Test Setting",
|
||||
"hint": "Test Setting",
|
||||
"value": false,
|
||||
"disabled": false
|
||||
},
|
||||
{
|
||||
"id": "test-setting2",
|
||||
"type": "bool",
|
||||
"text": "Test Setting 2",
|
||||
"hint": "Test Setting 2",
|
||||
"value": true,
|
||||
"disabled": false
|
||||
},
|
||||
{
|
||||
"id": "voice-disconnect",
|
||||
"type": "bool",
|
||||
"text": "Voice Disconnect",
|
||||
"hint": "Disconnect from voice server when Discord closes",
|
||||
"value": false,
|
||||
"disabled": true
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "menu-keybind",
|
||||
|
@ -40,8 +23,8 @@
|
|||
]
|
||||
},
|
||||
{
|
||||
"category": "advanced",
|
||||
"category_name": "Advanced",
|
||||
"id": "advanced",
|
||||
"name": "Advanced",
|
||||
"type": "drawer",
|
||||
"settings": [
|
||||
{
|
||||
|
@ -51,12 +34,44 @@
|
|||
"hint": "Adds some of BetterDiscord's internal modules to `global._bd`.",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "debugger-keybind",
|
||||
"type": "keybind",
|
||||
"text": "Debugger keybind",
|
||||
"hint": "Open developer tools and pause"
|
||||
},
|
||||
{
|
||||
"id": "ignore-content-manager-errors",
|
||||
"type": "bool",
|
||||
"text": "Ignore content manager errors",
|
||||
"hint": "Only when starting Discord. It gets annoying when you're reloading Discord often and have plugins that are meant to fail.",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "react-devtools",
|
||||
"type": "bool",
|
||||
"text": "React Developer Tools",
|
||||
"hint": "Place extension in ext/extensions/rdt",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "vue-devtools",
|
||||
"type": "bool",
|
||||
"text": "Vue Developer Tools",
|
||||
"hint": "Place extension in ext/extensions/vdt",
|
||||
"value": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "window-preferences",
|
||||
"name": "Window Preferences",
|
||||
"type": "drawer",
|
||||
"settings": [
|
||||
{
|
||||
"id": "window-preferences",
|
||||
"type": "custom",
|
||||
"component": "WindowPreferences"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -68,7 +83,7 @@
|
|||
"headertext": "UI Settings",
|
||||
"settings": [
|
||||
{
|
||||
"category": "default",
|
||||
"id": "default",
|
||||
"settings": [
|
||||
{
|
||||
"id": "hide-button",
|
||||
|
@ -77,6 +92,59 @@
|
|||
"hint": "When this is enabled you can use Ctrl/Cmd + B to open the BetterDiscord settings menu.",
|
||||
"value": false,
|
||||
"disabled": false
|
||||
},
|
||||
{
|
||||
"id": "enable-toasts",
|
||||
"type": "bool",
|
||||
"text": "Enable Toasts",
|
||||
"hint": "Allows plugins to show toasts.",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"id": "colored-text",
|
||||
"type": "bool",
|
||||
"text": "Colored Text",
|
||||
"hint": "Colors messages to match the user's role color.",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "24-hour",
|
||||
"type": "bool",
|
||||
"text": "24 Hour Timestamps",
|
||||
"hint": "Replaces 12 hour timestamps with proper ones.",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "kill-clyde",
|
||||
"type": "bool",
|
||||
"text": "Kill Clyde",
|
||||
"hint": "Prevents Clyde from sending you error messages.",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "blocked-messages",
|
||||
"type": "bool",
|
||||
"text": "Prevent Blocked Messages",
|
||||
"hint": "Hides blocked messages in chat and even hides the new message notification.",
|
||||
"value": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "advanced",
|
||||
"name": "Advanced",
|
||||
"type": "drawer",
|
||||
"settings": [
|
||||
{
|
||||
"id": "colored-text-intensity",
|
||||
"type": "slider",
|
||||
"text": "Colored Text Intensity",
|
||||
"hint": "Intensity of the colored text setting.",
|
||||
"value": 100,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"step": 1,
|
||||
"unit": "%"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -86,15 +154,47 @@
|
|||
"id": "emotes",
|
||||
"text": "Emotes",
|
||||
"headertext": "Emote Settings",
|
||||
"settings": []
|
||||
"settings": [
|
||||
{
|
||||
"id": "default",
|
||||
"settings": [
|
||||
{
|
||||
"id": "enable",
|
||||
"type": "bool",
|
||||
"text": "Enable emotes",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"id": "emoteasimage",
|
||||
"type": "bool",
|
||||
"text": "Image Emote",
|
||||
"hint": "Send single emotes as images if you have the permission",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"id": "emoteac",
|
||||
"type": "bool",
|
||||
"text": "Emote Autocomplete",
|
||||
"hint": "Autocomplete emotes when typing with ; prefix",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"id": "emoteactype",
|
||||
"type": "bool",
|
||||
"text": "Show most used instead of favourites",
|
||||
"hint": "Toggle with arrow keys in autocomplete menu",
|
||||
"value": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "css",
|
||||
"text": "CSS Editor",
|
||||
"hidden": true,
|
||||
"settings": [
|
||||
{
|
||||
"category": "default",
|
||||
"id": "default",
|
||||
"settings": [
|
||||
{
|
||||
"id": "live-update",
|
||||
|
@ -116,10 +216,96 @@
|
|||
},
|
||||
{
|
||||
"id": "security",
|
||||
"text": "Security",
|
||||
"headertext": "Security Settings",
|
||||
"text": "Security and Privacy",
|
||||
"headertext": "Security and Privacy Settings",
|
||||
"settings": [
|
||||
|
||||
{
|
||||
"id": "default",
|
||||
"settings": [
|
||||
{
|
||||
"id": "unsafe-content",
|
||||
"type": "bool",
|
||||
"text": "Allow unverified content",
|
||||
"hint": "Allow loading unverified plugins/themes",
|
||||
"value": "false"
|
||||
},
|
||||
{
|
||||
"id": "tracking-protection",
|
||||
"type": "bool",
|
||||
"text": "Tracking Protection",
|
||||
"hint": "Disable any Discord tracking",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "e2ee",
|
||||
"type": "bool",
|
||||
"text": "E2EE",
|
||||
"hint": "End-to-end encryption",
|
||||
"value": false
|
||||
},
|
||||
{
|
||||
"id": "use-keytar",
|
||||
"type": "bool",
|
||||
"text": "Use system keychain",
|
||||
"hint": "Store the master password in the system keychain",
|
||||
"value": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "e2eedb",
|
||||
"name": "E2EE Database",
|
||||
"type": "drawer",
|
||||
"settings": [
|
||||
{
|
||||
"id": "e2ekvps",
|
||||
"type": ["securekvp"],
|
||||
"value": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "e2ee-popout",
|
||||
"name": "E2EE Popout",
|
||||
"type": "drawer",
|
||||
"settings": [
|
||||
{
|
||||
"id": "position",
|
||||
"type": "radio",
|
||||
"text": "Position",
|
||||
"value": "above",
|
||||
"fullwidth": true,
|
||||
"options": [
|
||||
{
|
||||
"text": "Above the lock icon",
|
||||
"value": "above"
|
||||
},
|
||||
{
|
||||
"text": "Over the lock icon",
|
||||
"value": "over"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "trigger",
|
||||
"type": "radio",
|
||||
"text": "Trigger",
|
||||
"hint": "Only applies when the popout is over the lock icon",
|
||||
"value": "click",
|
||||
"fullwidth": true,
|
||||
"options": [
|
||||
{
|
||||
"text": "After clicking the lock icon",
|
||||
"value": "click"
|
||||
},
|
||||
{
|
||||
"text": "When hovering over the lock icon",
|
||||
"value": "hover"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
|
|
@ -0,0 +1,232 @@
|
|||
const dummyTags = ['dark', 'light', 'simple', 'minimal', 'extra', 'something', 'tag', 'whatever', 'another', 'transparent'];
|
||||
|
||||
export default class ServerEmu {
|
||||
|
||||
static async themes(args) {
|
||||
if (!this._themes) this._themes = this.generateThemes();
|
||||
|
||||
await new Promise(r => setTimeout(r, Math.random() * 3000));
|
||||
|
||||
let docs = [];
|
||||
|
||||
if (args && args.sterm) {
|
||||
const { sterm } = args;
|
||||
const reg = new RegExp(sterm, 'gi');
|
||||
docs = this._themes.filter(doc => doc.tags.includes(sterm) || reg.exec(doc.name) || reg.exec(doc.description));
|
||||
} else {
|
||||
docs = this._themes;
|
||||
}
|
||||
|
||||
if (args.sort) {
|
||||
switch (args.sort) {
|
||||
case 'updated':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => new Date(docA.updated).getTime() - new Date(docB.updated).getTime());
|
||||
else docs = docs.sort((docA, docB) => new Date(docB.updated).getTime() - new Date(docA.updated).getTime());
|
||||
break;
|
||||
case 'installs':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => docA.installs - docB.installs);
|
||||
else docs = docs.sort((docA, docB) => docB.installs - docA.installs);
|
||||
break;
|
||||
case 'users':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => docA.activeUsers - docB.activeUsers);
|
||||
else docs = docs.sort((docA, docB) => docB.activeUsers - docA.activeUsers);
|
||||
break;
|
||||
case 'rating':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => docA.rating - docB.rating);
|
||||
else docs = docs.sort((docA, docB) => docB.rating - docA.rating);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const total = docs.length;
|
||||
const pages = Math.ceil(total / 9);
|
||||
|
||||
let page = 1;
|
||||
if (args && args.page) {
|
||||
page = args.page;
|
||||
docs = docs.slice((page - 1) * 9, page * 9);
|
||||
} else {
|
||||
docs = docs.slice(0, 9);
|
||||
}
|
||||
|
||||
return {
|
||||
docs,
|
||||
filters: {
|
||||
sterm: args.sterm || '',
|
||||
ascending: args.ascending || false,
|
||||
sort: args.sort || 'name'
|
||||
},
|
||||
pagination: {
|
||||
total,
|
||||
pages,
|
||||
limit: 9,
|
||||
page
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async plugins(args) {
|
||||
if (!this._plugins) this._plugins = this.generatePlugins();
|
||||
|
||||
await new Promise(r => setTimeout(r, Math.random() * 3000));
|
||||
|
||||
let docs = [];
|
||||
|
||||
if (args && args.sterm) {
|
||||
const { sterm } = args;
|
||||
const reg = new RegExp(sterm, 'gi');
|
||||
docs = this._plugins.filter(doc => doc.tags.includes(sterm) || reg.exec(doc.name) || reg.exec(doc.description));
|
||||
} else {
|
||||
docs = this._plugins;
|
||||
}
|
||||
|
||||
if (args.sort) {
|
||||
switch (args.sort) {
|
||||
case 'updated':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => new Date(docA.updated).getTime() - new Date(docB.updated).getTime());
|
||||
else docs = docs.sort((docA, docB) => new Date(docB.updated).getTime() - new Date(docA.updated).getTime());
|
||||
break;
|
||||
case 'installs':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => docA.installs - docB.installs);
|
||||
else docs = docs.sort((docA, docB) => docB.installs - docA.installs);
|
||||
break;
|
||||
case 'users':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => docA.activeUsers - docB.activeUsers);
|
||||
else docs = docs.sort((docA, docB) => docB.activeUsers - docA.activeUsers);
|
||||
break;
|
||||
case 'rating':
|
||||
if (args.ascending) docs = docs.sort((docA, docB) => docA.rating - docB.rating);
|
||||
else docs = docs.sort((docA, docB) => docB.rating - docA.rating);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const total = docs.length;
|
||||
const pages = Math.ceil(total / 9);
|
||||
|
||||
let page = 1;
|
||||
if (args && args.page) {
|
||||
page = args.page;
|
||||
docs = docs.slice((page - 1) * 9, page * 9);
|
||||
} else {
|
||||
docs = docs.slice(0, 9);
|
||||
}
|
||||
|
||||
return {
|
||||
docs,
|
||||
filters: {
|
||||
sterm: args.sterm || '',
|
||||
ascending: args.ascending || false,
|
||||
sort: args.sort || 'name'
|
||||
},
|
||||
pagination: {
|
||||
total,
|
||||
pages,
|
||||
limit: 9,
|
||||
page
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static generateThemes() {
|
||||
const docs = [];
|
||||
const count = Math.floor(Math.random() * 50 + 30);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const id = `theme${i}-${this.randomId()}`;
|
||||
const name = `Dummy Theme ${i}`;
|
||||
const tags = dummyTags.sort(() => .5 - Math.random()).slice(0, 3);
|
||||
|
||||
docs.push({
|
||||
id,
|
||||
name,
|
||||
tags,
|
||||
installs: Math.floor(Math.random() * 5000) + 5000,
|
||||
updated: this.randomTimestamp(),
|
||||
rating: Math.floor(Math.random() * 500) + 500,
|
||||
activeUsers: Math.floor(Math.random() * 1000) + 1000,
|
||||
rated: Math.random() > .5,
|
||||
version: this.randomVersion(),
|
||||
repository: this.dummyThemeRepo,
|
||||
files: this.dummyFiles,
|
||||
author: this.dummyAuthor,
|
||||
description: ''
|
||||
});
|
||||
}
|
||||
|
||||
return docs;
|
||||
}
|
||||
|
||||
static generatePlugins() {
|
||||
const docs = [];
|
||||
const count = Math.floor(Math.random() * 50 + 30);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const id = `plugin${i}-${this.randomId()}`;
|
||||
const name = `Dummy Plugin ${i}`;
|
||||
const tags = dummyTags.sort(() => .5 - Math.random()).slice(0, 3);
|
||||
|
||||
docs.push({
|
||||
id,
|
||||
name,
|
||||
tags,
|
||||
installs: Math.floor(Math.random() * 5000) + 5000,
|
||||
updated: this.randomTimestamp(),
|
||||
rating: Math.floor(Math.random() * 500) + 500,
|
||||
activeUsers: Math.floor(Math.random() * 1000) + 1000,
|
||||
rated: Math.random() > .5,
|
||||
version: this.randomVersion(),
|
||||
repository: this.dummyPluginRepo,
|
||||
files: this.dummyFiles,
|
||||
author: this.dummyAuthor,
|
||||
description: ''
|
||||
});
|
||||
}
|
||||
|
||||
return docs;
|
||||
}
|
||||
|
||||
static get dummyThemeRepo() {
|
||||
return {
|
||||
name: 'ExampleRepository',
|
||||
baseUri: 'https://github.com/Jiiks/ExampleRepository',
|
||||
rawUri: 'https://github.com/Jiiks/ExampleRepository/raw/master',
|
||||
assetUri: 'https://api.github.com/repos/Jiiks/ExampleRepository/releases/assets/10023264'
|
||||
}
|
||||
}
|
||||
|
||||
static get dummyPluginRepo() {
|
||||
return {
|
||||
name: 'ExampleRepository',
|
||||
baseUri: 'https://github.com/Jiiks/ExampleRepository',
|
||||
rawUri: 'https://github.com/Jiiks/ExampleRepository/raw/master',
|
||||
assetUri: 'https://api.github.com/repos/Jiiks/ExampleRepository/releases/assets/10023265'
|
||||
}
|
||||
}
|
||||
|
||||
static get dummyFiles() {
|
||||
return {
|
||||
readme: 'Example/readme.md',
|
||||
previews: [{
|
||||
large: 'Example/preview1-big.png',
|
||||
thumb: 'Example/preview1-small.png'
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
static get dummyAuthor() {
|
||||
return 'Someone';
|
||||
}
|
||||
|
||||
static randomId() {
|
||||
return btoa(Math.random()).substring(3, 9);
|
||||
}
|
||||
|
||||
static randomTimestamp() {
|
||||
return `2018-${Math.floor((Math.random() * 12) + 1).toString().padStart(2, '0')}-${Math.floor((Math.random() * 30) + 1).toString().padStart(2, '0')}T14:51:32.057Z`;
|
||||
}
|
||||
|
||||
static randomVersion() {
|
||||
return `${Math.round(Math.random() * 3)}.${Math.round(Math.random() * 10)}.${Math.round(Math.random() * 10)}`;
|
||||
}
|
||||
}
|
|
@ -8,41 +8,47 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { DOM, BdUI, Modals, Reflection } from 'ui';
|
||||
import { DOM, BdUI, BdMenu, Modals, Toasts, Notifications, BdContextMenu, DiscordContextMenu, Autocomplete } from 'ui';
|
||||
import BdCss from './styles/index.scss';
|
||||
import { Patcher, MonkeyPatch, Vendor, Events, CssEditor, Globals, ExtModuleManager, PluginManager, ThemeManager, ModuleManager, WebpackModules, Settings, Database, ReactComponents, ReactAutoPatcher, DiscordApi } from 'modules';
|
||||
import { ClientLogger as Logger, ClientIPC, Utils } from 'common';
|
||||
import { EmoteModule } from 'builtin';
|
||||
const ignoreExternal = false;
|
||||
const DEV = true;
|
||||
import { Events, Globals, Settings, Database, Updater, ModuleManager, PluginManager, ThemeManager, ExtModuleManager, Vendor, Patcher, MonkeyPatch, ReactComponents, ReactHelpers, ReactAutoPatcher, DiscordApi, BdWebApi, Connectivity, Cache, Reflection, PackageInstaller } from 'modules';
|
||||
import { ClientLogger as Logger, ClientIPC, Utils, Axi } from 'common';
|
||||
import { BuiltinManager, EmoteModule, ReactDevtoolsModule, VueDevtoolsModule, TrackingProtection, E2EE } from 'builtin';
|
||||
import electron from 'electron';
|
||||
import path from 'path';
|
||||
|
||||
const tests = typeof PRODUCTION === 'undefined';
|
||||
const ignoreExternal = tests && true;
|
||||
|
||||
class BetterDiscord {
|
||||
|
||||
constructor() {
|
||||
Logger.file = tests ? path.resolve(__dirname, '..', '..', 'tests', 'log.txt') : path.join(__dirname, 'log.txt');
|
||||
Logger.trimLogFile();
|
||||
Logger.log('main', 'BetterDiscord starting');
|
||||
|
||||
this._bd = {
|
||||
DOM,
|
||||
BdUI,
|
||||
Modals,
|
||||
Reflection,
|
||||
Patcher,
|
||||
MonkeyPatch,
|
||||
DOM, BdUI, BdMenu, Modals, Reflection, Toasts, Notifications, BdContextMenu, DiscordContextMenu, Autocomplete,
|
||||
|
||||
Events, Globals, Settings, Database, Updater,
|
||||
ModuleManager, PluginManager, ThemeManager, ExtModuleManager, PackageInstaller,
|
||||
Vendor,
|
||||
Events,
|
||||
CssEditor,
|
||||
Globals,
|
||||
ExtModuleManager,
|
||||
PluginManager,
|
||||
ThemeManager,
|
||||
ModuleManager,
|
||||
WebpackModules,
|
||||
Settings,
|
||||
Database,
|
||||
ReactComponents,
|
||||
DiscordApi,
|
||||
Logger,
|
||||
ClientIPC,
|
||||
Utils,
|
||||
EmoteModule
|
||||
|
||||
Patcher, MonkeyPatch, ReactComponents, ReactHelpers, ReactAutoPatcher, DiscordApi,
|
||||
BuiltinManager, EmoteModule,
|
||||
BdWebApi,
|
||||
Connectivity,
|
||||
Cache,
|
||||
Logger, ClientIPC, Utils, Axi,
|
||||
|
||||
plugins: PluginManager.localContent,
|
||||
themes: ThemeManager.localContent,
|
||||
extmodules: ExtModuleManager.localContent,
|
||||
|
||||
__filename, __dirname,
|
||||
module: Globals.require.cache[__filename],
|
||||
require: Globals.require,
|
||||
webpack_require: __webpack_require__, // eslint-disable-line no-undef
|
||||
get discord_require() { return Reflection.require }
|
||||
};
|
||||
|
||||
const developermode = Settings.getSetting('core', 'advanced', 'developer-mode');
|
||||
|
@ -52,45 +58,84 @@ class BetterDiscord {
|
|||
else if (window._bd) delete window._bd;
|
||||
});
|
||||
|
||||
const debuggerkeybind = Settings.getSetting('core', 'advanced', 'debugger-keybind');
|
||||
debuggerkeybind.on('keybind-activated', () => {
|
||||
const currentWindow = electron.remote.getCurrentWindow();
|
||||
if (currentWindow.isDevToolsOpened()) return eval('debugger;');
|
||||
currentWindow.openDevTools();
|
||||
setTimeout(() => eval('debugger;'), 1000);
|
||||
});
|
||||
|
||||
DOM.injectStyle(BdCss, 'bdmain');
|
||||
this.globalReady = this.globalReady.bind(this);
|
||||
Events.on('global-ready', this.globalReady);
|
||||
Globals.initg();
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await Database.init();
|
||||
await Settings.loadSettings();
|
||||
await ModuleManager.initModules();
|
||||
Modals.showContentManagerErrors();
|
||||
if (!ignoreExternal) {
|
||||
await ExtModuleManager.loadAllModules(true);
|
||||
await PluginManager.loadAllPlugins(true);
|
||||
await ThemeManager.loadAllThemes(true);
|
||||
}
|
||||
if (!Settings.get('core', 'advanced', 'ignore-content-manager-errors'))
|
||||
Modals.showContentManagerErrors();
|
||||
Events.emit('ready');
|
||||
Events.emit('discord-ready');
|
||||
EmoteModule.observe();
|
||||
} catch (err) {
|
||||
Logger.err('main', ['FAILED TO LOAD!', err]);
|
||||
}
|
||||
}
|
||||
|
||||
globalReady() {
|
||||
BdUI.initUiEvents();
|
||||
this.vueInstance = BdUI.injectUi();
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await Database.init();
|
||||
await Settings.loadSettings();
|
||||
await ModuleManager.initModules();
|
||||
BuiltinManager.initAll();
|
||||
|
||||
if (tests) this.initTests();
|
||||
|
||||
if (!ignoreExternal) {
|
||||
await ExtModuleManager.loadAllModules(true);
|
||||
await PluginManager.loadAllPlugins(true);
|
||||
await ThemeManager.loadAllThemes(true);
|
||||
}
|
||||
|
||||
Events.emit('ready');
|
||||
Events.emit('discord-ready');
|
||||
|
||||
if (!Settings.get('core', 'advanced', 'ignore-content-manager-errors'))
|
||||
Modals.showContentManagerErrors();
|
||||
} catch (err) {
|
||||
Logger.err('main', ['FAILED TO LOAD!', err]);
|
||||
}
|
||||
}
|
||||
|
||||
initTests() {
|
||||
let notifications = 0;
|
||||
function showDummyNotif() { // eslint-disable-line no-inner-declarations
|
||||
Notifications.add(notifications++ ? `Notification ${notifications}` : undefined, 'Dummy Notification', [
|
||||
{
|
||||
text: 'Show Again', onClick: function () {
|
||||
setTimeout(showDummyNotif, 5000);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Ignore', onClick: function () {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]);
|
||||
}
|
||||
showDummyNotif();
|
||||
|
||||
DiscordContextMenu.add([
|
||||
{
|
||||
text: 'Hello',
|
||||
onClick: () => { Toasts.info('Hello!'); }
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (window.BetterDiscord) {
|
||||
Logger.log('main', 'Attempting to inject again?');
|
||||
} else {
|
||||
let instance = null;
|
||||
let instance;
|
||||
Events.on('autopatcher', () => instance = new BetterDiscord());
|
||||
ReactAutoPatcher.autoPatch().then(() => Events.emit('autopatcher'));
|
||||
}
|
||||
|
|
|
@ -0,0 +1,82 @@
|
|||
/**
|
||||
* BetterDiscord Web Apis
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import ServerEmu from '../dev/serveremu';
|
||||
|
||||
import { request } from 'vendor';
|
||||
|
||||
const APIBASE = 'ifyouareinwebtestthenyouknowwhatthisshouldbe'; // Do not push
|
||||
const ENDPOINTS = {
|
||||
'themes': `${APIBASE}/themes`,
|
||||
'theme': id => `${APIBASE}/theme/${id}`,
|
||||
'users': `${APIBASE}/users`,
|
||||
'user': id => `${APIBASE}/user/${id}`,
|
||||
'statistics': `${APIBASE}/statistics`
|
||||
};
|
||||
|
||||
export default class BdWebApi {
|
||||
|
||||
static get themes() {
|
||||
return {
|
||||
get: this.getThemes
|
||||
};
|
||||
}
|
||||
|
||||
static get plugins() {
|
||||
return {
|
||||
get: this.getPlugins
|
||||
};
|
||||
}
|
||||
|
||||
static get users() {
|
||||
return {
|
||||
get: this.getUsers
|
||||
};
|
||||
}
|
||||
|
||||
static get statistics() {
|
||||
return {
|
||||
get: this.getStatistics,
|
||||
patch: this.patchStatistics
|
||||
};
|
||||
}
|
||||
|
||||
static getThemes(args) {
|
||||
return ServerEmu.themes(args);
|
||||
// return dummyThemes();
|
||||
/*
|
||||
if (!args) return request.get(ENDPOINTS.themes);
|
||||
const { id } = args;
|
||||
if (id) return request.get(ENDPOINTS.theme(id));
|
||||
|
||||
return request.get(ENDPOINTS.themes);
|
||||
*/
|
||||
}
|
||||
|
||||
static getPlugins(args) {
|
||||
return ServerEmu.plugins(args);
|
||||
}
|
||||
|
||||
static getUsers(args) {
|
||||
if (!args) return request.get(ENDPOINTS.users);
|
||||
const { id } = args;
|
||||
if (id) return request.get(ENDPOINTS.user(id));
|
||||
|
||||
return request.get(ENDPOINTS.users);
|
||||
}
|
||||
|
||||
static getStatistics() {
|
||||
return request.get(ENDPOINTS.statistics);
|
||||
}
|
||||
|
||||
static patchStatistics(json) {
|
||||
return request({ method: 'PATCH', url: ENDPOINTS.statistics, json });
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
/**
|
||||
* BetterDiscord Cache Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
const CACHE = [];
|
||||
|
||||
export default class Cache {
|
||||
|
||||
static get cache() {
|
||||
return CACHE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push something to cache
|
||||
* @param {String} where Cache identifier
|
||||
* @param {any} data Data to push
|
||||
*/
|
||||
static push(where, data) {
|
||||
if (!this.cache[where]) this.cache[where] = [];
|
||||
this.cache[where].push(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find something in cache
|
||||
* @param {String} where Cache identifier
|
||||
* @param {Function} what Find callback
|
||||
*/
|
||||
static find(where, what) {
|
||||
if (!this.cache[where]) this.cache[where] = [];
|
||||
return this.cache[where].find(what);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* BetterDiscord Connectivity Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import BdWebApi from './bdwebapi';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
|
||||
export default class Connectivity {
|
||||
|
||||
static start() {
|
||||
Logger.info('Connectivity', `Patching anonymous statistics`);
|
||||
BdWebApi.statistics.patch({ themes: [], plugins: [] });
|
||||
setInterval(() => {
|
||||
Logger.info('Connectivity', `Patching anonymous statistics`);
|
||||
BdWebApi.statistics.patch({ themes: [], plugins: [] });
|
||||
}, 15*60*1000);
|
||||
}
|
||||
|
||||
}
|
|
@ -8,20 +8,26 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Utils, FileUtils, ClientLogger as Logger, AsyncEventEmitter } from 'common';
|
||||
import { Utils, ClientLogger as Logger, AsyncEventEmitter } from 'common';
|
||||
import { Modals } from 'ui';
|
||||
import Database from './database';
|
||||
|
||||
export default class Content {
|
||||
export default class Content extends AsyncEventEmitter {
|
||||
|
||||
constructor(internals) {
|
||||
super();
|
||||
|
||||
internals.loaded = Date.now();
|
||||
internals.started = undefined;
|
||||
internals.stopped = undefined;
|
||||
|
||||
Utils.deepfreeze(internals.info);
|
||||
Object.freeze(internals.paths);
|
||||
|
||||
this.__internals = internals;
|
||||
|
||||
this.settings.on('setting-updated', event => this.events.emit('setting-updated', event));
|
||||
this.settings.on('settings-updated', event => this.events.emit('settings-updated', event));
|
||||
this.settings.on('setting-updated', event => this.emit('setting-updated', event));
|
||||
this.settings.on('settings-updated', event => this.emit('settings-updated', event));
|
||||
this.settings.on('settings-updated', event => this.__settingsUpdated(event));
|
||||
|
||||
// Add hooks
|
||||
|
@ -49,16 +55,23 @@ export default class Content {
|
|||
get description() { return this.info.description }
|
||||
get authors() { return this.info.authors }
|
||||
get version() { return this.info.version }
|
||||
get loadedTimestamp() { return this.__internals.loaded }
|
||||
get startedTimestamp() { return this.__internals.started }
|
||||
get stoppedTimestamp() { return this.__internals.stopped }
|
||||
get contentPath() { return this.paths.contentPath }
|
||||
get dirName() { return this.paths.dirName }
|
||||
get enabled() { return this.userConfig.enabled }
|
||||
get settings() { return this.userConfig.config }
|
||||
get config() { return this.settings.categories }
|
||||
get data() { return this.userConfig.data || (this.userConfig.data = {}) }
|
||||
get events() { return this.EventEmitter || (this.EventEmitter = new AsyncEventEmitter()) }
|
||||
|
||||
get packed() { return this.dirName.packed }
|
||||
get packagePath() { return this.dirName.packagePath }
|
||||
get packageName() { return this.dirName.pkg }
|
||||
|
||||
/**
|
||||
* Opens a settings modal for this content.
|
||||
* @return {Modal}
|
||||
*/
|
||||
showSettingsModal() {
|
||||
return Modals.contentSettings(this);
|
||||
|
@ -73,20 +86,13 @@ export default class Content {
|
|||
|
||||
/**
|
||||
* Saves the content's current configuration.
|
||||
* @return {Promise}
|
||||
*/
|
||||
async saveConfiguration() {
|
||||
try {
|
||||
/*
|
||||
await FileUtils.writeFile(`${this.contentPath}/user.config.json`, JSON.stringify({
|
||||
enabled: this.enabled,
|
||||
config: this.settings.strip().settings,
|
||||
data: this.data
|
||||
}));
|
||||
*/
|
||||
Database.insertOrUpdate({ type: 'contentconfig', $or: [{ id: this.id }, { name: this.name }] }, {
|
||||
type: 'contentconfig',
|
||||
Database.insertOrUpdate({ type: `${this.type}-config`, id: this.id }, {
|
||||
type: `${this.type}-config`,
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
enabled: this.enabled,
|
||||
config: this.settings.strip().settings,
|
||||
data: this.data
|
||||
|
@ -116,6 +122,8 @@ export default class Content {
|
|||
await this.emit('enable');
|
||||
await this.emit('start');
|
||||
|
||||
this.__internals.started = Date.now();
|
||||
this.__internals.stopped = undefined;
|
||||
this.userConfig.enabled = true;
|
||||
if (save) await this.saveConfiguration();
|
||||
}
|
||||
|
@ -130,48 +138,12 @@ export default class Content {
|
|||
await this.emit('stop');
|
||||
await this.emit('disable');
|
||||
|
||||
this.__internals.started = undefined;
|
||||
this.__internals.stopped = Date.now();
|
||||
this.userConfig.enabled = false;
|
||||
if (save) await this.saveConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener.
|
||||
* @param {String} event The event to add the listener to
|
||||
* @param {Function} callback The function to call when the event is emitted
|
||||
*/
|
||||
on(...args) {
|
||||
return this.events.on(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an event listener.
|
||||
* @param {String} event The event to remove the listener from
|
||||
* @param {Function} callback The bound callback (optional)
|
||||
*/
|
||||
off(...args) {
|
||||
return this.events.removeListener(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an event listener that removes itself when called, therefore only being called once.
|
||||
* @param {String} event The event to add the listener to
|
||||
* @param {Function} callback The function to call when the event is emitted
|
||||
* @return {Promise|undefined}
|
||||
*/
|
||||
once(...args) {
|
||||
return this.events.once(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits an event.
|
||||
* @param {String} event The event to emit
|
||||
* @param {Any} data Data to be passed to listeners
|
||||
* @return {Promise|undefined}
|
||||
*/
|
||||
emit(...args) {
|
||||
return this.events.emit(...args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Object.freeze(Content.prototype);
|
||||
|
|
|
@ -8,15 +8,19 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import asar from 'asar';
|
||||
import path, { dirname } from 'path';
|
||||
import rimraf from 'rimraf';
|
||||
|
||||
import { remote } from 'electron';
|
||||
import Content from './content';
|
||||
import Globals from './globals';
|
||||
import Database from './database';
|
||||
import { Utils, FileUtils, ClientLogger as Logger } from 'common';
|
||||
import { Events } from 'modules';
|
||||
import { SettingsSet, ErrorEvent } from 'structs';
|
||||
import { Modals } from 'ui';
|
||||
import path from 'path';
|
||||
import Combokeys from 'combokeys';
|
||||
import Settings from './settings';
|
||||
|
||||
/**
|
||||
* Base class for managing external content
|
||||
|
@ -24,31 +28,74 @@ import Combokeys from 'combokeys';
|
|||
export default class {
|
||||
|
||||
/**
|
||||
* Any errors that happened
|
||||
* returns {Array}
|
||||
* Any errors that happened.
|
||||
* @return {Array}
|
||||
*/
|
||||
static get errors() {
|
||||
return this._errors || (this._errors = []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Locallly stored content
|
||||
* returns {Array}
|
||||
* Locally stored content.
|
||||
* @return {Array}
|
||||
*/
|
||||
static get localContent() {
|
||||
return this._localContent ? this._localContent : (this._localContent = []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Local path for content
|
||||
* returns {String}
|
||||
* The type of content this content manager manages.
|
||||
*/
|
||||
static get contentType() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of this content manager.
|
||||
*/
|
||||
static get moduleName() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path used to store this content manager's content.
|
||||
*/
|
||||
static get pathId() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local path for content.
|
||||
* @return {String}
|
||||
*/
|
||||
static get contentPath() {
|
||||
return Globals.getPath(this.pathId);
|
||||
}
|
||||
|
||||
static async packContent(path, contentPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
remote.dialog.showSaveDialog({
|
||||
title: 'Save Package',
|
||||
defaultPath: path,
|
||||
filters: [
|
||||
{
|
||||
name: 'BetterDiscord Package',
|
||||
extensions: ['bd']
|
||||
}
|
||||
]
|
||||
}, filepath => {
|
||||
if (!filepath) return;
|
||||
|
||||
asar.uncache(filepath);
|
||||
asar.createPackage(contentPath, filepath, () => {
|
||||
resolve(filepath);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all locally stored content
|
||||
* Load all locally stored content.
|
||||
* @param {bool} suppressErrors Suppress any errors that occur during loading of content
|
||||
*/
|
||||
static async loadAllContent(suppressErrors = false) {
|
||||
|
@ -56,13 +103,21 @@ export default class {
|
|||
await FileUtils.ensureDirectory(this.contentPath);
|
||||
const directories = await FileUtils.listDirectory(this.contentPath);
|
||||
|
||||
for (let dir of directories) {
|
||||
for (const dir of directories) {
|
||||
const packed = dir.endsWith('.bd');
|
||||
|
||||
if (!packed) {
|
||||
try {
|
||||
await FileUtils.directoryExists(path.join(this.contentPath, dir));
|
||||
} catch (err) { continue; }
|
||||
}
|
||||
|
||||
try {
|
||||
if (packed) {
|
||||
await this.preloadPackedContent(dir);
|
||||
} else {
|
||||
await this.preloadContent(dir);
|
||||
}
|
||||
} catch (err) {
|
||||
this.errors.push(new ErrorEvent({
|
||||
module: this.moduleName,
|
||||
|
@ -83,8 +138,6 @@ export default class {
|
|||
});
|
||||
this._errors = [];
|
||||
}
|
||||
|
||||
return this.localContent;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
|
@ -101,8 +154,10 @@ export default class {
|
|||
await FileUtils.ensureDirectory(this.contentPath);
|
||||
const directories = await FileUtils.listDirectory(this.contentPath);
|
||||
|
||||
for (let dir of directories) {
|
||||
// If content is already loaded this should resolve.
|
||||
for (const dir of directories) {
|
||||
const packed = dir.endsWith('.bd');
|
||||
|
||||
// If content is already loaded this should resolve
|
||||
if (this.getContentByDirName(dir)) continue;
|
||||
|
||||
try {
|
||||
|
@ -124,7 +179,7 @@ export default class {
|
|||
}
|
||||
}
|
||||
|
||||
for (let content of this.localContent) {
|
||||
for (const content of this.localContent) {
|
||||
if (directories.includes(content.dirName)) continue;
|
||||
|
||||
try {
|
||||
|
@ -150,13 +205,36 @@ export default class {
|
|||
});
|
||||
this._errors = [];
|
||||
}
|
||||
|
||||
return this.localContent;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
static async preloadPackedContent(pkg, reload = false, index) {
|
||||
try {
|
||||
const packagePath = path.join(this.contentPath, pkg);
|
||||
const packageName = pkg.replace('.bd', '');
|
||||
await FileUtils.fileExists(packagePath);
|
||||
|
||||
const config = JSON.parse(asar.extractFile(packagePath, 'config.json').toString());
|
||||
const unpackedPath = path.join(Globals.getPath('tmp'), packageName);
|
||||
|
||||
asar.extractAll(packagePath, unpackedPath);
|
||||
|
||||
return this.preloadContent({
|
||||
config,
|
||||
contentPath: unpackedPath,
|
||||
packagePath: packagePath,
|
||||
pkg,
|
||||
packageName,
|
||||
packed: true
|
||||
}, reload, index);
|
||||
} catch (err) {
|
||||
Logger.log('ContentManager', ['Error extracting packed content', err]);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Common loading procedure for loading content before passing it to the actual loader
|
||||
* @param {any} dirName Base directory for content
|
||||
|
@ -165,19 +243,24 @@ export default class {
|
|||
*/
|
||||
static async preloadContent(dirName, reload = false, index) {
|
||||
try {
|
||||
const contentPath = path.join(this.contentPath, dirName);
|
||||
const unsafeAllowed = Settings.getSetting('security', 'default', 'unsafe-content').value;
|
||||
const packed = typeof dirName === 'object' && dirName.packed;
|
||||
|
||||
// Block any unpacked content as they can't be verified
|
||||
if (!packed && !unsafeAllowed) {
|
||||
throw 'Blocked unsafe content';
|
||||
}
|
||||
|
||||
const contentPath = packed ? dirName.contentPath : path.join(this.contentPath, dirName);
|
||||
|
||||
await FileUtils.directoryExists(contentPath);
|
||||
|
||||
if (!reload) {
|
||||
const loaded = this.localContent.find(content => content.contentPath === contentPath);
|
||||
if (loaded) {
|
||||
if (!reload && this.getContentByPath(contentPath))
|
||||
throw { 'message': `Attempted to load already loaded user content: ${path}` };
|
||||
}
|
||||
}
|
||||
|
||||
const readConfig = await this.readConfig(contentPath);
|
||||
const mainPath = path.join(contentPath, readConfig.main);
|
||||
const configPath = path.resolve(contentPath, 'config.json');
|
||||
const readConfig = packed ? dirName.config : await FileUtils.readJsonFromFile(configPath);
|
||||
const mainPath = path.join(contentPath, readConfig.main || 'index.js');
|
||||
|
||||
const defaultConfig = new SettingsSet({
|
||||
settings: readConfig.defaultConfig,
|
||||
|
@ -191,30 +274,31 @@ export default class {
|
|||
};
|
||||
|
||||
try {
|
||||
//const readUserConfig = await this.readUserConfig(contentPath);
|
||||
const readUserConfig = await Database.find({ type: 'contentconfig', name: readConfig.info.name });
|
||||
const id = readConfig.info.id || readConfig.info.name.toLowerCase().replace(/[^a-zA-Z0-9-]/g, '-').replace(/--/g, '-');
|
||||
const readUserConfig = await Database.find({ type: `${this.contentType}-config`, id });
|
||||
if (readUserConfig.length) {
|
||||
userConfig.enabled = readUserConfig[0].enabled || false;
|
||||
// await userConfig.config.merge({ settings: readUserConfig.config });
|
||||
// userConfig.config.setSaved();
|
||||
// userConfig.config = userConfig.config.clone({ settings: readUserConfig.config });
|
||||
userConfig.config = readUserConfig[0].config;
|
||||
userConfig.data = readUserConfig[0].data || {};
|
||||
}
|
||||
} catch (err) { /*We don't care if this fails it either means that user config doesn't exist or there's something wrong with it so we revert to default config*/
|
||||
Logger.info(this.moduleName, `Failed reading config for ${this.contentType} ${readConfig.info.name} in ${dirName}`);
|
||||
Logger.err(this.moduleName, err);
|
||||
} catch (err) {
|
||||
// We don't care if this fails it either means that user config doesn't exist or there's something wrong with it so we revert to default config
|
||||
Logger.warn(this.moduleName, [`Failed reading config for ${this.contentType} ${readConfig.info.name} in ${packed ? dirName.pkg : dirName}`, err]);
|
||||
}
|
||||
|
||||
userConfig.config = defaultConfig.clone({ settings: userConfig.config });
|
||||
userConfig.config.setSaved();
|
||||
|
||||
for (let setting of userConfig.config.findSettings(() => true)) {
|
||||
for (const setting of userConfig.config.findSettings(() => true)) {
|
||||
// This will load custom settings
|
||||
// Setting the content's path on only the live config (and not the default config) ensures that custom settings will not be loaded on the default settings
|
||||
setting.setContentPath(contentPath);
|
||||
}
|
||||
|
||||
for (const scheme of userConfig.config.schemes) {
|
||||
scheme.setContentPath(contentPath);
|
||||
}
|
||||
|
||||
Utils.deepfreeze(defaultConfig, object => object instanceof Combokeys);
|
||||
|
||||
const configs = {
|
||||
|
@ -229,45 +313,43 @@ export default class {
|
|||
mainPath
|
||||
};
|
||||
|
||||
const content = await this.loadContent(paths, configs, readConfig.info, readConfig.main, readConfig.dependencies, readConfig.permissions);
|
||||
const content = await this.loadContent(paths, configs, readConfig.info, readConfig.main, readConfig.dependencies, readConfig.permissions, readConfig.mainExport, packed ? dirName : false);
|
||||
if (!content) return undefined;
|
||||
if (!reload && this.getContentById(content.id))
|
||||
throw { message: `A ${this.contentType} with the ID ${content.id} already exists.` };
|
||||
|
||||
if (reload) this.localContent[index] = content;
|
||||
if (reload) this.localContent.splice(index, 1, content);
|
||||
else this.localContent.push(content);
|
||||
return content;
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unload content
|
||||
* @param {any} content Content to unload
|
||||
* @param {bool} reload Whether to reload the content after
|
||||
* Delete content.
|
||||
* @param {Content|String} content Content to delete
|
||||
* @param {Boolean} force If true the content will be deleted even if an exception is thrown when disabling/unloading/deleting
|
||||
*/
|
||||
static async unloadContent(content, reload) {
|
||||
static async deleteContent(content, force) {
|
||||
content = this.findContent(content);
|
||||
if (!content) throw {message: `Could not find a ${this.contentType} from ${content}.`};
|
||||
|
||||
try {
|
||||
await content.disable(false);
|
||||
await content.emit('unload', reload);
|
||||
|
||||
const index = this.getContentIndex(content);
|
||||
|
||||
delete window.require.cache[window.require.resolve(content.paths.mainPath)];
|
||||
|
||||
if (reload) {
|
||||
const newcontent = await this.preloadContent(content.dirName, true, index);
|
||||
if (newcontent.enabled) {
|
||||
newcontent.userConfig.enabled = false;
|
||||
newcontent.start(false);
|
||||
await Modals.confirm(`Delete ${this.contentType}?`, `Are you sure you want to delete ${content.info.name} ?`, 'Delete').promise;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
return newcontent;
|
||||
} else this.localContent.splice(index, 1);
|
||||
|
||||
try {
|
||||
const unload = this.unloadContent(content, force, false);
|
||||
|
||||
if (!force)
|
||||
await unload;
|
||||
|
||||
await FileUtils.recursiveDeleteDirectory(content.paths.contentPath);
|
||||
if (content.packed) await FileUtils.recursiveDeleteDirectory(content.packagePath);
|
||||
return true;
|
||||
} catch (err) {
|
||||
Logger.err(this.moduleName, err);
|
||||
throw err;
|
||||
|
@ -275,34 +357,52 @@ export default class {
|
|||
}
|
||||
|
||||
/**
|
||||
* Reload content
|
||||
* @param {any} content Content to reload
|
||||
* Unload content.
|
||||
* @param {Content|String} content Content to unload
|
||||
* @param {Boolean} force If true the content will be unloaded even if an exception is thrown when disabling/unloading
|
||||
* @param {Boolean} reload Whether to reload the content after
|
||||
* @return {Content}
|
||||
*/
|
||||
static reloadContent(content) {
|
||||
return this.unloadContent(content, true);
|
||||
static async unloadContent(content, force, reload) {
|
||||
content = this.findContent(content);
|
||||
if (!content) throw {message: `Could not find a ${this.contentType} from ${content}.`};
|
||||
|
||||
try {
|
||||
const disablePromise = content.disable(false);
|
||||
const unloadPromise = content.emit('unload', reload);
|
||||
|
||||
if (!force) {
|
||||
await disablePromise;
|
||||
await unloadPromise;
|
||||
}
|
||||
|
||||
const index = this.getContentIndex(content);
|
||||
|
||||
if (this.unloadContentHook) this.unloadContentHook(content);
|
||||
|
||||
if (reload) return content.packed ? this.preloadPackedContent(content.packagePath, true, index) : this.preloadContent(content.dirName, true, index);
|
||||
|
||||
this.localContent.splice(index, 1);
|
||||
} catch (err) {
|
||||
Logger.err(this.moduleName, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read content config file
|
||||
* @param {any} configPath Config file path
|
||||
* Reload content.
|
||||
* @param {Content|String} content Content to reload
|
||||
* @param {Boolean} force If true the content will be unloaded even if an exception is thrown when disabling/unloading
|
||||
* @return {Content}
|
||||
*/
|
||||
static async readConfig(configPath) {
|
||||
configPath = path.resolve(configPath, 'config.json');
|
||||
return FileUtils.readJsonFromFile(configPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read content user config file
|
||||
* @param {any} configPath User config file path
|
||||
*/
|
||||
static async readUserConfig(configPath) {
|
||||
configPath = path.resolve(configPath, 'user.config.json');
|
||||
return FileUtils.readJsonFromFile(configPath);
|
||||
static reloadContent(content, force) {
|
||||
return this.unloadContent(content, force, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the passed object is an instance of this content type.
|
||||
* @param {any} content Object to check
|
||||
* @param {Any} content Object to check
|
||||
* @return {Boolean}
|
||||
*/
|
||||
static isThisContent(content) {
|
||||
return content instanceof Content;
|
||||
|
@ -318,8 +418,9 @@ export default class {
|
|||
|
||||
/**
|
||||
* Wildcard content finder
|
||||
* @param {any} wild Content ID / directory name / path / name
|
||||
* @param {bool} nonunique Allow searching attributes that may not be unique
|
||||
* @param {String} wild Content ID / directory name / path / name
|
||||
* @param {Boolean} nonunique Allow searching attributes that may not be unique
|
||||
* @return {Content}
|
||||
*/
|
||||
static findContent(wild, nonunique) {
|
||||
if (this.isThisContent(wild)) return wild;
|
||||
|
@ -338,18 +439,11 @@ export default class {
|
|||
|
||||
/**
|
||||
* Wait for content to load
|
||||
* @param {any} content_id
|
||||
* @param {String} content_id
|
||||
* @return {Promise => Content}
|
||||
*/
|
||||
static waitForContent(content_id) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const check = () => {
|
||||
const content = this.getContentById(content_id);
|
||||
if (content) return resolve(content);
|
||||
|
||||
setTimeout(check, 100);
|
||||
};
|
||||
check();
|
||||
});
|
||||
return Utils.until(() => this.getContentById(content_id), 100);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,12 +8,12 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { FileUtils, ClientLogger as Logger, ClientIPC } from 'common';
|
||||
import Settings from './settings';
|
||||
import { DOM } from 'ui';
|
||||
import filewatcher from 'filewatcher';
|
||||
import { FileUtils, ClientLogger as Logger, ClientIPC } from 'common';
|
||||
import path from 'path';
|
||||
import electron from 'electron';
|
||||
import filewatcher from 'filewatcher';
|
||||
import Settings from './settings';
|
||||
|
||||
/**
|
||||
* Custom css editor communications
|
||||
|
@ -32,24 +32,32 @@ export default new class {
|
|||
}
|
||||
|
||||
/**
|
||||
* Init css editor
|
||||
* Init css editor.
|
||||
*/
|
||||
init() {
|
||||
ClientIPC.on('bd-get-scss', () => this.sendToEditor('set-scss', { scss: this.scss }));
|
||||
ClientIPC.on('bd-get-scss', () => this.scss, true);
|
||||
ClientIPC.on('bd-update-scss', (e, scss) => this.updateScss(scss));
|
||||
ClientIPC.on('bd-save-csseditor-bounds', (e, bounds) => this.saveEditorBounds(bounds));
|
||||
ClientIPC.on('bd-editor-runScript', (e, script) => {
|
||||
try {
|
||||
new Function(script)();
|
||||
e.reply('ok');
|
||||
} catch (err) {
|
||||
e.reply({ err: err.stack || err });
|
||||
}
|
||||
});
|
||||
|
||||
ClientIPC.on('bd-save-scss', async (e, scss) => {
|
||||
await this.updateScss(scss);
|
||||
await this.save();
|
||||
});
|
||||
}, true);
|
||||
|
||||
this.liveupdate = Settings.getSetting('css', 'default', 'live-update');
|
||||
this.liveupdate.on('setting-updated', event => {
|
||||
this.sendToEditor('set-liveupdate', event.value);
|
||||
});
|
||||
|
||||
ClientIPC.on('bd-get-liveupdate', () => this.sendToEditor('set-liveupdate', this.liveupdate.value));
|
||||
ClientIPC.on('bd-get-liveupdate', () => this.liveupdate.value, true);
|
||||
ClientIPC.on('bd-set-liveupdate', (e, value) => this.liveupdate.value = value);
|
||||
|
||||
this.watchfilessetting = Settings.getSetting('css', 'default', 'watch-files');
|
||||
|
@ -60,22 +68,22 @@ export default new class {
|
|||
}
|
||||
|
||||
/**
|
||||
* Show css editor, flashes if already visible
|
||||
* Show css editor, flashes if already visible.
|
||||
*/
|
||||
async show() {
|
||||
await ClientIPC.send('openCssEditor', this.editor_bounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update css in client
|
||||
* @param {String} scss scss to compile
|
||||
* @param {bool} sendSource send to css editor instance
|
||||
* Update css in client.
|
||||
* @param {String} scss SCSS to compile
|
||||
* @param {bool} sendSource Whether to send to css editor instance
|
||||
*/
|
||||
async updateScss(scss, sendSource) {
|
||||
if (sendSource)
|
||||
this.sendToEditor('set-scss', { scss });
|
||||
this.sendToEditor('set-scss', scss);
|
||||
|
||||
if (!scss) {
|
||||
if (!scss && !await this.fileExists()) {
|
||||
this._scss = this.css = '';
|
||||
this.sendToEditor('scss-error', null);
|
||||
return;
|
||||
|
@ -97,51 +105,55 @@ export default new class {
|
|||
}
|
||||
|
||||
/**
|
||||
* Save css to file
|
||||
* Save css to file.
|
||||
* @return {Promise}
|
||||
*/
|
||||
async save() {
|
||||
Settings.saveSettings();
|
||||
save() {
|
||||
return Settings.saveSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save current editor bounds
|
||||
* @param {Rectangle} bounds editor bounds
|
||||
* Save current editor bounds.
|
||||
* @param {Rectangle} bounds Editor bounds
|
||||
* @return {Promise}
|
||||
*/
|
||||
saveEditorBounds(bounds) {
|
||||
this.editor_bounds = bounds;
|
||||
Settings.saveSettings();
|
||||
return Settings.saveSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send scss to core for compilation
|
||||
* @param {String} scss scss string
|
||||
* Send SCSS to core for compilation.
|
||||
* @param {String} scss SCSS string
|
||||
*/
|
||||
async compile(scss) {
|
||||
return await ClientIPC.send('bd-compileSass', {
|
||||
return ClientIPC.send('bd-compileSass', {
|
||||
data: scss,
|
||||
path: await this.fileExists() ? this.filePath : undefined
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Recompile the current SCSS
|
||||
* Recompile the current SCSS.
|
||||
* @return {Promise}
|
||||
*/
|
||||
async recompile() {
|
||||
return await this.updateScss(this.scss);
|
||||
return this.updateScss(this.scss);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send data to open editor
|
||||
* @param {any} channel
|
||||
* @param {any} data
|
||||
* Send data to open editor.
|
||||
* @param {String} channel
|
||||
* @param {Any} data
|
||||
* @return {Promise}
|
||||
*/
|
||||
async sendToEditor(channel, data) {
|
||||
return await ClientIPC.send('sendToCssEditor', { channel, data });
|
||||
return ClientIPC.sendToCssEditor(channel, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an SCSS file in a system editor
|
||||
* Opens an SCSS file in a system editor.
|
||||
* @return {Promise}
|
||||
*/
|
||||
async openSystemEditor() {
|
||||
try {
|
||||
|
@ -156,11 +168,12 @@ export default new class {
|
|||
|
||||
// For some reason this doesn't work
|
||||
// if (!electron.shell.openItem(this.filePath))
|
||||
if (!electron.shell.openExternal('file://' + this.filePath))
|
||||
if (!electron.shell.openExternal(`file://${this.filePath}`))
|
||||
throw {message: 'Failed to open system editor.'};
|
||||
}
|
||||
|
||||
/** Set current state
|
||||
/**
|
||||
* Set current state
|
||||
* @param {String} scss Current uncompiled SCSS
|
||||
* @param {String} css Current compiled CSS
|
||||
* @param {String} files Files imported in the SCSS
|
||||
|
@ -168,36 +181,35 @@ export default new class {
|
|||
*/
|
||||
setState(scss, css, files, err) {
|
||||
this._scss = scss;
|
||||
this.sendToEditor('set-scss', { scss });
|
||||
this.sendToEditor('set-scss', scss);
|
||||
this.css = css;
|
||||
this.files = files;
|
||||
this.error = err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current uncompiled scss
|
||||
* Current uncompiled scss.
|
||||
*/
|
||||
get scss() {
|
||||
return this._scss || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current scss
|
||||
* Set current scss.
|
||||
*/
|
||||
set scss(scss) {
|
||||
this.updateScss(scss, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Current compiled css
|
||||
* Current compiled css.
|
||||
*/
|
||||
get css() {
|
||||
return this._css || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject compiled css to head
|
||||
* {DOM}
|
||||
* Inject compiled css to head.
|
||||
*/
|
||||
set css(css) {
|
||||
this._css = css;
|
||||
|
@ -205,15 +217,14 @@ export default new class {
|
|||
}
|
||||
|
||||
/**
|
||||
* Current error
|
||||
* Current error.
|
||||
*/
|
||||
get error() {
|
||||
return this._error || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current error
|
||||
* {DOM}
|
||||
* Set current error.
|
||||
*/
|
||||
set error(err) {
|
||||
this._error = err;
|
||||
|
@ -264,7 +275,7 @@ export default new class {
|
|||
* @param {Array} files Files to watch
|
||||
*/
|
||||
set watchfiles(files) {
|
||||
for (let file of files) {
|
||||
for (const file of files) {
|
||||
if (!this.watchfiles.includes(file)) {
|
||||
this.filewatcher.add(file);
|
||||
this.watchfiles.push(file);
|
||||
|
@ -272,7 +283,7 @@ export default new class {
|
|||
}
|
||||
}
|
||||
|
||||
for (let index in this.watchfiles) {
|
||||
for (const index in this.watchfiles) {
|
||||
let file = this.watchfiles[index];
|
||||
while (file && !files.find(f => f === file)) {
|
||||
this.filewatcher.remove(file);
|
||||
|
@ -293,7 +304,7 @@ export default new class {
|
|||
|
||||
/**
|
||||
* Checks if the system editor's file exists.
|
||||
* @return {Boolean}
|
||||
* @return {Promise}
|
||||
*/
|
||||
async fileExists() {
|
||||
try {
|
||||
|
|
|
@ -8,7 +8,7 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { ClientIPC } from 'bdipc';
|
||||
import { ClientIPC } from 'common';
|
||||
|
||||
export default class {
|
||||
|
||||
|
@ -16,6 +16,12 @@ export default class {
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts or updates data in the database.
|
||||
* @param {Object} args The record to find
|
||||
* @param {Object} data The new record
|
||||
* @return {Promise}
|
||||
*/
|
||||
static async insertOrUpdate(args, data) {
|
||||
try {
|
||||
return ClientIPC.send('bd-dba', { action: 'update', args, data });
|
||||
|
@ -24,6 +30,11 @@ export default class {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds data in the database.
|
||||
* @param {Object} args The record to find
|
||||
* @return {Promise}
|
||||
*/
|
||||
static async find(args) {
|
||||
try {
|
||||
return ClientIPC.send('bd-dba', { action: 'find', args });
|
||||
|
@ -31,4 +42,20 @@ export default class {
|
|||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find first in the database
|
||||
* @param {Object} args The record to find
|
||||
* @return {Promise} null if record was not found
|
||||
*/
|
||||
static async findOne(args) {
|
||||
try {
|
||||
const find = await this.find(args);
|
||||
if (find && find.length) return find[0];
|
||||
return null;
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,47 +1,25 @@
|
|||
import { WebpackModules } from './webpackmodules';
|
||||
import { $ } from 'vendor';
|
||||
/**
|
||||
* BetterDiscord Discord API
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
class List extends Array {
|
||||
import { List } from 'structs';
|
||||
import { User, Channel, Guild, Message } from 'discordstructs';
|
||||
import Reflection from './reflection/index';
|
||||
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
}
|
||||
|
||||
get(...filters) {
|
||||
return this.find(item => {
|
||||
for (let filter of filters) {
|
||||
for (let key in filter) {
|
||||
if (filter.hasOwnProperty(key)) {
|
||||
if (item[key] !== filter[key]) return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class PermissionsError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'PermissionsError';
|
||||
}
|
||||
}
|
||||
|
||||
class InsufficientPermissions extends PermissionsError {
|
||||
constructor(message) {
|
||||
super(`Missing Permission — ${message}`)
|
||||
this.name = 'InsufficientPermissions';
|
||||
}
|
||||
}
|
||||
|
||||
const Modules = {
|
||||
export const Modules = {
|
||||
_getModule(name) {
|
||||
const foundModule = WebpackModules.getModuleByName(name);
|
||||
const foundModule = Reflection.module.byName(name);
|
||||
if (!foundModule) return null;
|
||||
delete this[name];
|
||||
return this[name] = foundModule;
|
||||
},
|
||||
|
||||
get ChannelSelector() { return this._getModule('ChannelSelector'); },
|
||||
get MessageActions() { return this._getModule('MessageActions'); },
|
||||
get MessageParser() { return this._getModule('MessageParser'); },
|
||||
|
@ -64,356 +42,294 @@ const Modules = {
|
|||
get UserStore() { return this._getModule('UserStore'); },
|
||||
get RelationshipStore() { return this._getModule('RelationshipStore'); },
|
||||
get RelationshipManager() { return this._getModule('RelationshipManager'); },
|
||||
get ChangeNicknameModal() { return this._getModule('ChangeNicknameModal'); },
|
||||
get UserSettingsStore() { return this._getModule('UserSettingsStore'); },
|
||||
get UserSettingsWindow() { return this._getModule('UserSettingsWindow'); },
|
||||
get UserStatusStore() { return this._getModule('UserStatusStore'); },
|
||||
get ChannelSettingsWindow() { return this._getModule('ChannelSettingsWindow'); },
|
||||
get GuildSettingsWindow() { return this._getModule('GuildSettingsWindow'); },
|
||||
get CreateChannelModal() { return this._getModule('CreateChannelModal'); },
|
||||
get PruneMembersModal() { return this._getModule('PruneMembersModal'); },
|
||||
get NotificationSettingsModal() { return this._getModule('NotificationSettingsModal'); },
|
||||
get PrivacySettingsModal() { return this._getModule('PrivacySettingsModal'); },
|
||||
get UserProfileModal() { return this._getModule('UserProfileModal'); },
|
||||
get APIModule() { return this._getModule('APIModule'); },
|
||||
get UserNoteStore() { return this._getModule('UserNoteStore'); },
|
||||
|
||||
get DiscordPermissions() { return this.DiscordConstants.Permissions; }
|
||||
|
||||
};
|
||||
|
||||
class User {
|
||||
constructor(data) {
|
||||
for (let key in data)
|
||||
if (data.hasOwnProperty(key))
|
||||
this[key] = data[key];
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
static fromId(id) {
|
||||
return new User(Modules.UserStore.getUser(id));
|
||||
}
|
||||
|
||||
async sendMessage(content, parse = true) {
|
||||
const id = await Modules.PrivateChannelActions.ensurePrivateChannel(DiscordApi.currentUser.id, this.id);
|
||||
const channel = new PrivateChannel(Modules.ChannelStore.getChannel(id));
|
||||
channel.sendMessage(content, parse);
|
||||
}
|
||||
|
||||
get isFriend() {
|
||||
return Modules.RelationshipStore.isFriend(this.id);
|
||||
}
|
||||
|
||||
get isBlocked() {
|
||||
return Modules.RelationshipStore.isBlocked(this.id);
|
||||
}
|
||||
|
||||
addFriend() {
|
||||
Modules.RelationshipManager.addRelationship(this.id, {location: 'Context Menu'});
|
||||
}
|
||||
|
||||
removeFriend() {
|
||||
Modules.RelationshipManager.removeRelationship(this.id, {location: 'Context Menu'});
|
||||
}
|
||||
|
||||
block() {
|
||||
Modules.RelationshipManager.addRelationship(this.id, {location: 'Context Menu'}, Modules.DiscordConstants.RelationshipTypes.BLOCKED);
|
||||
}
|
||||
|
||||
unblock() {
|
||||
Modules.RelationshipManager.removeRelationship(this.id, {location: 'Context Menu'});
|
||||
}
|
||||
}
|
||||
|
||||
class Member extends User {
|
||||
constructor(data, guild) {
|
||||
super(data);
|
||||
const userData = Modules.UserStore.getUser(data.userId);
|
||||
for (let key in userData)
|
||||
if (userData.hasOwnProperty(key))
|
||||
this[key] = userData[key];
|
||||
this.guild_id = guild;
|
||||
}
|
||||
|
||||
checkPermissions(perms) {
|
||||
return Modules.PermissionUtils.can(perms, DiscordApi.currentUser, Modules.GuildStore.getGuild(this.guild_id));
|
||||
}
|
||||
|
||||
kick(reason = '') {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.KICK_MEMBERS)) throw new InsufficientPermissions('KICK_MEMBERS');
|
||||
Modules.GuildActions.kickUser(this.guild_id, this.id, reason);
|
||||
}
|
||||
|
||||
ban(daysToDelete = '1', reason = '') {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.BAN_MEMBERS)) throw new InsufficientPermissions('BAN_MEMBERS');
|
||||
Modules.GuildActions.banUser(this.guild_id, this.id, daysToDelete, reason);
|
||||
}
|
||||
|
||||
unban() {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.BAN_MEMBERS)) throw new InsufficientPermissions('BAN_MEMBERS');
|
||||
Modules.GuildActions.unbanUser(this.guild_id, this.id);
|
||||
}
|
||||
|
||||
move(channel_id) {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.MOVE_MEMBERS)) throw new InsufficientPermissions('MOVE_MEMBERS');
|
||||
Modules.GuildActions.setChannel(this.guild_id, this.id, channel_id);
|
||||
}
|
||||
|
||||
mute(active = true) {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.MUTE_MEMBERS)) throw new InsufficientPermissions('MUTE_MEMBERS');
|
||||
Modules.GuildActions.setServerMute(this.guild_id, this.id, active);
|
||||
}
|
||||
|
||||
unmute(active = true) {
|
||||
this.mute(false);
|
||||
}
|
||||
|
||||
deafen(active = true) {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.DEAFEN_MEMBERS)) throw new InsufficientPermissions('DEAFEN_MEMBERS');
|
||||
Modules.GuildActions.setServerDeaf(this.guild_id, this.id, active);
|
||||
}
|
||||
|
||||
undeafen(active = true) {
|
||||
this.deafen(false);
|
||||
}
|
||||
}
|
||||
|
||||
class Guild {
|
||||
constructor(data) {
|
||||
for (let key in data)
|
||||
if (data.hasOwnProperty(key))
|
||||
this[key] = data[key];
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
get channels() {
|
||||
const channels = Modules.GuildChannelsStore.getChannels(this.id);
|
||||
const returnChannels = new List();
|
||||
for (const category in channels) {
|
||||
if (channels.hasOwnProperty(category)) {
|
||||
if (!Array.isArray(channels[category])) continue;
|
||||
const channelList = channels[category];
|
||||
for (const channel of channelList) {
|
||||
returnChannels.push(new GuildChannel(channel.channel));
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnChannels;
|
||||
}
|
||||
|
||||
get defaultChannel() {
|
||||
return new GuildChannel(Modules.GuildChannelsStore.getDefaultChannel(this.id));
|
||||
}
|
||||
|
||||
get members() {
|
||||
const members = Modules.GuildMemberStore.getMembers(this.id);
|
||||
const returnMembers = new List();
|
||||
for (const member of members) returnMembers.push(new Member(member, this.id));
|
||||
return returnMembers;
|
||||
}
|
||||
|
||||
get memberCount() {
|
||||
return Modules.MemberCountStore.getMemberCount(this.id);
|
||||
}
|
||||
|
||||
get emojis() {
|
||||
return Modules.EmojiUtils.getGuildEmoji(this.id);
|
||||
}
|
||||
|
||||
get permissions() {
|
||||
return Modules.GuildPermissions.getGuildPermissions(this.id);
|
||||
}
|
||||
|
||||
getMember(userId) {
|
||||
return Modules.GuildMemberStore.getMember(this.id, userId);
|
||||
}
|
||||
|
||||
isMember(userId) {
|
||||
return Modules.GuildMemberStore.isMember(this.id, userId);
|
||||
}
|
||||
|
||||
markAsRead() {
|
||||
Modules.GuildActions.markGuildAsRead(this.id);
|
||||
}
|
||||
|
||||
select() {
|
||||
Modules.GuildActions.selectGuild(this.id);
|
||||
}
|
||||
|
||||
nsfwAgree() {
|
||||
Modules.GuildActions.nsfwAgree(this.id);
|
||||
}
|
||||
|
||||
nsfwDisagree() {
|
||||
Modules.GuildActions.nsfwDisagree(this.id);
|
||||
}
|
||||
|
||||
changeSortLocation(index) {
|
||||
Modules.GuildActions.move(DiscordApi.guildPositions.indexOf(this.id), index);
|
||||
}
|
||||
}
|
||||
|
||||
class Channel {
|
||||
constructor(data) {
|
||||
for (let key in data)
|
||||
if (data.hasOwnProperty(key))
|
||||
this[key] = data[key];
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
checkPermissions(perms) {
|
||||
return Modules.PermissionUtils.can(perms, DiscordApi.currentUser, this.discordObject) || this.isPrivate();
|
||||
}
|
||||
|
||||
async sendMessage(content, parse = true) {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.VIEW_CHANNEL | Modules.DiscordPermissions.SEND_MESSAGES)) throw new InsufficientPermissions('SEND_MESSAGES');
|
||||
let response = {};
|
||||
if (parse) response = await Modules.MessageActions._sendMessage(this.id, Modules.MessageParser.parse(this.discordObject, content));
|
||||
else response = await Modules.MessageActions._sendMessage(this.id, {content});
|
||||
return new Message(Modules.MessageStore.getMessage(this.id, response.body.id));
|
||||
}
|
||||
|
||||
get messages() {
|
||||
const messages = Modules.MessageStore.getMessages(this.id).toArray();
|
||||
for (let i in messages)
|
||||
if (messages.hasOwnProperty(i))
|
||||
messages[i] = new Message(messages[i]);
|
||||
return new List(...messages);
|
||||
}
|
||||
|
||||
jumpToPresent() {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.VIEW_CHANNEL)) throw new InsufficientPermissions('VIEW_CHANNEL');
|
||||
if (this.hasMoreAfter) Modules.MessageActions.jumpToPresent(this.id, Modules.DiscordConstants.MAX_MESSAGES_PER_CHANNEL);
|
||||
else this.messages[this.messages.length - 1].jumpTo(false);
|
||||
}
|
||||
|
||||
get hasMoreAfter() {
|
||||
return Modules.MessageStore.getMessages(this.id).hasMoreAfter;
|
||||
}
|
||||
|
||||
sendInvite(inviteId) {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.VIEW_CHANNEL | Modules.DiscordPermissions.SEND_MESSAGES)) throw new InsufficientPermissions('SEND_MESSAGES');
|
||||
Modules.MessageActions.sendInvite(this.id, inviteId);
|
||||
}
|
||||
|
||||
select() {
|
||||
if (!this.checkPermissions(Modules.DiscordPermissions.VIEW_CHANNEL)) throw new InsufficientPermissions('VIEW_CHANNEL');
|
||||
Modules.NavigationUtils.transitionToGuild(this.guild_id ? this.guild_id : Modules.DiscordConstants.ME, this.id);
|
||||
}
|
||||
}
|
||||
|
||||
class GuildChannel extends Channel {
|
||||
|
||||
constructor(data) {
|
||||
super(data);
|
||||
}
|
||||
|
||||
get permissions() {
|
||||
return Modules.GuildPermissions.getChannelPermissions(this.id);
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return new Guild(Modules.GuildStore.getGuild(this.guild_id));
|
||||
}
|
||||
|
||||
isDefaultChannel() {
|
||||
return Modules.GuildChannelsStore.getDefaultChannel(this.guild_id).id === this.id;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class PrivateChannel extends Channel {
|
||||
constructor(data) {
|
||||
super(data);
|
||||
}
|
||||
}
|
||||
|
||||
class Message {
|
||||
constructor(data) {
|
||||
for (let key in data)
|
||||
if (data.hasOwnProperty(key))
|
||||
this[key] = data[key];
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
delete() {
|
||||
Modules.MessageActions.deleteMessage(this.channel_id, this.id);
|
||||
}
|
||||
|
||||
// programmatically update the content
|
||||
edit(content, parse = false) {
|
||||
if (this.author.id !== DiscordApi.currentUser.id) return;
|
||||
if (parse) Modules.MessageActions.editMessage(this.channel_id, this.id, Modules.MessageParser.parse(this.discordObject, content));
|
||||
else Modules.MessageActions.editMessage(this.channel_id, this.id, {content});
|
||||
}
|
||||
|
||||
// start the editing mode of GUI
|
||||
startEdit() {
|
||||
if (this.author.id !== DiscordApi.currentUser.id) return;
|
||||
Modules.MessageActions.startEditMessage(this.channel_id, this.id, this.content);
|
||||
}
|
||||
|
||||
// end editing mode of GUI
|
||||
endEdit() {
|
||||
Modules.MessageActions.endEditMessage();
|
||||
}
|
||||
|
||||
jumpTo(flash = true) {
|
||||
Modules.MessageActions.jumpToMessage(this.channel_id, this.id, flash);
|
||||
}
|
||||
}
|
||||
|
||||
export default class DiscordApi {
|
||||
|
||||
static get channels() {
|
||||
const channels = Modules.ChannelStore.getChannels();
|
||||
const returnChannels = new List();
|
||||
for (const [key, value] of Object.entries(channels)) {
|
||||
returnChannels.push(value.isPrivate() ? new PrivateChannel(value) : new GuildChannel(value));
|
||||
}
|
||||
return returnChannels;
|
||||
}
|
||||
static get modules() { return Modules }
|
||||
static get User() { return User }
|
||||
static get Channel() { return Channel }
|
||||
static get Guild() { return Guild }
|
||||
static get Message() { return Message }
|
||||
|
||||
/**
|
||||
* A list of loaded guilds.
|
||||
* @type {List<Guild>}
|
||||
*/
|
||||
static get guilds() {
|
||||
const guilds = Modules.GuildStore.getGuilds();
|
||||
const returnGuilds = new List();
|
||||
for (const [key, value] of Object.entries(guilds)) {
|
||||
returnGuilds.push(new Guild(value));
|
||||
}
|
||||
return returnGuilds;
|
||||
return List.from(Object.entries(guilds), ([i, g]) => Guild.from(g));
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of loaded channels.
|
||||
* @type {List<Channel>}
|
||||
*/
|
||||
static get channels() {
|
||||
const channels = Modules.ChannelStore.getChannels();
|
||||
return List.from(Object.entries(channels), ([i, c]) => Channel.from(c));
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of loaded users.
|
||||
* @type {List<User>}
|
||||
*/
|
||||
static get users() {
|
||||
const users = Modules.UserStore.getUsers();
|
||||
const returnUsers = new List();
|
||||
for (const [key, value] of Object.entries(users)) {
|
||||
returnUsers.push(new User(value));
|
||||
}
|
||||
return returnUsers;
|
||||
return List.from(Object.entries(users), ([i, u]) => User.from(u));
|
||||
}
|
||||
|
||||
/**
|
||||
* An object mapping guild IDs to their member counts.
|
||||
* @type {Object}
|
||||
*/
|
||||
static get memberCounts() {
|
||||
return Modules.MemberCountStore.getMemberCounts();
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of guilds in the order they appear in the server list.
|
||||
* @type {List<Guild>}
|
||||
*/
|
||||
static get sortedGuilds() {
|
||||
const guilds = Modules.SortedGuildStore.getSortedGuilds();
|
||||
const returnGuilds = new List();
|
||||
for (const guild of guilds) {
|
||||
returnGuilds.push(new Guild(guild));
|
||||
}
|
||||
return returnGuilds;
|
||||
return List.from(guilds, g => Guild.from(g));
|
||||
}
|
||||
|
||||
/**
|
||||
* An array of guild IDs in the order they appear in the server list.
|
||||
* @type {Number[]}
|
||||
*/
|
||||
static get guildPositions() {
|
||||
return Modules.SortedGuildStore.guildPositions;
|
||||
}
|
||||
|
||||
/**
|
||||
* The currently selected guild.
|
||||
* @type {Guild}
|
||||
*/
|
||||
static get currentGuild() {
|
||||
return new Guild(Modules.GuildStore.getGuild(Modules.SelectedGuildStore.getGuildId()));
|
||||
const guild = Modules.GuildStore.getGuild(Modules.SelectedGuildStore.getGuildId());
|
||||
if (guild) return Guild.from(guild);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The currently selected channel.
|
||||
* @type {Channel}
|
||||
*/
|
||||
static get currentChannel() {
|
||||
const channel = Modules.ChannelStore.getChannel(Modules.SelectedChannelStore.getChannelId());
|
||||
return channel.isPrivate ? new PrivateChannel(channel) : new GuildChannel(channel);
|
||||
if (channel) return Channel.from(channel);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The current user.
|
||||
* @type {User}
|
||||
*/
|
||||
static get currentUser() {
|
||||
return Modules.UserStore.getCurrentUser();
|
||||
const user = Modules.UserStore.getCurrentUser();
|
||||
if (user) return User.from(user);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of the current user's friends.
|
||||
* @type {List<User>}
|
||||
*/
|
||||
static get friends() {
|
||||
const friends = Modules.RelationshipStore.getFriendIDs();
|
||||
const returnUsers = new List();
|
||||
for (const id of friends) returnUsers.push(User.fromId(id));
|
||||
return returnUsers;
|
||||
return List.from(friends, id => User.fromId(id));
|
||||
}
|
||||
/**
|
||||
* User settings
|
||||
*/
|
||||
static get UserSettings() {
|
||||
return UserSettings;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export class UserSettings {
|
||||
/**
|
||||
* Opens Discord's settings UI.
|
||||
*/
|
||||
static open(section = 'ACCOUNT') {
|
||||
Modules.UserSettingsWindow.setSection(section);
|
||||
Modules.UserSettingsWindow.open();
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's current status. Either "online", "idle", "dnd" or "invisible".
|
||||
* @type {String}
|
||||
*/
|
||||
static get status() { return Modules.UserSettingsStore.status }
|
||||
|
||||
/**
|
||||
* The user's selected explicit content filter level.
|
||||
* 0 == off, 1 == everyone except friends, 2 == everyone
|
||||
* Configurable in the privacy and safety panel.
|
||||
* @type {Number}
|
||||
*/
|
||||
static get explicitContentFilter() { return Modules.UserSettingsStore.explicitContentFilter }
|
||||
|
||||
/**
|
||||
* Whether to disallow direct messages from server members by default.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get defaultGuildsRestricted() { return Modules.UserSettingsStore.defaultGuildsRestricted }
|
||||
|
||||
/**
|
||||
* An array of guilds to disallow direct messages from their members.
|
||||
* This is bypassed if the member is has another mutual guild with this disabled, or the member is friends with the current user.
|
||||
* Configurable in each server's privacy settings.
|
||||
* @type {Guild[]}
|
||||
*/
|
||||
static get restrictedGuildIds() { return Modules.UserSettingsStore.restrictedGuilds }
|
||||
|
||||
static get restrictedGuilds() {
|
||||
return List.from(this.restrictedGuildIds, id => Guild.fromId(id) || id);
|
||||
}
|
||||
|
||||
/**
|
||||
* An array of flags specifying who should be allowed to add the current user as a friend.
|
||||
* If everyone is checked, this will only have one item, "all". Otherwise it has either "mutual_friends", "mutual_guilds", both or neither.
|
||||
* Configurable in the privacy and safety panel.
|
||||
* @type {Array}
|
||||
*/
|
||||
static get friendSourceFlags() { return Object.keys(Modules.UserSettingsStore.friendSourceFlags) }
|
||||
static get friendSourceEveryone() { return this.friendSourceFlags.include('all') }
|
||||
static get friendSourceMutual_friends() { return this.friendSourceFlags.include('all') || this.friendSourceFlags.include('mutual_friends') }
|
||||
static get friendSourceMutual_guilds() { return this.friendSourceFlags.include('all') || this.friendSourceFlags.include('mutual_guilds') }
|
||||
static get friendSourceAnyone() { return this.friendSourceFlags.length > 0 }
|
||||
|
||||
/**
|
||||
* Whether to automatically add accounts from other platforms running on the user's computer.
|
||||
* Configurable in the connections panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get detectPlatformAccounts() { return Modules.UserSettingsStore.detectPlatformAccounts }
|
||||
|
||||
/**
|
||||
* The number of seconds Discord will wait for activity before sending mobile push notifications.
|
||||
* Configurable in the notifications panel.
|
||||
* @type {Number}
|
||||
*/
|
||||
static get afkTimeout() { return Modules.UserSettingsStore.afkTimeout }
|
||||
|
||||
/**
|
||||
* Whether to display the currently running game as a status message.
|
||||
* Configurable in the games panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get showCurrentGame() { return Modules.UserSettingsStore.showCurrentGame }
|
||||
|
||||
/**
|
||||
* Whether to show images uploaded directly to Discord.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get inlineAttachmentMedia() { return Modules.UserSettingsStore.inlineAttachmentMedia }
|
||||
|
||||
/**
|
||||
* Whether to show images linked in Discord.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get inlineEmbedMedia() { return Modules.UserSettingsStore.inlineEmbedMedia }
|
||||
|
||||
/**
|
||||
* Whether to automatically play GIFs when the Discord window is active without having to hover the mouse over the image.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get autoplayGifs() { return Modules.UserSettingsStore.gifAutoPlay }
|
||||
|
||||
/**
|
||||
* Whether to show content from HTTP[s] links as embeds.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get showEmbeds() { return Modules.UserSettingsStore.renderEmbeds }
|
||||
|
||||
/**
|
||||
* Whether to show a message's reactions.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get showReactions() { return Modules.UserSettingsStore.renderReactions }
|
||||
|
||||
/**
|
||||
* Whether to play animated emoji.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get animateEmoji() { return Modules.UserSettingsStore.animateEmoji }
|
||||
|
||||
/**
|
||||
* Whether to convert ASCII emoticons to emoji.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get convertEmoticons() { return Modules.UserSettingsStore.convertEmoticons }
|
||||
|
||||
/**
|
||||
* Whether to allow playing text-to-speech messages.
|
||||
* Configurable in the text and images panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get allowTts() { return Modules.UserSettingsStore.enableTTSCommand }
|
||||
|
||||
/**
|
||||
* The user's selected theme. Either "dark" or "light".
|
||||
* Configurable in the appearance panel.
|
||||
* @type {String}
|
||||
*/
|
||||
static get theme() { return Modules.UserSettingsStore.theme }
|
||||
|
||||
/**
|
||||
* Whether the user has enabled compact mode.
|
||||
* `true` if compact mode is enabled, `false` if cozy mode is enabled.
|
||||
* Configurable in the appearance panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get displayCompact() { return Modules.UserSettingsStore.messageDisplayCompact }
|
||||
|
||||
/**
|
||||
* Whether the user has enabled developer mode.
|
||||
* Currently only adds a "Copy ID" option to the context menu on users, guilds and channels.
|
||||
* Configurable in the appearance panel.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
static get developerMode() { return Modules.UserSettingsStore.developerMode }
|
||||
|
||||
/**
|
||||
* The user's selected language code.
|
||||
* Configurable in the language panel.
|
||||
* @type {String}
|
||||
*/
|
||||
static get locale() { return Modules.UserSettingsStore.locale }
|
||||
|
||||
/**
|
||||
* The user's timezone offset in hours.
|
||||
* This is not configurable.
|
||||
* @type {Number}
|
||||
*/
|
||||
static get timezoneOffset() { return Modules.UserSettingsStore.timezoneOffset }
|
||||
}
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
/**
|
||||
* BetterDiscord Editor Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import Module from './imodule';
|
||||
import { DOM } from 'ui';
|
||||
|
||||
export default new class extends Module {
|
||||
|
||||
get name() { return 'Editor' }
|
||||
get delay() { return false; }
|
||||
|
||||
setInitialState(state) {
|
||||
return {
|
||||
editorBounds: undefined
|
||||
};
|
||||
}
|
||||
|
||||
initialize() {
|
||||
super.initialize();
|
||||
(async () => {
|
||||
try {
|
||||
// TODO this is temporary
|
||||
const userScss = await this.send('readDataFile', 'user.scss');
|
||||
const compiled = await this.send('compileSass', { data: userScss });
|
||||
this.injectStyle('customcss', compiled.css.toString());
|
||||
} catch (err) {
|
||||
console.warn('SCSS Compilation error', err);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
events(ipc) {
|
||||
ipc.on('editor-runScript', (e, script) => {
|
||||
try {
|
||||
new Function(script)();
|
||||
e.reply('ok');
|
||||
} catch (err) {
|
||||
e.reply({ err: err.stack || err });
|
||||
}
|
||||
});
|
||||
|
||||
ipc.on('editor-injectStyle', (e, { id, style }) => {
|
||||
this.injectStyle(id, style);
|
||||
e.reply('ok');
|
||||
});
|
||||
}
|
||||
|
||||
injectStyle(id, style) {
|
||||
return DOM.injectStyle(style, `userstyle-${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show editor, flashes if already visible.
|
||||
*/
|
||||
async show() {
|
||||
await this.send('editor-open', this.state.editorBounds);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* BetterDiscord WebpackModules Module
|
||||
* BetterDiscord Event Hook
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
|
@ -8,14 +8,13 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import EventListener from './eventlistener';
|
||||
import { Utils } from 'common';
|
||||
import Reflection from './reflection/index';
|
||||
import { MonkeyPatch } from './patcher';
|
||||
import Events from './events';
|
||||
import { WebpackModules } from './webpackmodules';
|
||||
import EventListener from './eventlistener';
|
||||
|
||||
import * as SocketStructs from '../structs/socketstructs';
|
||||
|
||||
|
||||
/**
|
||||
* Discord socket event hook
|
||||
* @extends {EventListener}
|
||||
|
@ -23,7 +22,7 @@ import * as SocketStructs from '../structs/socketstructs';
|
|||
export default class extends EventListener {
|
||||
|
||||
init() {
|
||||
console.log(SocketStructs);
|
||||
this.ignoreMultiple = -1;
|
||||
this.hook();
|
||||
}
|
||||
|
||||
|
@ -38,22 +37,26 @@ export default class extends EventListener {
|
|||
}
|
||||
|
||||
hook() {
|
||||
const self = this;
|
||||
const orig = this.eventsModule.prototype.emit;
|
||||
this.eventsModule.prototype.emit = function (...args) {
|
||||
const { Events } = Reflection.modules;
|
||||
MonkeyPatch('BD:EVENTS', Events.prototype).after('emit', (obj, args, retVal) => {
|
||||
const eventId = args.length >= 3 ? args[2].id || -1 : -1;
|
||||
if (eventId === this.ignoreMultiple) return;
|
||||
this.ignoreMultiple = eventId;
|
||||
if (obj.webSocket) this.wsc = obj.webSocket;
|
||||
this.emit(...args);
|
||||
});
|
||||
/*
|
||||
const orig = Events.prototype.emit;
|
||||
Events.prototype.emit = function (...args) {
|
||||
orig.call(this, ...args);
|
||||
self.wsc = this;
|
||||
self.emit(...args);
|
||||
}
|
||||
}
|
||||
|
||||
get eventsModule() {
|
||||
return WebpackModules.getModuleByPrototypes(['setMaxListeners', 'emit']);
|
||||
};*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Discord emit overload
|
||||
* @param {any} e
|
||||
* @param {any} event
|
||||
* @param {any} action
|
||||
* @param {any} data
|
||||
*/
|
||||
|
@ -66,25 +69,32 @@ export default class extends EventListener {
|
|||
|
||||
/**
|
||||
* Emit callback
|
||||
* @param {any} e Event Action
|
||||
* @param {any} d Event Args
|
||||
* @param {any} event Event
|
||||
* @param {any} data Event data
|
||||
*/
|
||||
dispatch(e, d) {
|
||||
Events.emit('raw-event', { type: e, data: d });
|
||||
if (e === this.actions.READY || e === this.actions.RESUMED) {
|
||||
Events.emit(e, d);
|
||||
dispatch(type, data) {
|
||||
Events.emit('raw-event', { type, data });
|
||||
|
||||
if (type === this.actions.READY || type === this.actions.RESUMED) {
|
||||
Events.emit(type, data);
|
||||
return;
|
||||
}
|
||||
if (!Object.keys(SocketStructs).includes(e)) return;
|
||||
const evt = new SocketStructs[e](d);
|
||||
Events.emit(`discord:${e}`, evt);
|
||||
|
||||
if (!Object.keys(SocketStructs).includes(type)) return;
|
||||
Events.emit(`discord:${type}`, new SocketStructs[type](data));
|
||||
}
|
||||
|
||||
get SocketStructs() {
|
||||
return SocketStructs;
|
||||
}
|
||||
|
||||
/**
|
||||
* All known socket actions
|
||||
*/
|
||||
get actions() {
|
||||
return {
|
||||
if (this._actions) return this._actions;
|
||||
|
||||
return this._actions = {
|
||||
READY: 'READY', // Socket ready
|
||||
RESUMED: 'RESUMED', // Socket resumed
|
||||
TYPING_START: 'TYPING_START', // User typing start
|
||||
|
@ -143,7 +153,7 @@ export default class extends EventListener {
|
|||
LFG_LISTING_CREATE: 'LFG_LISTING_CREATE', // No groups here
|
||||
LFG_LISTING_DELETE: 'LFG_LISTING_DELETE', // Thank you
|
||||
BRAINTREE_POPUP_BRIDGE_CALLBACK: 'BRAINTREE_POPUP_BRIDGE_CALLBACK' // What
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -14,7 +14,7 @@ import Events from './events';
|
|||
export default class extends Module {
|
||||
|
||||
events() {
|
||||
for (let event of this.eventBindings) {
|
||||
for (const event of this.eventBindings) {
|
||||
Events.on(event.id, event.callback);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,16 +12,43 @@ import { EventEmitter } from 'events';
|
|||
const emitter = new EventEmitter();
|
||||
|
||||
export default class {
|
||||
static on(eventName, callBack) {
|
||||
emitter.on(eventName, callBack);
|
||||
|
||||
/**
|
||||
* Adds an event listener.
|
||||
* @param {String} event The event to listen for
|
||||
* @param {Function} callback The function to call when the event is emitted
|
||||
*/
|
||||
static on(event, callback) {
|
||||
emitter.on(event, callback);
|
||||
}
|
||||
|
||||
static off(eventName, callBack) {
|
||||
emitter.removeListener(eventName, callBack);
|
||||
/**
|
||||
* Adds an event listener that is only called once.
|
||||
* @param {String} event The event to listen for
|
||||
* @param {Function} callback The function to call when the event is emitted
|
||||
*/
|
||||
static once(event, callback) {
|
||||
emitter.once(event, callback);
|
||||
}
|
||||
|
||||
static emit(...args) {
|
||||
emitter.emit(...args);
|
||||
/**
|
||||
* Removes an event listener.
|
||||
* @param {String} event The event to remove
|
||||
* @param {Function} callback The listener to remove
|
||||
*/
|
||||
static off(event, callback) {
|
||||
emitter.removeListener(event, callback);
|
||||
}
|
||||
|
||||
static get removeListener() { return this.off }
|
||||
|
||||
/**
|
||||
* Emits an event
|
||||
* @param {String} event The event to emit
|
||||
* @param {Any} ...data Data to pass to the event listeners
|
||||
*/
|
||||
static emit(event, ...data) {
|
||||
emitter.emit(event, ...data);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -11,35 +11,45 @@
|
|||
const eventemitters = new WeakMap();
|
||||
|
||||
export default class EventsWrapper {
|
||||
constructor(eventemitter) {
|
||||
|
||||
constructor(eventemitter, bind) {
|
||||
eventemitters.set(this, eventemitter);
|
||||
this.bind = bind || this;
|
||||
}
|
||||
|
||||
get eventSubs() {
|
||||
return this._eventSubs || (this._eventSubs = []);
|
||||
}
|
||||
|
||||
get on() { return this.subscribe }
|
||||
subscribe(event, callback) {
|
||||
if (this.eventSubs.find(e => e.event === event && e.callback === callback)) return;
|
||||
this.eventSubs.push({
|
||||
event,
|
||||
callback
|
||||
});
|
||||
eventemitters.get(this).on(event, callback);
|
||||
const boundCallback = (...args) => callback.apply(this.bind, args);
|
||||
this.eventSubs.push({ event, callback, boundCallback });
|
||||
eventemitters.get(this).on(event, boundCallback);
|
||||
}
|
||||
|
||||
once(event, callback) {
|
||||
if (this.eventSubs.find(e => e.event === event && e.callback === callback)) return;
|
||||
const boundCallback = (...args) => this.off(event, callback) && callback.apply(this.bind, args);
|
||||
this.eventSubs.push({ event, callback, boundCallback });
|
||||
eventemitters.get(this).on(event, boundCallback);
|
||||
}
|
||||
|
||||
get off() { return this.unsubscribe }
|
||||
unsubscribe(event, callback) {
|
||||
for (let index of this.eventSubs) {
|
||||
if (this.eventSubs[index].event !== event || (callback && this.eventSubs[index].callback === callback)) return;
|
||||
eventemitters.get(this).off(event, this.eventSubs[index].callback);
|
||||
for (const index in this.eventSubs) {
|
||||
if (this.eventSubs[index].event !== event || (callback && this.eventSubs[index].callback === callback)) continue;
|
||||
eventemitters.get(this).removeListener(event, this.eventSubs[index].boundCallback);
|
||||
this.eventSubs.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
unsubscribeAll() {
|
||||
for (let event of this.eventSubs) {
|
||||
eventemitters.get(this).off(event.event, event.callback);
|
||||
for (const event of this.eventSubs) {
|
||||
eventemitters.get(this).removeListener(event.event, event.boundCallback);
|
||||
}
|
||||
this.eventSubs.splice(0, this.eventSubs.length);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,13 +8,14 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import Globals from './globals';
|
||||
import Content from './content';
|
||||
|
||||
export default class ExtModule extends Content {
|
||||
|
||||
constructor(internals) {
|
||||
super(internals);
|
||||
this.__require = window.require(this.paths.mainPath);
|
||||
this.__require = Globals.require(this.paths.mainPath);
|
||||
}
|
||||
|
||||
get type() { return 'module' }
|
||||
|
|
|
@ -10,8 +10,6 @@
|
|||
|
||||
import ContentManager from './contentmanager';
|
||||
import ExtModule from './extmodule';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import { Events } from 'modules';
|
||||
|
||||
export default class extends ContentManager {
|
||||
|
||||
|
|
|
@ -8,14 +8,20 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import sparkplug from 'sparkplug';
|
||||
import { ClientIPC } from 'common';
|
||||
import Module from './module';
|
||||
import Events from './events';
|
||||
import { ClientIPC } from 'bdipc';
|
||||
|
||||
export default new class extends Module {
|
||||
|
||||
constructor(args) {
|
||||
super(args);
|
||||
|
||||
// webpack replaces this with the normal require function
|
||||
// eslint-disable-next-line no-undef
|
||||
this.require = __non_webpack_require__;
|
||||
}
|
||||
|
||||
initg() {
|
||||
|
@ -28,28 +34,24 @@ export default new class extends Module {
|
|||
this.getObject = this.getObject.bind(this);
|
||||
}
|
||||
|
||||
first() {
|
||||
(async() => {
|
||||
async first() {
|
||||
const config = await ClientIPC.send('getConfig');
|
||||
this.setState(config);
|
||||
this.setState({ config });
|
||||
|
||||
// This is for Discord to stop error reporting :3
|
||||
window.BetterDiscord = {
|
||||
'version': config.version,
|
||||
'v': config.version
|
||||
version: config.version,
|
||||
v: config.version
|
||||
};
|
||||
window.jQuery = {};
|
||||
|
||||
if (window.__bd) {
|
||||
this.setState(window.__bd);
|
||||
window.__bd = {
|
||||
setWS: this.setWS
|
||||
}
|
||||
if (sparkplug.bd) {
|
||||
this.setState({ bd: sparkplug.bd });
|
||||
sparkplug.bd.setWS = this.setWS;
|
||||
}
|
||||
|
||||
Events.emit('global-ready');
|
||||
Events.emit('socket-created', this.state.wsHook);
|
||||
})();
|
||||
}
|
||||
|
||||
setWS(wSocket) {
|
||||
|
@ -60,19 +62,43 @@ export default new class extends Module {
|
|||
}
|
||||
|
||||
getObject(name) {
|
||||
return this.state[name];
|
||||
return this.config[name] || this.bd[name];
|
||||
}
|
||||
|
||||
get bd() {
|
||||
return this.state.bd;
|
||||
}
|
||||
|
||||
get localStorage() {
|
||||
return this.bd.localStorage;
|
||||
}
|
||||
|
||||
get webSocket() {
|
||||
return this.bd.wsHook;
|
||||
}
|
||||
|
||||
get WebSocket() {
|
||||
return this.bd.wsOrig;
|
||||
}
|
||||
|
||||
get ignited() {
|
||||
return this.bd.ignited;
|
||||
}
|
||||
|
||||
get config() {
|
||||
return this.state.config;
|
||||
}
|
||||
|
||||
get paths() {
|
||||
return this.config.paths;
|
||||
}
|
||||
|
||||
getPath(id) {
|
||||
return this.state.paths.find(path => path.id === id).path;
|
||||
return this.paths.find(path => path.id === id).path;
|
||||
}
|
||||
|
||||
static get paths() {
|
||||
return this.state.paths;
|
||||
}
|
||||
|
||||
static get version() {
|
||||
return this.state.version;
|
||||
get version() {
|
||||
return this.config.versions.core;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
/**
|
||||
* BetterDiscord Module Base
|
||||
* Copyright (c) 2015-present JsSucks - https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://github.com/JsSucks - https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Base Module that every non-static module should extend
|
||||
*/
|
||||
|
||||
import { ClientLogger as Logger, ClientIPC } from 'common';
|
||||
|
||||
export default class Module {
|
||||
|
||||
constructor(args) {
|
||||
this.__ = {
|
||||
state: args || {},
|
||||
args
|
||||
};
|
||||
this.setState = this.setState.bind(this);
|
||||
|
||||
if (this.delay) { // If delay is set then module is set to load delayed from modulemanager
|
||||
this.initialize = this.initialize.bind(this);
|
||||
this.init = this.initialize;
|
||||
} else {
|
||||
this.initialize();
|
||||
this.init = () => { };
|
||||
}
|
||||
}
|
||||
|
||||
initialize() {
|
||||
if (this.bindings) this.bindings();
|
||||
if (this.setInitialState) this.setState(this.setInitialState(this.state));
|
||||
if (this.events) this.events(ClientIPC);
|
||||
}
|
||||
|
||||
setState(newState) {
|
||||
const oldState = Object.assign({}, this.state);
|
||||
Object.assign(this.state, newState);
|
||||
if (this.stateChanged) this.stateChanged(oldState, newState);
|
||||
}
|
||||
|
||||
set args(t) { }
|
||||
get args() { return this.__.args; }
|
||||
|
||||
set state(state) { return this.__.state = state; }
|
||||
get state() { return this.__.state; }
|
||||
|
||||
async send(channel, message) {
|
||||
return ClientIPC.send(channel, message);
|
||||
}
|
||||
|
||||
log(msg) {
|
||||
Logger.log(this.name, msg);
|
||||
}
|
||||
|
||||
warn(msg) {
|
||||
Logger.log(this.name, msg);
|
||||
}
|
||||
|
||||
err(msg) {
|
||||
Logger.log(this.name, msg);
|
||||
}
|
||||
|
||||
info(msg) {
|
||||
Logger.log(this.name, msg);
|
||||
}
|
||||
|
||||
}
|
|
@ -8,17 +8,16 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/*
|
||||
Base Module that every non-static module should extend
|
||||
/**
|
||||
* Base Module that every non-static module should extend
|
||||
*/
|
||||
|
||||
export default class Module {
|
||||
|
||||
constructor(args) {
|
||||
this.__ = {
|
||||
state: args || {},
|
||||
args
|
||||
}
|
||||
};
|
||||
this.setState = this.setState.bind(this);
|
||||
this.initialize();
|
||||
}
|
||||
|
@ -38,7 +37,6 @@ export default class Module {
|
|||
set args(t) { }
|
||||
get args() { return this.__.args; }
|
||||
|
||||
|
||||
set state(state) { return this.__.state = state; }
|
||||
get state() { return this.__.state; }
|
||||
|
||||
|
|
|
@ -8,30 +8,39 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/*Module Manager initializes all modules when everything is ready*/
|
||||
|
||||
import { Events, SocketProxy, EventHook, CssEditor } from 'modules';
|
||||
import { ProfileBadges } from 'ui';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import { SocketProxy, EventHook } from 'modules';
|
||||
import { ProfileBadges, ClassNormaliser } from 'ui';
|
||||
import Updater from './updater';
|
||||
|
||||
/**
|
||||
* Module Manager initializes all modules when everything is ready
|
||||
*/
|
||||
export default class {
|
||||
|
||||
/**
|
||||
* An array of modules.
|
||||
*/
|
||||
static get modules() {
|
||||
return this._modules ? this._modules : (this._modules = [
|
||||
new ProfileBadges(),
|
||||
new ClassNormaliser(),
|
||||
new SocketProxy(),
|
||||
new EventHook(),
|
||||
CssEditor,
|
||||
new Updater()
|
||||
Updater
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes all modules.
|
||||
* @return {Promise}
|
||||
*/
|
||||
static async initModules() {
|
||||
for (let module of this.modules) {
|
||||
for (const module of this.modules) {
|
||||
try {
|
||||
if (module.init && module.init instanceof Function) module.init();
|
||||
} catch (err) {
|
||||
console.log(`Failed to initialize module: ${err}`);
|
||||
Logger.err('Module Manager', ['Failed to initialize module:', err]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
|
|
@ -1,19 +1,31 @@
|
|||
export { default as Events } from './events';
|
||||
export { default as Settings } from './settings';
|
||||
export { default as CssEditor } from './csseditor';
|
||||
export { default as ExtModuleManager } from './extmodulemanager';
|
||||
export { default as Editor } from './editor';
|
||||
export { default as Globals } from './globals';
|
||||
export { default as Settings } from './settings';
|
||||
export { default as Database } from './database';
|
||||
export { default as Updater } from './updater';
|
||||
|
||||
export { default as ModuleManager } from './modulemanager';
|
||||
export { default as PluginManager } from './pluginmanager';
|
||||
export { default as ThemeManager } from './thememanager';
|
||||
export { default as Globals } from './globals';
|
||||
export { default as ExtModuleManager } from './extmodulemanager';
|
||||
export { default as Permissions } from './permissionmanager';
|
||||
|
||||
export { default as EventsWrapper } from './eventswrapper';
|
||||
export { default as Vendor } from './vendor';
|
||||
|
||||
export * from './webpackmodules';
|
||||
export { default as ModuleManager } from './modulemanager';
|
||||
export * from './patcher';
|
||||
export * from './reactcomponents';
|
||||
export { default as Module } from './module';
|
||||
export { default as EventListener } from './eventlistener';
|
||||
export { default as SocketProxy } from './socketproxy';
|
||||
export { default as EventHook } from './eventhook';
|
||||
export { default as Permissions } from './permissionmanager';
|
||||
export { default as Database } from './database';
|
||||
export { default as EventsWrapper } from './eventswrapper';
|
||||
export { default as DiscordApi } from './discordapi';
|
||||
export * from './patcher';
|
||||
export * from './reactcomponents';
|
||||
export { default as DiscordApi, Modules as DiscordApiModules } from './discordapi';
|
||||
export { default as BdWebApi } from './bdwebapi';
|
||||
export { default as Connectivity } from './connectivity';
|
||||
export { default as Security } from './security';
|
||||
export { default as Cache } from './cache';
|
||||
export { default as Reflection } from './reflection/index';
|
||||
export { default as PackageInstaller } from './packageinstaller';
|
||||
|
|
|
@ -0,0 +1,178 @@
|
|||
import EventListener from './eventlistener';
|
||||
import asar from 'asar';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import rimraf from 'rimraf';
|
||||
|
||||
import { request } from 'vendor';
|
||||
import { Modals } from 'ui';
|
||||
import { Utils, FileUtils } from 'common';
|
||||
import PluginManager from './pluginmanager';
|
||||
import Globals from './globals';
|
||||
import Security from './security';
|
||||
import Reflection from './reflection';
|
||||
import DiscordApi from './discordapi';
|
||||
import ThemeManager from './thememanager';
|
||||
import { MonkeyPatch } from './patcher';
|
||||
import { DOM } from 'ui';
|
||||
|
||||
export default class PackageInstaller {
|
||||
|
||||
/**
|
||||
* Handler for drag and drop package install
|
||||
* @param {String} filePath Path to local file
|
||||
* @param {Boolean} canUpload If the user can upload files in current window
|
||||
* @returns {Number} returns action code from modal
|
||||
*/
|
||||
static async dragAndDropHandler(filePath, canUpload) {
|
||||
try {
|
||||
const config = JSON.parse(asar.extractFile(filePath, 'config.json').toString());
|
||||
const { info, main } = config;
|
||||
|
||||
let icon = null;
|
||||
if (info.icon && info.icon_type) {
|
||||
const extractIcon = asar.extractFile(filePath, info.icon);
|
||||
icon = `data:${info.icon_type};base64,${Utils.arrayBufferToBase64(extractIcon)}`;
|
||||
}
|
||||
|
||||
const isPlugin = info.type && info.type === 'plugin' || main.endsWith('.js');
|
||||
|
||||
// Show install modal
|
||||
const modalResult = await Modals.installModal(isPlugin ? 'plugin' : 'theme', config, filePath, icon, canUpload).promise;
|
||||
return modalResult;
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash and verify a package
|
||||
* @param {Byte[]|String} bytesOrPath byte array of binary or path to local file
|
||||
* @param {String} id Package id
|
||||
*/
|
||||
static async verifyPackage(bytesOrPath, id) {
|
||||
const bytes = typeof bytesOrPath === 'string' ? fs.readFileSync(bytesOrPath) : bytesOrPath;
|
||||
// Temporary hash to simulate response from server
|
||||
const tempVerified = ['2e3532ee366816adc37b0f478bfef35e03f96e7aeee9b115f5918ef6a4e94de8', '06a2eb4e37b926354ab80cd83207db67e544c932e9beddce545967a21f8db5aa'];
|
||||
const hashBytes = Security.hash('sha256', bytes, 'hex');
|
||||
|
||||
return tempVerified.includes(hashBytes);
|
||||
}
|
||||
|
||||
// TODO lots of stuff
|
||||
/**
|
||||
* Installs or updates defined package
|
||||
* @param {Byte[]|String} bytesOrPath byte array of binary or path to local file
|
||||
* @param {String} nameOrId Package name
|
||||
* @param {Boolean} update Does an older version already exist
|
||||
*/
|
||||
static async installPackage(bytesOrPath, nameOrId, contentType, update = false) {
|
||||
let outputPath = null;
|
||||
try {
|
||||
|
||||
const bytes = typeof bytesOrPath === 'string' ? fs.readFileSync(bytesOrPath) : bytesOrPath;
|
||||
const outputName = `${nameOrId}.bd`;
|
||||
|
||||
outputPath = path.join(Globals.getPath(`${contentType}s`), outputName);
|
||||
fs.writeFileSync(outputPath, bytes);
|
||||
|
||||
const manager = contentType === 'plugin' ? PluginManager : ThemeManager;
|
||||
|
||||
if (!update) return manager.preloadPackedContent(outputName);
|
||||
|
||||
const oldContent = manager.findContent(nameOrId);
|
||||
|
||||
await oldContent.unload(true);
|
||||
|
||||
if (oldContent.packed && oldContent.packageName !== nameOrId) {
|
||||
await FileUtils.deleteFile(oldContent.packagePath).catch(err => null);
|
||||
}
|
||||
await FileUtils.recursiveDeleteDirectory(oldContent.contentPath).catch(err => null);
|
||||
|
||||
return manager.preloadPackedContent(outputName);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install package from remote location. Only github/bdapi is supported.
|
||||
* @param {String} remoteLocation Remote resource location
|
||||
*/
|
||||
static async installRemotePackage(remoteLocation) {
|
||||
try {
|
||||
const { hostname } = Object.assign(document.createElement('a'), { href: remoteLocation });
|
||||
if (hostname !== 'api.github.com' && hostname !== 'secretbdapi') throw 'Invalid host!';
|
||||
|
||||
const options = {
|
||||
uri: remoteLocation,
|
||||
encoding: null,
|
||||
headers: {
|
||||
'User-Agent': 'BetterDiscordClient',
|
||||
'Accept': 'application/octet-stream'
|
||||
}
|
||||
};
|
||||
|
||||
const response = await request.get(options);
|
||||
const outputPath = path.join(Globals.getPath('tmp'), Security.hash('sha256', response, 'hex'));
|
||||
fs.writeFileSync(outputPath, response);
|
||||
console.log('response', response);
|
||||
console.log('output', outputPath);
|
||||
|
||||
await this.dragAndDropHandler(outputPath);
|
||||
rimraf(outputPath, err => {
|
||||
if (err) console.log(err);
|
||||
});
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
static async handleDrop(stateNode, e, original) {
|
||||
if (!e.dataTransfer.files.length || !e.dataTransfer.files[0].name.endsWith('.bd')) return original && original.call(stateNode, e);
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
if (stateNode) stateNode.clearDragging();
|
||||
|
||||
const currentChannel = DiscordApi.currentChannel;
|
||||
const canUpload = currentChannel ?
|
||||
currentChannel.checkPermissions(Reflection.modules.DiscordConstants.Permissions.SEND_MESSAGES) &&
|
||||
currentChannel.checkPermissions(Reflection.modules.DiscordConstants.Permissions.ATTACH_FILES) : false;
|
||||
|
||||
const files = Array.from(e.dataTransfer.files).slice(0);
|
||||
const actionCode = await this.dragAndDropHandler(e.dataTransfer.files[0].path, canUpload);
|
||||
|
||||
if (actionCode === 0 && stateNode) stateNode.promptToUpload(files, currentChannel.id, true, !e.shiftKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Patches Discord upload area for .bd files
|
||||
*/
|
||||
static async uploadAreaPatch(UploadArea) {
|
||||
// Add a listener to root for when not in a channel
|
||||
const root = DOM.getElement('#app-mount');
|
||||
const rootHandleDrop = this.handleDrop.bind(this, undefined);
|
||||
root.addEventListener('drop', rootHandleDrop);
|
||||
|
||||
const unpatchUploadAreaHandleDrop = MonkeyPatch('BD:ReactComponents', UploadArea.component.prototype).instead('handleDrop', (component, [e], original) => this.handleDrop(component, e, original));
|
||||
|
||||
this.unpatchUploadArea = () => {
|
||||
unpatchUploadAreaHandleDrop();
|
||||
root.removeEventListener('drop', rootHandleDrop);
|
||||
this.unpatchUploadArea = undefined;
|
||||
};
|
||||
|
||||
for (const element of document.querySelectorAll(UploadArea.important.selector)) {
|
||||
const stateNode = Reflection.DOM(element).getComponentStateNode(UploadArea);
|
||||
|
||||
element.removeEventListener('drop', stateNode.handleDrop);
|
||||
stateNode.handleDrop = UploadArea.component.prototype.handleDrop.bind(stateNode);
|
||||
element.addEventListener('drop', stateNode.handleDrop);
|
||||
|
||||
stateNode.forceUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -8,38 +8,70 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { WebpackModules } from './webpackmodules';
|
||||
import { ClientLogger as Logger, Utils } from 'common';
|
||||
import Reflection from './reflection/index';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
|
||||
/**
|
||||
* Function with no arguments and no return value that may be called to revert changes made by {@link Patcher}, restoring (unpatching) original method.
|
||||
* @callback Patcher~unpatch
|
||||
*/
|
||||
|
||||
/**
|
||||
* A callback that modifies method logic. This callback is called on each call of the original method and is provided all data about original call. Any of the data can be modified if necessary, but do so wisely.
|
||||
*
|
||||
* The third argument for the callback will be `undefined` for `before` patches. `originalFunction` for `instead` patches and `returnValue` for `after` patches.
|
||||
*
|
||||
* @callback Patcher~patchCallback
|
||||
* @param {object} thisObject - `this` in the context of the original function.
|
||||
* @param {arguments} arguments - The original arguments of the original function.
|
||||
* @param {(function|*)} extraValue - For `instead` patches, this is the original function from the module. For `after` patches, this is the return value of the function.
|
||||
* @return {*} Makes sense only when using an `instead` or `after` patch. If something other than `undefined` is returned, the returned value replaces the value of `returnValue`. If used for `before` the return value is ignored.
|
||||
*/
|
||||
|
||||
export class Patcher {
|
||||
static get patches() { return this._patches || (this._patches = {}) }
|
||||
|
||||
static get patches() { return this._patches || (this._patches = []) }
|
||||
|
||||
/**
|
||||
* Returns all the patches done by a specific caller
|
||||
* @param {string} id - Name of the patch caller
|
||||
* @method
|
||||
*/
|
||||
static getPatchesByCaller(id) {
|
||||
if (!id) return [];
|
||||
const patches = [];
|
||||
for (const patch in this.patches) {
|
||||
if (this.patches.hasOwnProperty(patch)) {
|
||||
if (this.patches[patch].caller === id) patches.push(this.patches[patch]);
|
||||
for (const patch of this.patches) {
|
||||
for (const childPatch of patch.children) {
|
||||
if (childPatch.caller === id) patches.push(childPatch);
|
||||
}
|
||||
}
|
||||
return patches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unpatches all patches passed, or when a string is passed unpatches all
|
||||
* patches done by that specific caller.
|
||||
* @param {Array|string} patches - Either an array of patches to unpatch or a caller name
|
||||
*/
|
||||
static unpatchAll(patches) {
|
||||
if (typeof patches === 'string')
|
||||
patches = this.getPatchesByCaller(patches);
|
||||
|
||||
for (const patch of patches) {
|
||||
for (const child of patch.children) {
|
||||
child.unpatch();
|
||||
}
|
||||
patch.unpatch();
|
||||
}
|
||||
}
|
||||
|
||||
static resolveModule(module) {
|
||||
if (module instanceof Function || (module instanceof Object && !(module instanceof Array))) return module;
|
||||
if ('string' === typeof module) return WebpackModules.getModuleByName(module);
|
||||
if (module instanceof Array) return WebpackModules.getModuleByProps(module);
|
||||
if (module instanceof Function || (module instanceof Object)) return module;
|
||||
if (typeof module === 'string') return Reflection.module.byName(module);
|
||||
return null;
|
||||
}
|
||||
|
||||
static overrideFn(patch) {
|
||||
return function () {
|
||||
let retVal = null;
|
||||
if (!patch.children) return patch.originalFunction.apply(this, arguments);
|
||||
let retVal = undefined;
|
||||
if (!patch.children || !patch.children.length) return patch.originalFunction.apply(this, arguments);
|
||||
for (const superPatch of patch.children.filter(c => c.type === 'before')) {
|
||||
try {
|
||||
superPatch.callback(this, arguments);
|
||||
|
@ -54,7 +86,8 @@ export class Patcher {
|
|||
} else {
|
||||
for (const insteadPatch of insteads) {
|
||||
try {
|
||||
retVal = insteadPatch.callback(this, arguments);
|
||||
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
|
||||
if (typeof tempReturn !== 'undefined') retVal = tempReturn;
|
||||
} catch (err) {
|
||||
Logger.err(`Patcher:${patch.id}`, err);
|
||||
}
|
||||
|
@ -63,7 +96,8 @@ export class Patcher {
|
|||
|
||||
for (const slavePatch of patch.children.filter(c => c.type === 'after')) {
|
||||
try {
|
||||
slavePatch.callback(this, arguments, retVal);
|
||||
const tempReturn = slavePatch.callback(this, arguments, retVal, r => retVal = r);
|
||||
if (typeof tempReturn !== 'undefined') retVal = tempReturn;
|
||||
} catch (err) {
|
||||
Logger.err(`Patcher:${patch.id}`, err);
|
||||
}
|
||||
|
@ -73,7 +107,9 @@ export class Patcher {
|
|||
}
|
||||
|
||||
static rePatch(patch) {
|
||||
patch.proxyFunction = patch.module[patch.functionName] = this.overrideFn(patch);
|
||||
if (patch.module instanceof Array && typeof patch.functionName === 'number')
|
||||
patch.module.splice(patch.functionName, 1, patch.proxyFunction = this.overrideFn(patch));
|
||||
else patch.proxyFunction = patch.module[patch.functionName] = this.overrideFn(patch);
|
||||
}
|
||||
|
||||
static pushPatch(caller, id, module, functionName) {
|
||||
|
@ -87,25 +123,75 @@ export class Patcher {
|
|||
revert: () => { // Calling revert will destroy any patches added to the same module after this
|
||||
patch.module[patch.functionName] = patch.originalFunction;
|
||||
patch.proxyFunction = null;
|
||||
patch.slaves = patch.supers = [];
|
||||
patch.children = [];
|
||||
},
|
||||
counter: 0,
|
||||
children: []
|
||||
};
|
||||
patch.proxyFunction = module[functionName] = this.overrideFn(patch);
|
||||
return this.patches[id] = patch;
|
||||
return this.patches.push(patch), patch;
|
||||
}
|
||||
|
||||
static before() { return this.pushChildPatch(...arguments, 'before') }
|
||||
static after() { return this.pushChildPatch(...arguments, 'after') }
|
||||
static instead() { return this.pushChildPatch(...arguments, 'instead') }
|
||||
/**
|
||||
* This method patches onto another function, allowing your code to run beforehand.
|
||||
* Using this, you are also able to modify the incoming arguments before the original method is run.
|
||||
*
|
||||
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link Patcher#unpatchAll}.
|
||||
* @param {object} unresolvedModule - Object with the function to be patched. Can also patch an object's prototype.
|
||||
* @param {string} functionName - Name of the method to be patched
|
||||
* @param {Patcher~patchCallback} callback - Function to run before the original method
|
||||
* @param {string} [displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
|
||||
* @return {Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
|
||||
*/
|
||||
static before(caller, unresolvedModule, functionName, callback, displayName) { return this.pushChildPatch(caller, unresolvedModule, functionName, callback, displayName, 'before') }
|
||||
|
||||
/**
|
||||
* This method patches onto another function, allowing your code to run afterwards.
|
||||
* Using this, you are also able to modify the return value, using the return of your code instead.
|
||||
*
|
||||
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link Patcher#unpatchAll}.
|
||||
* @param {object} unresolvedModule - Object with the function to be patched. Can also patch an object's prototype.
|
||||
* @param {string} functionName - Name of the method to be patched
|
||||
* @param {Patcher~patchCallback} callback - Function to run after the original method
|
||||
* @param {string} [displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
|
||||
* @return {Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
|
||||
*/
|
||||
static after(caller, unresolvedModule, functionName, callback, displayName) { return this.pushChildPatch(caller, unresolvedModule, functionName, callback, displayName, 'after') }
|
||||
|
||||
/**
|
||||
* This method patches onto another function, allowing your code to run instead, preventing the running of the original code.
|
||||
* Using this, you are also able to modify the return value, using the return of your code instead.
|
||||
*
|
||||
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link Patcher#unpatchAll}.
|
||||
* @param {object} unresolvedModule - Object with the function to be patched. Can also patch an object's prototype.
|
||||
* @param {string} functionName - Name of the method to be patched
|
||||
* @param {Patcher~patchCallback} callback - Function to run instead of the original method
|
||||
* @param {string} [displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
|
||||
* @return {Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
|
||||
*/
|
||||
static instead(caller, unresolvedModule, functionName, callback, displayName) { return this.pushChildPatch(caller, unresolvedModule, functionName, callback, displayName, 'instead') }
|
||||
|
||||
/**
|
||||
* This method patches onto another function, allowing your code to run before, instead or after the original function.
|
||||
* Using this you are able to modify the incoming arguments before the original function is run as well as the return
|
||||
* value before the original function actually returns.
|
||||
*
|
||||
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link Patcher#unpatchAll}.
|
||||
* @param {object} unresolvedModule - Object with the function to be patched. Can also patch an object's prototype.
|
||||
* @param {string} functionName - Name of the method to be patched
|
||||
* @param {Patcher~patchCallback} callback - Function to run after the original method
|
||||
* @param {string} [displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
|
||||
* @param {string} [type=after] - Determines whether to run the function `before`, `instead`, or `after` the original.
|
||||
* @return {Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
|
||||
*/
|
||||
static pushChildPatch(caller, unresolvedModule, functionName, callback, displayName, type = 'after') {
|
||||
const module = this.resolveModule(unresolvedModule);
|
||||
if (!module || !module[functionName] || !(module[functionName] instanceof Function)) return null;
|
||||
displayName = 'string' === typeof unresolvedModule ? unresolvedModule : displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
|
||||
displayName = typeof unresolvedModule === 'string' ? unresolvedModule :
|
||||
displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
|
||||
const patchId = `${displayName}:${functionName}:${caller}`;
|
||||
|
||||
const patch = this.patches[patchId] || this.pushPatch(caller, patchId, module, functionName);
|
||||
const patch = this.patches.find(p => p.module == module && p.functionName == functionName) || this.pushPatch(caller, patchId, module, functionName);
|
||||
if (!patch.proxyFunction) this.rePatch(patch);
|
||||
const child = {
|
||||
caller,
|
||||
|
@ -114,7 +200,11 @@ export class Patcher {
|
|||
callback,
|
||||
unpatch: () => {
|
||||
patch.children.splice(patch.children.findIndex(cpatch => cpatch.id === child.id && cpatch.type === type), 1);
|
||||
if (patch.children.length <= 0) delete this.patches[patchId];
|
||||
if (patch.children.length <= 0) {
|
||||
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
|
||||
this.patches[patchNum].revert();
|
||||
this.patches.splice(patchNum, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
patch.children.push(child);
|
||||
|
|
|
@ -15,15 +15,15 @@ export default class Plugin extends Content {
|
|||
|
||||
get type() { return 'plugin' }
|
||||
|
||||
// Don't use - these will eventually be removed!
|
||||
get pluginPath() { return this.contentPath }
|
||||
get pluginConfig() { return this.config }
|
||||
|
||||
get start() { return this.enable }
|
||||
get stop() { return this.disable }
|
||||
|
||||
unload() {
|
||||
PluginManager.unloadPlugin(this);
|
||||
reload(force) {
|
||||
return PluginManager.reloadPlugin(this, force);
|
||||
}
|
||||
|
||||
unload(force) {
|
||||
return PluginManager.unloadPlugin(this, force);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* BetterDiscord Plugin Api
|
||||
* BetterDiscord Plugin API
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
|
@ -8,43 +8,43 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Utils, ClientLogger as Logger, ClientIPC } from 'common';
|
||||
import { EmoteModule } from 'builtin';
|
||||
import { SettingsSet, SettingsCategory, Setting, SettingsScheme } from 'structs';
|
||||
import { BdMenu, Modals, DOM, DOMObserver, VueInjector, Toasts, Notifications, BdContextMenu, DiscordContextMenu } from 'ui';
|
||||
import * as CommonComponents from 'commoncomponents';
|
||||
import { default as Components } from '../ui/components/generic';
|
||||
import { Utils, Filters, ClientLogger as Logger, ClientIPC, AsyncEventEmitter } from 'common';
|
||||
import Settings from './settings';
|
||||
import ExtModuleManager from './extmodulemanager';
|
||||
import PluginManager from './pluginmanager';
|
||||
import ThemeManager from './thememanager';
|
||||
import Events from './events';
|
||||
import EventsWrapper from './eventswrapper';
|
||||
import { WebpackModules } from './webpackmodules';
|
||||
import { SettingsSet, SettingsCategory, Setting, SettingsScheme } from 'structs';
|
||||
import { BdMenuItems, Modals, DOM, Reflection } from 'ui';
|
||||
import Reflection from './reflection/index';
|
||||
import DiscordApi from './discordapi';
|
||||
import { ReactComponents } from './reactcomponents';
|
||||
import { MonkeyPatch } from './patcher';
|
||||
import { ReactComponents, ReactHelpers } from './reactcomponents';
|
||||
import { Patcher, MonkeyPatch } from './patcher';
|
||||
import GlobalAc from '../ui/autocomplete';
|
||||
import Vue from 'vue';
|
||||
import path from 'path';
|
||||
import Globals from './globals';
|
||||
|
||||
export default class PluginApi {
|
||||
|
||||
constructor(pluginInfo) {
|
||||
constructor(pluginInfo, pluginPath) {
|
||||
this.pluginInfo = pluginInfo;
|
||||
this.pluginPath = pluginPath;
|
||||
|
||||
this.Events = new EventsWrapper(Events);
|
||||
Utils.defineSoftGetter(this.Events, 'bind', () => this.plugin);
|
||||
|
||||
this._menuItems = undefined;
|
||||
this._injectedStyles = undefined;
|
||||
this._modalStack = undefined;
|
||||
}
|
||||
get Discord() {
|
||||
return DiscordApi;
|
||||
}
|
||||
get ReactComponents() {
|
||||
return ReactComponents;
|
||||
}
|
||||
get Reflection() {
|
||||
return Reflection;
|
||||
}
|
||||
get MonkeyPatch() {
|
||||
return module => MonkeyPatch(this.pluginInfo.id, module);
|
||||
}
|
||||
|
||||
get plugin() {
|
||||
return PluginManager.getPluginById(this.pluginInfo.id || this.pluginInfo.name.toLowerCase().replace(/[^a-zA-Z0-9-]/g, '-').replace(/--/g, '-'));
|
||||
return PluginManager.getPluginByPath(this.pluginPath);
|
||||
}
|
||||
|
||||
async bridge(plugin_id) {
|
||||
|
@ -61,22 +61,37 @@ export default class PluginApi {
|
|||
|
||||
get Api() { return this }
|
||||
|
||||
get AsyncEventEmitter() { return AsyncEventEmitter }
|
||||
get EventsWrapper() { return EventsWrapper }
|
||||
|
||||
get CommonComponents() { return CommonComponents }
|
||||
get Components() { return Components }
|
||||
get Filters() { return Filters }
|
||||
get Discord() { return DiscordApi }
|
||||
get DiscordApi() { return DiscordApi }
|
||||
get ReactComponents() { return ReactComponents }
|
||||
get ReactHelpers() { return ReactHelpers }
|
||||
get Reflection() { return Reflection }
|
||||
get DOM() { return DOM }
|
||||
get VueInjector() { return VueInjector }
|
||||
|
||||
get observer() {
|
||||
return this._observer || (this._observer = new DOMObserver());
|
||||
}
|
||||
|
||||
/**
|
||||
* Logger
|
||||
*/
|
||||
|
||||
loggerLog(...message) { Logger.log(this.pluginInfo.name, message) }
|
||||
loggerErr(...message) { Logger.err(this.pluginInfo.name, message) }
|
||||
loggerWarn(...message) { Logger.warn(this.pluginInfo.name, message) }
|
||||
loggerInfo(...message) { Logger.info(this.pluginInfo.name, message) }
|
||||
loggerDbg(...message) { Logger.dbg(this.pluginInfo.name, message) }
|
||||
get Logger() {
|
||||
return {
|
||||
log: this.loggerLog.bind(this),
|
||||
err: this.loggerErr.bind(this),
|
||||
warn: this.loggerWarn.bind(this),
|
||||
info: this.loggerInfo.bind(this),
|
||||
dbg: this.loggerDbg.bind(this)
|
||||
log: (...message) => Logger.log(this.plugin.name, message),
|
||||
error: (...message) => Logger.err(this.plugin.name, message),
|
||||
err: (...message) => Logger.err(this.plugin.name, message),
|
||||
warn: (...message) => Logger.warn(this.plugin.name, message),
|
||||
info: (...message) => Logger.info(this.plugin.name, message),
|
||||
debug: (...message) => Logger.dbg(this.plugin.name, message),
|
||||
dbg: (...message) => Logger.dbg(this.plugin.name, message)
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -86,15 +101,18 @@ export default class PluginApi {
|
|||
|
||||
get Utils() {
|
||||
return {
|
||||
overload: () => Utils.overload.apply(Utils, arguments),
|
||||
monkeyPatch: () => Utils.monkeyPatch.apply(Utils, arguments),
|
||||
monkeyPatchOnce: () => Utils.monkeyPatchOnce.apply(Utils, arguments),
|
||||
compatibleMonkeyPatch: () => Utils.monkeyPatchOnce.apply(Utils, arguments),
|
||||
tryParseJson: () => Utils.tryParseJson.apply(Utils, arguments),
|
||||
toCamelCase: () => Utils.toCamelCase.apply(Utils, arguments),
|
||||
compare: () => Utils.compare.apply(Utils, arguments),
|
||||
deepclone: () => Utils.deepclone.apply(Utils, arguments),
|
||||
deepfreeze: () => Utils.deepfreeze.apply(Utils, arguments)
|
||||
overload: (...args) => Utils.overload.apply(Utils, args),
|
||||
tryParseJson: (...args) => Utils.tryParseJson.apply(Utils, args),
|
||||
toCamelCase: (...args) => Utils.toCamelCase.apply(Utils, args),
|
||||
compare: (...args) => Utils.compare.apply(Utils, args),
|
||||
deepclone: (...args) => Utils.deepclone.apply(Utils, args),
|
||||
deepfreeze: (...args) => Utils.deepfreeze.apply(Utils, args),
|
||||
removeFromArray: (...args) => Utils.removeFromArray.apply(Utils, args),
|
||||
defineSoftGetter: (...args) => Utils.defineSoftGetter.apply(Utils, args),
|
||||
wait: (...args) => Utils.wait.apply(Utils, args),
|
||||
until: (...args) => Utils.until.apply(Utils, args),
|
||||
findInTree: (...args) => Utils.findInTree.apply(Utils, args),
|
||||
findInReactTree: (...args) => Utils.findInReactTree.apply(Utils, args)
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -142,6 +160,9 @@ export default class PluginApi {
|
|||
|
||||
get BdMenu() {
|
||||
return {
|
||||
open: BdMenu.open.bind(BdMenu),
|
||||
close: BdMenu.close.bind(BdMenu),
|
||||
items: this.BdMenuItems,
|
||||
BdMenuItems: this.BdMenuItems
|
||||
};
|
||||
}
|
||||
|
@ -154,23 +175,23 @@ export default class PluginApi {
|
|||
return this._menuItems || (this._menuItems = []);
|
||||
}
|
||||
addMenuItem(item) {
|
||||
return BdMenuItems.add(item);
|
||||
return BdMenu.items.add(item);
|
||||
}
|
||||
addMenuSettingsSet(category, set, text) {
|
||||
const item = BdMenuItems.addSettingsSet(category, set, text);
|
||||
const item = BdMenu.items.addSettingsSet(category, set, text);
|
||||
return this.menuItems.push(item);
|
||||
}
|
||||
addMenuVueComponent(category, text, component) {
|
||||
const item = BdMenuItems.addVueComponent(category, text, component);
|
||||
const item = BdMenu.items.addVueComponent(category, text, component);
|
||||
return this.menuItems.push(item);
|
||||
}
|
||||
removeMenuItem(item) {
|
||||
BdMenuItems.remove(item);
|
||||
BdMenu.items.remove(item);
|
||||
Utils.removeFromArray(this.menuItems, item);
|
||||
}
|
||||
removeAllMenuItems() {
|
||||
for (let item of this.menuItems)
|
||||
BdMenuItems.remove(item);
|
||||
for (const item of this.menuItems)
|
||||
BdMenu.items.remove(item);
|
||||
}
|
||||
get BdMenuItems() {
|
||||
return Object.defineProperty({
|
||||
|
@ -184,6 +205,25 @@ export default class PluginApi {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* BdContextMenu
|
||||
*/
|
||||
|
||||
showContextMenu(event, groups) {
|
||||
BdContextMenu.show(event, groups);
|
||||
this.activeMenu.menu = BdContextMenu.activeMenu.menu;
|
||||
}
|
||||
get activeMenu() {
|
||||
return this._activeMenu || (this._activeMenu = { menu: null });
|
||||
}
|
||||
get BdContextMenu() {
|
||||
return Object.defineProperty({
|
||||
show: this.showContextMenu.bind(this)
|
||||
}, 'activeMenu', {
|
||||
get: () => this.activeMenu
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* CssUtils
|
||||
*/
|
||||
|
@ -218,8 +258,8 @@ export default class PluginApi {
|
|||
this.injectedStyles.splice(this.injectedStyles.indexOf(styleid), 1);
|
||||
DOM.deleteStyle(styleid);
|
||||
}
|
||||
deleteAllStyles(id, css) {
|
||||
for (let id of this.injectedStyles) {
|
||||
deleteAllStyles(id) {
|
||||
for (const id of this.injectedStyles) {
|
||||
this.deleteStyle(id);
|
||||
}
|
||||
}
|
||||
|
@ -242,16 +282,9 @@ export default class PluginApi {
|
|||
get modalStack() {
|
||||
return this._modalStack || (this._modalStack = []);
|
||||
}
|
||||
get baseModalComponent() {
|
||||
return Modals.baseComponent;
|
||||
}
|
||||
addModal(_modal, component) {
|
||||
const modal = Modals.add(_modal, component);
|
||||
modal.on('close', () => {
|
||||
let index;
|
||||
while ((index = this.modalStack.findIndex(m => m === modal)) > -1)
|
||||
this.modalStack.splice(index, 1);
|
||||
});
|
||||
modal.on('close', () => Utils.removeFromArray(this.modalStack, modal));
|
||||
this.modalStack.push(modal);
|
||||
return modal;
|
||||
}
|
||||
|
@ -260,7 +293,7 @@ export default class PluginApi {
|
|||
}
|
||||
closeAllModals(force) {
|
||||
const promises = [];
|
||||
for (let modal of this.modalStack)
|
||||
for (const modal of this.modalStack)
|
||||
promises.push(modal.close(force));
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
@ -269,10 +302,10 @@ export default class PluginApi {
|
|||
return this.modalStack[this.modalStack.length - 1].close(force);
|
||||
}
|
||||
basicModal(title, text) {
|
||||
return this.addModal(Modals.basic(title, text));
|
||||
return this.addModal(Modals.createBasicModal(title, text));
|
||||
}
|
||||
settingsModal(settingsset, headertext, options) {
|
||||
return this.addModal(Modals.settings(settingsset, headertext, options));
|
||||
return this.addModal(Modals.createSettingsModal(settingsset, headertext, options));
|
||||
}
|
||||
get Modals() {
|
||||
return Object.defineProperties({
|
||||
|
@ -287,7 +320,177 @@ export default class PluginApi {
|
|||
get: () => this.modalStack
|
||||
},
|
||||
baseComponent: {
|
||||
get: () => this.baseModalComponent
|
||||
get: () => Modals.baseComponent
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Toasts
|
||||
*/
|
||||
|
||||
showToast(message, options = {}) {
|
||||
return Toasts.push(message, options);
|
||||
}
|
||||
showSuccessToast(message, options = {}) {
|
||||
return Toasts.success(message, options);
|
||||
}
|
||||
showInfoToast(message, options = {}) {
|
||||
return Toasts.info(message, options);
|
||||
}
|
||||
showErrorToast(message, options = {}) {
|
||||
return Toasts.error(message, options);
|
||||
}
|
||||
showWarningToast(message, options = {}) {
|
||||
return Toasts.warning(message, options);
|
||||
}
|
||||
get Toasts() {
|
||||
return {
|
||||
push: this.showToast.bind(this),
|
||||
success: this.showSuccessToast.bind(this),
|
||||
error: this.showErrorToast.bind(this),
|
||||
info: this.showInfoToast.bind(this),
|
||||
warning: this.showWarningToast.bind(this),
|
||||
get enabled() { return Toasts.enabled }
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifications
|
||||
*/
|
||||
|
||||
get notificationStack() {
|
||||
return this._notificationStack || (this._notificationStack = []);
|
||||
}
|
||||
addNotification(title, text, buttons = []) {
|
||||
if (arguments.length <= 1) text = title, title = undefined;
|
||||
if (arguments[1] instanceof Array) [text, buttons] = arguments, title = undefined;
|
||||
|
||||
const notification = Notifications.add(title, text, buttons, () => Utils.removeFromArray(this.notificationStack, notification));
|
||||
this.notificationStack.push(notification);
|
||||
return notification;
|
||||
}
|
||||
dismissNotification(index) {
|
||||
index = Notifications.stack.indexOf(this.notificationStack[index]);
|
||||
if (index) Notifications.dismiss(index);
|
||||
}
|
||||
dismissAllNotifications() {
|
||||
for (const index in this.notificationStack) {
|
||||
this.dismissNotification(index);
|
||||
}
|
||||
}
|
||||
get Notifications() {
|
||||
return Object.defineProperty({
|
||||
add: this.addNotification.bind(this),
|
||||
dismiss: this.dismissNotification.bind(this),
|
||||
dismissAll: this.dismissAllNotifications.bind(this)
|
||||
}, 'stack', {
|
||||
get: () => this.notificationStack
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Autocomplete
|
||||
*/
|
||||
|
||||
get autocompleteSets() {
|
||||
return this._autocompleteSets || (this._autocompleteSets = new Map());
|
||||
}
|
||||
addAutocompleteController(prefix, controller) {
|
||||
if (!controller) controller = this.plugin;
|
||||
if (GlobalAc.validPrefix(prefix)) return;
|
||||
GlobalAc.add(prefix, controller);
|
||||
this.autocompleteSets.set(prefix, controller);
|
||||
}
|
||||
removeAutocompleteController(prefix) {
|
||||
if (this.autocompleteSets.get(prefix) !== GlobalAc.sets.get(prefix)) return;
|
||||
GlobalAc.remove(prefix);
|
||||
this.autocompleteSets.delete(prefix);
|
||||
}
|
||||
removeAllAutocompleteControllers() {
|
||||
for (const [prefix] of this.autocompleteSets) {
|
||||
this.removeAutocompleteController(prefix);
|
||||
}
|
||||
}
|
||||
validAutocompletePrefix(prefix) {
|
||||
return GlobalAc.validPrefix(prefix);
|
||||
}
|
||||
toggleAutocompleteMode(prefix, sterm) {
|
||||
return GlobalAc.toggle(prefix, sterm);
|
||||
}
|
||||
searchAutocomplete(prefix, sterm) {
|
||||
return GlobalAc.items(prefix, sterm);
|
||||
}
|
||||
get Autocomplete() {
|
||||
return Object.defineProperty({
|
||||
add: this.addAutocompleteController.bind(this),
|
||||
remove: this.removeAutocompleteController.bind(this),
|
||||
removeAll: this.removeAllAutocompleteControllers.bind(this),
|
||||
validPrefix: this.validAutocompletePrefix.bind(this),
|
||||
toggle: this.toggleAutocompleteMode.bind(this),
|
||||
search: this.searchAutocomplete.bind(this)
|
||||
}, 'sets', {
|
||||
get: () => this.autocompleteSets
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Emotes
|
||||
*/
|
||||
|
||||
get emotes() {
|
||||
return EmoteModule.database;
|
||||
}
|
||||
get favouriteEmotes() {
|
||||
return EmoteModule.favourites;
|
||||
}
|
||||
get mostUsedEmotes() {
|
||||
return EmoteModule.mostUsed;
|
||||
}
|
||||
setFavouriteEmote(emote, favourite) {
|
||||
return EmoteModule[favourite ? 'removeFavourite' : 'addFavourite'](emote);
|
||||
}
|
||||
addFavouriteEmote(emote) {
|
||||
return EmoteModule.addFavourite(emote);
|
||||
}
|
||||
removeFavouriteEmote(emote) {
|
||||
return EmoteModule.removeFavourite(emote);
|
||||
}
|
||||
isFavouriteEmote(emote) {
|
||||
return EmoteModule.isFavourite(emote);
|
||||
}
|
||||
getEmote(emote) {
|
||||
return EmoteModule.findByName(emote, true);
|
||||
}
|
||||
getEmoteUseCount(emote) {
|
||||
const mostUsed = EmoteModule.mostUsed.find(mu => mu.key === emote.name);
|
||||
return mostUsed ? mostUsed.useCount : 0;
|
||||
}
|
||||
incrementEmoteUseCount(emote) {
|
||||
return EmoteModule.addToMostUsed(emote);
|
||||
}
|
||||
searchEmotes(regex, limit) {
|
||||
return EmoteModule.search(regex, limit);
|
||||
}
|
||||
get Emotes() {
|
||||
return Object.defineProperties({
|
||||
setFavourite: this.setFavouriteEmote.bind(this),
|
||||
addFavourite: this.addFavouriteEmote.bind(this),
|
||||
removeFavourite: this.removeFavouriteEmote.bind(this),
|
||||
isFavourite: this.isFavouriteEmote.bind(this),
|
||||
getEmote: this.getEmote.bind(this),
|
||||
getUseCount: this.getEmoteUseCount.bind(this),
|
||||
incrementUseCount: this.incrementEmoteUseCount.bind(this),
|
||||
search: this.searchEmotes.bind(this)
|
||||
}, {
|
||||
emotes: {
|
||||
get: () => this.emotes
|
||||
},
|
||||
favourites: {
|
||||
get: () => this.favouriteEmotes
|
||||
},
|
||||
mostused: {
|
||||
get: () => this.mostUsedEmotes
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -298,7 +501,7 @@ export default class PluginApi {
|
|||
|
||||
async getPlugin(plugin_id) {
|
||||
// This should require extra permissions
|
||||
return await PluginManager.waitForPlugin(plugin_id);
|
||||
return PluginManager.waitForPlugin(plugin_id);
|
||||
}
|
||||
listPlugins() {
|
||||
return PluginManager.localContent.map(plugin => plugin.id);
|
||||
|
@ -316,7 +519,7 @@ export default class PluginApi {
|
|||
|
||||
async getTheme(theme_id) {
|
||||
// This should require extra permissions
|
||||
return await ThemeManager.waitForContent(theme_id);
|
||||
return ThemeManager.waitForContent(theme_id);
|
||||
}
|
||||
listThemes() {
|
||||
return ThemeManager.localContent.map(theme => theme.id);
|
||||
|
@ -334,7 +537,7 @@ export default class PluginApi {
|
|||
|
||||
async getModule(module_id) {
|
||||
// This should require extra permissions
|
||||
return await ExtModuleManager.waitForContent(module_id);
|
||||
return ExtModuleManager.waitForContent(module_id);
|
||||
}
|
||||
listModules() {
|
||||
return ExtModuleManager.localContent.map(module => module.id);
|
||||
|
@ -347,39 +550,71 @@ export default class PluginApi {
|
|||
}
|
||||
|
||||
/**
|
||||
* WebpackModules
|
||||
* Patcher
|
||||
*/
|
||||
|
||||
get webpackRequire() {
|
||||
return WebpackModules.require;
|
||||
get patches() {
|
||||
return Patcher.getPatchesByCaller(this.plugin.id);
|
||||
}
|
||||
getWebpackModule(filter, first = true) {
|
||||
return WebpackModules.getModule(filter, first);
|
||||
patchBefore(...args) { return this.pushChildPatch(...args, 'before') }
|
||||
patchAfter(...args) { return this.pushChildPatch(...args, 'after') }
|
||||
patchInstead(...args) { return this.pushChildPatch(...args, 'instead') }
|
||||
pushChildPatch(...args) {
|
||||
return Patcher.pushChildPatch(this.plugin.id, ...args);
|
||||
}
|
||||
getWebpackModuleByName(name, fallback) {
|
||||
return WebpackModules.getModuleByName(name, fallback);
|
||||
unpatchAll(patches) {
|
||||
return Patcher.unpatchAll(patches || this.plugin.id);
|
||||
}
|
||||
getWebpackModuleByRegex(regex, first = true) {
|
||||
return WebpackModules.getModuleByRegex(regex, first);
|
||||
}
|
||||
getWebpackModuleByProperties(props, first = true) {
|
||||
return WebpackModules.getModuleByProps(props, first);
|
||||
}
|
||||
getWebpackModuleByPrototypeFields(props, first = true) {
|
||||
return WebpackModules.getModuleByPrototypes(props, first);
|
||||
}
|
||||
get WebpackModules() {
|
||||
get Patcher() {
|
||||
return Object.defineProperty({
|
||||
getModule: this.getWebpackModule.bind(this),
|
||||
getModuleByName: this.getWebpackModuleByName.bind(this),
|
||||
getModuleByDisplayName: this.getWebpackModuleByName.bind(this),
|
||||
getModuleByRegex: this.getWebpackModuleByRegex.bind(this),
|
||||
getModuleByProperties: this.getWebpackModuleByProperties.bind(this),
|
||||
getModuleByPrototypeFields: this.getWebpackModuleByPrototypeFields.bind(this)
|
||||
}, 'require', {
|
||||
get: () => this.webpackRequire
|
||||
before: this.patchBefore.bind(this),
|
||||
after: this.patchAfter.bind(this),
|
||||
instead: this.patchInstead.bind(this),
|
||||
pushChildPatch: this.pushChildPatch.bind(this),
|
||||
unpatchAll: this.unpatchAll.bind(this),
|
||||
monkeyPatch: this.monkeyPatch.bind(this)
|
||||
}, 'patches', {
|
||||
get: () => this.patches
|
||||
});
|
||||
}
|
||||
get monkeyPatch() {
|
||||
return m => MonkeyPatch(this.plugin.id, m);
|
||||
}
|
||||
|
||||
/**
|
||||
* DiscordContextMenu
|
||||
*/
|
||||
|
||||
get discordContextMenus() {
|
||||
return this._discordContextMenus || (this._discordContextMenus = []);
|
||||
}
|
||||
addDiscordContextMenu(items, filter) {
|
||||
const menu = DiscordContextMenu.add(items, filter);
|
||||
this.discordContextMenus.push(menu);
|
||||
return menu;
|
||||
}
|
||||
removeDiscordContextMenu(menu) {
|
||||
DiscordContextMenu.remove(menu);
|
||||
Utils.removeFromArray(this.discordContextMenus, menu);
|
||||
}
|
||||
removeAllDiscordContextMenus() {
|
||||
for (const menu of this.discordContextMenus) {
|
||||
this.removeDiscordContextMenu(menu);
|
||||
}
|
||||
}
|
||||
get DiscordContextMenu() {
|
||||
return Object.defineProperty({
|
||||
add: this.addDiscordContextMenu.bind(this),
|
||||
remove: this.removeDiscordContextMenu.bind(this),
|
||||
removeAll: this.removeAllDiscordContextMenus.bind(this)
|
||||
}, 'menus', {
|
||||
get: () => this.discordContextMenus
|
||||
});
|
||||
}
|
||||
|
||||
Vuewrap(id, component, props) {
|
||||
return VueInjector.createReactElement(Vue.component(id, component), props);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -8,15 +8,16 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Permissions } from 'modules';
|
||||
import { Modals } from 'ui';
|
||||
import { ErrorEvent } from 'structs';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import Globals from './globals';
|
||||
import ContentManager from './contentmanager';
|
||||
import ExtModuleManager from './extmodulemanager';
|
||||
import Plugin from './plugin';
|
||||
import PluginApi from './pluginapi';
|
||||
import Vendor from './vendor';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import { Events, Permissions } from 'modules';
|
||||
import { Modals } from 'ui';
|
||||
import { ErrorEvent } from 'structs';
|
||||
|
||||
export default class extends ContentManager {
|
||||
|
||||
|
@ -40,7 +41,7 @@ export default class extends ContentManager {
|
|||
this.loaded = false;
|
||||
const loadAll = await this.loadAllContent(true);
|
||||
this.loaded = true;
|
||||
for (let plugin of this.localPlugins) {
|
||||
for (const plugin of this.localPlugins) {
|
||||
if (!plugin.enabled) continue;
|
||||
plugin.userConfig.enabled = false;
|
||||
|
||||
|
@ -73,42 +74,42 @@ export default class extends ContentManager {
|
|||
static get refreshPlugins() { return this.refreshContent }
|
||||
|
||||
static get loadContent() { return this.loadPlugin }
|
||||
static async loadPlugin(paths, configs, info, main, dependencies, permissions) {
|
||||
static async loadPlugin(paths, configs, info, main, dependencies, permissions, mainExport, packed = false) {
|
||||
if (permissions && permissions.length > 0) {
|
||||
for (let perm of permissions) {
|
||||
console.log(`Permission: ${Permissions.permissionText(perm).HEADER} - ${Permissions.permissionText(perm).BODY}`);
|
||||
for (const perm of permissions) {
|
||||
Logger.log(this.moduleName, `Permission: ${Permissions.permissionText(perm).HEADER} - ${Permissions.permissionText(perm).BODY}`);
|
||||
}
|
||||
try {
|
||||
const allowed = await Modals.permissions(`${info.name} wants to:`, info.name, permissions).promise;
|
||||
} catch (err) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const deps = [];
|
||||
const deps = {};
|
||||
if (dependencies) {
|
||||
for (const [key, value] of Object.entries(dependencies)) {
|
||||
const extModule = ExtModuleManager.findModule(key);
|
||||
if (!extModule) {
|
||||
throw {
|
||||
'message': `Dependency: ${key}:${value} is not loaded`
|
||||
};
|
||||
throw {message: `Dependency ${key}:${value} is not loaded.`};
|
||||
}
|
||||
deps[key] = extModule.__require;
|
||||
}
|
||||
}
|
||||
|
||||
const plugin = window.require(paths.mainPath)(Plugin, new PluginApi(info), Vendor, deps);
|
||||
if (!(plugin.prototype instanceof Plugin))
|
||||
const pluginExports = Globals.require(paths.mainPath);
|
||||
|
||||
const pluginFunction = mainExport ? pluginExports[mainExport]
|
||||
: pluginExports.__esModule ? pluginExports.default : pluginExports;
|
||||
if (typeof pluginFunction !== 'function')
|
||||
throw {message: `Plugin ${info.name} did not export a function.`};
|
||||
|
||||
const plugin = pluginFunction.call(pluginExports, Plugin, new PluginApi(info, paths.contentPath), Vendor, deps);
|
||||
if (!plugin || !(plugin.prototype instanceof Plugin))
|
||||
throw {message: `Plugin ${info.name} did not return a class that extends Plugin.`};
|
||||
|
||||
const instance = new plugin({
|
||||
configs, info, main,
|
||||
paths: {
|
||||
contentPath: paths.contentPath,
|
||||
dirName: paths.dirName,
|
||||
mainPath: paths.mainPath
|
||||
}
|
||||
configs, info, main, paths
|
||||
});
|
||||
|
||||
if (instance.enabled && this.loaded) {
|
||||
|
@ -118,27 +119,38 @@ export default class extends ContentManager {
|
|||
return instance;
|
||||
}
|
||||
|
||||
static get deletePlugin() { return this.deleteContent }
|
||||
static get unloadPlugin() { return this.unloadContent }
|
||||
static get reloadPlugin() { return this.reloadContent }
|
||||
|
||||
static stopPlugin(name) {
|
||||
const plugin = name instanceof Plugin ? name : this.getPluginByName(name);
|
||||
try {
|
||||
if (plugin) return plugin.stop();
|
||||
} catch (err) {
|
||||
// Logger.err('PluginManager', err);
|
||||
static unloadContentHook(content, reload) {
|
||||
delete Globals.require.cache[Globals.require.resolve(content.paths.mainPath)];
|
||||
const uncache = [];
|
||||
for (const required in Globals.require.cache) {
|
||||
if (!required.includes(content.paths.contentPath)) continue;
|
||||
uncache.push(Globals.require.resolve(required));
|
||||
}
|
||||
return true; //Return true anyways since plugin doesn't exist
|
||||
for (const u of uncache) delete Globals.require.cache[u];
|
||||
}
|
||||
|
||||
static startPlugin(name) {
|
||||
const plugin = name instanceof Plugin ? name : this.getPluginByName(name);
|
||||
try {
|
||||
if (plugin) return plugin.start();
|
||||
} catch (err) {
|
||||
// Logger.err('PluginManager', err);
|
||||
/**
|
||||
* Stops a plugin.
|
||||
* @param {Plugin|String} plugin
|
||||
* @return {Promise}
|
||||
*/
|
||||
static stopPlugin(plugin) {
|
||||
plugin = this.isPlugin(plugin) ? plugin : this.getPluginById(plugin);
|
||||
return plugin.stop();
|
||||
}
|
||||
return true; //Return true anyways since plugin doesn't exist
|
||||
|
||||
/**
|
||||
* Starts a plugin.
|
||||
* @param {Plugin|String} plugin
|
||||
* @return {Promise}
|
||||
*/
|
||||
static startPlugin(plugin) {
|
||||
plugin = this.isPlugin(plugin) ? plugin : this.getPluginById(plugin);
|
||||
return plugin.start();
|
||||
}
|
||||
|
||||
static get isPlugin() { return this.isThisContent }
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
/**
|
||||
* BetterDiscord React Component Manipulations
|
||||
* original concept and some code by samogot - https://github.com/samogot / https://github.com/samogot/betterdiscord-plugins/tree/master/v2/1Lib%20Discord%20Internals
|
||||
* Original concept and some code by samogot - https://github.com/samogot / https://github.com/samogot/betterdiscord-plugins/tree/master/v2/1Lib%20Discord%20Internals
|
||||
*
|
||||
* Copyright (c) 2015-present JsSucks - https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://github.com/JsSucks - https://betterdiscord.net
|
||||
|
@ -9,16 +10,18 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { MonkeyPatch, Patcher } from './patcher';
|
||||
import { WebpackModules, Filters } from './webpackmodules';
|
||||
import { DOM, Modals } from 'ui';
|
||||
import { Utils, Filters, ClientLogger as Logger } from 'common';
|
||||
import { MonkeyPatch } from './patcher';
|
||||
import Reflection from './reflection/index';
|
||||
import DiscordApi from './discordapi';
|
||||
import { EmoteModule } from 'builtin';
|
||||
import { Reflection } from 'ui';
|
||||
import PackageInstaller from './packageinstaller';
|
||||
|
||||
class Helpers {
|
||||
static get plannedActions() {
|
||||
return this._plannedActions || (this._plannedActions = new Map());
|
||||
}
|
||||
|
||||
static recursiveArray(parent, key, count = 1) {
|
||||
let index = 0;
|
||||
function* innerCall(parent, key) {
|
||||
|
@ -34,6 +37,7 @@ class Helpers {
|
|||
|
||||
return innerCall(parent, key);
|
||||
}
|
||||
|
||||
static recursiveArrayCount(parent, key) {
|
||||
let count = 0;
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
|
@ -41,23 +45,26 @@ class Helpers {
|
|||
++count;
|
||||
return this.recursiveArray(parent, key, count);
|
||||
}
|
||||
|
||||
static get recursiveChildren() {
|
||||
return function* (parent, key, index = 0, count = 1) {
|
||||
const item = parent[key];
|
||||
yield { item, parent, key, index, count };
|
||||
if (item && item.props && item.props.children) {
|
||||
for (let { parent, key, index, count } of this.recursiveArrayCount(item.props, 'children')) {
|
||||
for (const { parent, key, index, count } of this.recursiveArrayCount(item.props, 'children')) {
|
||||
yield* this.recursiveChildren(parent, key, index, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static returnFirst(iterator, process) {
|
||||
for (let child of iterator) {
|
||||
for (const child of iterator) {
|
||||
const retVal = process(child);
|
||||
if (retVal !== undefined) return retVal;
|
||||
}
|
||||
}
|
||||
|
||||
static getFirstChild(rootParent, rootKey, selector) {
|
||||
const getDirectChild = (item, selector) => {
|
||||
if (item && item.props && item.props.children) {
|
||||
|
@ -105,26 +112,27 @@ class Helpers {
|
|||
if (match) {
|
||||
if (selector.child) {
|
||||
return getDirectChild(item, selector.child);
|
||||
}
|
||||
else if (selector.successor) {
|
||||
} else if (selector.successor) {
|
||||
return this.getFirstChild(parent, key, selector.successor);
|
||||
}
|
||||
else {
|
||||
|
||||
return { item, parent, key };
|
||||
}
|
||||
}
|
||||
};
|
||||
return this.returnFirst(this.recursiveChildren(rootParent, rootKey), checkFilter.bind(null, selector)) || {};
|
||||
}
|
||||
|
||||
static parseSelector(selector) {
|
||||
if (selector.startsWith('.')) return { className: selector.substr(1) }
|
||||
if (selector.startsWith('#')) return { id: selector.substr(1) }
|
||||
return {}
|
||||
}
|
||||
|
||||
static findByProp(obj, what, value) {
|
||||
if (obj.hasOwnProperty(what) && obj[what] === value) return obj;
|
||||
if (obj.props && !obj.children) return this.findByProp(obj.props, what, value);
|
||||
if (!obj.children || !obj.children.length) return null;
|
||||
if (!obj.children) return null;
|
||||
if (!(obj.children instanceof Array)) return this.findByProp(obj.children, what, value);
|
||||
for (const child of obj.children) {
|
||||
if (!child) continue;
|
||||
const findInChild = this.findByProp(child, what, value);
|
||||
|
@ -132,6 +140,7 @@ class Helpers {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static findProp(obj, what) {
|
||||
if (obj.hasOwnProperty(what)) return obj[what];
|
||||
if (obj.props && !obj.children) return this.findProp(obj.props, what);
|
||||
|
@ -144,25 +153,40 @@ class Helpers {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static get React() {
|
||||
return Reflection.modules.React;
|
||||
}
|
||||
|
||||
static get ReactDOM() {
|
||||
return WebpackModules.getModuleByName('ReactDOM');
|
||||
return Reflection.modules.ReactDOM;
|
||||
}
|
||||
}
|
||||
|
||||
export { Helpers as ReactHelpers };
|
||||
|
||||
class ReactComponent {
|
||||
constructor(id, component, retVal) {
|
||||
this._id = id;
|
||||
this._component = component;
|
||||
this._retVal = retVal;
|
||||
constructor(id, component, retVal, important) {
|
||||
this.id = id;
|
||||
this.component = component;
|
||||
this.retVal = retVal;
|
||||
this.important = important;
|
||||
}
|
||||
get id() {
|
||||
return this._id;
|
||||
|
||||
get elements() {
|
||||
if (!this.important || !this.important.selector) return [];
|
||||
|
||||
return document.querySelectorAll(this.important.selector);
|
||||
}
|
||||
get component() {
|
||||
return this._component;
|
||||
|
||||
get stateNodes() {
|
||||
return [...this.elements].map(e => Reflection.DOM(e).getComponentStateNode(this));
|
||||
}
|
||||
|
||||
forceUpdateAll() {
|
||||
for (const e of this.elements) {
|
||||
Reflection.DOM(e).forceUpdate(this);
|
||||
}
|
||||
get retVal() {
|
||||
return this._retVal;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -171,61 +195,119 @@ export class ReactComponents {
|
|||
static get unknownComponents() { return this._unknownComponents || (this._unknownComponents = []) }
|
||||
static get listeners() { return this._listeners || (this._listeners = []) }
|
||||
static get nameSetters() { return this._nameSetters || (this._nameSetters = []) }
|
||||
static get componentAliases() { return this._componentAliases || (this._componentAliases = []) }
|
||||
|
||||
static push(component, retVal) {
|
||||
static get ReactComponent() { return ReactComponent }
|
||||
|
||||
static push(component, retVal, important) {
|
||||
if (!(component instanceof Function)) return null;
|
||||
const { displayName } = component;
|
||||
if (!displayName) {
|
||||
return this.processUnknown(component, retVal);
|
||||
}
|
||||
|
||||
const have = this.components.find(comp => comp.id === displayName);
|
||||
if (have) return component;
|
||||
const c = new ReactComponent(displayName, component, retVal);
|
||||
this.components.push(c);
|
||||
const listener = this.listeners.find(listener => listener.id === displayName);
|
||||
if (!listener) return c;
|
||||
for (const l of listener.listeners) {
|
||||
l(c);
|
||||
if (have) {
|
||||
if (!have.important) have.important = important;
|
||||
return component;
|
||||
}
|
||||
this.listeners.splice(this.listeners.findIndex(listener => listener.id === displayName), 1);
|
||||
|
||||
const c = new ReactComponent(displayName, component, retVal, important);
|
||||
this.components.push(c);
|
||||
|
||||
const listener = this.listeners.find(listener => listener.id === displayName);
|
||||
if (listener) {
|
||||
for (const l of listener.listeners) l(c);
|
||||
Utils.removeFromArray(this.listeners, listener);
|
||||
}
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
static async getComponent(name, important) {
|
||||
/**
|
||||
* Finds a component from the components array or by waiting for it to be mounted.
|
||||
* @param {String} name The component's name
|
||||
* @param {Object} important An object containing a selector to look for
|
||||
* @param {Function} filter A function to filter components if a single element is rendered by multiple components
|
||||
* @return {Promise => ReactComponent}
|
||||
*/
|
||||
static async getComponent(name, important, filter) {
|
||||
name = this.getComponentName(name);
|
||||
|
||||
const have = this.components.find(c => c.id === name);
|
||||
if (have) return have;
|
||||
|
||||
if (important) {
|
||||
const importantInterval = setInterval(() => {
|
||||
const callback = () => {
|
||||
if (this.components.find(c => c.id === name)) {
|
||||
console.info(`Important component ${name} already found`);
|
||||
clearInterval(importantInterval);
|
||||
Logger.info('ReactComponents', `Important component ${name} already found`);
|
||||
DOM.observer.unsubscribe(observerSubscription);
|
||||
return;
|
||||
}
|
||||
const select = document.querySelector(important.selector);
|
||||
if (!select) return;
|
||||
const reflect = Reflection(select);
|
||||
if (!reflect.component) {
|
||||
clearInterval(importantInterval);
|
||||
console.error(`FAILED TO GET IMPORTANT COMPONENT ${name} WITH REFLECTION FROM`, select);
|
||||
|
||||
const elements = document.querySelectorAll(important.selector);
|
||||
if (!elements.length) return;
|
||||
|
||||
let component, reflect;
|
||||
for (const element of elements) {
|
||||
reflect = Reflection.DOM(element);
|
||||
component = filter ? reflect.components.find(component => {
|
||||
try {
|
||||
return filter.call(undefined, component);
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}) : reflect.component;
|
||||
if (component) break;
|
||||
}
|
||||
|
||||
if (!component && filter) {
|
||||
Logger.log('ReactComponents', ['Found elements matching the query selector but no components passed the filter']);
|
||||
return;
|
||||
}
|
||||
if (!reflect.component.displayName) reflect.component.displayName = name;
|
||||
console.info(`Found important component ${name} with reflection.`);
|
||||
this.push(reflect.component);
|
||||
clearInterval(importantInterval);
|
||||
}, 50);
|
||||
|
||||
DOM.observer.unsubscribe(observerSubscription);
|
||||
|
||||
if (!component) {
|
||||
Logger.err('ReactComponents', [`FAILED TO GET IMPORTANT COMPONENT ${name} WITH REFLECTION FROM`, elements]);
|
||||
return;
|
||||
}
|
||||
const listener = this.listeners.find(l => l.id === name);
|
||||
if (!listener) this.listeners.push({
|
||||
|
||||
if (!component.displayName) component.displayName = name;
|
||||
Logger.info('ReactComponents', [`Found important component ${name} with reflection`, reflect]);
|
||||
important.filter = filter;
|
||||
this.push(component, undefined, important);
|
||||
};
|
||||
|
||||
const observerSubscription = DOM.observer.subscribeToQuerySelector(callback, important.selector, null, true);
|
||||
setTimeout(callback, 0);
|
||||
}
|
||||
|
||||
let listener = this.listeners.find(l => l.id === name);
|
||||
if (!listener) this.listeners.push(listener = {
|
||||
id: name,
|
||||
listeners: []
|
||||
});
|
||||
|
||||
return new Promise(resolve => {
|
||||
this.listeners.find(l => l.id === name).listeners.push(c => resolve(c));
|
||||
listener.listeners.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
static setName(name, filter, callback) {
|
||||
static getComponentName(name) {
|
||||
const resolvedAliases = [];
|
||||
|
||||
while (this.componentAliases[name]) {
|
||||
resolvedAliases.push(name);
|
||||
name = this.componentAliases[name];
|
||||
|
||||
if (resolvedAliases.includes(name)) break;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
static setName(name, filter) {
|
||||
const have = this.components.find(c => c.id === name);
|
||||
if (have) return have;
|
||||
|
||||
|
@ -243,7 +325,7 @@ export class ReactComponents {
|
|||
const have = this.unknownComponents.find(c => c.component === component);
|
||||
for (const [fi, filter] of this.nameSetters.entries()) {
|
||||
if (filter.filter.filter(component)) {
|
||||
console.log('filter match!');
|
||||
Logger.log('ReactComponents', 'Filter match!');
|
||||
component.displayName = filter.name;
|
||||
this.nameSetters.splice(fi, 1);
|
||||
return this.push(component, retVal);
|
||||
|
@ -256,36 +338,34 @@ export class ReactComponents {
|
|||
}
|
||||
|
||||
export class ReactAutoPatcher {
|
||||
/**
|
||||
* Wait for React to be loaded and patch it's createElement to store all unknown components.
|
||||
* Also patches some known components.
|
||||
*/
|
||||
static async autoPatch() {
|
||||
await this.ensureReact();
|
||||
this.React = {};
|
||||
this.React.unpatchCreateElement = MonkeyPatch('BD:ReactComponents:createElement', 'React').before('createElement', (component, args) => {
|
||||
ReactComponents.push(args[0]);
|
||||
});
|
||||
const React = await Reflection.module.waitForModuleByName('React');
|
||||
|
||||
this.unpatchCreateElement = MonkeyPatch('BD:ReactComponents:createElement', React).before('createElement', (component, args) => ReactComponents.push(args[0]));
|
||||
|
||||
this.patchComponents();
|
||||
return 1;
|
||||
}
|
||||
|
||||
static async ensureReact() {
|
||||
while (!window.webpackJsonp || !WebpackModules.getModuleByName('React')) await new Promise(resolve => setTimeout(resolve, 10));
|
||||
return 1;
|
||||
}
|
||||
|
||||
static async patchComponents() {
|
||||
await this.patchMessage();
|
||||
await this.patchMessageGroup();
|
||||
await this.patchChannelMember();
|
||||
await this.patchGuild();
|
||||
await this.patchChannel();
|
||||
await this.patchChannelList();
|
||||
this.forceUpdate();
|
||||
/**
|
||||
* Patches a few known components.
|
||||
*/
|
||||
static patchComponents() {
|
||||
const componentPatchFunctions = Object.getOwnPropertyNames(this).filter(p => p.startsWith('patch') && p !== 'patchComponents');
|
||||
return Promise.all(componentPatchFunctions.map(p => this[p].call(this)));
|
||||
}
|
||||
|
||||
static async patchMessage() {
|
||||
this.Message = await ReactComponents.getComponent('Message', { selector: '.message' });
|
||||
const { selector } = Reflection.resolve('message', 'messageCozy', 'messageCompact');
|
||||
this.Message = await ReactComponents.getComponent('Message', {selector}, m => m.prototype && m.prototype.renderCozy);
|
||||
|
||||
this.unpatchMessageRender = MonkeyPatch('BD:ReactComponents', this.Message.component.prototype).after('render', (component, args, retVal) => {
|
||||
const { message } = component.props;
|
||||
const { message, jumpSequenceId, canFlash } = component.props;
|
||||
const { id, colorString, bot, author, attachments, embeds } = message;
|
||||
if (jumpSequenceId && canFlash) retVal = retVal.props.children;
|
||||
retVal.props['data-message-id'] = id;
|
||||
retVal.props['data-colourstring'] = colorString;
|
||||
if (author && author.id) retVal.props['data-user-id'] = author.id;
|
||||
|
@ -293,62 +373,214 @@ export class ReactAutoPatcher {
|
|||
if (attachments && attachments.length) retVal.props.className += ' bd-hasAttachments';
|
||||
if (embeds && embeds.length) retVal.props.className += ' bd-hasEmbeds';
|
||||
if (author && author.id === DiscordApi.currentUser.id) retVal.props.className += ' bd-isCurrentUser';
|
||||
|
||||
const dapiMessage = DiscordApi.Message.from(message);
|
||||
if (dapiMessage.guild && author.id === dapiMessage.guild.ownerId) retVal.props.className += ' bd-isGuildOwner';
|
||||
if (dapiMessage.guild && dapiMessage.guild.isMember(author.id)) retVal.props.className += ' bd-isGuildMember';
|
||||
});
|
||||
|
||||
this.Message.forceUpdateAll();
|
||||
}
|
||||
|
||||
static async patchMessageContent() {
|
||||
const { selector } = Reflection.resolve('container', 'containerCozy', 'containerCompact', 'edited');
|
||||
this.MessageContent = await ReactComponents.getComponent('MessageContent', {selector}, c => c.defaultProps && c.defaultProps.hasOwnProperty('disableButtons'));
|
||||
}
|
||||
|
||||
static async patchSpoiler() {
|
||||
const { selector } = Reflection.resolve('spoilerText', 'spoilerContainer');
|
||||
this.Spoiler = await ReactComponents.getComponent('Spoiler', {selector}, c => c.prototype.renderSpoilerText);
|
||||
}
|
||||
|
||||
static async patchMessageAccessories() {
|
||||
const { selector } = Reflection.resolve('container', 'containerCozy', 'embedWrapper');
|
||||
this.MessageAccessories = await ReactComponents.getComponent('MessageAccessories', {selector});
|
||||
}
|
||||
|
||||
static async patchMessageGroup() {
|
||||
this.MessageGroup = await ReactComponents.getComponent('MessageGroup', { selector: '.message-group' });
|
||||
const { selector } = Reflection.resolve('container', 'message', 'messageCozy');
|
||||
this.MessageGroup = await ReactComponents.getComponent('MessageGroup', {selector});
|
||||
|
||||
this.unpatchMessageGroupRender = MonkeyPatch('BD:ReactComponents', this.MessageGroup.component.prototype).after('render', (component, args, retVal) => {
|
||||
const { author, type } = component.props.messages[0];
|
||||
retVal.props['data-author-id'] = author.id;
|
||||
if (author.id === DiscordApi.currentUser.id) retVal.props.className += ' bd-isCurrentUser';
|
||||
if (type !== 0) retVal.props.className += ' bd-isSystemMessage';
|
||||
|
||||
const dapiMessage = DiscordApi.Message.from(component.props.messages[0]);
|
||||
if (dapiMessage.guild && author.id === dapiMessage.guild.ownerId) retVal.props.className += ' bd-isGuildOwner';
|
||||
if (dapiMessage.guild && dapiMessage.guild.isMember(author.id)) retVal.props.className += ' bd-isGuildMember';
|
||||
});
|
||||
|
||||
this.MessageGroup.forceUpdateAll();
|
||||
}
|
||||
|
||||
static async patchImageWrapper() {
|
||||
ReactComponents.componentAliases.ImageWrapper = 'Image';
|
||||
|
||||
const { selector } = Reflection.resolve('imageWrapper');
|
||||
this.ImageWrapper = await ReactComponents.getComponent('ImageWrapper', {selector}, c => typeof c.defaultProps.children === 'function');
|
||||
}
|
||||
|
||||
static async patchChannelMember() {
|
||||
this.ChannelMember = await ReactComponents.getComponent('ChannelMember', { selector: '.member.member-status' });
|
||||
ReactComponents.componentAliases.ChannelMember = 'MemberListItem';
|
||||
|
||||
const { selector } = Reflection.resolve('member', 'memberInner', 'activity');
|
||||
this.ChannelMember = await ReactComponents.getComponent('ChannelMember', {selector}, m => m.prototype.renderActivity);
|
||||
|
||||
this.unpatchChannelMemberRender = MonkeyPatch('BD:ReactComponents', this.ChannelMember.component.prototype).after('render', (component, args, retVal) => {
|
||||
if (!retVal.props || !retVal.props.children || !retVal.props.children.length) return;
|
||||
if (!retVal.props || !retVal.props.children) return;
|
||||
const user = Helpers.findProp(component, 'user');
|
||||
if (!user) return;
|
||||
retVal.props['data-user-id'] = user.id;
|
||||
retVal.props['data-colourstring'] = component.props.colorString;
|
||||
if (component.props.isOwner) retVal.props.className += ' bd-isGuildOwner';
|
||||
});
|
||||
|
||||
this.ChannelMember.forceUpdateAll();
|
||||
}
|
||||
|
||||
static async patchNameTag() {
|
||||
const { selector } = Reflection.resolve('nameTag', 'username', 'discriminator', 'ownerIcon');
|
||||
this.NameTag = await ReactComponents.getComponent('NameTag', {selector});
|
||||
}
|
||||
|
||||
static async patchGuild() {
|
||||
this.Guild = await ReactComponents.getComponent('Guild');
|
||||
const selector = `div.${Reflection.resolve('container', 'guildIcon', 'selected', 'unread').className}:not(:first-child)`;
|
||||
this.Guild = await ReactComponents.getComponent('Guild', {selector}, m => m.prototype.renderBadge);
|
||||
|
||||
this.unpatchGuild = MonkeyPatch('BD:ReactComponents', this.Guild.component.prototype).after('render', (component, args, retVal) => {
|
||||
const { guild } = component.props;
|
||||
if (!guild) return;
|
||||
retVal.props['data-guild-id'] = guild.id;
|
||||
retVal.props['data-guild-name'] = guild.name;
|
||||
});
|
||||
|
||||
this.Guild.forceUpdateAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* The Channel component contains the header, message scroller, message form and member list.
|
||||
*/
|
||||
static async patchChannel() {
|
||||
this.Channel = await ReactComponents.getComponent('Channel');
|
||||
const { selector } = Reflection.resolve('chat', 'title', 'channelName');
|
||||
this.Channel = await ReactComponents.getComponent('Channel', {selector});
|
||||
|
||||
this.unpatchChannel = MonkeyPatch('BD:ReactComponents', this.Channel.component.prototype).after('render', (component, args, retVal) => {
|
||||
const channel = component.props.channel || component.state.channel;
|
||||
if (!channel) return;
|
||||
retVal.props['data-channel-id'] = channel.id;
|
||||
retVal.props['data-channel-name'] = channel.name;
|
||||
if ([0, 2, 4].includes(channel.type)) retVal.props.className += ' bd-isGuildChannel';
|
||||
if ([1, 3].includes(channel.type)) retVal.props.className += ' bd-isPrivateChannel';
|
||||
if (channel.type === 3) retVal.props.className += ' bd-isGroupChannel';
|
||||
});
|
||||
|
||||
this.Channel.forceUpdateAll();
|
||||
}
|
||||
|
||||
static async patchChannelList() {
|
||||
this.GuildChannel = await ReactComponents.getComponent('GuildChannel', { selector: '.containerDefault-7RImuF' });
|
||||
this.unpatchGuildChannel = MonkeyPatch('BD:ReactComponents', this.GuildChannel.component.prototype).after('render', (component, args, retVal) => {
|
||||
static async patchChannelTextArea() {
|
||||
const { selector } = Reflection.resolve('channelTextArea', 'autocomplete');
|
||||
this.ChannelTextArea = await ReactComponents.getComponent('ChannelTextArea', {selector});
|
||||
}
|
||||
|
||||
/**
|
||||
* The GuildTextChannel component represents a text channel in the guild channel list.
|
||||
*/
|
||||
static async patchGuildTextChannel() {
|
||||
ReactComponents.componentAliases.GuildTextChannel = 'TextChannel';
|
||||
|
||||
const { selector } = Reflection.resolve('containerDefault', 'actionIcon');
|
||||
this.GuildTextChannel = await ReactComponents.getComponent('GuildTextChannel', {selector}, c => c.prototype.renderMentionBadge);
|
||||
|
||||
this.unpatchGuildTextChannel = MonkeyPatch('BD:ReactComponents', this.GuildTextChannel.component.prototype).after('render', this._afterChannelRender);
|
||||
|
||||
this.GuildTextChannel.forceUpdateAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* The GuildVoiceChannel component represents a voice channel in the guild channel list.
|
||||
*/
|
||||
static async patchGuildVoiceChannel() {
|
||||
ReactComponents.componentAliases.GuildVoiceChannel = 'VoiceChannel';
|
||||
|
||||
const { selector } = Reflection.resolve('containerDefault', 'actionIcon');
|
||||
this.GuildVoiceChannel = await ReactComponents.getComponent('GuildVoiceChannel', {selector}, c => c.prototype.handleVoiceConnect);
|
||||
|
||||
this.unpatchGuildVoiceChannel = MonkeyPatch('BD:ReactComponents', this.GuildVoiceChannel.component.prototype).after('render', this._afterChannelRender);
|
||||
|
||||
this.GuildVoiceChannel.forceUpdateAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* The DirectMessage component represents a channel in the direct messages list.
|
||||
*/
|
||||
static async patchDirectMessage() {
|
||||
ReactComponents.componentAliases.DirectMessage = 'PrivateChannel';
|
||||
|
||||
const { selector } = Reflection.resolve('channel', 'avatar', 'name');
|
||||
this.DirectMessage = await ReactComponents.getComponent('DirectMessage', {selector}, c => c.prototype.renderAvatar);
|
||||
|
||||
this.unpatchDirectMessage = MonkeyPatch('BD:ReactComponents', this.DirectMessage.component.prototype).after('render', this._afterChannelRender);
|
||||
|
||||
this.DirectMessage.forceUpdateAll();
|
||||
}
|
||||
|
||||
static _afterChannelRender(component, args, retVal) {
|
||||
const { channel } = component.props;
|
||||
if (!channel) return;
|
||||
|
||||
retVal.props['data-channel-id'] = channel.id;
|
||||
retVal.props['data-channel-name'] = channel.name;
|
||||
});
|
||||
if ([0, 2, 4].includes(channel.type)) retVal.props.className += ' bd-isGuildChannel';
|
||||
if (channel.type === 2) retVal.props.className += ' bd-isVoiceChannel';
|
||||
// if (channel.type === 4) retVal.props.className += ' bd-isChannelCategory';
|
||||
if ([1, 3].includes(channel.type)) retVal.props.className += ' bd-isPrivateChannel';
|
||||
if (channel.type === 3) retVal.props.className += ' bd-isGroupChannel';
|
||||
}
|
||||
|
||||
static forceUpdate() {
|
||||
for (const e of document.querySelectorAll('.message,.message-group,.guild,.containerDefault-7RImuF,.channel-members .member')) {
|
||||
Reflection(e).forceUpdate();
|
||||
}
|
||||
static async patchUserProfileModal() {
|
||||
ReactComponents.componentAliases.UserProfileModal = 'UserProfileBody';
|
||||
|
||||
const { selector } = Reflection.resolve('root', 'topSectionNormal');
|
||||
this.UserProfileModal = await ReactComponents.getComponent('UserProfileModal', {selector}, c => c.prototype.renderHeader && c.prototype.renderBadges);
|
||||
|
||||
this.unpatchUserProfileModal = MonkeyPatch('BD:ReactComponents', this.UserProfileModal.component.prototype).after('render', (component, args, retVal) => {
|
||||
const root = retVal.props.children[0] || retVal.props.children;
|
||||
const { user } = component.props;
|
||||
if (!user) return;
|
||||
root.props['data-user-id'] = user.id;
|
||||
if (user.bot) root.props.className += ' bd-isBot';
|
||||
if (user.id === DiscordApi.currentUser.id) root.props.className += ' bd-isCurrentUser';
|
||||
});
|
||||
|
||||
this.UserProfileModal.forceUpdateAll();
|
||||
}
|
||||
|
||||
static async patchUserPopout() {
|
||||
const { selector } = Reflection.resolve('userPopout', 'headerNormal');
|
||||
this.UserPopout = await ReactComponents.getComponent('UserPopout', {selector}, c => c.prototype.renderHeader);
|
||||
|
||||
this.unpatchUserPopout = MonkeyPatch('BD:ReactComponents', this.UserPopout.component.prototype).after('render', (component, args, retVal) => {
|
||||
const root = retVal.props.children[0] || retVal.props.children;
|
||||
const { user, guild, guildMember } = component.props;
|
||||
if (!user) return;
|
||||
root.props['data-user-id'] = user.id;
|
||||
if (user.bot) root.props.className += ' bd-isBot';
|
||||
if (user.id === DiscordApi.currentUser.id) root.props.className += ' bd-isCurrentUser';
|
||||
if (guild) root.props['data-guild-id'] = guild.id;
|
||||
if (guild && user.id === guild.ownerId) root.props.className += ' bd-isGuildOwner';
|
||||
if (guild && guildMember) root.props.className += ' bd-isGuildMember';
|
||||
if (guildMember && guildMember.roles.length) root.props.className += ' bd-hasRoles';
|
||||
});
|
||||
|
||||
this.UserPopout.forceUpdateAll();
|
||||
}
|
||||
|
||||
static async patchUploadArea() {
|
||||
const { selector } = Reflection.resolve('uploadArea');
|
||||
this.UploadArea = await ReactComponents.getComponent('UploadArea', {selector});
|
||||
|
||||
PackageInstaller.uploadAreaPatch(this.UploadArea);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
* BetterDiscord Reflection Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Module, Modules } from './modules';
|
||||
import { Reflection as DOM } from 'ui';
|
||||
import Resolver from './resolver';
|
||||
|
||||
export default class Reflection {
|
||||
|
||||
static get module() {
|
||||
return Module;
|
||||
}
|
||||
|
||||
static get modules() {
|
||||
return Modules;
|
||||
}
|
||||
|
||||
static get resolve() {
|
||||
return Resolver.resolve;
|
||||
}
|
||||
|
||||
static get resolveAsync() {
|
||||
return Resolver.resolveAsync;
|
||||
}
|
||||
|
||||
static get resolver() {
|
||||
return Resolver;
|
||||
}
|
||||
|
||||
static get DOM() {
|
||||
return DOM;
|
||||
}
|
||||
|
||||
static get require() {
|
||||
return Module.require;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,433 @@
|
|||
/**
|
||||
* BetterDiscord Reflection Modules
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Utils, Filters } from 'common';
|
||||
import Events from '../events';
|
||||
|
||||
const KnownModules = {
|
||||
React: Filters.byProperties(['createElement', 'cloneElement']),
|
||||
ReactDOM: Filters.byProperties(['render', 'findDOMNode']),
|
||||
|
||||
Events: Filters.byPrototypeFields(['setMaxListeners', 'emit']),
|
||||
|
||||
/* Guild Info, Stores, and Utilities */
|
||||
GuildStore: Filters.byProperties(['getGuild']),
|
||||
SortedGuildStore: Filters.byProperties(['getSortedGuilds']),
|
||||
SelectedGuildStore: Filters.byProperties(['getLastSelectedGuildId']),
|
||||
GuildSync: Filters.byProperties(['getSyncedGuilds']),
|
||||
GuildInfo: Filters.byProperties(['getAcronym']),
|
||||
GuildChannelsStore: Filters.byProperties(['getChannels', 'getDefaultChannel']),
|
||||
GuildMemberStore: Filters.byProperties(['getMember']),
|
||||
MemberCountStore: Filters.byProperties(['getMemberCounts']),
|
||||
GuildEmojiStore: Filters.byProperties(['getEmojis']),
|
||||
GuildActions: Filters.byProperties(['markGuildAsRead']),
|
||||
GuildPermissions: Filters.byProperties(['getGuildPermissions']),
|
||||
|
||||
/* Channel Store & Actions */
|
||||
ChannelStore: Filters.byProperties(['getChannels', 'getDMFromUserId']),
|
||||
SelectedChannelStore: Filters.byProperties(['getLastSelectedChannelId']),
|
||||
ChannelActions: Filters.byProperties(['selectChannel']),
|
||||
PrivateChannelActions: Filters.byProperties(['openPrivateChannel']),
|
||||
ChannelSelector: Filters.byProperties(['selectGuild', 'selectChannel']),
|
||||
VoiceChannelActions: Filters.byProperties(['selectVoiceChannel']),
|
||||
|
||||
/* Current User Info, State and Settings */
|
||||
UserInfoStore: Filters.byProperties(['getToken']),
|
||||
UserSettingsStore: Filters.byProperties(['guildPositions']),
|
||||
AccountManager: Filters.byProperties(['register', 'login']),
|
||||
UserSettingsUpdater: Filters.byProperties(['updateRemoteSettings']),
|
||||
OnlineWatcher: Filters.byProperties(['isOnline']),
|
||||
CurrentUserIdle: Filters.byProperties(['getIdleTime']),
|
||||
RelationshipStore: Filters.byProperties(['isBlocked', 'isFriend']),
|
||||
RelationshipManager: Filters.byProperties(['addRelationship']),
|
||||
MentionStore: Filters.byProperties(['getMentions']),
|
||||
|
||||
/* User Stores and Utils */
|
||||
UserStore: Filters.byProperties(['getCurrentUser']),
|
||||
UserStatusStore: Filters.byProperties(['getStatuses']),
|
||||
UserTypingStore: Filters.byProperties(['isTyping']),
|
||||
UserActivityStore: Filters.byProperties(['getActivity']),
|
||||
UserNameResolver: Filters.byProperties(['getName']),
|
||||
UserNoteStore: Filters.byProperties(['getNote']),
|
||||
UserNoteActions: Filters.byProperties(['updateNote']),
|
||||
DraftActions: Filters.byProperties(['changeDraft']),
|
||||
|
||||
/* Emoji Store and Utils */
|
||||
EmojiInfo: Filters.byProperties(['isEmojiDisabled']),
|
||||
EmojiUtils: Filters.byProperties(['getGuildEmoji']),
|
||||
EmojiStore: Filters.byProperties(['getByCategory', 'EMOJI_NAME_RE']),
|
||||
|
||||
/* Invite Store and Utils */
|
||||
InviteStore: Filters.byProperties(['getInvites']),
|
||||
InviteResolver: Filters.byProperties(['findInvite']),
|
||||
InviteActions: Filters.byProperties(['acceptInvite']),
|
||||
|
||||
/* Discord Objects & Utils */
|
||||
DiscordConstants: Filters.byProperties(['Permissions', 'ActivityTypes', 'StatusTypes']),
|
||||
Permissions: Filters.byProperties(['getHighestRole']),
|
||||
ColorConverter: Filters.byProperties(['hex2int']),
|
||||
ColorShader: Filters.byProperties(['darken']),
|
||||
TinyColor: Filters.byPrototypeFields(['toRgb']),
|
||||
ClassResolver: Filters.byProperties(['getClass']),
|
||||
ButtonData: Filters.byProperties(['ButtonSizes']),
|
||||
IconNames: Filters.byProperties(['IconNames']),
|
||||
NavigationUtils: Filters.byProperties(['transitionTo', 'replaceWith', 'getHistory']),
|
||||
|
||||
/* Discord Messages */
|
||||
MessageStore: Filters.byProperties(['getMessages']),
|
||||
MessageActions: Filters.byProperties(['jumpToMessage', '_sendMessage']),
|
||||
MessageQueue: Filters.byProperties(['enqueue']),
|
||||
MessageParser: Filters.byProperties(['createMessage', 'parse', 'unparse']),
|
||||
|
||||
/* In-Game Overlay */
|
||||
OverlayUserPopoutSettings: Filters.byProperties(['openUserPopout']),
|
||||
OverlayUserPopoutInfo: Filters.byProperties(['getOpenedUserPopout']),
|
||||
|
||||
/* Experiments */
|
||||
ExperimentStore: Filters.byProperties(['getExperimentOverrides']),
|
||||
ExperimentsManager: Filters.byProperties(['isDeveloper']),
|
||||
CurrentExperiment: Filters.byProperties(['getExperimentId']),
|
||||
|
||||
/* Images, Avatars and Utils */
|
||||
ImageResolver: Filters.byProperties(['getUserAvatarURL']),
|
||||
ImageUtils: Filters.byProperties(['getSizedImageSrc']),
|
||||
AvatarDefaults: Filters.byProperties(['getUserAvatarURL', 'DEFAULT_AVATARS']),
|
||||
|
||||
/* Drag & Drop */
|
||||
DNDActions: Filters.byProperties(['beginDrag']),
|
||||
DNDSources: Filters.byProperties(['addTarget']),
|
||||
DNDObjects: Filters.byProperties(['DragSource']),
|
||||
|
||||
/* Electron & Other Internals with Utils */
|
||||
ElectronModule: Filters.byProperties(['_getMainWindow']),
|
||||
Dispatcher: Filters.byProperties(['dirtyDispatch']),
|
||||
PathUtils: Filters.byProperties(['hasBasename']),
|
||||
NotificationModule: Filters.byProperties(['showNotification']),
|
||||
RouterModule: Filters.byProperties(['Router']),
|
||||
APIModule: Filters.byProperties(['getAPIBaseURL']),
|
||||
AnalyticEvents: Filters.byProperties(['AnalyticEventConfigs']),
|
||||
KeyGenerator: Filters.byCode(/"binary"/),
|
||||
Buffers: Filters.byProperties(['Buffer', 'kMaxLength']),
|
||||
DeviceStore: Filters.byProperties(['getDevices']),
|
||||
SoftwareInfo: Filters.byProperties(['os']),
|
||||
CurrentContext: Filters.byProperties(['setTagsContext']),
|
||||
|
||||
/* Media Stuff (Audio/Video) */
|
||||
MediaDeviceInfo: Filters.byProperties(['Codecs', 'SUPPORTED_BROWSERS']),
|
||||
MediaInfo: Filters.byProperties(['getOutputVolume']),
|
||||
MediaEngineInfo: Filters.byProperties(['MediaEngineFeatures']),
|
||||
VoiceInfo: Filters.byProperties(['EchoCancellation']),
|
||||
VideoStream: Filters.byProperties(['getVideoStream']),
|
||||
SoundModule: Filters.byProperties(['playSound']),
|
||||
|
||||
/* Window, DOM, HTML */
|
||||
WindowInfo: Filters.byProperties(['isFocused', 'windowSize']),
|
||||
TagInfo: Filters.byProperties(['VALID_TAG_NAMES']),
|
||||
DOMInfo: Filters.byProperties(['canUseDOM']),
|
||||
|
||||
/* Locale/Location and Time */
|
||||
LocaleManager: Filters.byProperties(['setLocale']),
|
||||
Moment: Filters.byProperties(['parseZone']),
|
||||
LocationManager: Filters.byProperties(['createLocation']),
|
||||
Timestamps: Filters.byProperties(['fromTimestamp']),
|
||||
TimeFormatter: Filters.byProperties(['dateFormat']),
|
||||
|
||||
/* Strings and Utils */
|
||||
Strings: Filters.byProperties(['TEXT', 'TEXTAREA_PLACEHOLDER']),
|
||||
StringFormats: Filters.byProperties(['a', 'z']),
|
||||
StringUtils: Filters.byProperties(['toASCII']),
|
||||
|
||||
/* URLs and Utils */
|
||||
URLParser: Filters.byProperties(['Url', 'parse']),
|
||||
ExtraURLs: Filters.byProperties(['getArticleURL']),
|
||||
|
||||
/* Text Processing */
|
||||
hljs: Filters.byProperties(['highlight', 'highlightBlock']),
|
||||
SimpleMarkdown: Filters.byProperties(['parseBlock', 'parseInline', 'defaultOutput']),
|
||||
|
||||
/* DOM/React Components */
|
||||
/* ==================== */
|
||||
LayerManager: Filters.byProperties(['popLayer', 'pushLayer']),
|
||||
UserSettingsWindow: Filters.byProperties(['open', 'updateAccount']),
|
||||
ChannelSettingsWindow: Filters.byProperties(['open', 'updateChannel']),
|
||||
GuildSettingsWindow: Filters.byProperties(['open', 'updateGuild']),
|
||||
|
||||
/* Modals */
|
||||
ModalStack: Filters.byProperties(['push', 'update', 'pop', 'popWithKey']),
|
||||
ConfirmModal: Filters.byPrototypeFields(['handleCancel', 'handleSubmit', 'handleMinorConfirm']),
|
||||
UserProfileModal: Filters.byProperties(['fetchMutualFriends', 'setSection']),
|
||||
ChangeNicknameModal: Filters.byProperties(['open', 'changeNickname']),
|
||||
CreateChannelModal: Filters.byProperties(['open', 'createChannel']),
|
||||
PruneMembersModal: Filters.byProperties(['open', 'prune']),
|
||||
NotificationSettingsModal: Filters.byProperties(['open', 'updateNotificationSettings']),
|
||||
PrivacySettingsModal: Filters.byCode(/PRIVACY_SETTINGS_MODAL_OPEN/, m => m.open),
|
||||
CreateInviteModal: Filters.byProperties(['open', 'createInvite']),
|
||||
|
||||
/* Popouts */
|
||||
PopoutStack: Filters.byProperties(['open', 'close', 'closeAll']),
|
||||
PopoutOpener: Filters.byProperties(['openPopout']),
|
||||
EmojiPicker: Filters.byPrototypeFields(['onHoverEmoji', 'selectEmoji']),
|
||||
|
||||
/* Context Menus */
|
||||
ContextMenuActions: Filters.byCode(/CONTEXT_MENU_CLOSE/, c => c.close),
|
||||
ContextMenuItemsGroup: Filters.byCode(/itemGroup/),
|
||||
ContextMenuItem: Filters.byCode(/\.label\b.*\.hint\b.*\.action\b/),
|
||||
|
||||
/* In-Message Links */
|
||||
ExternalLink: Filters.byCode(/\.trusted\b/)
|
||||
};
|
||||
|
||||
class Module {
|
||||
|
||||
/**
|
||||
* Finds a module using a filter function.
|
||||
* @param {Function} filter A function to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @param {Array} modules An array of modules to search in
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModule(filter, first = true, _modules) {
|
||||
const modules = _modules || this.getAllModules();
|
||||
const rm = [];
|
||||
for (const index in modules) {
|
||||
if (!modules.hasOwnProperty(index)) continue;
|
||||
const module = modules[index];
|
||||
const { exports } = module;
|
||||
let foundModule = null;
|
||||
|
||||
if (!exports) continue;
|
||||
if (exports.__esModule && exports.default && filter(exports.default)) foundModule = exports.default;
|
||||
if (filter(exports)) foundModule = exports;
|
||||
if (!foundModule) continue;
|
||||
if (first) return foundModule;
|
||||
rm.push(foundModule);
|
||||
}
|
||||
return first ? undefined : rm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's name.
|
||||
* @param {String} name The name of the module
|
||||
* @param {Function} fallback A function to use to filter modules if not finding a known module
|
||||
* @return {Any}
|
||||
*/
|
||||
static byName(name, fallback) {
|
||||
if (Cache.hasOwnProperty(name)) return Cache[name];
|
||||
if (KnownModules.hasOwnProperty(name)) fallback = KnownModules[name];
|
||||
if (!fallback) return undefined;
|
||||
const module = this.getModule(fallback, true);
|
||||
return module ? Cache[name] = module : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's display name.
|
||||
* @param {String} name The display name of the module
|
||||
* @return {Any}
|
||||
*/
|
||||
static byDisplayName(name) {
|
||||
return this.getModule(Filters.byDisplayName(name), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using it's code.
|
||||
* @param {RegEx} regex A regular expression to use to filter modules
|
||||
* @param {Boolean} first Whether to return the only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static byRegex(regex, first = true) {
|
||||
return this.getModule(Filters.byCode(regex), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first module using properties on it's prototype.
|
||||
* @param {any} props Properties to use to filter modules
|
||||
* @return {Any}
|
||||
*/
|
||||
static byPrototypes(...prototypes) {
|
||||
return this.getModule(Filters.byPrototypeFields(prototypes), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all modules using properties on it's prototype.
|
||||
* @param {any} props Properties to use to filter modules
|
||||
* @return {Any}
|
||||
*/
|
||||
static allByPrototypes(...prototypes) {
|
||||
return this.getModule(Filters.byPrototypeFields(prototypes), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first module using it's own properties.
|
||||
* @param {any} props Properties to use to filter modules
|
||||
* @return {Any}
|
||||
*/
|
||||
static byProps(...props) {
|
||||
return this.getModule(Filters.byProperties(props), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all modules using it's own properties.
|
||||
* @param {any} props Properties to use to filter modules
|
||||
* @return {Any}
|
||||
*/
|
||||
static allByProps(...props) {
|
||||
return this.getModule(Filters.byProperties(props), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Discord's __webpack_require__ function.
|
||||
*/
|
||||
static get require() {
|
||||
if (this._require) return this._require;
|
||||
|
||||
const __webpack_require__ = this.getWebpackRequire();
|
||||
if (!__webpack_require__) return null;
|
||||
|
||||
this.hookWebpackRequireCache(__webpack_require__);
|
||||
return this._require = __webpack_require__;
|
||||
}
|
||||
|
||||
static getWebpackRequire() {
|
||||
const id = 'bd-webpackmodules';
|
||||
|
||||
if (typeof window.webpackJsonp === 'function') {
|
||||
const __webpack_require__ = window['webpackJsonp']([], {
|
||||
[id]: (module, exports, __webpack_require__) => exports.default = __webpack_require__
|
||||
}, [id]).default;
|
||||
delete __webpack_require__.m[id];
|
||||
delete __webpack_require__.c[id];
|
||||
return __webpack_require__;
|
||||
} else if (window.webpackJsonp && window.webpackJsonp.push) {
|
||||
const __webpack_require__ = window['webpackJsonp'].push([[], {
|
||||
[id]: (module, exports, req) => exports.default = req
|
||||
}, [[id]]]).default;
|
||||
window['webpackJsonp'].pop();
|
||||
delete __webpack_require__.m[id];
|
||||
delete __webpack_require__.c[id];
|
||||
return __webpack_require__;
|
||||
}
|
||||
}
|
||||
|
||||
static hookWebpackRequireCache(__webpack_require__) {
|
||||
__webpack_require__.c = new Proxy(__webpack_require__.c, {
|
||||
set(module_cache, module_id, module) {
|
||||
// Add it to our emitter cache and emit a module-loading event
|
||||
this.moduleLoading(module_id, module);
|
||||
Events.emit('module-loading', module);
|
||||
|
||||
// Add the module to the cache as normal
|
||||
module_cache[module_id] = module;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static moduleLoading(module_id, module) {
|
||||
if (this.require.c[module_id]) return;
|
||||
|
||||
if (!this.moduleLoadedEventTimeout) {
|
||||
this.moduleLoadedEventTimeout = setTimeout(() => {
|
||||
this.moduleLoadedEventTimeout = undefined;
|
||||
|
||||
// Emit a module-loaded event for every module
|
||||
for (const module of this.modulesLoadingCache) {
|
||||
Events.emit('module-loaded', module);
|
||||
}
|
||||
|
||||
// Emit a modules-loaded event
|
||||
Events.emit('modules-loaded', this.modulesLoadingCache);
|
||||
|
||||
this.modulesLoadedCache = [];
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Add this to our own cache
|
||||
if (!this.modulesLoadingCache) this.modulesLoadingCache = [];
|
||||
this.modulesLoadingCache.push(module);
|
||||
}
|
||||
|
||||
static waitForWebpackRequire() {
|
||||
return Utils.until(() => this.require, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a module to load.
|
||||
* This only returns a single module, as it can't guarentee there are no more modules that could
|
||||
* match the filter, which is pretty much what that would be asking for.
|
||||
* @param {Function} filter The name of a known module or a filter function
|
||||
* @return {Any}
|
||||
*/
|
||||
static async waitForModule(filter) {
|
||||
const module = this.getModule(filter);
|
||||
if (module) return module;
|
||||
|
||||
while (this.require.m.length > this.require.c.length) {
|
||||
const additionalModules = await Events.once('modules-loaded');
|
||||
|
||||
const module = this.getModule(filter, true, additionalModules);
|
||||
if (module) return module;
|
||||
}
|
||||
|
||||
throw new Error('All modules have now been loaded. None match the passed filter.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's name.
|
||||
* @param {String} name The name of the module
|
||||
* @param {Function} fallback A function to use to filter modules if not finding a known module
|
||||
* @return {Any}
|
||||
*/
|
||||
static async waitForModuleByName(name, fallback) {
|
||||
if (Cache.hasOwnProperty(name)) return Cache[name];
|
||||
if (KnownModules.hasOwnProperty(name)) fallback = KnownModules[name];
|
||||
if (!fallback) return undefined;
|
||||
const module = await this.waitForModule(fallback, true);
|
||||
return module ? Cache[name] = module : undefined;
|
||||
}
|
||||
|
||||
static waitForModuleByDisplayName(props) {
|
||||
return this.waitForModule(Filters.byDisplayName(props));
|
||||
}
|
||||
static waitForModuleByRegex(props) {
|
||||
return this.waitForModule(Filters.byCode(props));
|
||||
}
|
||||
static waitForModuleByProps(props) {
|
||||
return this.waitForModule(Filters.byProperties(props));
|
||||
}
|
||||
static waitForModuleByPrototypes(props) {
|
||||
return this.waitForModule(Filters.byPrototypeFields(props));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all loaded modules.
|
||||
* @return {Array}
|
||||
*/
|
||||
static getAllModules() {
|
||||
return this.require.c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of known modules.
|
||||
* @return {Array}
|
||||
*/
|
||||
static listKnownModules() {
|
||||
return Object.keys(KnownModules);
|
||||
}
|
||||
|
||||
static get KnownModules() { return KnownModules }
|
||||
|
||||
}
|
||||
|
||||
const Modules = new Proxy(Module, {
|
||||
get(Module, name) {
|
||||
return Module.byName(name);
|
||||
}
|
||||
});
|
||||
|
||||
export { Module, Modules }
|
|
@ -0,0 +1,59 @@
|
|||
/**
|
||||
* BetterDiscord Reflection Resolver
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Module } from './modules';
|
||||
|
||||
class Resolved {
|
||||
|
||||
constructor(module, ...classes) {
|
||||
this.module = Module.byProps(...classes);
|
||||
this.classes = classes;
|
||||
}
|
||||
|
||||
get className() {
|
||||
return this.module && this.module[this.classes[0]] ? this.module[this.classes[0]].split(' ')[0] : this.classes[0];
|
||||
}
|
||||
|
||||
get selector() {
|
||||
return `.${this.className}`;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default class Resolver {
|
||||
|
||||
static resolve(...classes) {
|
||||
return new Resolved(Module.byProps(...classes), ...classes);
|
||||
}
|
||||
|
||||
static async resolveAsync(...classes) {
|
||||
const module = await Module.waitForModuleByProps([...classes]);
|
||||
return new Resolved(module, ...classes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for a class module and returns a class from it.
|
||||
* @param {String} base The first part of the class to find
|
||||
* @param {String} ...additional_classes Additional classes to look for to filter duplicate class modules
|
||||
* @return {String}
|
||||
*/
|
||||
static getClassName(base, ...additional_classes) {
|
||||
const class_module = Module.byProps([base, ...additional_classes]);
|
||||
if (class_module && class_module[base]) return class_module[base].split(' ')[0];
|
||||
}
|
||||
static async waitForClassName(base, ...additional_classes) {
|
||||
const class_module = await Module.waitForModuleByProps([base, ...additional_classes]);
|
||||
if (class_module && class_module[base]) return class_module[base].split(' ')[0];
|
||||
}
|
||||
static getSelector(base, ...additional_classes) {
|
||||
const gcn = this.getClassName(base, ...additional_classes);
|
||||
if (gcn) return `.${gcn}`;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,430 @@
|
|||
/**
|
||||
* BetterDiscord WebpackModules Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Utils, Filters } from 'common';
|
||||
import Events from '../events';
|
||||
|
||||
const KnownModules = {
|
||||
React: Filters.byProperties(['createElement', 'cloneElement']),
|
||||
ReactDOM: Filters.byProperties(['render', 'findDOMNode']),
|
||||
|
||||
Events: Filters.byPrototypeFields(['setMaxListeners', 'emit']),
|
||||
|
||||
/* Guild Info, Stores, and Utilities */
|
||||
GuildStore: Filters.byProperties(['getGuild']),
|
||||
SortedGuildStore: Filters.byProperties(['getSortedGuilds']),
|
||||
SelectedGuildStore: Filters.byProperties(['getLastSelectedGuildId']),
|
||||
GuildSync: Filters.byProperties(['getSyncedGuilds']),
|
||||
GuildInfo: Filters.byProperties(['getAcronym']),
|
||||
GuildChannelsStore: Filters.byProperties(['getChannels', 'getDefaultChannel']),
|
||||
GuildMemberStore: Filters.byProperties(['getMember']),
|
||||
MemberCountStore: Filters.byProperties(['getMemberCounts']),
|
||||
GuildEmojiStore: Filters.byProperties(['getEmojis']),
|
||||
GuildActions: Filters.byProperties(['markGuildAsRead']),
|
||||
GuildPermissions: Filters.byProperties(['getGuildPermissions']),
|
||||
|
||||
/* Channel Store & Actions */
|
||||
ChannelStore: Filters.byProperties(['getChannels', 'getDMFromUserId']),
|
||||
SelectedChannelStore: Filters.byProperties(['getLastSelectedChannelId']),
|
||||
ChannelActions: Filters.byProperties(['selectChannel']),
|
||||
PrivateChannelActions: Filters.byProperties(['openPrivateChannel']),
|
||||
ChannelSelector: Filters.byProperties(['selectGuild', 'selectChannel']),
|
||||
VoiceChannelActions: Filters.byProperties(['selectVoiceChannel']),
|
||||
|
||||
/* Current User Info, State and Settings */
|
||||
UserInfoStore: Filters.byProperties(['getToken']),
|
||||
UserSettingsStore: Filters.byProperties(['guildPositions']),
|
||||
AccountManager: Filters.byProperties(['register', 'login']),
|
||||
UserSettingsUpdater: Filters.byProperties(['updateRemoteSettings']),
|
||||
OnlineWatcher: Filters.byProperties(['isOnline']),
|
||||
CurrentUserIdle: Filters.byProperties(['getIdleTime']),
|
||||
RelationshipStore: Filters.byProperties(['isBlocked', 'isFriend']),
|
||||
RelationshipManager: Filters.byProperties(['addRelationship']),
|
||||
MentionStore: Filters.byProperties(['getMentions']),
|
||||
|
||||
/* User Stores and Utils */
|
||||
UserStore: Filters.byProperties(['getCurrentUser']),
|
||||
UserStatusStore: Filters.byProperties(['getStatuses']),
|
||||
UserTypingStore: Filters.byProperties(['isTyping']),
|
||||
UserActivityStore: Filters.byProperties(['getActivity']),
|
||||
UserNameResolver: Filters.byProperties(['getName']),
|
||||
UserNoteStore: Filters.byProperties(['getNote']),
|
||||
UserNoteActions: Filters.byProperties(['updateNote']),
|
||||
DraftActions: Filters.byProperties(['changeDraft']),
|
||||
|
||||
/* Emoji Store and Utils */
|
||||
EmojiInfo: Filters.byProperties(['isEmojiDisabled']),
|
||||
EmojiUtils: Filters.byProperties(['getGuildEmoji']),
|
||||
EmojiStore: Filters.byProperties(['getByCategory', 'EMOJI_NAME_RE']),
|
||||
|
||||
/* Invite Store and Utils */
|
||||
InviteStore: Filters.byProperties(['getInvites']),
|
||||
InviteResolver: Filters.byProperties(['findInvite']),
|
||||
InviteActions: Filters.byProperties(['acceptInvite']),
|
||||
|
||||
/* Discord Objects & Utils */
|
||||
DiscordConstants: Filters.byProperties(['Permissions', 'ActivityTypes', 'StatusTypes']),
|
||||
Permissions: Filters.byProperties(['getHighestRole']),
|
||||
ColorConverter: Filters.byProperties(['hex2int']),
|
||||
ColorShader: Filters.byProperties(['darken']),
|
||||
TinyColor: Filters.byPrototypeFields(['toRgb']),
|
||||
ClassResolver: Filters.byProperties(['getClass']),
|
||||
ButtonData: Filters.byProperties(['ButtonSizes']),
|
||||
IconNames: Filters.byProperties(['IconNames']),
|
||||
NavigationUtils: Filters.byProperties(['transitionTo', 'replaceWith', 'getHistory']),
|
||||
|
||||
/* Discord Messages */
|
||||
MessageStore: Filters.byProperties(['getMessages']),
|
||||
MessageActions: Filters.byProperties(['jumpToMessage', '_sendMessage']),
|
||||
MessageQueue: Filters.byProperties(['enqueue']),
|
||||
MessageParser: Filters.byProperties(['createMessage', 'parse', 'unparse']),
|
||||
|
||||
/* In-Game Overlay */
|
||||
OverlayUserPopoutSettings: Filters.byProperties(['openUserPopout']),
|
||||
OverlayUserPopoutInfo: Filters.byProperties(['getOpenedUserPopout']),
|
||||
|
||||
/* Experiments */
|
||||
ExperimentStore: Filters.byProperties(['getExperimentOverrides']),
|
||||
ExperimentsManager: Filters.byProperties(['isDeveloper']),
|
||||
CurrentExperiment: Filters.byProperties(['getExperimentId']),
|
||||
|
||||
/* Images, Avatars and Utils */
|
||||
ImageResolver: Filters.byProperties(['getUserAvatarURL']),
|
||||
ImageUtils: Filters.byProperties(['getSizedImageSrc']),
|
||||
AvatarDefaults: Filters.byProperties(['getUserAvatarURL', 'DEFAULT_AVATARS']),
|
||||
|
||||
/* Drag & Drop */
|
||||
DNDActions: Filters.byProperties(['beginDrag']),
|
||||
DNDSources: Filters.byProperties(['addTarget']),
|
||||
DNDObjects: Filters.byProperties(['DragSource']),
|
||||
|
||||
/* Electron & Other Internals with Utils */
|
||||
ElectronModule: Filters.byProperties(['_getMainWindow']),
|
||||
Dispatcher: Filters.byProperties(['dirtyDispatch']),
|
||||
PathUtils: Filters.byProperties(['hasBasename']),
|
||||
NotificationModule: Filters.byProperties(['showNotification']),
|
||||
RouterModule: Filters.byProperties(['Router']),
|
||||
APIModule: Filters.byProperties(['getAPIBaseURL']),
|
||||
AnalyticEvents: Filters.byProperties(['AnalyticEventConfigs']),
|
||||
KeyGenerator: Filters.byCode(/"binary"/),
|
||||
Buffers: Filters.byProperties(['Buffer', 'kMaxLength']),
|
||||
DeviceStore: Filters.byProperties(['getDevices']),
|
||||
SoftwareInfo: Filters.byProperties(['os']),
|
||||
CurrentContext: Filters.byProperties(['setTagsContext']),
|
||||
|
||||
/* Media Stuff (Audio/Video) */
|
||||
MediaDeviceInfo: Filters.byProperties(['Codecs', 'SUPPORTED_BROWSERS']),
|
||||
MediaInfo: Filters.byProperties(['getOutputVolume']),
|
||||
MediaEngineInfo: Filters.byProperties(['MediaEngineFeatures']),
|
||||
VoiceInfo: Filters.byProperties(['EchoCancellation']),
|
||||
VideoStream: Filters.byProperties(['getVideoStream']),
|
||||
SoundModule: Filters.byProperties(['playSound']),
|
||||
|
||||
/* Window, DOM, HTML */
|
||||
WindowInfo: Filters.byProperties(['isFocused', 'windowSize']),
|
||||
TagInfo: Filters.byProperties(['VALID_TAG_NAMES']),
|
||||
DOMInfo: Filters.byProperties(['canUseDOM']),
|
||||
|
||||
/* Locale/Location and Time */
|
||||
LocaleManager: Filters.byProperties(['setLocale']),
|
||||
Moment: Filters.byProperties(['parseZone']),
|
||||
LocationManager: Filters.byProperties(['createLocation']),
|
||||
Timestamps: Filters.byProperties(['fromTimestamp']),
|
||||
TimeFormatter: Filters.byProperties(['dateFormat']),
|
||||
|
||||
/* Strings and Utils */
|
||||
Strings: Filters.byProperties(['TEXT', 'TEXTAREA_PLACEHOLDER']),
|
||||
StringFormats: Filters.byProperties(['a', 'z']),
|
||||
StringUtils: Filters.byProperties(['toASCII']),
|
||||
|
||||
/* URLs and Utils */
|
||||
URLParser: Filters.byProperties(['Url', 'parse']),
|
||||
ExtraURLs: Filters.byProperties(['getArticleURL']),
|
||||
|
||||
/* Text Processing */
|
||||
hljs: Filters.byProperties(['highlight', 'highlightBlock']),
|
||||
SimpleMarkdown: Filters.byProperties(['parseBlock', 'parseInline', 'defaultOutput']),
|
||||
|
||||
/* DOM/React Components */
|
||||
/* ==================== */
|
||||
LayerManager: Filters.byProperties(['popLayer', 'pushLayer']),
|
||||
UserSettingsWindow: Filters.byProperties(['open', 'updateAccount']),
|
||||
ChannelSettingsWindow: Filters.byProperties(['open', 'updateChannel']),
|
||||
GuildSettingsWindow: Filters.byProperties(['open', 'updateGuild']),
|
||||
|
||||
/* Modals */
|
||||
ModalStack: Filters.byProperties(['push', 'update', 'pop', 'popWithKey']),
|
||||
ConfirmModal: Filters.byPrototypeFields(['handleCancel', 'handleSubmit', 'handleMinorConfirm']),
|
||||
UserProfileModal: Filters.byProperties(['fetchMutualFriends', 'setSection']),
|
||||
ChangeNicknameModal: Filters.byProperties(['open', 'changeNickname']),
|
||||
CreateChannelModal: Filters.byProperties(['open', 'createChannel']),
|
||||
PruneMembersModal: Filters.byProperties(['open', 'prune']),
|
||||
NotificationSettingsModal: Filters.byProperties(['open', 'updateNotificationSettings']),
|
||||
PrivacySettingsModal: Filters.byCode(/PRIVACY_SETTINGS_MODAL_OPEN/, m => m.open),
|
||||
CreateInviteModal: Filters.byProperties(['open', 'createInvite']),
|
||||
|
||||
/* Popouts */
|
||||
PopoutStack: Filters.byProperties(['open', 'close', 'closeAll']),
|
||||
PopoutOpener: Filters.byProperties(['openPopout']),
|
||||
EmojiPicker: Filters.byPrototypeFields(['onHoverEmoji', 'selectEmoji']),
|
||||
|
||||
/* Context Menus */
|
||||
ContextMenuActions: Filters.byCode(/CONTEXT_MENU_CLOSE/, c => c.close),
|
||||
ContextMenuItemsGroup: Filters.byCode(/itemGroup/),
|
||||
ContextMenuItem: Filters.byCode(/\.label\b.*\.hint\b.*\.action\b/),
|
||||
|
||||
/* In-Message Links */
|
||||
ExternalLink: Filters.byCode(/\.trusted\b/)
|
||||
};
|
||||
|
||||
class WebpackModules {
|
||||
|
||||
/**
|
||||
* Finds a module using a filter function.
|
||||
* @param {Function} filter A function to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @param {Array} modules An array of modules to search in
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModule(filter, first = true, _modules) {
|
||||
const modules = _modules || this.getAllModules();
|
||||
const rm = [];
|
||||
for (const index in modules) {
|
||||
if (!modules.hasOwnProperty(index)) continue;
|
||||
const module = modules[index];
|
||||
const { exports } = module;
|
||||
let foundModule = null;
|
||||
|
||||
if (!exports) continue;
|
||||
if (exports.__esModule && exports.default && filter(exports.default)) foundModule = exports.default;
|
||||
if (filter(exports)) foundModule = exports;
|
||||
if (!foundModule) continue;
|
||||
if (first) return foundModule;
|
||||
rm.push(foundModule);
|
||||
}
|
||||
return first ? undefined : rm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's name.
|
||||
* @param {String} name The name of the module
|
||||
* @param {Function} fallback A function to use to filter modules if not finding a known module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByName(name, fallback) {
|
||||
if (Cache.hasOwnProperty(name)) return Cache[name];
|
||||
if (KnownModules.hasOwnProperty(name)) fallback = KnownModules[name];
|
||||
if (!fallback) return undefined;
|
||||
const module = this.getModule(fallback, true);
|
||||
return module ? Cache[name] = module : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's display name.
|
||||
* @param {String} name The display name of the module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByDisplayName(name) {
|
||||
return this.getModule(Filters.byDisplayName(name), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using it's code.
|
||||
* @param {RegEx} regex A regular expression to use to filter modules
|
||||
* @param {Boolean} first Whether to return the only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByRegex(regex, first = true) {
|
||||
return this.getModule(Filters.byCode(regex), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using properties on it's prototype.
|
||||
* @param {Array} props Properties to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByPrototypes(prototypes, first = true) {
|
||||
return this.getModule(Filters.byPrototypeFields(prototypes), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using it's own properties.
|
||||
* @param {Array} props Properties to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByProps(props, first = true) {
|
||||
return this.getModule(Filters.byProperties(props), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Discord's __webpack_require__ function.
|
||||
*/
|
||||
static get require() {
|
||||
if (this._require) return this._require;
|
||||
|
||||
const __webpack_require__ = this.getWebpackRequire();
|
||||
if (!__webpack_require__) return null;
|
||||
|
||||
this.hookWebpackRequireCache(__webpack_require__);
|
||||
return this._require = __webpack_require__;
|
||||
}
|
||||
|
||||
static getWebpackRequire() {
|
||||
const id = 'bd-webpackmodules';
|
||||
|
||||
if (typeof window.webpackJsonp === 'function') {
|
||||
const __webpack_require__ = window['webpackJsonp']([], {
|
||||
[id]: (module, exports, __webpack_require__) => exports.default = __webpack_require__
|
||||
}, [id]).default;
|
||||
delete __webpack_require__.m[id];
|
||||
delete __webpack_require__.c[id];
|
||||
return __webpack_require__;
|
||||
} else if (window.webpackJsonp && window.webpackJsonp.push) {
|
||||
const __webpack_require__ = window['webpackJsonp'].push([[], {
|
||||
[id]: (module, exports, req) => exports.default = req
|
||||
}, [[id]]]).default;
|
||||
window['webpackJsonp'].pop();
|
||||
delete __webpack_require__.m[id];
|
||||
delete __webpack_require__.c[id];
|
||||
return __webpack_require__;
|
||||
}
|
||||
}
|
||||
|
||||
static hookWebpackRequireCache(__webpack_require__) {
|
||||
__webpack_require__.c = new Proxy(__webpack_require__.c, {
|
||||
set(module_cache, module_id, module) {
|
||||
// Add it to our emitter cache and emit a module-loading event
|
||||
this.moduleLoading(module_id, module);
|
||||
Events.emit('module-loading', module);
|
||||
|
||||
// Add the module to the cache as normal
|
||||
module_cache[module_id] = module;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static moduleLoading(module_id, module) {
|
||||
if (this.require.c[module_id]) return;
|
||||
|
||||
if (!this.moduleLoadedEventTimeout) {
|
||||
this.moduleLoadedEventTimeout = setTimeout(() => {
|
||||
this.moduleLoadedEventTimeout = undefined;
|
||||
|
||||
// Emit a module-loaded event for every module
|
||||
for (const module of this.modulesLoadingCache) {
|
||||
Events.emit('module-loaded', module);
|
||||
}
|
||||
|
||||
// Emit a modules-loaded event
|
||||
Events.emit('modules-loaded', this.modulesLoadingCache);
|
||||
|
||||
this.modulesLoadedCache = [];
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Add this to our own cache
|
||||
if (!this.modulesLoadingCache) this.modulesLoadingCache = [];
|
||||
this.modulesLoadingCache.push(module);
|
||||
}
|
||||
|
||||
static waitForWebpackRequire() {
|
||||
return Utils.until(() => this.require, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a module to load.
|
||||
* This only returns a single module, as it can't guarentee there are no more modules that could
|
||||
* match the filter, which is pretty much what that would be asking for.
|
||||
* @param {Function} filter The name of a known module or a filter function
|
||||
* @return {Any}
|
||||
*/
|
||||
static async waitForModule(filter) {
|
||||
const module = this.getModule(filter);
|
||||
if (module) return module;
|
||||
|
||||
while (this.require.m.length > this.require.c.length) {
|
||||
const additionalModules = await Events.once('modules-loaded');
|
||||
|
||||
const module = this.getModule(filter, true, additionalModules);
|
||||
if (module) return module;
|
||||
}
|
||||
|
||||
throw new Error('All modules have now been loaded. None match the passed filter.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's name.
|
||||
* @param {String} name The name of the module
|
||||
* @param {Function} fallback A function to use to filter modules if not finding a known module
|
||||
* @return {Any}
|
||||
*/
|
||||
static async waitForModuleByName(name, fallback) {
|
||||
if (Cache.hasOwnProperty(name)) return Cache[name];
|
||||
if (KnownModules.hasOwnProperty(name)) fallback = KnownModules[name];
|
||||
if (!fallback) return undefined;
|
||||
const module = await this.waitForModule(fallback, true);
|
||||
return module ? Cache[name] = module : undefined;
|
||||
}
|
||||
|
||||
static waitForModuleByDisplayName(props) {
|
||||
return this.waitForModule(Filters.byDisplayName(props));
|
||||
}
|
||||
static waitForModuleByRegex(props) {
|
||||
return this.waitForModule(Filters.byCode(props));
|
||||
}
|
||||
static waitForModuleByProps(props) {
|
||||
return this.waitForModule(Filters.byProperties(props));
|
||||
}
|
||||
static waitForModuleByPrototypes(props) {
|
||||
return this.waitForModule(Filters.byPrototypeFields(props));
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for a class module and returns a class from it.
|
||||
* @param {String} base The first part of the class to find
|
||||
* @param {String} ...additional_classes Additional classes to look for to filter duplicate class modules
|
||||
* @return {String}
|
||||
*/
|
||||
static getClassName(base, ...additional_classes) {
|
||||
const class_module = this.getModuleByProps([base, ...additional_classes]);
|
||||
if (class_module && class_module[base]) return class_module[base].split(' ')[0];
|
||||
}
|
||||
static async waitForClassName(base, ...additional_classes) {
|
||||
const class_module = await this.waitForModuleByProps([base, ...additional_classes]);
|
||||
if (class_module && class_module[base]) return class_module[base].split(' ')[0];
|
||||
}
|
||||
static getSelector(base, ...additional_classes) {
|
||||
const gcn = this.getClassName(base, ...additional_classes);
|
||||
if (gcn) return `.${gcn}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all loaded modules.
|
||||
* @return {Array}
|
||||
*/
|
||||
static getAllModules() {
|
||||
return this.require.c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of known modules.
|
||||
* @return {Array}
|
||||
*/
|
||||
static listKnownModules() {
|
||||
return Object.keys(KnownModules);
|
||||
}
|
||||
|
||||
static get KnownModules() { return KnownModules }
|
||||
|
||||
}
|
||||
|
||||
export { WebpackModules }
|
|
@ -0,0 +1,111 @@
|
|||
/**
|
||||
* BetterDiscord Security Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import nodecrypto from 'node-crypto';
|
||||
import aes256 from 'aes256';
|
||||
|
||||
export default class Security {
|
||||
|
||||
static encrypt(key, content, prefix = '') {
|
||||
if (key instanceof Array || content instanceof Array) return this.deepEncrypt(key, content, prefix);
|
||||
return `${prefix}${aes256.encrypt(key, content)}`;
|
||||
}
|
||||
|
||||
static decrypt(key, content, prefix = '') {
|
||||
if (key instanceof Array || content instanceof Array) {
|
||||
return this.deepDecrypt(key, content, prefix);
|
||||
}
|
||||
return aes256.decrypt(key, content.replace(prefix, ''));
|
||||
}
|
||||
|
||||
static deepEncrypt(keys, content, prefix = '') {
|
||||
if (content && content instanceof Array) return this.deepEncryptContent(keys, content, prefix);
|
||||
let encrypt = null;
|
||||
for (const key of keys) {
|
||||
if (encrypt === null) encrypt = this.encrypt(key, content, prefix);
|
||||
else encrypt = this.encrypt(key, encrypt, prefix);
|
||||
}
|
||||
return encrypt;
|
||||
}
|
||||
|
||||
static deepEncryptContent(key, contents, prefix = '') {
|
||||
let encrypt = null;
|
||||
for (const content of contents) {
|
||||
if (encrypt === null) encrypt = this.encrypt(key, content, prefix);
|
||||
else encrypt = this.encrypt(encrypt, content, prefix);
|
||||
}
|
||||
return encrypt;
|
||||
}
|
||||
|
||||
static deepDecrypt(keys, content, prefix = '') {
|
||||
if (content && content instanceof Array) return this.deepDecryptContent(keys, content, prefix);
|
||||
let decrypt = null;
|
||||
for (const key of keys.reverse()) {
|
||||
if (decrypt === null) decrypt = this.decrypt(key, content, prefix);
|
||||
else decrypt = this.decrypt(key, decrypt, prefix);
|
||||
}
|
||||
return decrypt;
|
||||
}
|
||||
|
||||
static deepDecryptContent(key, contents, prefix = '') {
|
||||
let decrypt = null;
|
||||
for (const content of contents) {
|
||||
if (decrypt === null) decrypt = this.decrypt(key, content, prefix);
|
||||
else decrypt = this.decrypt(decrypt, content, prefix);
|
||||
}
|
||||
return decrypt;
|
||||
}
|
||||
|
||||
static randomBytes(length = 64, to = 'hex') {
|
||||
return nodecrypto.randomBytes(length).toString(to);
|
||||
}
|
||||
|
||||
static async createHmac(key, data, algorithm = 'sha256') {
|
||||
const hmac = nodecrypto.createHmac(algorithm, key);
|
||||
return new Promise((resolve, reject) => {
|
||||
hmac.on('readable', () => {
|
||||
const data = hmac.read();
|
||||
if (data) return resolve(data.toString('hex'));
|
||||
reject(null);
|
||||
});
|
||||
hmac.write(data);
|
||||
hmac.end();
|
||||
});
|
||||
}
|
||||
|
||||
static createECDH(curve = 'secp384r1') {
|
||||
return nodecrypto.createECDH(curve);
|
||||
}
|
||||
|
||||
static hash(algorithm, data, encoding) {
|
||||
const hash = nodecrypto.createHash(algorithm);
|
||||
hash.update(data);
|
||||
return hash.digest(encoding);
|
||||
}
|
||||
|
||||
static sha256(text) {
|
||||
const hash = nodecrypto.createHash('sha256');
|
||||
hash.update(text);
|
||||
return hash.digest('base64');
|
||||
}
|
||||
|
||||
static generateECDHKeys(ecdh) {
|
||||
return ecdh.generateKeys('base64');
|
||||
}
|
||||
|
||||
static getECDHPublicKey(ecdh) {
|
||||
return ecdh.getPublicKey('base64');
|
||||
}
|
||||
|
||||
static computeECDHSecret(ecdh, otherPublicKey) {
|
||||
return ecdh.computeSecret(otherPublicKey, 'base64', 'base64');
|
||||
}
|
||||
|
||||
}
|
|
@ -8,47 +8,62 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import defaultSettings from '../data/user.settings.default';
|
||||
import { Toasts } from 'ui';
|
||||
import { SettingsSet } from 'structs';
|
||||
import { FileUtils, ClientLogger as Logger } from 'common';
|
||||
import path from 'path';
|
||||
import process from 'process';
|
||||
import Globals from './globals';
|
||||
import CssEditor from './csseditor';
|
||||
import Events from './events';
|
||||
import { Utils, FileUtils, ClientLogger as Logger } from 'common';
|
||||
import { SettingsSet, SettingUpdatedEvent } from 'structs';
|
||||
import path from 'path';
|
||||
import defaultSettings from '../data/user.settings.default';
|
||||
|
||||
export default new class Settings {
|
||||
|
||||
constructor() {
|
||||
this.settings = defaultSettings.map(_set => {
|
||||
const set = new SettingsSet(_set);
|
||||
|
||||
set.on('setting-updated', event => {
|
||||
const { category, setting, value, old_value } = event;
|
||||
Logger.log('Settings', `${set.id}/${category.id}/${setting.id} was changed from ${old_value} to ${value}`);
|
||||
Logger.log('Settings', [`${set.id}/${category.id}/${setting.id} was changed from`, old_value, 'to', value]);
|
||||
Events.emit('setting-updated', event);
|
||||
Events.emit(`setting-updated-${set.id}_${category.id}_${setting.id}`, event);
|
||||
Toasts.success(`${set.id}/${category.id}/${setting.id} was changed from ${old_value} to ${value}`); // Just for debugging purposes remove in prod
|
||||
});
|
||||
|
||||
set.on('settings-updated', async (event) => {
|
||||
await this.saveSettings();
|
||||
set.on('settings-updated', async event => {
|
||||
if (!event.data || !event.data.dont_save) await this.saveSettings();
|
||||
Events.emit('settings-updated', event);
|
||||
});
|
||||
|
||||
return set;
|
||||
});
|
||||
|
||||
// Set a hint for each platform for the use-keytar setting
|
||||
const useKeytarSetting = this.getSetting('security', 'default', 'use-keytar');
|
||||
if (process.platform === 'win32') useKeytarSetting.hint = 'Store the master password in Credential Manager';
|
||||
if (process.platform === 'darwin') useKeytarSetting.hint = 'Store the master password in the default keychain';
|
||||
if (process.platform === 'linux') useKeytarSetting.hint = 'Store the master password in libsecret';
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads BetterDiscord's settings.
|
||||
*/
|
||||
async loadSettings() {
|
||||
Logger.log('Settings', ['Loading settings']);
|
||||
|
||||
try {
|
||||
await FileUtils.ensureDirectory(this.dataPath);
|
||||
|
||||
const settingsPath = path.resolve(this.dataPath, 'user.settings.json');
|
||||
const user_config = await FileUtils.readJsonFromFile(settingsPath);
|
||||
const { settings, scss, css, css_editor_files, scss_error, css_editor_bounds } = user_config;
|
||||
const { settings, scss, css, css_editor_files, scss_error, css_editor_bounds, favourite_emotes } = user_config;
|
||||
|
||||
for (let set of this.settings) {
|
||||
for (const set of this.settings) {
|
||||
const newSet = settings.find(s => s.id === set.id);
|
||||
if (!newSet) continue;
|
||||
set.merge(newSet);
|
||||
await set.merge(newSet, {dont_save: true});
|
||||
set.setSaved();
|
||||
}
|
||||
|
||||
|
@ -57,11 +72,16 @@ export default new class Settings {
|
|||
} catch (err) {
|
||||
// There was an error loading settings
|
||||
// This probably means that the user doesn't have any settings yet
|
||||
Logger.err('Settings', err);
|
||||
Logger.warn('Settings', ['Failed to load internal settings', err]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves BetterDiscord's settings including CSS editor data.
|
||||
*/
|
||||
async saveSettings() {
|
||||
Logger.log('Settings', ['Saving settings']);
|
||||
|
||||
try {
|
||||
await FileUtils.ensureDirectory(this.dataPath);
|
||||
|
||||
|
@ -72,26 +92,26 @@ export default new class Settings {
|
|||
css: CssEditor.css,
|
||||
css_editor_files: CssEditor.files,
|
||||
scss_error: CssEditor.error,
|
||||
css_editor_bounds: {
|
||||
width: CssEditor.editor_bounds.width,
|
||||
height: CssEditor.editor_bounds.height,
|
||||
x: CssEditor.editor_bounds.x,
|
||||
y: CssEditor.editor_bounds.y
|
||||
}
|
||||
css_editor_bounds: CssEditor.editor_bounds
|
||||
});
|
||||
|
||||
for (let set of this.getSettings) {
|
||||
for (const set of this.settings) {
|
||||
set.setSaved();
|
||||
}
|
||||
} catch (err) {
|
||||
// There was an error saving settings
|
||||
Logger.err('Settings', err);
|
||||
Logger.err('Settings', ['Failed to save internal settings', err]);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds one of BetterDiscord's settings sets.
|
||||
* @param {String} set_id The ID of the set to find
|
||||
* @return {SettingsSet}
|
||||
*/
|
||||
getSet(set_id) {
|
||||
return this.getSettings.find(s => s.id === set_id);
|
||||
return this.settings.find(s => s.id === set_id);
|
||||
}
|
||||
|
||||
get core() { return this.getSet('core') }
|
||||
|
@ -100,39 +120,46 @@ export default new class Settings {
|
|||
get css() { return this.getSet('css') }
|
||||
get security() { return this.getSet('security') }
|
||||
|
||||
/**
|
||||
* Finds a category in one of BetterDiscord's settings sets.
|
||||
* @param {String} set_id The ID of the set to look in
|
||||
* @param {String} category_id The ID of the category to find
|
||||
* @return {SettingsCategory}
|
||||
*/
|
||||
getCategory(set_id, category_id) {
|
||||
const set = this.getSet(set_id);
|
||||
return set ? set.getCategory(category_id) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a setting in one of BetterDiscord's settings sets.
|
||||
* @param {String} set_id The ID of the set to look in
|
||||
* @param {String} category_id The ID of the category to look in
|
||||
* @param {String} setting_id The ID of the setting to find
|
||||
* @return {Setting}
|
||||
*/
|
||||
getSetting(set_id, category_id, setting_id) {
|
||||
const set = this.getSet(set_id);
|
||||
return set ? set.getSetting(category_id, setting_id) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a setting's value in one of BetterDiscord's settings sets.
|
||||
* @param {String} set_id The ID of the set to look in
|
||||
* @param {String} category_id The ID of the category to look in
|
||||
* @param {String} setting_id The ID of the setting to find
|
||||
* @return {Any}
|
||||
*/
|
||||
get(set_id, category_id, setting_id) {
|
||||
const set = this.getSet(set_id);
|
||||
return set ? set.get(category_id, setting_id) : undefined;
|
||||
}
|
||||
|
||||
async mergeSettings(set_id, newSettings) {
|
||||
const set = this.getSet(set_id);
|
||||
if (!set) return;
|
||||
|
||||
return await set.merge(newSettings);
|
||||
}
|
||||
|
||||
setSetting(set_id, category_id, setting_id, value) {
|
||||
const setting = this.getSetting(set_id, category_id, setting_id);
|
||||
if (!setting) throw {message: `Tried to set ${set_id}/${category_id}/${setting_id}, which doesn't exist`};
|
||||
setting.value = value;
|
||||
}
|
||||
|
||||
get getSettings() {
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path to store user data in.
|
||||
*/
|
||||
get dataPath() {
|
||||
return Globals.getPath('data');
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,6 +8,7 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import EventListener from './eventlistener';
|
||||
|
||||
export default class SocketProxy extends EventListener {
|
||||
|
@ -19,7 +20,7 @@ export default class SocketProxy extends EventListener {
|
|||
|
||||
get eventBindings() {
|
||||
return [
|
||||
{ id: 'socket-created', 'callback': this.socketCreated }
|
||||
{ id: 'socket-created', callback: this.socketCreated }
|
||||
];
|
||||
}
|
||||
|
||||
|
@ -33,7 +34,7 @@ export default class SocketProxy extends EventListener {
|
|||
}
|
||||
|
||||
onMessage(e) {
|
||||
console.info(e);
|
||||
Logger.info('SocketProxy', e);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -31,10 +31,6 @@ export default class Theme extends Content {
|
|||
get type() { return 'theme' }
|
||||
get css() { return this.data.css }
|
||||
|
||||
// Don't use - these will eventually be removed!
|
||||
get themePath() { return this.contentPath }
|
||||
get themeConfig() { return this.config }
|
||||
|
||||
/**
|
||||
* Called when settings are updated.
|
||||
* This can be overridden by other content types.
|
||||
|
@ -63,7 +59,7 @@ export default class Theme extends Content {
|
|||
* @return {Promise}
|
||||
*/
|
||||
async compile() {
|
||||
console.log('Compiling CSS');
|
||||
Logger.log(this.name, 'Compiling CSS');
|
||||
|
||||
if (this.info.type === 'sass') {
|
||||
const config = await ThemeManager.getConfigAsSCSS(this.settings);
|
||||
|
@ -73,21 +69,20 @@ export default class Theme extends Content {
|
|||
path: this.paths.mainPath.replace(/\\/g, '/')
|
||||
});
|
||||
|
||||
// Why are these getters?
|
||||
Logger.log(this.name, ['Finished compiling theme', new class Info {
|
||||
get SCSS_variables() { console.log(config); }
|
||||
get Compiled_SCSS() { console.log(result.css.toString()); }
|
||||
get Result() { console.log(result); }
|
||||
get SCSS_variables() { console.log(config); return ''; }
|
||||
get Compiled_SCSS() { console.log(result.css.toString()); return ''; }
|
||||
get Result() { console.log(result); return ''; }
|
||||
}]);
|
||||
|
||||
return {
|
||||
css: result.css.toString(),
|
||||
files: result.stats.includedFiles
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
css: await FileUtils.readFile(this.paths.mainPath)
|
||||
};
|
||||
}
|
||||
|
||||
return { css: await FileUtils.readFile(this.paths.mainPath) }
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -121,6 +116,7 @@ export default class Theme extends Content {
|
|||
*/
|
||||
set files(files) {
|
||||
this.data.files = files;
|
||||
|
||||
if (Settings.get('css', 'default', 'watch-files'))
|
||||
this.watchfiles = files;
|
||||
}
|
||||
|
@ -151,7 +147,14 @@ export default class Theme extends Content {
|
|||
* @param {Array} files Files to watch
|
||||
*/
|
||||
set watchfiles(files) {
|
||||
for (let file of files) {
|
||||
if (this.packed) {
|
||||
// Don't watch files for packed themes
|
||||
return;
|
||||
}
|
||||
|
||||
if (!files) files = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (!this.watchfiles.includes(file)) {
|
||||
this.filewatcher.add(file);
|
||||
this.watchfiles.push(file);
|
||||
|
@ -159,7 +162,7 @@ export default class Theme extends Content {
|
|||
}
|
||||
}
|
||||
|
||||
for (let index in this.watchfiles) {
|
||||
for (const index in this.watchfiles) {
|
||||
let file = this.watchfiles[index];
|
||||
while (file && !files.find(f => f === file)) {
|
||||
this.filewatcher.remove(file);
|
||||
|
|
|
@ -10,8 +10,6 @@
|
|||
|
||||
import ContentManager from './contentmanager';
|
||||
import Theme from './theme';
|
||||
import { FileUtils } from 'common';
|
||||
import path from 'path';
|
||||
|
||||
export default class ThemeManager extends ContentManager {
|
||||
|
||||
|
@ -38,12 +36,7 @@ export default class ThemeManager extends ContentManager {
|
|||
static async loadTheme(paths, configs, info, main) {
|
||||
try {
|
||||
const instance = new Theme({
|
||||
configs, info, main,
|
||||
paths: {
|
||||
contentPath: paths.contentPath,
|
||||
dirName: paths.dirName,
|
||||
mainPath: paths.mainPath
|
||||
}
|
||||
configs, info, main, paths
|
||||
});
|
||||
if (instance.enabled) {
|
||||
instance.userConfig.enabled = false;
|
||||
|
@ -55,6 +48,7 @@ export default class ThemeManager extends ContentManager {
|
|||
}
|
||||
}
|
||||
|
||||
static get deleteTheme() { return this.deleteContent }
|
||||
static get unloadTheme() { return this.unloadContent }
|
||||
static async reloadTheme(theme) {
|
||||
theme = await this.reloadContent(theme);
|
||||
|
@ -62,11 +56,11 @@ export default class ThemeManager extends ContentManager {
|
|||
}
|
||||
|
||||
static enableTheme(theme) {
|
||||
theme.enable();
|
||||
return theme.enable();
|
||||
}
|
||||
|
||||
static disableTheme(theme) {
|
||||
theme.disable();
|
||||
return theme.disable();
|
||||
}
|
||||
|
||||
static get isTheme() { return this.isThisContent }
|
||||
|
@ -74,11 +68,16 @@ export default class ThemeManager extends ContentManager {
|
|||
return theme instanceof Theme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a representation of a settings set's values in SCSS.
|
||||
* @param {SettingsSet} settingsset The set to convert to SCSS
|
||||
* @return {Promise}
|
||||
*/
|
||||
static async getConfigAsSCSS(settingsset) {
|
||||
const variables = [];
|
||||
|
||||
for (let category of settingsset.categories) {
|
||||
for (let setting of category.settings) {
|
||||
for (const category of settingsset.categories) {
|
||||
for (const setting of category.settings) {
|
||||
const setting_scss = await this.parseSetting(setting);
|
||||
if (setting_scss) variables.push(`$${setting_scss[0]}: ${setting_scss[1]};`);
|
||||
}
|
||||
|
@ -87,27 +86,41 @@ export default class ThemeManager extends ContentManager {
|
|||
return variables.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a representation of a settings set's values as an SCSS map.
|
||||
* @param {SettingsSet} settingsset The set to convert to an SCSS map
|
||||
* @return {Promise}
|
||||
*/
|
||||
static async getConfigAsSCSSMap(settingsset) {
|
||||
const variables = [];
|
||||
|
||||
for (let category of settingsset.categories) {
|
||||
for (let setting of category.settings) {
|
||||
for (const category of settingsset.categories) {
|
||||
for (const setting of category.settings) {
|
||||
const setting_scss = await this.parseSetting(setting);
|
||||
if (setting_scss) variables.push(`${setting_scss[0]}: (${setting_scss[1]})`);
|
||||
}
|
||||
}
|
||||
|
||||
return '(' + variables.join(', ') + ')';
|
||||
return `(${variables.join(', ')})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a setting's name and value as a string that can be included in SCSS.
|
||||
* @param {Setting} setting The setting to convert to SCSS
|
||||
* @return {Promise}
|
||||
*/
|
||||
static async parseSetting(setting) {
|
||||
const { type, id, value } = setting;
|
||||
const name = id.replace(/[^a-zA-Z0-9-]/g, '-').replace(/--/g, '-');
|
||||
const name = setting.id.replace(/[^a-zA-Z0-9-]/g, '-').replace(/--/g, '-');
|
||||
const scss = await setting.toSCSS();
|
||||
|
||||
if (scss) return [name, scss];
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a string so it can be included in SCSS.
|
||||
* @param {String} value The string to escape
|
||||
* @return {String}
|
||||
*/
|
||||
static toSCSSString(value) {
|
||||
if (typeof value !== 'string' && value.toString) value = value.toString();
|
||||
return `'${typeof value === 'string' ? value.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') : ''}'`;
|
||||
|
|
|
@ -8,56 +8,182 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import Events from './events';
|
||||
import Globals from './globals';
|
||||
import { $ } from 'vendor';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
import { Notifications } from 'ui';
|
||||
import { Reflection, Globals } from 'modules';
|
||||
|
||||
export default class {
|
||||
import Events from './events';
|
||||
import Module from './imodule';
|
||||
|
||||
export default new class extends Module {
|
||||
|
||||
get updates() { return this.state.updates }
|
||||
get bdUpdates() { return this.state.updates.bd }
|
||||
get error() { return null; }
|
||||
get updatesAvailable() { return this.state.updatesAvailable; }
|
||||
|
||||
constructor() {
|
||||
window.updater = this;
|
||||
this.updatesAvailable = false;
|
||||
this.init = this.init.bind(this);
|
||||
this.checkForUpdates = this.checkForUpdates.bind(this);
|
||||
super({
|
||||
updatesAvailable: false,
|
||||
error: null,
|
||||
updates: { bd: [] },
|
||||
updating: false
|
||||
});
|
||||
}
|
||||
|
||||
get interval() {
|
||||
return 60 * 1000 * 30;
|
||||
bindings() {
|
||||
this.restartNotif = this.restartNotif.bind(this);
|
||||
this.reloadNotif = this.reloadNotif.bind(this);
|
||||
this.startUpdate = this.startUpdate.bind(this);
|
||||
this.setUpdateStatus = this.setUpdateStatus.bind(this);
|
||||
this.testUi = this.testUi.bind(this);
|
||||
}
|
||||
|
||||
init() {
|
||||
this.updateInterval = setInterval(this.checkForUpdates, this.interval);
|
||||
}
|
||||
|
||||
update() {
|
||||
// TODO
|
||||
this.updatesAvailable = false;
|
||||
Events.emit('update-check-end');
|
||||
}
|
||||
|
||||
checkForUpdates() {
|
||||
if (this.updatesAvailable) return;
|
||||
Events.emit('update-check-start');
|
||||
Logger.info('Updater', 'Checking for updates');
|
||||
$.ajax({
|
||||
type: 'GET',
|
||||
url: 'https://rawgit.com/JsSucks/BetterDiscordApp/master/package.json',
|
||||
cache: false,
|
||||
success: e => {
|
||||
try {
|
||||
Events.emit('update-check-end');
|
||||
Logger.info('Updater',
|
||||
`Latest Version: ${e.version} - Current Version: ${Globals.version}`);
|
||||
if (e.version !== Globals.version) {
|
||||
this.updatesAvailable = true;
|
||||
Events.emit('updates-available');
|
||||
}
|
||||
} catch (err) {
|
||||
Events.emit('update-check-fail', err);
|
||||
}
|
||||
restartNotif() {
|
||||
Notifications.add('Updates Finished!', 'Restart required.', [
|
||||
{
|
||||
text: 'Restart Later',
|
||||
onClick: () => { setTimeout(this.restartNotif, 5 * 60000); return true; }
|
||||
},
|
||||
fail: e => Events.emit('update-check-fail', e)
|
||||
{
|
||||
text: 'Restart Now',
|
||||
onClick: () => {
|
||||
try {
|
||||
const { remote } = Globals.require('electron');
|
||||
window.close();
|
||||
Reflection.module.byProps('showToken', 'hideToken').showToken();
|
||||
remote.app.relaunch();
|
||||
remote.app.exit(0);
|
||||
} catch (err) {
|
||||
console.err(err);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
reloadNotif() {
|
||||
Notifications.add('Updates Finished!', 'Reload required.', [
|
||||
{
|
||||
text: 'Reload Later',
|
||||
onClick: () => { setTimeout(this.reloadNotif, 5 * 60000); return true; }
|
||||
},
|
||||
{
|
||||
text: 'Reload Now',
|
||||
onClick: () => {
|
||||
document.location.reload();
|
||||
}
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
events(ipc) {
|
||||
ipc.on('updater-checkForUpdates', () => {
|
||||
if (this.state.updating) return; // We're already updating. Updater should be paused anyways at this point.
|
||||
Events.emit('update-check-start');
|
||||
});
|
||||
|
||||
ipc.on('updater-noUpdates', () => {
|
||||
if (this.state.updatesAvailable) return; // If for some reason we get this even though we have updates already.
|
||||
this.setState({
|
||||
updatesAvailable: false,
|
||||
updates: {}
|
||||
});
|
||||
});
|
||||
|
||||
ipc.on('updater-updatesAvailable', (_, updates) => {
|
||||
console.log(updates);
|
||||
if (this.state.updating) return; // If for some reason we get more updates when we're already updating
|
||||
updates.bd = updates.bd.map(update => {
|
||||
update.text = `${update.id.charAt(0).toUpperCase()}${update.id.slice(1)}`;
|
||||
update.hint = `Current: ${update.currentVersion} | Latest: ${update.version}`;
|
||||
update.status = {
|
||||
update: true,
|
||||
updating: false,
|
||||
updated: false,
|
||||
error: null
|
||||
};
|
||||
|
||||
return update;
|
||||
});
|
||||
this.setState({
|
||||
updates,
|
||||
updatesAvailable: true
|
||||
});
|
||||
});
|
||||
|
||||
ipc.on('updater-updated', (_, info) => {
|
||||
const { reloadRequired, restartRequired } = info;
|
||||
if (restartRequired) {
|
||||
this.restartNotif();
|
||||
return;
|
||||
}
|
||||
|
||||
if (reloadRequired) {
|
||||
this.reloadNotif();
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
ipc.on('updater-updateFinished', (_, update) => {
|
||||
this.setUpdateStatus(update.id, 'updated', true);
|
||||
});
|
||||
|
||||
ipc.on('updater-updateError', (_, update) => {
|
||||
this.setUpdateStatus(update.id, 'error', update.error);
|
||||
});
|
||||
}
|
||||
|
||||
stateChanged(oldState, newState) {
|
||||
if (!newState.updatesAvailable) return Events.emit('update-check-end');
|
||||
if (!oldState.updatesAvailable && newState.updatesAvailable) {
|
||||
Events.emit('updates-available');
|
||||
Notifications.add('', 'Updates Available!', [
|
||||
{
|
||||
text: 'Ignore',
|
||||
onClick: () => { return true; }
|
||||
},
|
||||
{
|
||||
text: 'Show Updates',
|
||||
onClick: () => {
|
||||
Events.emit('bd-open-menu', 'updater');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
setUpdateStatus(updateId, statusChild, statusValue) {
|
||||
for (const u of this.bdUpdates) {
|
||||
if (u.id === updateId) {
|
||||
u.status[statusChild] = statusValue;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toggleUpdate(update) {
|
||||
update.status.update = !update.status.update;
|
||||
}
|
||||
|
||||
async startUpdate() {
|
||||
console.log('start update');
|
||||
const updates = { bd: [] };
|
||||
for (const update of this.bdUpdates) {
|
||||
if (update.status.update) {
|
||||
update.status.updating = true;
|
||||
updates.bd.push(update);
|
||||
}
|
||||
}
|
||||
console.log(updates);
|
||||
this.send('updater-startUpdate', updates);
|
||||
}
|
||||
|
||||
testUi(updates) {
|
||||
this.setState({
|
||||
updates,
|
||||
updatesAvailable: true
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -8,32 +8,46 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { WebpackModules } from './webpackmodules';
|
||||
import jQuery from 'jquery';
|
||||
import lodash from 'lodash';
|
||||
import Vue from 'vue';
|
||||
import { Axi } from 'common';
|
||||
|
||||
export { jQuery as $ };
|
||||
import request from 'request-promise-native';
|
||||
|
||||
import Combokeys from 'combokeys';
|
||||
import filetype from 'file-type';
|
||||
import filewatcher from 'filewatcher';
|
||||
import VTooltip from 'v-tooltip';
|
||||
|
||||
export { jQuery as $, request };
|
||||
|
||||
export default class {
|
||||
|
||||
static get jQuery() {
|
||||
return jQuery;
|
||||
}
|
||||
/**
|
||||
* jQuery
|
||||
*/
|
||||
static get jQuery() { return jQuery }
|
||||
static get $() { return this.jQuery }
|
||||
|
||||
static get $() {
|
||||
return this.jQuery;
|
||||
}
|
||||
/**
|
||||
* Lodash
|
||||
*/
|
||||
static get lodash() { return lodash }
|
||||
static get _() { return this.lodash }
|
||||
|
||||
static get lodash() {
|
||||
return lodash;
|
||||
}
|
||||
/**
|
||||
* Vue
|
||||
*/
|
||||
static get Vue() { return Vue }
|
||||
|
||||
static get _() {
|
||||
return this.lodash;
|
||||
}
|
||||
static get axios() { return Axi.axios }
|
||||
|
||||
static get moment() {
|
||||
return WebpackModules.getModuleByName('Moment');
|
||||
}
|
||||
static get request() { return request }
|
||||
|
||||
static get Combokeys() { return Combokeys }
|
||||
static get filetype() { return filetype }
|
||||
static get filewatcher() { return filewatcher }
|
||||
static get VTooltip() { return VTooltip }
|
||||
|
||||
}
|
||||
|
|
|
@ -1,318 +1,12 @@
|
|||
/**
|
||||
* BetterDiscord WebpackModules Module
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
/* Deprecation Notice */
|
||||
import { WebpackModules } from './reflection/wpm.depr.js';
|
||||
import { ClientLogger as Logger } from 'common';
|
||||
|
||||
export class Filters {
|
||||
static byProperties(props, selector = m => m) {
|
||||
return module => {
|
||||
const component = selector(module);
|
||||
if (!component) return false;
|
||||
return props.every(property => component[property] !== undefined);
|
||||
};
|
||||
const DeprecationWarning = new Proxy(WebpackModules, {
|
||||
get(WebpackModules, property) {
|
||||
Logger.warn('DEPR', 'WebpackModules is deprecated. Use Reflection.Modules instead.');
|
||||
return WebpackModules[property] || WebpackModules.getModuleByName(property);
|
||||
}
|
||||
});
|
||||
|
||||
static byPrototypeFields(fields, selector = m => m) {
|
||||
return module => {
|
||||
const component = selector(module);
|
||||
if (!component) return false;
|
||||
if (!component.prototype) return false;
|
||||
return fields.every(field => component.prototype[field] !== undefined);
|
||||
};
|
||||
}
|
||||
|
||||
static byCode(search, selector = m => m) {
|
||||
return module => {
|
||||
const method = selector(module);
|
||||
if (!method) return false;
|
||||
return method.toString().search(search) !== -1;
|
||||
};
|
||||
}
|
||||
|
||||
static byDisplayName(name) {
|
||||
return module => {
|
||||
return module && module.displayName === name;
|
||||
};
|
||||
}
|
||||
|
||||
static combine(...filters) {
|
||||
return module => {
|
||||
return filters.every(filter => filter(module));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const KnownModules = {
|
||||
React: Filters.byProperties(['createElement', 'cloneElement']),
|
||||
ReactDOM: Filters.byProperties(['render', 'findDOMNode']),
|
||||
|
||||
/* Guild Info, Stores, and Utilities */
|
||||
GuildStore: Filters.byProperties(['getGuild']),
|
||||
SortedGuildStore: Filters.byProperties(['getSortedGuilds']),
|
||||
SelectedGuildStore: Filters.byProperties(['getLastSelectedGuildId']),
|
||||
GuildSync: Filters.byProperties(["getSyncedGuilds"]),
|
||||
GuildInfo: Filters.byProperties(["getAcronym"]),
|
||||
GuildChannelsStore: Filters.byProperties(['getChannels', 'getDefaultChannel']),
|
||||
GuildMemberStore: Filters.byProperties(['getMember']),
|
||||
MemberCountStore: Filters.byProperties(["getMemberCounts"]),
|
||||
GuildEmojiStore: Filters.byProperties(['getEmojis']),
|
||||
GuildActions: Filters.byProperties(['markGuildAsRead']),
|
||||
GuildPermissions: Filters.byProperties(['getGuildPermissions']),
|
||||
|
||||
/* Channel Store & Actions */
|
||||
ChannelStore: Filters.byProperties(['getChannels', 'getDMFromUserId']),
|
||||
SelectedChannelStore: Filters.byProperties(['getLastSelectedChannelId']),
|
||||
ChannelActions: Filters.byProperties(["selectChannel"]),
|
||||
PrivateChannelActions: Filters.byProperties(["openPrivateChannel"]),
|
||||
ChannelSelector: Filters.byProperties(["selectGuild", "selectChannel"]),
|
||||
|
||||
/* Current User Info, State and Settings */
|
||||
UserInfoStore: Filters.byProperties(["getToken"]),
|
||||
UserSettingsStore: Filters.byProperties(["guildPositions"]),
|
||||
AccountManager: Filters.byProperties(['register', 'login']),
|
||||
UserSettingsUpdater: Filters.byProperties(['updateRemoteSettings']),
|
||||
OnlineWatcher: Filters.byProperties(['isOnline']),
|
||||
CurrentUserIdle: Filters.byProperties(['getIdleTime']),
|
||||
RelationshipStore: Filters.byProperties(['isBlocked']),
|
||||
RelationshipManager: Filters.byProperties(['addRelationship']),
|
||||
MentionStore: Filters.byProperties(["getMentions"]),
|
||||
|
||||
/* User Stores and Utils */
|
||||
UserStore: Filters.byProperties(['getCurrentUser']),
|
||||
UserStatusStore: Filters.byProperties(['getStatuses']),
|
||||
UserTypingStore: Filters.byProperties(['isTyping']),
|
||||
UserActivityStore: Filters.byProperties(['getActivity']),
|
||||
UserNameResolver: Filters.byProperties(['getName']),
|
||||
|
||||
|
||||
/* Emoji Store and Utils */
|
||||
EmojiInfo: Filters.byProperties(['isEmojiDisabled']),
|
||||
EmojiUtils: Filters.byProperties(['getGuildEmoji']),
|
||||
EmojiStore: Filters.byProperties(['getByCategory', 'EMOJI_NAME_RE']),
|
||||
|
||||
/* Invite Store and Utils */
|
||||
InviteStore: Filters.byProperties(["getInvites"]),
|
||||
InviteResolver: Filters.byProperties(['findInvite']),
|
||||
InviteActions: Filters.byProperties(['acceptInvite']),
|
||||
|
||||
|
||||
/* Discord Objects & Utils */
|
||||
DiscordConstants: Filters.byProperties(["Permissions", "ActivityTypes", "StatusTypes"]),
|
||||
Permissions: Filters.byProperties(['getHighestRole']),
|
||||
ColorConverter: Filters.byProperties(['hex2int']),
|
||||
ColorShader: Filters.byProperties(['darken']),
|
||||
ClassResolver: Filters.byProperties(["getClass"]),
|
||||
ButtonData: Filters.byProperties(["ButtonSizes"]),
|
||||
IconNames: Filters.byProperties(["IconNames"]),
|
||||
NavigationUtils: Filters.byProperties(['transitionTo', 'replaceWith', 'getHistory']),
|
||||
|
||||
/* Discord Messages */
|
||||
MessageStore: Filters.byProperties(['getMessages']),
|
||||
MessageActions: Filters.byProperties(['jumpToMessage', '_sendMessage']),
|
||||
MessageQueue: Filters.byProperties(['enqueue']),
|
||||
MessageParser: Filters.byProperties(['createMessage', 'parse', 'unparse']),
|
||||
|
||||
/* In-Game Overlay */
|
||||
OverlayUserPopoutSettings: Filters.byProperties(['openUserPopout']),
|
||||
OverlayUserPopoutInfo: Filters.byProperties(['getOpenedUserPopout']),
|
||||
|
||||
/* Experiments */
|
||||
ExperimentStore: Filters.byProperties(['getExperimentOverrides']),
|
||||
ExperimentsManager: Filters.byProperties(['isDeveloper']),
|
||||
CurrentExperiment: Filters.byProperties(['getExperimentId']),
|
||||
|
||||
|
||||
/* Images, Avatars and Utils */
|
||||
ImageResolver: Filters.byProperties(["getUserAvatarURL"]),
|
||||
ImageUtils: Filters.byProperties(['getSizedImageSrc']),
|
||||
AvatarDefaults: Filters.byProperties(["getUserAvatarURL", "DEFAULT_AVATARS"]),
|
||||
|
||||
/* Drag & Drop */
|
||||
DNDActions: Filters.byProperties(["beginDrag"]),
|
||||
DNDSources: Filters.byProperties(["addTarget"]),
|
||||
DNDObjects: Filters.byProperties(["DragSource"]),
|
||||
|
||||
/* Electron & Other Internals with Utils*/
|
||||
ElectronModule: Filters.byProperties(["_getMainWindow"]),
|
||||
Dispatcher: Filters.byProperties(['dirtyDispatch']),
|
||||
PathUtils: Filters.byProperties(["hasBasename"]),
|
||||
NotificationModule: Filters.byProperties(["showNotification"]),
|
||||
RouterModule: Filters.byProperties(["Router"]),
|
||||
APIModule: Filters.byProperties(["getAPIBaseURL"]),
|
||||
AnalyticEvents: Filters.byProperties(["AnalyticEventConfigs"]),
|
||||
KeyGenerator: Filters.byCode(/"binary"/),
|
||||
Buffers: Filters.byProperties(['Buffer', 'kMaxLength']),
|
||||
DeviceStore: Filters.byProperties(['getDevices']),
|
||||
SoftwareInfo: Filters.byProperties(["os"]),
|
||||
CurrentContext: Filters.byProperties(["setTagsContext"]),
|
||||
|
||||
/* Media Stuff (Audio/Video) */
|
||||
MediaDeviceInfo: Filters.byProperties(["Codecs", "SUPPORTED_BROWSERS"]),
|
||||
MediaInfo: Filters.byProperties(["getOutputVolume"]),
|
||||
MediaEngineInfo: Filters.byProperties(['MediaEngineFeatures']),
|
||||
VoiceInfo: Filters.byProperties(["EchoCancellation"]),
|
||||
VideoStream: Filters.byProperties(["getVideoStream"]),
|
||||
SoundModule: Filters.byProperties(["playSound"]),
|
||||
|
||||
/* Window, DOM, HTML */
|
||||
WindowInfo: Filters.byProperties(['isFocused', 'windowSize']),
|
||||
TagInfo: Filters.byProperties(['VALID_TAG_NAMES']),
|
||||
DOMInfo: Filters.byProperties(['canUseDOM']),
|
||||
HTMLUtils: Filters.byProperties(['htmlFor', 'sanitizeUrl']),
|
||||
|
||||
/* Locale/Location and Time */
|
||||
LocaleManager: Filters.byProperties(['setLocale']),
|
||||
Moment: Filters.byProperties(['parseZone']),
|
||||
LocationManager: Filters.byProperties(["createLocation"]),
|
||||
Timestamps: Filters.byProperties(["fromTimestamp"]),
|
||||
|
||||
/* Strings and Utils */
|
||||
Strings: Filters.byProperties(["TEXT", "TEXTAREA_PLACEHOLDER"]),
|
||||
StringFormats: Filters.byProperties(['a', 'z']),
|
||||
StringUtils: Filters.byProperties(["toASCII"]),
|
||||
|
||||
/* URLs and Utils */
|
||||
URLParser: Filters.byProperties(['Url', 'parse']),
|
||||
ExtraURLs: Filters.byProperties(['getArticleURL']),
|
||||
|
||||
|
||||
/* DOM/React Components */
|
||||
/* ==================== */
|
||||
UserSettingsWindow: Filters.byProperties(['open', 'updateAccount']),
|
||||
LayerManager: Filters.byProperties(['popLayer', 'pushLayer']),
|
||||
|
||||
/* Modals */
|
||||
ModalStack: Filters.byProperties(['push', 'update', 'pop', 'popWithKey']),
|
||||
UserProfileModals: Filters.byProperties(['fetchMutualFriends', 'setSection']),
|
||||
ConfirmModal: Filters.byPrototypeFields(['handleCancel', 'handleSubmit', 'handleMinorConfirm']),
|
||||
|
||||
/* Popouts */
|
||||
PopoutStack: Filters.byProperties(['open', 'close', 'closeAll']),
|
||||
PopoutOpener: Filters.byProperties(['openPopout']),
|
||||
EmojiPicker: Filters.byPrototypeFields(['onHoverEmoji', 'selectEmoji']),
|
||||
|
||||
/* Context Menus */
|
||||
ContextMenuActions: Filters.byCode(/CONTEXT_MENU_CLOSE/, c => c.close),
|
||||
ContextMenuItemsGroup: Filters.byCode(/itemGroup/),
|
||||
ContextMenuItem: Filters.byCode(/\.label\b.*\.hint\b.*\.action\b/),
|
||||
|
||||
/* In-Message Links */
|
||||
ExternalLink: Filters.byCode(/\.trusted\b/)
|
||||
};
|
||||
|
||||
export class WebpackModules {
|
||||
|
||||
/**
|
||||
* Finds a module using a filter function.
|
||||
* @param {Function} filter A function to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModule(filter, first = true) {
|
||||
const modules = this.getAllModules();
|
||||
const rm = [];
|
||||
for (let index in modules) {
|
||||
if (!modules.hasOwnProperty(index)) continue;
|
||||
const module = modules[index];
|
||||
const { exports } = module;
|
||||
let foundModule = null;
|
||||
|
||||
if (!exports) continue;
|
||||
if (exports.__esModule && exports.default && filter(exports.default)) foundModule = exports.default;
|
||||
if (filter(exports)) foundModule = exports;
|
||||
if (!foundModule) continue;
|
||||
if (first) return foundModule;
|
||||
rm.push(foundModule);
|
||||
}
|
||||
return first || rm.length == 0 ? undefined : rm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's name.
|
||||
* @param {String} name The name of the module
|
||||
* @param {Function} fallback A function to use to filter modules if not finding a known module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByName(name, fallback) {
|
||||
if (Cache.hasOwnProperty(name)) return Cache[name];
|
||||
if (KnownModules.hasOwnProperty(name)) fallback = KnownModules[name];
|
||||
if (!fallback) return undefined;
|
||||
const module = this.getModule(fallback, true);
|
||||
return module ? Cache[name] = module : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module by it's display name.
|
||||
* @param {String} name The display name of the module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByDisplayName(name) {
|
||||
return this.getModule(Filters.byDisplayName(name), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using it's code.
|
||||
* @param {RegEx} regex A regular expression to use to filter modules
|
||||
* @param {Boolean} first Whether to return the only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByRegex(regex, first = true) {
|
||||
return this.getModule(Filters.byCode(regex), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using properties on it's prototype.
|
||||
* @param {Array} props Properties to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByPrototypes(prototypes, first = true) {
|
||||
return this.getModule(Filters.byPrototypeFields(prototypes), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a module using it's own properties.
|
||||
* @param {Array} props Properties to use to filter modules
|
||||
* @param {Boolean} first Whether to return only the first matching module
|
||||
* @return {Any}
|
||||
*/
|
||||
static getModuleByProps(props, first = true) {
|
||||
return this.getModule(Filters.byProperties(props), first);
|
||||
}
|
||||
|
||||
/**
|
||||
* Discord's __webpack_require__ function.
|
||||
*/
|
||||
static get require() {
|
||||
if (this._require) return this._require;
|
||||
const id = 'bd-webpackmodules';
|
||||
const __webpack_require__ = window['webpackJsonp']([], {
|
||||
[id]: (module, exports, __webpack_require__) => exports.default = __webpack_require__
|
||||
}, [id]).default;
|
||||
delete __webpack_require__.m[id];
|
||||
delete __webpack_require__.c[id];
|
||||
return this._require = __webpack_require__;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all loaded modules.
|
||||
* @return {Array}
|
||||
*/
|
||||
static getAllModules() {
|
||||
return this.require.c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of known modules.
|
||||
* @return {Array}
|
||||
*/
|
||||
static listKnownModules() {
|
||||
return Object.keys(KnownModules);
|
||||
}
|
||||
|
||||
}
|
||||
export { DeprecationWarning as WebpackModules };
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
export default class {
|
||||
|
||||
}
|
|
@ -0,0 +1,441 @@
|
|||
/*
|
||||
* BetterDiscord Channel Struct
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { DiscordApi, DiscordApiModules as Modules } from 'modules';
|
||||
import { List, InsufficientPermissions } from 'structs';
|
||||
import { Guild } from './guild';
|
||||
import { Message } from './message';
|
||||
import { User, GuildMember } from './user';
|
||||
|
||||
const channels = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Channel
|
||||
*/
|
||||
export class Channel {
|
||||
|
||||
constructor(data) {
|
||||
if (channels.has(data)) return channels.get(data);
|
||||
channels.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
static from(channel) {
|
||||
switch (channel.type) {
|
||||
default: return new Channel(channel);
|
||||
case 0: return new GuildTextChannel(channel);
|
||||
case 1: return new DirectMessageChannel(channel);
|
||||
case 2: return new GuildVoiceChannel(channel);
|
||||
case 3: return new GroupChannel(channel);
|
||||
case 4: return new ChannelCategory(channel);
|
||||
}
|
||||
}
|
||||
|
||||
static fromId(id) {
|
||||
const channel = Modules.ChannelStore.getChannel(id);
|
||||
if (channel) return Channel.from(channel);
|
||||
}
|
||||
|
||||
static get GuildChannel() { return GuildChannel }
|
||||
static get GuildTextChannel() { return GuildTextChannel }
|
||||
static get GuildVoiceChannel() { return GuildVoiceChannel }
|
||||
static get ChannelCategory() { return ChannelCategory }
|
||||
static get PrivateChannel() { return PrivateChannel }
|
||||
static get DirectMessageChannel() { return DirectMessageChannel }
|
||||
static get GroupChannel() { return GroupChannel }
|
||||
|
||||
get id() { return this.discordObject.id }
|
||||
get applicationId() { return this.discordObject.application_id }
|
||||
get type() { return this.discordObject.type }
|
||||
get name() { return this.discordObject.name }
|
||||
|
||||
/**
|
||||
* Send a message in this channel.
|
||||
* @param {String} content The new message's content
|
||||
* @param {Boolean} parse Whether to parse the message or send it as it is
|
||||
* @return {Promise => Message}
|
||||
*/
|
||||
async sendMessage(content, parse = false) {
|
||||
if (this.assertPermissions) this.assertPermissions('SEND_MESSAGES', Modules.DiscordPermissions.VIEW_CHANNEL | Modules.DiscordPermissions.SEND_MESSAGES);
|
||||
|
||||
this.select();
|
||||
|
||||
if (parse) content = Modules.MessageParser.parse(this.discordObject, content);
|
||||
else content = {content};
|
||||
|
||||
const response = await Modules.MessageActions._sendMessage(this.id, content);
|
||||
return Message.from(Modules.MessageStore.getMessage(this.id, response.body.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a bot message in this channel that only the current user can see.
|
||||
* @param {String} content The new message's content
|
||||
* @return {Message}
|
||||
*/
|
||||
sendBotMessage(content) {
|
||||
this.select();
|
||||
const message = Modules.MessageParser.createBotMessage(this.id, content);
|
||||
Modules.MessageActions.receiveMessage(this.id, message);
|
||||
return Message.from(Modules.MessageStore.getMessage(this.id, message.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of messages in this channel.
|
||||
* @type {List<Message>}
|
||||
*/
|
||||
get messages() {
|
||||
const messages = Modules.MessageStore.getMessages(this.id).toArray();
|
||||
return List.from(messages, m => Message.from(m));
|
||||
}
|
||||
|
||||
/**
|
||||
* Jumps to the latest message in this channel.
|
||||
*/
|
||||
jumpToPresent() {
|
||||
if (this.assertPermissions) this.assertPermissions('VIEW_CHANNEL', Modules.DiscordPermissions.VIEW_CHANNEL);
|
||||
if (this.hasMoreAfter) Modules.MessageActions.jumpToPresent(this.id, Modules.DiscordConstants.MAX_MESSAGES_PER_CHANNEL);
|
||||
else this.messages[this.messages.length - 1].jumpTo(false);
|
||||
}
|
||||
|
||||
get hasMoreAfter() {
|
||||
return Modules.MessageStore.getMessages(this.id).hasMoreAfter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an invite in this channel.
|
||||
* @param {String} code The invite code
|
||||
* @return {Promise => Messaage}
|
||||
*/
|
||||
async sendInvite(code) {
|
||||
if (this.assertPermissions) this.assertPermissions('SEND_MESSAGES', Modules.DiscordPermissions.VIEW_CHANNEL | Modules.DiscordPermissions.SEND_MESSAGES);
|
||||
const response = Modules.MessageActions.sendInvite(this.id, code);
|
||||
return Message.from(Modules.MessageStore.getMessage(this.id, response.body.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens this channel in the UI.
|
||||
*/
|
||||
select() {
|
||||
if (this.assertPermissions) this.assertPermissions('VIEW_CHANNEL', Modules.DiscordPermissions.VIEW_CHANNEL);
|
||||
Modules.NavigationUtils.transitionToGuild(this.guildId ? this.guildId : Modules.DiscordConstants.ME, this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this channel is currently selected.
|
||||
* @type {Boolean}
|
||||
*/
|
||||
get isSelected() {
|
||||
return DiscordApi.currentChannel === this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel.
|
||||
* @return {Promise}
|
||||
*/
|
||||
async updateChannel(body) {
|
||||
if (this.assertPermissions) this.assertPermissions('MANAGE_CHANNELS', Modules.DiscordPermissions.MANAGE_CHANNELS);
|
||||
const response = await Modules.APIModule.patch({
|
||||
url: `${Modules.DiscordConstants.Endpoints.CHANNELS}/${this.id}`,
|
||||
body
|
||||
});
|
||||
|
||||
this.discordObject = Modules.ChannelStore.getChannel(this.id);
|
||||
channels.set(this.discordObject, this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export class PermissionOverwrite {
|
||||
constructor(data, channel_id) {
|
||||
this.discordObject = data;
|
||||
this.channelId = channel_id;
|
||||
}
|
||||
|
||||
static from(data, channel_id) {
|
||||
switch (data.type) {
|
||||
default: return new PermissionOverwrite(data, channel_id);
|
||||
case 'role': return new RolePermissionOverwrite(data, channel_id);
|
||||
case 'member': return new MemberPermissionOverwrite(data, channel_id);
|
||||
}
|
||||
}
|
||||
|
||||
static get RolePermissionOverwrite() { return RolePermissionOverwrite }
|
||||
static get MemberPermissionOverwrite() { return MemberPermissionOverwrite }
|
||||
|
||||
get type() { return this.discordObject.type }
|
||||
get allow() { return this.discordObject.allow }
|
||||
get deny() { return this.discordObject.deny }
|
||||
|
||||
get channel() {
|
||||
return Channel.fromId(this.channelId);
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return this.channel ? this.channel.guild : null;
|
||||
}
|
||||
}
|
||||
|
||||
export class RolePermissionOverwrite extends PermissionOverwrite {
|
||||
get roleId() { return this.discordObject.id }
|
||||
|
||||
get role() {
|
||||
return this.guild ? this.guild.roles.find(r => r.id === this.roleId) : null;
|
||||
}
|
||||
}
|
||||
|
||||
export class MemberPermissionOverwrite extends PermissionOverwrite {
|
||||
get memberId() { return this.discordObject.id }
|
||||
|
||||
get member() {
|
||||
return GuildMember.fromId(this.memberId);
|
||||
}
|
||||
}
|
||||
|
||||
export class GuildChannel extends Channel {
|
||||
static get PermissionOverwrite() { return PermissionOverwrite }
|
||||
|
||||
get guildId() { return this.discordObject.guild_id }
|
||||
get parentId() { return this.discordObject.parent_id } // Channel category
|
||||
get position() { return this.discordObject.position }
|
||||
get nicks() { return this.discordObject.nicks }
|
||||
|
||||
checkPermissions(perms) {
|
||||
return Modules.PermissionUtils.can(perms, DiscordApi.currentUser, this.discordObject);
|
||||
}
|
||||
|
||||
assertPermissions(name, perms) {
|
||||
if (!this.checkPermissions(perms)) throw new InsufficientPermissions(name);
|
||||
}
|
||||
|
||||
get category() {
|
||||
return Channel.fromId(this.parentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The current user's permissions on this channel.
|
||||
*/
|
||||
get permissions() {
|
||||
return Modules.GuildPermissions.getChannelPermissions(this.id);
|
||||
}
|
||||
|
||||
get permissionOverwrites() {
|
||||
return List.from(Object.entries(this.discordObject.permissionOverwrites), ([i, p]) => PermissionOverwrite.from(p, this.id));
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return Guild.fromId(this.guildId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this channel is the guild's default channel.
|
||||
*/
|
||||
get isDefaultChannel() {
|
||||
return Modules.GuildChannelsStore.getDefaultChannel(this.guildId).id === this.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens this channel's settings window.
|
||||
* @param {String} section The section to open (see DiscordConstants.ChannelSettingsSections)
|
||||
*/
|
||||
openSettings(section = 'OVERVIEW') {
|
||||
Modules.ChannelSettingsWindow.setSection(section);
|
||||
Modules.ChannelSettingsWindow.open(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel's name.
|
||||
* @param {String} name The channel's new name
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateName(name) {
|
||||
return this.updateChannel({ name });
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the channel's position.
|
||||
* @param {Number} position The channel's new position
|
||||
* @return {Promise}
|
||||
*/
|
||||
changeSortLocation(position = 0) {
|
||||
if (position instanceof GuildChannel) position = position.position;
|
||||
return this.updateChannel({ position });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel's permission overwrites.
|
||||
* @param {Array} permissionOverwrites An array of permission overwrites
|
||||
* @return {Promise}
|
||||
*/
|
||||
updatePermissionOverwrites(permission_overwrites) {
|
||||
return this.updateChannel({ permission_overwrites });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel's category.
|
||||
* @param {ChannelCategory} category The new channel category
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateCategory(category) {
|
||||
return this.updateChannel({ parent_id: category.id || category });
|
||||
}
|
||||
}
|
||||
|
||||
// Type 0 - GUILD_TEXT
|
||||
export class GuildTextChannel extends GuildChannel {
|
||||
get type() { return 'GUILD_TEXT' }
|
||||
get topic() { return this.discordObject.topic }
|
||||
get nsfw() { return this.discordObject.nsfw }
|
||||
|
||||
/**
|
||||
* Updates this channel's topic.
|
||||
* @param {String} topc The new channel topic
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateTopic(topic) {
|
||||
return this.updateChannel({ topic });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel's not-safe-for-work flag.
|
||||
* @param {Boolean} nsfw Whether the channel should be marked as NSFW
|
||||
* @return {Promise}
|
||||
*/
|
||||
setNsfw(nsfw = true) {
|
||||
return this.updateChannel({ nsfw });
|
||||
}
|
||||
|
||||
setNotNsfw() {
|
||||
return this.setNsfw(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Type 2 - GUILD_VOICE
|
||||
export class GuildVoiceChannel extends GuildChannel {
|
||||
get type() { return 'GUILD_VOICE' }
|
||||
get userLimit() { return this.discordObject.userLimit }
|
||||
get bitrate() { return this.discordObject.bitrate }
|
||||
|
||||
sendMessage() { throw new Error('Cannot send messages in a voice channel.'); }
|
||||
get messages() { return new List(); }
|
||||
jumpToPresent() { throw new Error('Cannot select a voice channel.'); }
|
||||
get hasMoreAfter() { return false; }
|
||||
sendInvite() { throw new Error('Cannot invite someone to a voice channel.'); }
|
||||
select() { throw new Error('Cannot select a voice channel.'); }
|
||||
|
||||
/**
|
||||
* Updates this channel's bitrate.
|
||||
* @param {Number} bitrate The new bitrate
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateBitrate(bitrate) {
|
||||
return this.updateChannel({ bitrate });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel's user limit.
|
||||
* @param {Number} userLimit The new user limit
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateUserLimit(user_limit) {
|
||||
return this.updateChannel({ user_limit });
|
||||
}
|
||||
}
|
||||
|
||||
// Type 4 - GUILD_CATEGORY
|
||||
export class ChannelCategory extends GuildChannel {
|
||||
get type() { return 'GUILD_CATEGORY' }
|
||||
get parentId() { return undefined }
|
||||
get category() { return undefined }
|
||||
|
||||
sendMessage() { throw new Error('Cannot send messages in a channel category.'); }
|
||||
get messages() { return new List(); }
|
||||
jumpToPresent() { throw new Error('Cannot select a channel category.'); }
|
||||
get hasMoreAfter() { return false; }
|
||||
sendInvite() { throw new Error('Cannot invite someone to a channel category.'); }
|
||||
select() { throw new Error('Cannot select a channel category.'); }
|
||||
updateCategory() { throw new Error('Cannot set a channel category on another channel category.'); }
|
||||
|
||||
/**
|
||||
* A list of channels in this category.
|
||||
*/
|
||||
get channels() {
|
||||
return List.from(this.guild.channels.filter(c => c.parentId === this.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the create channel modal for this guild.
|
||||
* @param {Number} type The type of channel to create - either 0 (text), 2 (voice) or 4 (category)
|
||||
* @param {GuildChannel} clone A channel to clone permissions of
|
||||
*/
|
||||
openCreateChannelModal(type, category, clone) {
|
||||
this.guild.openCreateChannelModal(type, this.id, this, clone);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a channel in this category.
|
||||
* @param {Number} type The type of channel to create - either 0 (text) or 2 (voice)
|
||||
* @param {String} name A name for the new channel
|
||||
* @param {Array} permission_overwrites An array of PermissionOverwrite-like objects - leave to use the permissions of the category
|
||||
* @return {Promise => GuildChannel}
|
||||
*/
|
||||
createChannel(type, name, permission_overwrites) {
|
||||
return this.guild.createChannel(type, name, this, permission_overwrites);
|
||||
}
|
||||
}
|
||||
|
||||
export class PrivateChannel extends Channel {
|
||||
get userLimit() { return this.discordObject.userLimit }
|
||||
get bitrate() { return this.discordObject.bitrate }
|
||||
}
|
||||
|
||||
// Type 1 - DM
|
||||
export class DirectMessageChannel extends PrivateChannel {
|
||||
get type() { return 'DM' }
|
||||
get recipientId() { return this.discordObject.recipients[0] }
|
||||
|
||||
/**
|
||||
* The other user of this direct message channel.
|
||||
*/
|
||||
get recipient() {
|
||||
return User.fromId(this.recipientId);
|
||||
}
|
||||
}
|
||||
|
||||
// Type 3 - GROUP_DM
|
||||
export class GroupChannel extends PrivateChannel {
|
||||
get ownerId() { return this.discordObject.ownerId }
|
||||
get type() { return 'GROUP_DM' }
|
||||
get name() { return this.discordObject.name }
|
||||
get icon() { return this.discordObject.icon }
|
||||
|
||||
/**
|
||||
* A list of the other members of this group direct message channel.
|
||||
*/
|
||||
get members() {
|
||||
return List.from(this.discordObject.recipients, id => User.fromId(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner of this group direct message channel. This is usually the person who created it.
|
||||
*/
|
||||
get owner() {
|
||||
return User.fromId(this.ownerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this channel's name.
|
||||
* @param {String} name The channel's new name
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateName(name) {
|
||||
return this.updateChannel({ name });
|
||||
}
|
||||
}
|
|
@ -0,0 +1,492 @@
|
|||
/*
|
||||
* BetterDiscord Guild Struct
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { DiscordApi, DiscordApiModules as Modules } from 'modules';
|
||||
import { List, InsufficientPermissions } from 'structs';
|
||||
import { FileUtils } from 'common';
|
||||
import { Channel } from './channel';
|
||||
import { GuildMember } from './user';
|
||||
|
||||
const roles = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Role
|
||||
*/
|
||||
export class Role {
|
||||
constructor(data, guild_id) {
|
||||
if (roles.has(data)) return roles.get(data);
|
||||
roles.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
this.guildId = guild_id;
|
||||
}
|
||||
|
||||
get id() { return this.discordObject.id }
|
||||
get name() { return this.discordObject.name }
|
||||
get position() { return this.discordObject.position }
|
||||
get originalPosition() { return this.discordObject.originalPosition }
|
||||
get permissions() { return this.discordObject.permissions }
|
||||
get managed() { return this.discordObject.managed }
|
||||
get mentionable() { return this.discordObject.mentionable }
|
||||
get hoist() { return this.discordObject.hoist }
|
||||
get colour() { return this.discordObject.color }
|
||||
get colourString() { return this.discordObject.colorString }
|
||||
|
||||
get guild() {
|
||||
return Guild.fromId(this.guildId);
|
||||
}
|
||||
|
||||
get members() {
|
||||
return this.guild.members.filter(m => m.roles.includes(this));
|
||||
}
|
||||
}
|
||||
|
||||
const emojis = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Emoji
|
||||
*/
|
||||
export class Emoji {
|
||||
constructor(data) {
|
||||
if (emojis.has(data)) return emojis.get(data);
|
||||
emojis.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
get id() { return this.discordObject.id }
|
||||
get guildId() { return this.discordObject.guild_id }
|
||||
get name() { return this.discordObject.name }
|
||||
get managed() { return this.discordObject.managed }
|
||||
get animated() { return this.discordObject.animated }
|
||||
get allNamesString() { return this.discordObject.allNamesString }
|
||||
get requireColons() { return this.discordObject.require_colons }
|
||||
get url() { return this.discordObject.url }
|
||||
get roles() { return this.discordObject.roles }
|
||||
|
||||
get guild() {
|
||||
return Guild.fromId(this.guildId);
|
||||
}
|
||||
}
|
||||
|
||||
const guilds = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Guild
|
||||
*/
|
||||
export class Guild {
|
||||
|
||||
constructor(data) {
|
||||
if (guilds.has(data)) return guilds.get(data);
|
||||
guilds.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
static from(data) {
|
||||
return new Guild(data);
|
||||
}
|
||||
|
||||
static fromId(id) {
|
||||
const guild = Modules.GuildStore.getGuild(id);
|
||||
if (guild) return Guild.from(guild);
|
||||
}
|
||||
|
||||
static get Role() { return Role }
|
||||
static get Emoji() { return Emoji }
|
||||
|
||||
get id() { return this.discordObject.id }
|
||||
get ownerId() { return this.discordObject.ownerId }
|
||||
get applicationId() { return this.discordObject.application_id }
|
||||
get systemChannelId() { return this.discordObject.systemChannelId }
|
||||
get name() { return this.discordObject.name }
|
||||
get acronym() { return this.discordObject.acronym }
|
||||
get icon() { return this.discordObject.icon }
|
||||
get joinedAt() { return this.discordObject.joinedAt }
|
||||
get verificationLevel() { return this.discordObject.verificationLevel }
|
||||
get mfaLevel() { return this.discordObject.mfaLevel }
|
||||
get large() { return this.discordObject.large }
|
||||
get lazy() { return this.discordObject.lazy }
|
||||
get voiceRegion() { return this.discordObject.region }
|
||||
get afkChannelId() { return this.discordObject.afkChannelId }
|
||||
get afkTimeout() { return this.discordObject.afkTimeout }
|
||||
get explicitContentFilter() { return this.discordObject.explicitContentFilter }
|
||||
get defaultMessageNotifications() { return this.discordObject.defaultMessageNotifications }
|
||||
get splash() { return this.discordObject.splash }
|
||||
get features() { return this.discordObject.features }
|
||||
|
||||
get owner() {
|
||||
return this.members.find(m => m.userId === this.ownerId);
|
||||
}
|
||||
|
||||
get roles() {
|
||||
return List.from(Object.entries(this.discordObject.roles), ([i, r]) => new Role(r, this.id))
|
||||
.sort((r1, r2) => r1.position === r2.position ? 0 : r1.position > r2.position ? 1 : -1);
|
||||
}
|
||||
|
||||
get channels() {
|
||||
const channels = Modules.GuildChannelsStore.getChannels(this.id);
|
||||
const returnChannels = new List();
|
||||
for (const category in channels) {
|
||||
if (channels.hasOwnProperty(category)) {
|
||||
if (!Array.isArray(channels[category])) continue;
|
||||
const channelList = channels[category];
|
||||
for (const channel of channelList) {
|
||||
// For some reason Discord adds a new category with the ID "null" and name "Uncategorized"
|
||||
if (channel.channel.id === 'null') continue;
|
||||
returnChannels.push(Channel.from(channel.channel));
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnChannels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Channels that don't have a parent. (Channel categories and any text/voice channel not in one.)
|
||||
*/
|
||||
get mainChannels() {
|
||||
return this.channels.filter(c => !c.parentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The guild's default channel. (Usually the first in the list.)
|
||||
*/
|
||||
get defaultChannel() {
|
||||
return Channel.from(Modules.GuildChannelsStore.getDefaultChannel(this.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* The guild's AFK channel.
|
||||
*/
|
||||
get afkChannel() {
|
||||
return this.afkChannelId ? Channel.fromId(this.afkChannelId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel system messages are sent to.
|
||||
*/
|
||||
get systemChannel() {
|
||||
return this.systemChannelId ? Channel.fromId(this.systemChannelId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of GuildMember objects.
|
||||
*/
|
||||
get members() {
|
||||
const members = Modules.GuildMemberStore.getMembers(this.id);
|
||||
return List.from(members, m => new GuildMember(m, this.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* The current user as a GuildMember of this guild.
|
||||
*/
|
||||
get currentUser() {
|
||||
return this.members.find(m => m.user === DiscordApi.currentUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* The total number of members in the guild.
|
||||
*/
|
||||
get memberCount() {
|
||||
return Modules.MemberCountStore.getMemberCount(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* An array of the guild's custom emojis.
|
||||
*/
|
||||
get emojis() {
|
||||
return List.from(Modules.EmojiUtils.getGuildEmoji(this.id), e => new Emoji(e, this.id));
|
||||
}
|
||||
|
||||
checkPermissions(perms) {
|
||||
return Modules.PermissionUtils.can(perms, DiscordApi.currentUser, this.discordObject);
|
||||
}
|
||||
|
||||
assertPermissions(name, perms) {
|
||||
if (!this.checkPermissions(perms)) throw new InsufficientPermissions(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* The current user's permissions on this guild.
|
||||
*/
|
||||
get permissions() {
|
||||
return Modules.GuildPermissions.getGuildPermissions(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the GuildMember object for a user.
|
||||
* @param {User|GuildMember|Number} user A User or GuildMember object or a user ID
|
||||
* @return {GuildMember}
|
||||
*/
|
||||
getMember(user) {
|
||||
const member = Modules.GuildMemberStore.getMember(this.id, user.userId || user.id || user);
|
||||
if (member) return new GuildMember(member, this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a user is a member of this guild.
|
||||
* @param {User|GuildMember|Number} user A User or GuildMember object or a user ID
|
||||
* @return {Boolean}
|
||||
*/
|
||||
isMember(user) {
|
||||
return Modules.GuildMemberStore.isMember(this.id, user.userId || user.id || user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user has not restricted direct messages from members of this guild.
|
||||
*/
|
||||
get allowPrivateMessages() {
|
||||
return !DiscordApi.UserSettings.restrictedGuildIds.includes(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks all messages in the guild as read.
|
||||
*/
|
||||
markAsRead() {
|
||||
Modules.GuildActions.markGuildAsRead(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects the guild in the UI.
|
||||
*/
|
||||
select() {
|
||||
Modules.GuildActions.selectGuild(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this guild is currently selected.
|
||||
*/
|
||||
get isSelected() {
|
||||
return DiscordApi.currentGuild === this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens this guild's settings window.
|
||||
* @param {String} section The section to open (see DiscordConstants.GuildSettingsSections)
|
||||
*/
|
||||
openSettings(section = 'OVERVIEW') {
|
||||
Modules.GuildSettingsWindow.setSection(section);
|
||||
Modules.GuildSettingsWindow.open(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks members who don't have any roles and haven't been seen in the number of days passed.
|
||||
* @param {Number} days
|
||||
*/
|
||||
pruneMembers(days) {
|
||||
this.assertPermissions('KICK_MEMBERS', Modules.DiscordPermissions.KICK_MEMBERS);
|
||||
Modules.PruneMembersModal.prune(this.id, days);
|
||||
}
|
||||
|
||||
openPruneMumbersModal() {
|
||||
this.assertPermissions('KICK_MEMBERS', Modules.DiscordPermissions.KICK_MEMBERS);
|
||||
Modules.PruneMembersModal.open(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the create channel modal for this guild.
|
||||
* @param {Number} type The type of channel to create - either 0 (text), 2 (voice) or 4 (category)
|
||||
* @param {ChannelCategory} category The category to create the channel in
|
||||
* @param {GuildChannel} clone A channel to clone permissions, topic, bitrate and user limit of
|
||||
*/
|
||||
openCreateChannelModal(type, category, clone) {
|
||||
this.assertPermissions('MANAGE_CHANNELS', Modules.DiscordPermissions.MANAGE_CHANNELS);
|
||||
Modules.CreateChannelModal.open(type, this.id, category ? category.id : undefined, clone ? clone.id : undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a channel in this guild.
|
||||
* @param {Number} type The type of channel to create - either 0 (text), 2 (voice) or 4 (category)
|
||||
* @param {String} name A name for the new channel
|
||||
* @param {ChannelCategory} category The category to create the channel in
|
||||
* @param {Array} permission_overwrites An array of PermissionOverwrite-like objects - leave to use the permissions of the category
|
||||
* @return {Promise => GuildChannel}
|
||||
*/
|
||||
async createChannel(type, name, category, permission_overwrites) {
|
||||
this.assertPermissions('MANAGE_CHANNELS', Modules.DiscordPermissions.MANAGE_CHANNELS);
|
||||
const response = await Modules.APIModule.post({
|
||||
url: Modules.DiscordConstants.Endpoints.GUILD_CHANNELS(this.id),
|
||||
body: {
|
||||
type, name,
|
||||
parent_id: category ? category.id : undefined,
|
||||
permission_overwrites: permission_overwrites ? permission_overwrites.map(p => ({
|
||||
type: p.type,
|
||||
id: (p.type === 'user' ? p.userId : p.roleId) || p.id,
|
||||
allow: p.allow,
|
||||
deny: p.deny
|
||||
})) : undefined
|
||||
}
|
||||
});
|
||||
|
||||
return Channel.fromId(response.body.id);
|
||||
}
|
||||
|
||||
openNotificationSettingsModal() {
|
||||
Modules.NotificationSettingsModal.open(this.id);
|
||||
}
|
||||
|
||||
openPrivacySettingsModal() {
|
||||
Modules.PrivacySettingsModal.open(this.id);
|
||||
}
|
||||
|
||||
nsfwAgree() {
|
||||
Modules.GuildActions.nsfwAgree(this.id);
|
||||
}
|
||||
|
||||
nsfwDisagree() {
|
||||
Modules.GuildActions.nsfwDisagree(this.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the guild's position in the list.
|
||||
* @param {Number} index The new position
|
||||
*/
|
||||
changeSortLocation(index) {
|
||||
Modules.GuildActions.move(DiscordApi.guildPositions.indexOf(this.id), index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild.
|
||||
* @return {Promise}
|
||||
*/
|
||||
async updateGuild(body) {
|
||||
this.assertPermissions('MANAGE_GUILD', Modules.DiscordPermissions.MANAGE_GUILD);
|
||||
const response = await Modules.APIModule.patch({
|
||||
url: Modules.DiscordConstants.Endpoints.GUILD(this.id),
|
||||
body
|
||||
});
|
||||
|
||||
this.discordObject = Modules.GuildStore.getGuild(this.id);
|
||||
guilds.set(this.discordObject, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's name.
|
||||
* @param {String} name The new name
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateName(name) {
|
||||
return this.updateGuild({ name });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's voice region.
|
||||
* @param {String} region The ID of the new voice region (obtainable via the API - see https://discordapp.com/developers/docs/resources/voice#list-voice-regions)
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateVoiceRegion(region) {
|
||||
return this.updateGuild({ region });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's verification level.
|
||||
* @param {Number} verificationLevel The new verification level (see https://discordapp.com/developers/docs/resources/guild#guild-object-verification-level)
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateVerificationLevel(verification_level) {
|
||||
return this.updateGuild({ verification_level });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's default message notification level.
|
||||
* @param {Number} defaultMessageNotifications The new default notification level (0: all messages, 1: only mentions)
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateDefaultMessageNotifications(default_message_notifications) {
|
||||
return this.updateGuild({ default_message_notifications });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's explicit content filter level.
|
||||
* @param {Number} explicitContentFilter The new explicit content filter level (0: disabled, 1: members without roles, 2: everyone)
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateExplicitContentFilter(explicit_content_filter) {
|
||||
return this.updateGuild({ explicit_content_filter });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's AFK channel.
|
||||
* @param {GuildVoiceChannel} afkChannel The new AFK channel
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateAfkChannel(afk_channel) {
|
||||
return this.updateGuild({ afk_channel_id: afk_channel.id || afk_channel });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's AFK timeout.
|
||||
* @param {Number} afkTimeout The new AFK timeout
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateAfkTimeout(afk_timeout) {
|
||||
return this.updateGuild({ afk_timeout });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's icon.
|
||||
* @param {Buffer|String} icon A buffer/base 64 encoded 128x128 JPEG image
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateIcon(icon) {
|
||||
return this.updateGuild({ icon: typeof icon === 'string' ? icon : icon.toString('base64') });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's icon using a local file.
|
||||
* TODO
|
||||
* @param {String} icon_path The path to the new icon
|
||||
* @return {Promise}
|
||||
*/
|
||||
async updateIconFromFile(icon_path) {
|
||||
const buffer = await FileUtils.readFileBuffer(icon_path);
|
||||
return this.updateIcon(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's owner. (Should plugins really ever need to do this?)
|
||||
* @param {User|GuildMember} owner The user/guild member to transfer ownership to
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateOwner(owner) {
|
||||
return this.updateGuild({ owner_id: owner.user ? owner.user.id : owner.id || owner });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's splash image.
|
||||
* (I don't know what this is actually used for. The API documentation says it's VIP-only.)
|
||||
* @param {Buffer|String} icon A buffer/base 64 encoded 128x128 JPEG image
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateSplash(splash) {
|
||||
return this.updateGuild({ splash: typeof splash === 'string' ? splash : splash.toString('base64') });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's splash image using a local file.
|
||||
* TODO
|
||||
* @param {String} splash_path The path to the new splash
|
||||
* @return {Promise}
|
||||
*/
|
||||
async updateSplashFromFile(splash_path) {
|
||||
const buffer = await FileUtils.readFileBuffer(splash_path);
|
||||
return this.updateSplash(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this guild's system channel.
|
||||
* @param {GuildTextChannel} systemChannel The new system channel
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateSystemChannel(system_channel) {
|
||||
return this.updateGuild({ system_channel_id: system_channel.id || system_channel });
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,319 @@
|
|||
/**
|
||||
* BetterDiscord Message Struct
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { DiscordApi, DiscordApiModules as Modules } from 'modules';
|
||||
import { List, InsufficientPermissions } from 'structs';
|
||||
import { Channel } from './channel';
|
||||
import { User } from './user';
|
||||
|
||||
const reactions = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Reaction
|
||||
*/
|
||||
export class Reaction {
|
||||
constructor(data, message_id, channel_id) {
|
||||
if (reactions.has(data)) return reactions.get(data);
|
||||
reactions.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
this.messageId = message_id;
|
||||
this.channelId = channel_id;
|
||||
}
|
||||
|
||||
get emoji() {
|
||||
const id = this.discordObject.emoji.id;
|
||||
if (!id || !this.guild) return this.discordObject.emoji;
|
||||
return this.guild.emojis.find(e => e.id === id);
|
||||
}
|
||||
|
||||
get count() { return this.discordObject.count }
|
||||
get me() { return this.discordObject.me }
|
||||
|
||||
get channel() {
|
||||
return Channel.fromId(this.channel_id);
|
||||
}
|
||||
|
||||
get message() {
|
||||
return this.channel ? this.channel.messages.find(m => m.id === this.messageId) : null;
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return this.channel ? this.channel.guild : null;
|
||||
}
|
||||
}
|
||||
|
||||
const embeds = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Embed
|
||||
*/
|
||||
export class Embed {
|
||||
constructor(data, message_id, channel_id) {
|
||||
if (embeds.has(data)) return embeds.get(data);
|
||||
embeds.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
this.messageId = message_id;
|
||||
this.channelId = channel_id;
|
||||
}
|
||||
|
||||
get title() { return this.discordObject.title }
|
||||
get type() { return this.discordObject.type }
|
||||
get description() { return this.discordObject.description }
|
||||
get url() { return this.discordObject.url }
|
||||
get timestamp() { return this.discordObject.timestamp }
|
||||
get colour() { return this.discordObject.color }
|
||||
get footer() { return this.discordObject.footer }
|
||||
get image() { return this.discordObject.image }
|
||||
get thumbnail() { return this.discordObject.thumbnail }
|
||||
get video() { return this.discordObject.video }
|
||||
get provider() { return this.discordObject.provider }
|
||||
get author() { return this.discordObject.author }
|
||||
get fields() { return this.discordObject.fields }
|
||||
|
||||
get channel() {
|
||||
return Channel.fromId(this.channelId);
|
||||
}
|
||||
|
||||
get message() {
|
||||
return this.channel ? this.channel.messages.find(m => m.id === this.messageId) : null;
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return this.channel ? this.channel.guild : null;
|
||||
}
|
||||
}
|
||||
|
||||
const messages = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Message
|
||||
*/
|
||||
export class Message {
|
||||
|
||||
constructor(data) {
|
||||
if (messages.has(data)) return messages.get(data);
|
||||
messages.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
static from(data) {
|
||||
switch (data.type) {
|
||||
default: return new Message(data);
|
||||
case 0: return new DefaultMessage(data);
|
||||
case 1: return new RecipientAddMessage(data);
|
||||
case 2: return new RecipientRemoveMessage(data);
|
||||
case 3: return new CallMessage(data);
|
||||
case 4: return new GroupChannelNameChangeMessage(data);
|
||||
case 5: return new GroupChannelIconChangeMessage(data);
|
||||
case 6: return new MessagePinnedMessage(data);
|
||||
case 7: return new GuildMemberJoinMessage(data);
|
||||
}
|
||||
}
|
||||
|
||||
static get DefaultMessage() { return DefaultMessage }
|
||||
static get RecipientAddMessage() { return RecipientAddMessage }
|
||||
static get RecipientRemoveMessage() { return RecipientRemoveMessage }
|
||||
static get CallMessage() { return CallMessage }
|
||||
static get GroupChannelNameChangeMessage() { return GroupChannelNameChangeMessage }
|
||||
static get GroupChannelIconChangeMessage() { return GroupChannelIconChangeMessage }
|
||||
static get MessagePinnedMessage() { return MessagePinnedMessage }
|
||||
static get GuildMemberJoinMessage() { return GuildMemberJoinMessage }
|
||||
|
||||
static get Reaction() { return Reaction }
|
||||
static get Embed() { return Embed }
|
||||
|
||||
get id() { return this.discordObject.id }
|
||||
get channelId() { return this.discordObject.channel_id }
|
||||
get nonce() { return this.discordObject.nonce }
|
||||
get type() { return this.discordObject.type }
|
||||
get timestamp() { return this.discordObject.timestamp }
|
||||
get state() { return this.discordObject.state }
|
||||
get nick() { return this.discordObject.nick }
|
||||
get colourString() { return this.discordObject.colorString }
|
||||
|
||||
get author() {
|
||||
if (this.discordObject.author && !this.webhookId) return User.from(this.discordObject.author);
|
||||
return null;
|
||||
}
|
||||
|
||||
get channel() {
|
||||
return Channel.fromId(this.channelId);
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return this.channel ? this.channel.guild : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the message.
|
||||
* @return {Promise}
|
||||
*/
|
||||
delete() {
|
||||
if (!this.isDeletable) throw new Error(`Message type ${this.type} is not deletable.`);
|
||||
if (this.author === DiscordApi.currentUser) {}
|
||||
else if (this.channel.assertPermissions) this.channel.assertPermissions('MANAGE_MESSAGES', Modules.DiscordPermissions.MANAGE_MESSAGES);
|
||||
else if (!this.channel.owner === DiscordApi.currentUser) throw new InsufficientPermissions('MANAGE_MESSAGES');
|
||||
|
||||
return Modules.APIModule.delete(`${Modules.DiscordConstants.Endpoints.MESSAGES(this.channelId)}/${this.id}`);
|
||||
}
|
||||
|
||||
get isDeletable() {
|
||||
return this.type === 'DEFAULT' || this.type === 'CHANNEL_PINNED_MESSAGE' || this.type === 'GUILD_MEMBER_JOIN';
|
||||
}
|
||||
|
||||
/**
|
||||
* Jumps to the message.
|
||||
*/
|
||||
jumpTo(flash = true) {
|
||||
Modules.MessageActions.jumpToMessage(this.channelId, this.id, flash);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Class representing a default Discord Message
|
||||
*/
|
||||
export class DefaultMessage extends Message {
|
||||
get webhookId() { return this.discordObject.webhookId }
|
||||
get type() { return 'DEFAULT' }
|
||||
get content() { return this.discordObject.content }
|
||||
get contentParsed() { return this.discordObject.contentParsed }
|
||||
get inviteCodes() { return this.discordObject.invites }
|
||||
get attachments() { return this.discordObject.attachments }
|
||||
get mentionIds() { return this.discordObject.mentions }
|
||||
get mentionRoleIds() { return this.discordObject.mentionRoles }
|
||||
get mentionEveryone() { return this.discordObject.mentionEveryone }
|
||||
get editedTimestamp() { return this.discordObject.editedTimestamp }
|
||||
get tts() { return this.discordObject.tts }
|
||||
get mentioned() { return this.discordObject.mentioned }
|
||||
get bot() { return this.discordObject.bot }
|
||||
get blocked() { return this.discordObject.blocked }
|
||||
get pinned() { return this.discordObject.pinned }
|
||||
get activity() { return this.discordObject.activity }
|
||||
get application() { return this.discordObject.application }
|
||||
|
||||
get webhook() {
|
||||
return this.webhookId ? this.discordObject.author : null;
|
||||
}
|
||||
|
||||
get mentions() {
|
||||
return List.from(this.mentionIds, id => User.fromId(id));
|
||||
}
|
||||
|
||||
get mention_roles() {
|
||||
return List.from(this.mentionRoleIds, id => this.guild.roles.find(r => r.id === id));
|
||||
}
|
||||
|
||||
get embeds() {
|
||||
return List.from(this.discordObject.embeds, r => new Embed(r, this.id, this.channelId));
|
||||
}
|
||||
|
||||
get reactions() {
|
||||
return List.from(this.discordObject.reactions, r => new Reaction(r, this.id, this.channelId));
|
||||
}
|
||||
|
||||
get edited() {
|
||||
return !!this.editedTimestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Programmatically update the message's content.
|
||||
* @param {String} content The message's new content
|
||||
* @param {Boolean} parse Whether to parse the message or update it as it is
|
||||
* @return {Promise}
|
||||
*/
|
||||
async edit(content, parse = false) {
|
||||
if (this.author !== DiscordApi.currentUser) throw new Error('Cannot edit messages sent by other users.');
|
||||
if (parse) content = Modules.MessageParser.parse(this.discordObject, content);
|
||||
else content = {content};
|
||||
|
||||
const response = await Modules.APIModule.patch({
|
||||
url: `${Modules.DiscordConstants.Endpoints.MESSAGES(this.channelId)}/${this.id}`,
|
||||
body: content
|
||||
});
|
||||
|
||||
this.discordObject = Modules.MessageStore.getMessage(this.id, response.body.id);
|
||||
messages.set(this.discordObject, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the edit mode of the UI.
|
||||
* @param {String} content A string to show in the message text area - if empty the message's current content will be used
|
||||
*/
|
||||
startEdit(content) {
|
||||
if (this.author !== DiscordApi.currentUser) throw new Error('Cannot edit messages sent by other users.');
|
||||
Modules.MessageActions.startEditMessage(this.channelId, this.id, content || this.content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Exit the edit mode of the UI.
|
||||
*/
|
||||
endEdit() {
|
||||
Modules.MessageActions.endEditMessage();
|
||||
}
|
||||
}
|
||||
|
||||
export class RecipientAddMessage extends Message {
|
||||
get type() { return 'RECIPIENT_ADD' }
|
||||
get addedUserId() { return this.discordObject.mentions[0] }
|
||||
|
||||
get addedUser() {
|
||||
return User.fromId(this.addedUserId);
|
||||
}
|
||||
}
|
||||
|
||||
export class RecipientRemoveMessage extends Message {
|
||||
get type() { return 'RECIPIENT_REMOVE' }
|
||||
get removedUserId() { return this.discordObject.mentions[0] }
|
||||
|
||||
get removedUser() {
|
||||
return User.fromId(this.removedUserId);
|
||||
}
|
||||
|
||||
get userLeft() {
|
||||
return this.author === this.removedUser;
|
||||
}
|
||||
}
|
||||
|
||||
export class CallMessage extends Message {
|
||||
get type() { return 'CALL' }
|
||||
get mentionIds() { return this.discordObject.mentions }
|
||||
get call() { return this.discordObject.call }
|
||||
|
||||
get endedTimestamp() { return this.call.endedTimestamp }
|
||||
|
||||
get mentions() {
|
||||
return List.from(this.mentionIds, id => User.fromId(id));
|
||||
}
|
||||
|
||||
get participants() {
|
||||
return List.from(this.call.participants, id => User.fromId(id));
|
||||
}
|
||||
}
|
||||
|
||||
export class GroupChannelNameChangeMessage extends Message {
|
||||
get type() { return 'CHANNEL_NAME_CHANGE' }
|
||||
get newName() { return this.discordObject.content }
|
||||
}
|
||||
|
||||
export class GroupChannelIconChangeMessage extends Message {
|
||||
get type() { return 'CHANNEL_ICON_CHANGE' }
|
||||
}
|
||||
|
||||
export class MessagePinnedMessage extends Message {
|
||||
get type() { return 'CHANNEL_PINNED_MESSAGE' }
|
||||
}
|
||||
|
||||
export class GuildMemberJoinMessage extends Message {
|
||||
get type() { return 'GUILD_MEMBER_JOIN' }
|
||||
}
|
|
@ -0,0 +1,336 @@
|
|||
/*
|
||||
* BetterDiscord User Struct
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { DiscordApi, DiscordApiModules as Modules } from 'modules';
|
||||
import { List, InsufficientPermissions } from 'structs';
|
||||
import { Utils } from 'common';
|
||||
import { Guild } from './guild';
|
||||
import { Channel } from './channel';
|
||||
|
||||
const users = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord user
|
||||
*/
|
||||
export class User {
|
||||
|
||||
constructor(data) {
|
||||
if (users.has(data)) return users.get(data);
|
||||
users.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
}
|
||||
|
||||
static from(data) {
|
||||
return new User(data);
|
||||
}
|
||||
|
||||
static fromId(id) {
|
||||
const user = Modules.UserStore.getUser(id);
|
||||
if (user) return User.from(user);
|
||||
}
|
||||
|
||||
static get GuildMember() { return GuildMember }
|
||||
|
||||
get id() { return this.discordObject.id }
|
||||
get username() { return this.discordObject.username }
|
||||
get usernameLowerCase() { return this.discordObject.usernameLowerCase }
|
||||
get discriminator() { return this.discordObject.discriminator }
|
||||
get avatar() { return this.discordObject.avatar }
|
||||
get email() { return undefined }
|
||||
get phone() { return undefined }
|
||||
get flags() { return this.discordObject.flags }
|
||||
get isBot() { return this.discordObject.bot }
|
||||
get premium() { return this.discordObject.premium }
|
||||
get verified() { return this.discordObject.verified }
|
||||
get mfaEnabled() { return this.discordObject.mfaEnabled }
|
||||
get mobile() { return this.discordObject.mobile }
|
||||
|
||||
get tag() { return this.discordObject.tag }
|
||||
get avatarUrl() { return this.discordObject.avatarURL }
|
||||
get createdAt() { return this.discordObject.createdAt }
|
||||
|
||||
get isClamied() { return this.discordObject.isClaimed() }
|
||||
get isLocalBot() { return this.discordObject.isLocalBot() }
|
||||
get isPhoneVerified() { return this.discordObject.isPhoneVerified() }
|
||||
|
||||
get guilds() {
|
||||
return DiscordApi.guilds.filter(g => g.members.find(m => m.user === this));
|
||||
}
|
||||
|
||||
get status() {
|
||||
return Modules.UserStatusStore.getStatus(this.id);
|
||||
}
|
||||
|
||||
get activity() {
|
||||
// type can be either 0 (normal/rich presence game), 1 (streaming) or 2 (listening to Spotify)
|
||||
// (3 appears as watching but is undocumented)
|
||||
return Modules.UserStatusStore.getActivity(this.id);
|
||||
}
|
||||
|
||||
get note() {
|
||||
const note = Modules.UserNoteStore.getNote(this.id);
|
||||
return note ? note : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the note for this user.
|
||||
* @param {String} note The new note
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateNote(note) {
|
||||
return Modules.APIModule.put({
|
||||
url: `${Modules.DiscordConstants.Endpoints.NOTES}/${this.id}`,
|
||||
body: { note }
|
||||
});
|
||||
}
|
||||
|
||||
get privateChannel() {
|
||||
return DiscordApi.channels.find(c => c.type === 'DM' && c.recipientId === this.id);
|
||||
}
|
||||
|
||||
async ensurePrivateChannel() {
|
||||
if (DiscordApi.currentUser === this)
|
||||
throw new Error('Cannot create a direct message channel to the current user.');
|
||||
return Channel.fromId(await Modules.PrivateChannelActions.ensurePrivateChannel(DiscordApi.currentUser.id, this.id));
|
||||
}
|
||||
|
||||
async sendMessage(content, parse = true) {
|
||||
const channel = await this.ensurePrivateChannel();
|
||||
return channel.sendMessage(content, parse);
|
||||
}
|
||||
|
||||
get isFriend() {
|
||||
return Modules.RelationshipStore.isFriend(this.id);
|
||||
}
|
||||
|
||||
get isBlocked() {
|
||||
return Modules.RelationshipStore.isBlocked(this.id);
|
||||
}
|
||||
|
||||
addFriend() {
|
||||
Modules.RelationshipManager.addRelationship(this.id, {location: 'Context Menu'});
|
||||
}
|
||||
|
||||
removeFriend() {
|
||||
Modules.RelationshipManager.removeRelationship(this.id, {location: 'Context Menu'});
|
||||
}
|
||||
|
||||
block() {
|
||||
Modules.RelationshipManager.addRelationship(this.id, {location: 'Context Menu'}, Modules.DiscordConstants.RelationshipTypes.BLOCKED);
|
||||
}
|
||||
|
||||
unblock() {
|
||||
Modules.RelationshipManager.removeRelationship(this.id, {location: 'Context Menu'});
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the profile modal for this user.
|
||||
* @param {String} section The section to open (see DiscordConstants.UserProfileSections)
|
||||
*/
|
||||
openUserProfileModal(section = 'USER_INFO') {
|
||||
Modules.UserProfileModal.open(this.id);
|
||||
Modules.UserProfileModal.setSection(section);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const guild_members = new WeakMap();
|
||||
|
||||
/**
|
||||
* Class representing a Discord Guild Member
|
||||
*/
|
||||
export class GuildMember {
|
||||
constructor(data, guild_id) {
|
||||
if (guild_members.has(data)) return guild_members.get(data);
|
||||
guild_members.set(data, this);
|
||||
|
||||
this.discordObject = data;
|
||||
this.guildId = guild_id;
|
||||
}
|
||||
|
||||
get userId() { return this.discordObject.userId }
|
||||
get nickname() { return this.discordObject.nick }
|
||||
get colourString() { return this.discordObject.colorString }
|
||||
get hoistRoleId() { return this.discordObject.hoistRoleId }
|
||||
get roleIds() { return this.discordObject.roles }
|
||||
|
||||
get user() {
|
||||
return User.fromId(this.userId);
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this.nickname || this.user.username;
|
||||
}
|
||||
|
||||
get guild() {
|
||||
return Guild.fromId(this.guildId);
|
||||
}
|
||||
|
||||
get roles() {
|
||||
return List.from(this.roleIds, id => this.guild.roles.find(r => r.id === id))
|
||||
.sort((r1, r2) => r1.position === r2.position ? 0 : r1.position > r2.position ? 1 : -1);
|
||||
}
|
||||
|
||||
get hoistRole() {
|
||||
return this.guild.roles.find(r => r.id === this.hoistRoleId);
|
||||
}
|
||||
|
||||
checkPermissions(perms) {
|
||||
return Modules.PermissionUtils.can(perms, DiscordApi.currentUser.discordObject, this.guild.discordObject);
|
||||
}
|
||||
|
||||
assertPermissions(name, perms) {
|
||||
if (!this.checkPermissions(perms)) throw new InsufficientPermissions(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the modal to change this user's nickname.
|
||||
*/
|
||||
openChangeNicknameModal() {
|
||||
if (DiscordApi.currentUser === this.user)
|
||||
this.assertPermissions('CHANGE_NICKNAME', Modules.DiscordPermissions.CHANGE_NICKNAME);
|
||||
else this.assertPermissions('MANAGE_NICKNAMES', Modules.DiscordPermissions.MANAGE_NICKNAMES);
|
||||
|
||||
Modules.ChangeNicknameModal.open(this.guildId, this.userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the user's nickname on this guild.
|
||||
* @param {String} nickname The user's new nickname
|
||||
* @return {Promise}
|
||||
*/
|
||||
changeNickname(nick) {
|
||||
if (DiscordApi.currentUser === this.user)
|
||||
this.assertPermissions('CHANGE_NICKNAME', Modules.DiscordPermissions.CHANGE_NICKNAME);
|
||||
else this.assertPermissions('MANAGE_NICKNAMES', Modules.DiscordPermissions.MANAGE_NICKNAMES);
|
||||
|
||||
return Modules.APIModule.patch({
|
||||
url: `${Modules.DiscordConstants.Endpoints.GUILD_MEMBERS(this.guild_id)}/${DiscordApi.currentUser === this.user ? '@me/nick' : this.userId}`,
|
||||
body: { nick }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks this user from the guild.
|
||||
* @param {String} reason A reason to attach to the audit log entry
|
||||
* @return {Promise}
|
||||
*/
|
||||
kick(reason = '') {
|
||||
this.assertPermissions('KICK_MEMBERS', Modules.DiscordPermissions.KICK_MEMBERS);
|
||||
return Modules.GuildActions.kickUser(this.guildId, this.userId, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bans this user from the guild.
|
||||
* @param {Number} daysToDelete The number of days of the user's recent message history to delete
|
||||
* @param {String} reason A reason to attach to the audit log entry
|
||||
* @return {Promise}
|
||||
*/
|
||||
ban(daysToDelete = 1, reason = '') {
|
||||
this.assertPermissions('BAN_MEMBERS', Modules.DiscordPermissions.BAN_MEMBERS);
|
||||
return Modules.GuildActions.banUser(this.guildId, this.userId, daysToDelete, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the ban for this user.
|
||||
* @return {Promise}
|
||||
*/
|
||||
unban() {
|
||||
this.assertPermissions('BAN_MEMBERS', Modules.DiscordPermissions.BAN_MEMBERS);
|
||||
return Modules.GuildActions.unbanUser(this.guildId, this.userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves this user to another voice channel.
|
||||
* @param {GuildVoiceChannel} channel The channel to move this user to
|
||||
*/
|
||||
move(channel) {
|
||||
this.assertPermissions('MOVE_MEMBERS', Modules.DiscordPermissions.MOVE_MEMBERS);
|
||||
Modules.GuildActions.setChannel(this.guildId, this.userId, channel.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutes this user for everyone in the guild.
|
||||
*/
|
||||
mute(active = true) {
|
||||
this.assertPermissions('MUTE_MEMBERS', Modules.DiscordPermissions.MUTE_MEMBERS);
|
||||
Modules.GuildActions.setServerMute(this.guildId, this.userId, active);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmutes this user.
|
||||
*/
|
||||
unmute() {
|
||||
this.mute(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deafens this user.
|
||||
*/
|
||||
deafen(active = true) {
|
||||
this.assertPermissions('DEAFEN_MEMBERS', Modules.DiscordPermissions.DEAFEN_MEMBERS);
|
||||
Modules.GuildActions.setServerDeaf(this.guildId, this.userId, active);
|
||||
}
|
||||
|
||||
/**
|
||||
* Undeafens this user.
|
||||
*/
|
||||
undeafen() {
|
||||
this.deafen(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives this user a role.
|
||||
* @param {Role} role The role to add
|
||||
* @return {Promise}
|
||||
*/
|
||||
addRole(...roles) {
|
||||
const newRoles = this.roleIds.concat([]);
|
||||
let changed = false;
|
||||
for (const role of roles) {
|
||||
if (newRoles.includes(role.id || role)) continue;
|
||||
newRoles.push(role.id || role);
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
return this.updateRoles(newRoles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a role from this user.
|
||||
* @param {Role} role The role to remove
|
||||
* @return {Promise}
|
||||
*/
|
||||
removeRole(...roles) {
|
||||
const newRoles = this.roleIds.concat([]);
|
||||
let changed = false;
|
||||
for (const role of roles) {
|
||||
if (!newRoles.includes(role.id || role)) continue;
|
||||
Utils.removeFromArray(newRoles, role.id || role);
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
return this.updateRoles(newRoles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this user's roles.
|
||||
* @param {Array} roles An array of Role objects or role IDs
|
||||
* @return {Promise}
|
||||
*/
|
||||
updateRoles(roles) {
|
||||
roles = roles.map(r => r.id || r);
|
||||
return Modules.APIModule.patch({
|
||||
url: `${Modules.DiscordConstants.Endpoints.GUILD_MEMBERS(this.guildId)}/${this.userId}`,
|
||||
body: { roles }
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
export * from './discord/user';
|
||||
export * from './discord/guild';
|
||||
export * from './discord/channel';
|
||||
export * from './discord/message';
|
|
@ -17,22 +17,37 @@ export default class ErrorEvent extends Event {
|
|||
this.showStack = false; // For error modal
|
||||
}
|
||||
|
||||
/**
|
||||
* The module the error occured in.
|
||||
*/
|
||||
get module() {
|
||||
return this.args.module;
|
||||
}
|
||||
|
||||
/**
|
||||
* A message describing the error.
|
||||
*/
|
||||
get message() {
|
||||
return this.args.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* The original error object.
|
||||
*/
|
||||
get err() {
|
||||
return this.args.err;
|
||||
}
|
||||
|
||||
/**
|
||||
* A trace showing which functions were called when the error occured.
|
||||
*/
|
||||
get stackTrace() {
|
||||
return this.err.stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of event.
|
||||
*/
|
||||
get __eventType() {
|
||||
return 'error';
|
||||
}
|
||||
|
|
|
@ -17,14 +17,30 @@ export default class Event {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An object containing information about the event.
|
||||
*/
|
||||
get event() {
|
||||
return this.__eventInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra data associated with this event.
|
||||
*/
|
||||
get data() {
|
||||
return this.args.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first argument that was passed to the constructor, which contains information about the event.
|
||||
*/
|
||||
get args() {
|
||||
return this.event.args[0];
|
||||
}
|
||||
|
||||
get __eventType() { return null; }
|
||||
/**
|
||||
* The type of event.
|
||||
*/
|
||||
get __eventType() { return undefined; }
|
||||
|
||||
}
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
export { default as SettingUpdatedEvent } from './settingupdated';
|
||||
export { default as SettingsUpdatedEvent } from './settingsupdated';
|
||||
export { default as ErrorEvent } from './error';
|
||||
export { PermissionsError, InsufficientPermissions } from './permissionserror';
|
||||
|
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* BetterDiscord Permissions Error Struct
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import ErrorEvent from './error';
|
||||
|
||||
export class PermissionsError extends ErrorEvent {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'PermissionsError';
|
||||
}
|
||||
}
|
||||
|
||||
export class InsufficientPermissions extends PermissionsError {
|
||||
constructor(message) {
|
||||
super(`Missing Permission — ${message}`);
|
||||
this.name = 'InsufficientPermissions';
|
||||
}
|
||||
}
|
|
@ -12,10 +12,16 @@ import Event from './event';
|
|||
|
||||
export default class SettingsUpdatedEvent extends Event {
|
||||
|
||||
/**
|
||||
* An array of SettingUpdated events.
|
||||
*/
|
||||
get updatedSettings() {
|
||||
return this.args.updatedSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of event.
|
||||
*/
|
||||
get __eventType() {
|
||||
return 'settings-updated';
|
||||
}
|
||||
|
|
|
@ -12,38 +12,65 @@ import Event from './event';
|
|||
|
||||
export default class SettingUpdatedEvent extends Event {
|
||||
|
||||
/**
|
||||
* The set containing the setting that was updated.
|
||||
*/
|
||||
get set() {
|
||||
return this.args.set;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ID of the set containing the setting that was updated.
|
||||
*/
|
||||
get set_id() {
|
||||
return this.args.set.id;
|
||||
return this.set.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The category containing the setting that was updated.
|
||||
*/
|
||||
get category() {
|
||||
return this.args.category;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ID of the category containing the setting that was updated.
|
||||
*/
|
||||
get category_id() {
|
||||
return this.args.category.id;
|
||||
return this.category.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The setting that was updated.
|
||||
*/
|
||||
get setting() {
|
||||
return this.args.setting;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ID of the setting that was updated.
|
||||
*/
|
||||
get setting_id() {
|
||||
return this.args.setting.id;
|
||||
return this.setting.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The setting's new value.
|
||||
*/
|
||||
get value() {
|
||||
return this.args.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The setting's old value.
|
||||
*/
|
||||
get old_value() {
|
||||
return this.args.old_value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of event.
|
||||
*/
|
||||
get __eventType() {
|
||||
return 'setting-updated';
|
||||
}
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* BetterDiscord List
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Class representing a list.
|
||||
* @extends Array
|
||||
*/
|
||||
|
||||
export default class List extends Array {
|
||||
|
||||
get(...filters) {
|
||||
return this.find(item => {
|
||||
for (const filter of filters) {
|
||||
for (const key in filter) {
|
||||
if (filter.hasOwnProperty(key)) {
|
||||
if (item[key] !== filter[key]) return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -2,3 +2,4 @@ export { default as SettingsSet } from './settingsset';
|
|||
export { default as SettingsCategory } from './settingscategory';
|
||||
export { default as Setting } from './setting';
|
||||
export { default as SettingsScheme } from './settingsscheme';
|
||||
export * from './types';
|
||||
|
|
|
@ -8,28 +8,33 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Utils } from 'common';
|
||||
|
||||
export default class MultipleChoiceOption {
|
||||
|
||||
constructor(args) {
|
||||
this.args = args.args || args;
|
||||
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* This option's ID.
|
||||
*/
|
||||
get id() {
|
||||
return this.args.id || this.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* A string describing this option.
|
||||
*/
|
||||
get text() {
|
||||
return this.args.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* The value to return when this option is active.
|
||||
*/
|
||||
get value() {
|
||||
return this.args.value;
|
||||
}
|
||||
|
||||
clone() {
|
||||
return new MultipleChoiceOption(Utils.deepclone(this.args));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,8 +8,6 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { Utils } from 'common';
|
||||
|
||||
import BoolSetting from './types/bool';
|
||||
import StringSetting from './types/text';
|
||||
import NumberSetting from './types/number';
|
||||
|
@ -21,6 +19,9 @@ import KeybindSetting from './types/keybind';
|
|||
import FileSetting from './types/file';
|
||||
import GuildSetting from './types/guild';
|
||||
import ArraySetting from './types/array';
|
||||
import CollectionSetting from './types/collection';
|
||||
import KvpSetting from './types/kvp';
|
||||
import SecureKvpSetting from './types/securekvp';
|
||||
import CustomSetting from './types/custom';
|
||||
|
||||
export default class Setting {
|
||||
|
@ -28,6 +29,7 @@ export default class Setting {
|
|||
constructor(args, ...merge) {
|
||||
args = args.args || args;
|
||||
|
||||
if (args.type instanceof Array) args.subtype = args.type[0], args.type = 'collection';
|
||||
if (args.type === 'color') args.type = 'colour';
|
||||
|
||||
if (args.type === 'bool') return new BoolSetting(args, ...merge);
|
||||
|
@ -41,8 +43,11 @@ export default class Setting {
|
|||
else if (args.type === 'file') return new FileSetting(args, ...merge);
|
||||
else if (args.type === 'guild') return new GuildSetting(args, ...merge);
|
||||
else if (args.type === 'array') return new ArraySetting(args, ...merge);
|
||||
else if (args.type === 'collection') return new CollectionSetting(args, ...merge);
|
||||
else if (args.type === 'kvp') return new KvpSetting(args, ...merge);
|
||||
else if (args.type === 'securekvp') return new SecureKvpSetting(args, ...merge);
|
||||
else if (args.type === 'custom') return new CustomSetting(args, ...merge);
|
||||
else throw {message: `Setting type ${args.type} unknown`};
|
||||
throw {message: `Setting type ${args.type} unknown`};
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,27 +8,35 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import { SettingUpdatedEvent, SettingsUpdatedEvent } from 'structs';
|
||||
import { ClientLogger as Logger, AsyncEventEmitter } from 'common';
|
||||
import Setting from './setting';
|
||||
import BaseSetting from './types/basesetting';
|
||||
import { ClientLogger as Logger, AsyncEventEmitter } from 'common';
|
||||
import { SettingUpdatedEvent, SettingsUpdatedEvent } from 'structs';
|
||||
import SettingsProxy from './settingsproxy';
|
||||
|
||||
export default class SettingsCategory {
|
||||
export default class SettingsCategory extends AsyncEventEmitter {
|
||||
|
||||
constructor(args, ...merge) {
|
||||
this.emitter = new AsyncEventEmitter();
|
||||
this.args = args.args || args;
|
||||
super();
|
||||
|
||||
if (typeof args === 'string')
|
||||
args = {id: args};
|
||||
this.args = args.args || args || {};
|
||||
|
||||
this.args.id = this.args.id || this.args.category || 'default';
|
||||
this.args.name = this.args.name || this.args.category_name || this.id;
|
||||
this.type = this.args.type;
|
||||
|
||||
this.args.settings = this.settings.map(setting => new Setting(setting));
|
||||
|
||||
for (let newCategory of merge) {
|
||||
for (const newCategory of merge) {
|
||||
this._merge(newCategory);
|
||||
}
|
||||
|
||||
this.__settingUpdated = this.__settingUpdated.bind(this);
|
||||
this.__settingsUpdated = this.__settingsUpdated.bind(this);
|
||||
|
||||
for (let setting of this.settings) {
|
||||
for (const setting of this.settings) {
|
||||
setting.on('setting-updated', this.__settingUpdated);
|
||||
setting.on('settings-updated', this.__settingsUpdated);
|
||||
}
|
||||
|
@ -56,6 +64,10 @@ export default class SettingsCategory {
|
|||
return this.name;
|
||||
}
|
||||
|
||||
set name(value) {
|
||||
this.args.name = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Category type
|
||||
* Currently either "drawer", "static", or undefined.
|
||||
|
@ -64,6 +76,13 @@ export default class SettingsCategory {
|
|||
return this.args.type;
|
||||
}
|
||||
|
||||
set type(value) {
|
||||
if (!value) this.args.type = undefined;
|
||||
else if (value === 'drawer' || value === 'static')
|
||||
this.args.type = value;
|
||||
else throw {message: `Invalid category type ${value}`};
|
||||
}
|
||||
|
||||
/**
|
||||
* An array of settings in this category.
|
||||
*/
|
||||
|
@ -155,6 +174,14 @@ export default class SettingsCategory {
|
|||
await this.emit('removed-category', event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a proxy which can be used to access the category's values like a normal object.
|
||||
* @return {SettingsCategoryProxy}
|
||||
*/
|
||||
get proxy() {
|
||||
return this._proxy || (this._proxy = SettingsProxy.createProxy(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first setting where calling {function} returns true.
|
||||
* @param {Function} function A function to call to filter settings
|
||||
|
@ -189,7 +216,7 @@ export default class SettingsCategory {
|
|||
_merge(newCategory) {
|
||||
let updatedSettings = [];
|
||||
|
||||
for (let newSetting of newCategory.settings) {
|
||||
for (const newSetting of newCategory.settings) {
|
||||
const setting = this.settings.find(setting => setting.id === newSetting.id);
|
||||
if (!setting) {
|
||||
Logger.warn('SettingsCategory', `Trying to merge setting ${this.id}/${newSetting.id}, which does not exist.`);
|
||||
|
@ -216,7 +243,7 @@ export default class SettingsCategory {
|
|||
async merge(newCategory, emit_multi = true) {
|
||||
let updatedSettings = [];
|
||||
|
||||
for (let newSetting of newCategory.settings) {
|
||||
for (const newSetting of newCategory.settings) {
|
||||
const setting = this.settings.find(setting => setting.id === newSetting.id);
|
||||
if (!setting) {
|
||||
Logger.warn('SettingsCategory', `Trying to merge setting ${this.id}/${newSetting.id}, which does not exist.`);
|
||||
|
@ -244,7 +271,7 @@ export default class SettingsCategory {
|
|||
* Marks all settings in this set as saved (not changed).
|
||||
*/
|
||||
setSaved() {
|
||||
for (let setting of this.settings) {
|
||||
for (const setting of this.settings) {
|
||||
setting.setSaved();
|
||||
}
|
||||
}
|
||||
|
@ -276,8 +303,4 @@ export default class SettingsCategory {
|
|||
}, ...merge);
|
||||
}
|
||||
|
||||
on(...args) { return this.emitter.on(...args); }
|
||||
off(...args) { return this.emitter.removeListener(...args); }
|
||||
emit(...args) { return this.emitter.emit(...args); }
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,109 @@
|
|||
/**
|
||||
* BetterDiscord Settings Proxy
|
||||
* Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks
|
||||
* All rights reserved.
|
||||
* https://betterdiscord.net
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import SettingsSet from './settingsset';
|
||||
import SettingsCategory from './settingscategory';
|
||||
|
||||
const setHandler = {
|
||||
get({ set }, category_id) {
|
||||
const category = set.getCategory(category_id);
|
||||
if (category) return SettingsProxy.createProxy(category);
|
||||
|
||||
const setting = set.getSetting(category_id);
|
||||
if (setting) return setting.value;
|
||||
},
|
||||
set({ set }, category_id, values) {
|
||||
const category = set.getCategory(category_id);
|
||||
if (category) return category.merge(values);
|
||||
|
||||
const setting = set.getSetting(category_id);
|
||||
if (setting) return setting.value = values;
|
||||
},
|
||||
has({ set }, category_id) {
|
||||
const category = set.getCategory(category_id);
|
||||
if (category) return true;
|
||||
|
||||
const setting = set.getSetting(category_id);
|
||||
if (setting) return true;
|
||||
},
|
||||
getPrototypeOf({ set }) {
|
||||
return SettingsSetProxy.prototype;
|
||||
},
|
||||
setPrototypeOf({ set }) {},
|
||||
isExtensible({ set }) {
|
||||
return false;
|
||||
},
|
||||
preventExtensions({ set }) {},
|
||||
getOwnPropertyDescriptor({ set }, category_id) {
|
||||
return {
|
||||
value: setHandler.get({ set }, category_id),
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
},
|
||||
defineProperty({ set }) {},
|
||||
deleteProperty({ set }) {},
|
||||
ownKeys({ set }) {
|
||||
return set.categories.map(c => c.id);
|
||||
}
|
||||
};
|
||||
|
||||
const categoryHandler = {
|
||||
get({ category }, setting_id) {
|
||||
const setting = category.getSetting(setting_id);
|
||||
if (setting) return setting.value;
|
||||
},
|
||||
set({ category }, setting_id, value) {
|
||||
const setting = category.getSetting(setting_id);
|
||||
if (setting) return setting.value = value;
|
||||
},
|
||||
has({ category }, setting_id) {
|
||||
const setting = category.getSetting(setting_id);
|
||||
if (setting) return true;
|
||||
},
|
||||
getPrototypeOf({ category }) {
|
||||
return SettingsCategoryProxy.prototype;
|
||||
},
|
||||
setPrototypeOf({ category }) {},
|
||||
isExtensible({ category }) {
|
||||
return false;
|
||||
},
|
||||
preventExtensions({ category }) {},
|
||||
getOwnPropertyDescriptor({ category }, setting_id) {
|
||||
return {
|
||||
value: categoryHandler.get({ category }, setting_id),
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
},
|
||||
defineProperty({ category }) {},
|
||||
deleteProperty({ category }) {},
|
||||
ownKeys({ category }) {
|
||||
return category.settings.map(s => s.id);
|
||||
}
|
||||
};
|
||||
|
||||
export default class SettingsProxy {
|
||||
|
||||
constructor(args) {
|
||||
Object.assign(this, args);
|
||||
}
|
||||
|
||||
static createProxy(set) {
|
||||
if (set instanceof SettingsSet) return new Proxy(new SettingsSetProxy({ set }), setHandler);
|
||||
if (set instanceof SettingsCategory) return new Proxy(new SettingsCategoryProxy({ category: set }), categoryHandler);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export class SettingsSetProxy extends SettingsProxy {}
|
||||
export class SettingsCategoryProxy extends SettingsProxy {}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue