package io.github.lonamiwebs.overgram.network; import io.github.lonamiwebs.overgram.network.connection.Connection; import io.github.lonamiwebs.overgram.tl.TLObject; import io.github.lonamiwebs.overgram.tl.TLRequest; import io.github.lonamiwebs.overgram.utils.BinaryReader; import io.github.lonamiwebs.overgram.utils.BinaryWriter; import java.io.IOException; import java.nio.ByteBuffer; public class MTProtoPlainSender { private final Connection connection; private final MTProtoState state; public MTProtoPlainSender(final Connection connection) { this.connection = connection; this.state = new MTProtoState(null); } public T send(final TLRequest request) throws IOException, ClassNotFoundException { final long msgId = state.getNewMsgId(); final BinaryWriter writer = new BinaryWriter(); request.serialize(writer); final byte[] requestBytes = writer.toBytes(); writer.clear(); writer.write(0L); writer.write(msgId); writer.write(requestBytes.length); writer.writeRaw(requestBytes); connection.send(writer.toBytes()); final byte[] body = connection.recv(); if (body[0] == (byte) 0x6c && body[1] == (byte) 0xfe && body[2] == (byte) 0xff && body[3] == (byte) 0xff) { // -404 as little endian, broken authorization throw new RuntimeException(); } final BinaryReader reader = new BinaryReader(ByteBuffer.wrap(body)); final long authKeyId = reader.readLong(); assert authKeyId == 0; final long serverMsgId = reader.readLong(); assert serverMsgId != 0; final int length = reader.readInt(); assert length > 0; //noinspection unchecked return (T) reader.readTl(); } }