utils.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. #!/usr/bin/env python3
  2. #
  3. # This program is made by the World Sus Foundation by luky3x. No rights
  4. # reserved.
  5. #
  6. # Various utility functions for the Internet Delay Chat server written
  7. # in Python Trio. This library is not intended to be used outside of
  8. # that program.
  9. #
  10. # Written by: Andrew <https://www.andrewyu.org>
  11. # luk3yx <https://luk3yx.github.io>
  12. #
  13. # This is free and unencumbered software released into the public
  14. # domain.
  15. #
  16. # Anyone is free to copy, modify, publish, use, compile, sell, or
  17. # distribute this software, either in source code form or as a compiled
  18. # binary, for any purpose, commercial or non-commercial, and by any
  19. # means.
  20. #
  21. # In jurisdictions that recognize copyright laws, the author or authors
  22. # of this software dedicate any and all copyright interest in the
  23. # software to the public domain. We make this dedication for the benefit
  24. # of the public at large and to the detriment of our heirs and
  25. # successors. We intend this dedication to be an overt act of
  26. # relinquishment in perpetuity of all present and future rights to this
  27. # software under copyright law.
  28. #
  29. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  30. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  32. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  33. # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  34. # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  35. # OTHER DEALINGS IN THE SOFTWARE.
  36. #
  37. from __future__ import annotations
  38. from typing import TypeVar, Iterator, Optional, Union, List
  39. import pprint
  40. import sys
  41. import re
  42. import time
  43. import minilog
  44. import exceptions
  45. import entities
  46. def ts() -> bytes:
  47. """
  48. Return the current floating-point timestamp as a bytestring.
  49. """
  50. return str(time.time()).encode("ascii")
  51. _esc_re = re.compile(rb"\\(.)")
  52. _idc_escapes = {
  53. b"\\": b"\\\\",
  54. b"r": b"\r",
  55. b"n": b"\n",
  56. b"t": b"\t",
  57. }
  58. def _get_idc_args(
  59. command: bytes, kwdict: dict[str, Optional[bytes]]
  60. ) -> Iterator[bytes]:
  61. yield command.upper()
  62. seen = set()
  63. for key, value in kwdict.items():
  64. if key != key.upper():
  65. raise exceptions.IdiotError(
  66. "Why are you using lowercase keys in the code?"
  67. )
  68. if key in seen:
  69. raise exceptions.KeyCollisionError(
  70. key.encode("ascii")
  71. + b" was already seen in the arguments."
  72. )
  73. seen.add(key)
  74. if value is not None:
  75. for escape_char, char in _idc_escapes.items():
  76. value = value.replace(char, b"\\" + escape_char)
  77. yield key.encode("ascii") + b"=" + value
  78. def stdToBytes(command: bytes, **kwargs: Optional[bytes]) -> bytes:
  79. """
  80. Turns a standard tuple into a raw IDC message, adding the final
  81. CR-LF.
  82. "Hey! Saw that underscore? Why are you even looking at this?"
  83. """
  84. r = b"\t".join(_get_idc_args(command, kwargs)) + b"\r\n"
  85. return r
  86. def bytesToStd(msg: bytes) -> tuple[bytes, dict[str, bytes]]:
  87. """
  88. Parses a raw IDC message into the command and key/value pairs.
  89. The message MUST contain the CR-LF.
  90. Example: PRIVMSG TARGET:yay MESSAGE:Hi
  91. (b'PRIVMSG', {b'TARGET': b'yay', b'MESSAGE': b'Hi'})
  92. """
  93. if msg.endswith(b"\n"):
  94. msg = msg[:-1]
  95. if msg.endswith(b"\r"):
  96. msg = msg[:-1]
  97. cmd = b""
  98. args = {}
  99. for arg in msg.split(b"\t"):
  100. if b"=" in arg:
  101. key, value = arg.split(b"=", 1)
  102. key = key.upper()
  103. try:
  104. key_str = key.decode("ascii")
  105. except UnicodeDecodeError:
  106. raise exceptions.NonAlphaKeyError(
  107. b"Argument keys must be ASCII alphabet sequences. (decode error)"
  108. )
  109. else:
  110. if not key_str.isalpha():
  111. raise exceptions.NonAlphaKeyError(
  112. b"Argument keys must be ASCII alphabet sequences. (not isalpha)"
  113. )
  114. def s(m: re.Match[bytes]) -> bytes:
  115. try:
  116. return _idc_escapes[m.group(1)]
  117. except KeyError:
  118. raise exceptions.EscapeSequenceError(
  119. b"\\"
  120. + m.group(1)
  121. + b"is an invalid escape sequence."
  122. )
  123. args[key_str] = _esc_re.sub(
  124. s,
  125. value,
  126. )
  127. elif cmd != b"":
  128. raise exceptions.MultiCommandError(
  129. b"You can't use multiple commands inside one line!"
  130. )
  131. else:
  132. cmd = arg
  133. return cmd, args
  134. T = TypeVar("T")
  135. U = TypeVar("U")
  136. def carg(
  137. adict: dict[str, bytes], key: str, cmd: bytes = b"This command"
  138. ) -> bytes:
  139. try:
  140. return adict[key]
  141. except KeyError:
  142. raise exceptions.MissingArgumentError(
  143. cmd
  144. + b" requires an argument with the key "
  145. + key.encode("utf-8")
  146. + b" but was not provided."
  147. )
  148. def getKeyByValue(d: dict[T, U], s: U) -> list[T]:
  149. """
  150. From a dictionary d, retreive all keys that have value s, returned
  151. as a list.
  152. """
  153. r = []
  154. for k, v in d.items():
  155. if s == v:
  156. r.append(k)
  157. return r
  158. V = Union[
  159. entities.Client,
  160. entities.User,
  161. List[entities.User],
  162. List[entities.Client],
  163. entities.Channel,
  164. List[entities.Channel],
  165. ]
  166. async def send(
  167. recver: V,
  168. command: bytes,
  169. delayable: bool = True,
  170. **kwargs: Optional[bytes],
  171. ) -> None:
  172. # rs = kwargs.get("RSTS", None)
  173. # if rs is None:
  174. # kwargs.insert(0, ("RSTS", ts()))
  175. kwargs["RSTS"] = kwargs.get("RSTS", ts())
  176. if isinstance(recver, list):
  177. for t in recver:
  178. await send(t, command, delayable, **kwargs)
  179. elif isinstance(recver, entities.Client):
  180. b = stdToBytes(command, **kwargs)
  181. minilog.debug(f"{recver.cid.decode('ascii')} <<< {b!r}")
  182. await recver.stream.send_all(b)
  183. elif isinstance(recver, entities.User):
  184. if recver.connected_clients:
  185. for c in recver.connected_clients:
  186. await send(c, command, delayable, **kwargs)
  187. elif delayable:
  188. recver.queue.append(stdToBytes(command, **kwargs))
  189. else:
  190. raise exceptions.TargetOfflineError(
  191. recver.username
  192. + b" is offline and this action requires them to be online."
  193. )
  194. elif isinstance(recver, entities.Channel):
  195. for t in recver.broadcast_to:
  196. await send(t, command, delayable, **kwargs)
  197. else:
  198. raise Exception("1")
  199. async def quote(c: entities.Client, line: bytes) -> None:
  200. await c.stream.send_all(line)
  201. def exit(i: int) -> None:
  202. sys.exit(i)