Repository: Zapix/mtpylon (language: python)

Issue:
Intermediate
implement intermediate protocol 


Discussion / hints:

Fix patch:
diff --git a/mtpylon/transports/__init__.py b/mtpylon/transports/__init__.py
new file mode 100644
index 0000000..40a96af
--- /dev/null
+++ b/mtpylon/transports/__init__.py
@@ -0,0 +1,1 @@
+# -*- coding: utf-8 -*-
diff --git a/mtpylon/transports/intermediate.py b/mtpylon/transports/intermediate.py
new file mode 100644
index 0000000..bb1d4eb
--- /dev/null
+++ b/mtpylon/transports/intermediate.py
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+"""
+    Intermediate payload structure is:
+
+    +----+----...----+
+    +len.+  payload  +
+    +----+----...----+
+
+    Payloads are wrapped in the following envelope:
+
+    - Length: payload length encoded as 4 length bytes (little endian)
+    - Payload: the MTProto payload
+"""
+PROTOCOL_TAG = 0xeeeeeeee
+
+
+def wrap(buffer: bytes) -> bytes:
+    return len(buffer).to_bytes(4, 'little') + buffer
+
+
+def unwrap(buffer: bytes) -> bytes:
+    tlen = int.from_bytes(buffer[:4], 'little')
+    return buffer[4:tlen + 4]


Test patch:
diff --git a/tests/test_transports/__init__.py b/tests/test_transports/__init__.py
new file mode 100644
index 0000000..40a96af
--- /dev/null
+++ b/tests/test_transports/__init__.py
@@ -0,0 +1,1 @@
+# -*- coding: utf-8 -*-
diff --git a/tests/test_transports/test_intermediate.py b/tests/test_transports/test_intermediate.py
new file mode 100644
index 0000000..a7ee72e
--- /dev/null
+++ b/tests/test_transports/test_intermediate.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+from mtpylon.transports.intermediate import wrap, unwrap
+
+
+original_message = b'\x47\xac\x9f\xf1\xf1\x7d\xd4\xc0\xcd\xde\xdf\x86\xad\x73'
+wrapped_message = b'\x0e\x00\x00\x00' + original_message
+
+
+def test_wrap():
+    returned_message = wrap(original_message)
+
+    assert returned_message == wrapped_message
+
+
+def test_unwrap():
+    returned_message = unwrap(wrapped_message)
+
+    assert returned_message == original_message