Compare commits

..

34 Commits

Author SHA1 Message Date
RoyceDa
33582e2730 Начало трансляции сервероного кода к новому протоколу 2026-04-18 17:50:23 +02:00
RoyceDa
068492b56d Обновленеи протокола, убран legacy код, переход на более практичную схему TLV 2026-04-18 17:49:58 +02:00
9432969cb4 Игнорирование отстуствия файлов APNs/FCM при разработке 2026-04-12 23:23:08 +02:00
RoyceDa
f87198c054 Видеосообщения (кружочки) 2026-04-10 17:36:31 +02:00
RoyceDa
58fe3c409d Новый тип вложений - голосовое сообщение
All checks were successful
Build rosetta-wss / build (push) Successful in 1m51s
2026-04-10 17:28:32 +02:00
RoyceDa
bdc44f36f0 Push READ теперь с пустым уведомлением для точного пробуждения
All checks were successful
Build rosetta-wss / build (push) Successful in 1m57s
2026-04-08 22:11:52 +02:00
RoyceDa
145aaf8288 Исправление кика с сервера при гонке с закрытием RTC на SFU
All checks were successful
Build rosetta-wss / build (push) Successful in 1m31s
2026-04-07 15:24:45 +02:00
RoyceDa
ddcd08aeae END_CALL для остальных устройств принявшего звонок пользователя 2026-04-07 15:16:00 +02:00
RoyceDa
435d6fefa8 Защита от подмены src в пакетах 2026-04-07 15:10:27 +02:00
RoyceDa
986cd765d8 Дополнительные комментарии 2026-04-07 14:56:56 +02:00
RoyceDa
a9c4612a72 Исправление недохода END_CALL к вызываемому пользователю если он авторизован 2026-04-07 14:55:39 +02:00
RoyceDa
bc0a64f450 Исправление зависших сессий на сервере при преждевременном RTC close 2026-04-07 14:43:32 +02:00
faaffd86d0 Обновить src/main/java/im/rosetta/service/dispatch/push/dispatchers/VoIPApns.java
All checks were successful
Build rosetta-wss / build (push) Successful in 1m45s
2026-04-05 21:03:41 +00:00
b1d3416684 Обновить src/main/java/im/rosetta/service/dispatch/push/dispatchers/VoIPApns.java
All checks were successful
Build rosetta-wss / build (push) Successful in 2m14s
2026-04-05 14:46:34 +00:00
RoyceDa
7eacaa6298 Расширены коды ошибок
All checks were successful
Build rosetta-wss / build (push) Successful in 3m42s
2026-04-04 18:59:08 +02:00
RoyceDa
76a007ff42 Фикс киков с сервера
All checks were successful
Build rosetta-wss / build (push) Successful in 3m30s
2026-04-04 18:49:39 +02:00
RoyceDa
20dd5933d9 Merge branch 'dev' into main
All checks were successful
Build rosetta-wss / build (push) Successful in 4m14s
2026-04-04 18:35:51 +02:00
RoyceDa
939a4d55f4 Обновление протокола для неавторизованных звонков 2026-04-04 18:31:05 +02:00
RoyceDa
c59687564e Merge branch 'main' of https://git.rosetta.im/Rosetta/rosetta-wss into main
All checks were successful
Build rosetta-wss / build (push) Successful in 1m45s
2026-04-02 18:29:39 +02:00
RoyceDa
9b8d8cd863 Merge branch 'dev' into main 2026-04-02 18:29:36 +02:00
RoyceDa
3c6b2e0e71 Обновление протокола звонков 2026-04-02 18:11:24 +02:00
398b869e59 Методы в SignalPeer без авторизации 2026-04-02 00:31:18 +02:00
69c6bc63b3 DEVELOPMENT_APNS_HOST
All checks were successful
Build rosetta-wss / build (push) Successful in 1m43s
2026-04-01 14:51:05 +00:00
RoyceDa
aa6361c253 Merge branch 'main' of https://git.rosetta.im/Rosetta/rosetta-wss into main
All checks were successful
Build rosetta-wss / build (push) Successful in 1m46s
2026-04-01 16:08:18 +02:00
RoyceDa
b07f76ba1e Добавлены call-pushes 2026-04-01 16:06:35 +02:00
d4448a629b Удалить serviceAccount.json
Some checks failed
Build rosetta-wss / build (push) Has been cancelled
2026-04-01 13:01:03 +00:00
RoyceDa
aa17dd8d9d Тест 1
All checks were successful
Build rosetta-wss / build (push) Successful in 1m43s
2026-03-31 19:51:43 +02:00
RoyceDa
a76496204c Фикс сравнения
All checks were successful
Build rosetta-wss / build (push) Successful in 1m47s
2026-03-31 19:46:32 +02:00
RoyceDa
475f3230f3 Фикс device_id
All checks were successful
Build rosetta-wss / build (push) Successful in 1m30s
2026-03-31 19:42:35 +02:00
RoyceDa
7f09b7764b Фикс LIE
All checks were successful
Build rosetta-wss / build (push) Successful in 1m32s
2026-03-31 19:38:16 +02:00
RoyceDa
8bba69ddb6 Debug
All checks were successful
Build rosetta-wss / build (push) Successful in 1m45s
2026-03-31 18:46:40 +02:00
RoyceDa
02a8a1024b Фикс LazyInitializationException
All checks were successful
Build rosetta-wss / build (push) Successful in 2m11s
2026-03-31 18:39:31 +02:00
RoyceDa
16093fd693 Фикс LazyInitializationException
All checks were successful
Build rosetta-wss / build (push) Successful in 1m45s
2026-03-31 18:16:18 +02:00
RoyceDa
d2263c6b9a Новый протокол регистрации токенов
All checks were successful
Build rosetta-wss / build (push) Successful in 1m48s
2026-03-31 17:44:09 +02:00
167 changed files with 5779 additions and 3452 deletions

4
.env
View File

@@ -14,6 +14,10 @@ SDU_SERVERS=http://10.211.55.2:7777
#Firebase Credentials
FIREBASE_CREDENTIALS_PATH=serviceAccount.json
#Apple APNS
APNS_KEY_PATH=voip.p12
APNS_P12_PASSWORD=rosetta1
IOS_BUNDLE_ID=com.rosetta.dev
#Каждые сколько дней будет очищаться буфер (максимальная дистанция синхронизации сообщений)
BUFFER_CLEANUP_DAYS=7

3
.gitignore vendored
View File

@@ -34,6 +34,9 @@ target
.settings
.project
.classpath
serviceAccount.json
build/*.p12
*.p12
build/.env
build/.env*

View File

@@ -46,6 +46,12 @@
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>pushy</artifactId>
<version>0.15.4</version>
</dependency>
</dependencies>
<build>

View File

@@ -1,13 +0,0 @@
{
"type": "service_account",
"project_id": "rosetta-messanger-dev",
"private_key_id": "69822675ff0a49a8ce0bd147dbab3ef432963485",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/iYhrgWfi/ecP\nIs7Y0u7MueE/leU0QZF3V6hIcs1Iq1/CSUYcszv+YXuKItfwi0pYtntPmnCtdKnv\nFgZZN/9I0/AjFPlggqEXBH223FjsAfoNTk8a0PXyF8oOG0u2pN34t20nxXFSYars\n/6yJMKOBdaJ+L51dlBeCj40UFm3zQSVpejRkspWmT5Qz7kWh2e8yj6ukPyXEfrrD\n8jmM6uQeKwzlmfjD8YbL7R2m+lE1hzkoFCo0PrqMQYIIpAMT9n9meCk/LrQMIUnA\n+zICsTffFwbFzmJ2A022po3ObL4dUYgqGrPs5DqjxwTF4mI0g2dkPvoxpUKkVzC7\nHzzOYTwRAgMBAAECggEAGIacDSa1rpdpfK2DLrjFHY+YXAPYehpX7fVaVeXmtcKa\nppkAXSYcQq9T2jUqUSGyOZgq7l9Yb0rhhFJd1L3QDBDLY9/zK3GpU/ZeF0oG1DhP\n6bVDJCwUBNXD/eNujKrMG5AimOBLlEtvpMemXa4jOa1eSxR+F4tM1AndUZr/pZFT\nIdPBrId3WemkcWH2b1R4RLVu8zqci1x+nWvL4Gt8O/gDpDzlmV2Disvpf300a5wU\ngIKcOI2H6vouOwL9ltMPTBXdpDIC64Q8zvK3973d3Fqx2Mt2mO4ZgylFpk2nmAm6\n3wknrkJDE+Z/H7XmdwpMhRmmyku3vuqsDwmy7BEGGwKBgQD03oOJ6eb9kG6JX830\nRH/Vhh3NlpVEzuHzRA8WznsX5WaeyMF9NWo4Lh9ifBxkRAQKftEC0CR5GZp3/895\nQuoMMbrrklWWkVRwCZWYQBquRXNHbTPj6ztvHaZZrw8HhemZWtOF89T5f8Kn4LcD\nFwR8kIqXeLxeTbfc2hQXZvP7vwKBgQDIPmhM2Td/Ni4Mbe3wGmOyS0RweK5qcKBF\n32N1rCr8smrD1irg+w9Qrmz2cX3udtVJDRLz4ctSmiEPs+UrzuyG6yTbdv7bh8AN\nsqHOdc4GRqGsB/jfXagVjRMSeObQk5fR03tiPLP15J+lpoEsjwUzw7L3Ioacaq62\nqSi87br8LwKBgQDu/uMJz4bJg5evcxeUSusuH5mlGE0WfIniIlJL4zoXR6qSXcUk\nDOdgb/vn5tTbM9tx1vbvNPH0VH4Ek2QPqbTANCWJWSk6LRxpwaEFmcOwxk5Or5IO\n6X/34suDCy6zHAu0xwZe3m7HGeCGc/iMBoI1heoPDyNjM5257AviD3UhBwKBgCWS\nmC17QI+NEfzhD5lSykwlFVVpP4jXUytpLBdjU7mQnLncULVgRlJkOCvRxchd4c1Q\nN7MtNeJs6zEwFxsuO3FhY8wOOunkQeQQFY5QynShAiruYANBZo2Mp/x6VQzj9MO5\nQ9h9/WJxIIeLg4dh2p8I5Ga8wrdMyTWa7frtPH2fAoGALUkccsu4Mcws55Xy1aHH\nNETI6CRQpaU4v6jNhuuY4g6jp5ScaqkpuuzHOYorpmdC3180YXzPn2pwKeYWa0BA\nTjR8z603bCpdRfpic1UvYi96jwAcNiJTAGGVwmyYopIFBdHphfGS3hWZlYfonVps\n+k87j3WGwOiUGqoKSGJi1cw=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-fbsvc@rosetta-messanger-dev.iam.gserviceaccount.com",
"client_id": "115421173243098464717",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40rosetta-messanger-dev.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}

View File

@@ -1,9 +1,10 @@
package im.rosetta;
import im.rosetta.calls.CallManager;
import im.rosetta.client.ClientManager;
import im.rosetta.client.OnlineManager;
import im.rosetta.event.EventManager;
import im.rosetta.executors.Executor0Handshake;
import im.rosetta.executors.ExecutorHandshake;
import im.rosetta.executors.Executor10RequestUpdate;
import im.rosetta.executors.Executor11Typeing;
import im.rosetta.executors.Executor15RequestTransport;
@@ -11,7 +12,7 @@ import im.rosetta.executors.Executor16PushNotification;
import im.rosetta.executors.Executor17GroupCreate;
import im.rosetta.executors.Executor18GroupInfo;
import im.rosetta.executors.Executor19GroupInviteInfo;
import im.rosetta.executors.Executor1UserInfo;
import im.rosetta.executors.ExecutorUserInfo;
import im.rosetta.executors.Executor20GroupJoin;
import im.rosetta.executors.Executor21GroupLeave;
import im.rosetta.executors.Executor22GroupBan;
@@ -32,32 +33,7 @@ import im.rosetta.listeners.ServerStopListener;
import im.rosetta.logger.Logger;
import im.rosetta.logger.enums.Color;
import im.rosetta.logger.enums.LogLevel;
import im.rosetta.packet.Packet0Handshake;
import im.rosetta.packet.Packet10RequestUpdate;
import im.rosetta.packet.Packet11Typeing;
import im.rosetta.packet.Packet15RequestTransport;
import im.rosetta.packet.Packet16PushNotification;
import im.rosetta.packet.Packet17GroupCreate;
import im.rosetta.packet.Packet18GroupInfo;
import im.rosetta.packet.Packet19GroupInviteInfo;
import im.rosetta.packet.Packet1UserInfo;
import im.rosetta.packet.Packet20GroupJoin;
import im.rosetta.packet.Packet21GroupLeave;
import im.rosetta.packet.Packet22GroupBan;
import im.rosetta.packet.Packet23DeviceList;
import im.rosetta.packet.Packet24DeviceResolve;
import im.rosetta.packet.Packet25Sync;
import im.rosetta.packet.Packet26SignalPeer;
import im.rosetta.packet.Packet27WebRTC;
import im.rosetta.packet.Packet28IceServers;
import im.rosetta.packet.Packet2Result;
import im.rosetta.packet.Packet3Search;
import im.rosetta.packet.Packet4OnlineSubscribe;
import im.rosetta.packet.Packet5OnlineState;
import im.rosetta.packet.Packet6Message;
import im.rosetta.packet.Packet7Read;
import im.rosetta.packet.Packet8Delivery;
import im.rosetta.packet.Packet9DeviceNew;
import im.rosetta.network.RccGeneratedPacketRegistry;
import im.rosetta.service.services.BufferCleanupService;
import im.rosetta.service.services.ForwardUnitService;
import io.orprotocol.Server;
@@ -82,6 +58,7 @@ public class Boot {
private OnlineManager onlineManager;
private BufferCleanupService bufferCleanupService;
private ForwardUnitService forwardUnitService;
private CallManager callManager;
/**
* Конструктор по умолчанию, использует порт 3000 для сервера
@@ -104,7 +81,8 @@ public class Boot {
port,
30
), packetManager, this.serverAdapter);
this.clientManager = new ClientManager(server);
this.clientManager = new ClientManager(this.server);
this.callManager = new CallManager(this.clientManager);
/**
* Каждые сколько дней будет очищаться буфер (это влияет на синхронизацию сообщений, так
* как при синхронизации клиент запрашивает пакеты из буфера за последние 7 дней, если этот параметр будет меньше,
@@ -113,7 +91,7 @@ public class Boot {
int cleanupEveryDays = System.getenv("BUFFER_CLEANUP_DAYS") != null ?
Integer.parseInt(System.getenv("BUFFER_CLEANUP_DAYS")) : 7;
this.bufferCleanupService = new BufferCleanupService(cleanupEveryDays, this.logger);
this.forwardUnitService = new ForwardUnitService(this.logger, this.clientManager);
this.forwardUnitService = new ForwardUnitService(this.logger, this.clientManager, this.callManager);
}
/**
@@ -155,7 +133,7 @@ public class Boot {
public Boot bootstrap() {
try{
this.server.start();
this.registerAllPackets();
RccGeneratedPacketRegistry.registerAll(this.packetManager);
this.registerAllExecutors();
this.registerAllEvents();
this.printBootMessage();
@@ -177,41 +155,9 @@ public class Boot {
this.eventManager.registerListener(new DeviceListListener(this.clientManager));
}
private void registerAllPackets() {
this.packetManager.registerPacket(0, Packet0Handshake.class);
this.packetManager.registerPacket(1, Packet1UserInfo.class);
this.packetManager.registerPacket(2, Packet2Result.class);
this.packetManager.registerPacket(3, Packet3Search.class);
this.packetManager.registerPacket(4, Packet4OnlineSubscribe.class);
this.packetManager.registerPacket(5, Packet5OnlineState.class);
this.packetManager.registerPacket(6, Packet6Message.class);
this.packetManager.registerPacket(7, Packet7Read.class);
this.packetManager.registerPacket(8, Packet8Delivery.class);
this.packetManager.registerPacket(9, Packet9DeviceNew.class);
this.packetManager.registerPacket(10, Packet10RequestUpdate.class);
this.packetManager.registerPacket(11, Packet11Typeing.class);
//RESERVED 12 PACKET AVATAR (unused)
//RESERVED 13 PACKET KERNEL UPDATE (unused)
//RESERVED 14 PACKET APP UPDATE (unused)
this.packetManager.registerPacket(15, Packet15RequestTransport.class);
this.packetManager.registerPacket(16, Packet16PushNotification.class);
this.packetManager.registerPacket(17, Packet17GroupCreate.class);
this.packetManager.registerPacket(18, Packet18GroupInfo.class);
this.packetManager.registerPacket(19, Packet19GroupInviteInfo.class);
this.packetManager.registerPacket(20, Packet20GroupJoin.class);
this.packetManager.registerPacket(21, Packet21GroupLeave.class);
this.packetManager.registerPacket(22, Packet22GroupBan.class);
this.packetManager.registerPacket(23, Packet23DeviceList.class);
this.packetManager.registerPacket(24, Packet24DeviceResolve.class);
this.packetManager.registerPacket(25, Packet25Sync.class);
this.packetManager.registerPacket(26, Packet26SignalPeer.class);
this.packetManager.registerPacket(27, Packet27WebRTC.class);
this.packetManager.registerPacket(28, Packet28IceServers.class);
}
private void registerAllExecutors() {
this.packetManager.registerExecutor(0, new Executor0Handshake(this.eventManager, this.clientManager, this.packetManager));
this.packetManager.registerExecutor(1, new Executor1UserInfo());
this.packetManager.registerExecutor(0, new ExecutorHandshake(this.eventManager, this.clientManager, this.packetManager));
this.packetManager.registerExecutor(1, new ExecutorUserInfo());
this.packetManager.registerExecutor(3, new Executor3Search(this.clientManager));
this.packetManager.registerExecutor(4, new Executor4OnlineState(this.onlineManager, this.clientManager));
this.packetManager.registerExecutor(6, new Executor6Message(this.clientManager, this.packetManager));
@@ -228,8 +174,8 @@ public class Boot {
this.packetManager.registerExecutor(22, new Executor22GroupBan());
this.packetManager.registerExecutor(24, new Executor24DeviceResolve(this.clientManager, this.eventManager, this.packetManager));
this.packetManager.registerExecutor(25, new Executor25Sync(this.packetManager));
this.packetManager.registerExecutor(26, new Executor26SignalPeer(this.clientManager, this.forwardUnitService));
this.packetManager.registerExecutor(27, new Executor27WebRTC(this.forwardUnitService));
this.packetManager.registerExecutor(26, new Executor26SignalPeer(this.clientManager, this.forwardUnitService, this.callManager));
this.packetManager.registerExecutor(27, new Executor27WebRTC(this.callManager));
this.packetManager.registerExecutor(28, new Executor28IceServers(this.forwardUnitService));
}

View File

@@ -27,7 +27,11 @@ public enum Failures implements BaseFailures {
/**
* Слишком много подписок на онлайн статусы
*/
TOO_MANY_ONLINE_SUBSCRIPTIONS(3010);
TOO_MANY_ONLINE_SUBSCRIPTIONS(3010),
/**
* Нет сессии звонка
*/
NO_CALL_SESSION(3011);
private final int code;

View File

@@ -0,0 +1,119 @@
package im.rosetta.calls;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import im.rosetta.client.ClientManager;
import im.rosetta.packet.Packet26SignalPeer;
import im.rosetta.packet.runtime.NetworkSignalType;
import io.g365sfu.Room;
import io.orprotocol.ProtocolException;
import io.orprotocol.client.Client;
import io.orprotocol.packet.Packet;
public class CallManager {
private List<CallSession> callSessions = new ArrayList<>();
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private static final long RINGING_TIMEOUT = 30 * 1000;
private ClientManager clientManager;
public CallManager(ClientManager clientManager) {
this.clientManager = clientManager;
scheduler.scheduleAtFixedRate(this::cleanupCallSessions, 0, 1, TimeUnit.SECONDS);
}
public void cleanupCallSessions() {
/**
* Такая конструкция нужна для избежания ConcurrentModificationException,
* так как мы не можем удалять элементы из списка, по которому проходим в цикле,
* поэтому мы сначала собираем сессии звонков, которые нужно удалить, а потом
* удаляем их из основного списка
*/
List<CallSession> sessionsToRemove = new ArrayList<>();
for (CallSession session : this.callSessions) {
if (session.shouldRemove()) {
/**
* Отправляем всем в сессии что звонок завершился, так как он устарел, и удаляем сессию из списка активных сессий
*/
Packet26SignalPeer rtout = new Packet26SignalPeer();
rtout.setSignalType(NetworkSignalType.RINGING_TIMEOUT);
Packet26SignalPeer endCallPacket = new Packet26SignalPeer();
endCallPacket.setSignalType(NetworkSignalType.END_CALL);
endCallPacket.setJoinToken(session.getJoinToken());
endCallPacket.setCallId(session.getCallId());
try {
session.sendPacket(rtout, null);
this.sendPacketToRinging(session, endCallPacket);
} catch (ProtocolException e) {
e.printStackTrace();
}
sessionsToRemove.add(session);
}
}
for (CallSession session : sessionsToRemove) {
this.callSessions.remove(session);
}
}
public CallSession createCall(String callId, String joinToken) {
CallSession session = new CallSession(callId, joinToken, RINGING_TIMEOUT);
this.callSessions.add(session);
return session;
}
public CallSession getCallSession(String callId, String joinToken) {
for (CallSession session : this.callSessions) {
if (session.getCallId().equals(callId) && session.getJoinToken().equals(joinToken)) {
return session;
}
}
return null;
}
public CallSession getCallSession(Room room) {
for (CallSession session : this.callSessions) {
if (session.getRoom() != null && session.getRoom().equals(room)) {
return session;
}
}
return null;
}
public boolean isBusy(String publicKey) {
for (CallSession session : this.callSessions) {
if (session.clients.containsKey(publicKey)) {
return true;
}
if(session.ringing.containsKey(publicKey)) {
return true;
}
}
return false;
}
public void sendPacketToRinging(CallSession session, Packet packet) throws ProtocolException {
for (String publicKey : session.ringing.keySet()) {
this.clientManager.sendPacketToAuthorizedPK(publicKey, packet);
}
}
public CallSession getCallSession(Client client) {
for (CallSession session : this.callSessions) {
if (session.clients.containsValue(client)) {
return session;
}
}
return null;
}
public void removeSession(CallSession session) {
this.callSessions.remove(session);
}
}

View File

@@ -0,0 +1,131 @@
package im.rosetta.calls;
import java.util.HashMap;
import io.g365sfu.Room;
import io.orprotocol.ProtocolException;
import io.orprotocol.client.Client;
import io.orprotocol.packet.Packet;
public class CallSession {
public String callId;
public String joinToken;
public Long createdAt;
public Long ringingTimeout;
/**
* Клиенты которым сейчас идет дозвон (публичные ключи)
* Клиенты в этом списке не могут принимать другие звонки, так как они уже заняты дозвоном,
* но они еще не в звонке, так как не приняли звонок
*
* Клиенты удаляются из этого списка, когда они принимают звонок или отклоняют его,
* тогда они либо переходят в звонок, либо становятся свободными для других звонков
* pk -> время начала дозвона (timestamp в миллисекундах)
*/
public HashMap<String, Long> ringing;
/**
* Клиенты, которые уже приняли звонок и находятся в звонке (публичные ключи) и их сокеты
* pk -> client
*/
public HashMap<String, Client> clients;
/**
* Если звонок активен у него появляется комната, иначе комната null
*/
public Room room;
public CallSession(String callId, String joinToken, Long ringingTimeout) {
this.callId = callId;
this.joinToken = joinToken;
this.clients = new HashMap<>();
this.ringing = new HashMap<>();
this.createdAt = System.currentTimeMillis();
this.ringingTimeout = ringingTimeout;
}
public void joinCall(String publicKey, Client client) {
if(this.ringing.containsKey(publicKey)) {
this.ringing.remove(publicKey);
}
this.clients.put(publicKey, client);
}
/**
* Проверяет, может ли этот публичный ключ выполнять какие-либо действия в рамках этой сессии звонка,
* чтобы не допустить выполнение действий от посторонних публичных ключей, которые не участвуют в звонке
* @param publicKey Публичный ключ для проверки
* @return true, если этот публичный ключ может выполнять действия в рамках этой сессии звонка, false иначе
*/
public boolean isValidSource(String publicKey) {
return this.ringing.containsKey(publicKey) || this.clients.containsKey(publicKey);
}
/**
* Получаем публичный ключ клиента по его сокету, чтобы понимать, кто отправляет сигналы в рамках звонка
* @param client Сокет клиента, для которого нужно получить публичный ключ
* @return Публичный ключ клиента, или null если клиент не найден в сессии звонка
*/
public String getPublicKey(Client client) {
for (String publicKey : this.clients.keySet()) {
if (this.clients.get(publicKey).equals(client)) {
return publicKey;
}
}
return null;
}
public String getCallId() {
return this.callId;
}
public String getJoinToken() {
return this.joinToken;
}
public void leaveCall(String publicKey) {
if(this.clients.containsKey(publicKey)) {
this.clients.remove(publicKey);
}
if(this.ringing.containsKey(publicKey)) {
this.ringing.remove(publicKey);
}
}
public void addRinging(String publicKey) {
this.ringing.put(publicKey, System.currentTimeMillis());
}
public void setRoom(Room room) {
this.room = room;
}
public Room getRoom() {
return this.room;
}
/**
* Отправляем пакет всем участникам звонка, кроме исключенного клиента (обычно отправителя)
* @param packet Пакет для отправки
* @param excludeClient Клиент, которому не нужно отправлять пакет (обычно отправитель)
* @throws ProtocolException Если произошла ошибка при отправке пакета клиенту
*/
public void sendPacket(Packet packet, Client excludeClient) throws ProtocolException {
for (Client client : this.clients.values()) {
if (!client.equals(excludeClient)) {
client.send(packet);
}
}
}
/**
* Проверяем, нужно ли удалять сессию звонка.
* Сессию звонка нужно удалять, если в ней меньше 2 клиентов и при этом нет клиентов в состоянии дозвона,
* или если сессия была создана более 1 минуты назад, так как это значит, что клиенты не ответили на звонок и он устарел
* @return true, если сессию звонка нужно удалять, false иначе
*/
public boolean shouldRemove() {
return this.clients.size() <= 1 && (this.ringing.size() == 0 || System.currentTimeMillis() - this.createdAt > this.ringingTimeout);
}
}

View File

@@ -56,9 +56,10 @@ public class ClientManager {
* Отправить пакет ВСЕМ АВТОРИЗОВАННЫМ клиентам с публичным ключом publicKey
* @param publicKey публичный ключ получателя
* @param packet пакет для отправки
* @param exclude клиент, который не должен получать этот пакет, может быть null
* @throws ProtocolException если произошла ошибка при отправке пакета клиенту
*/
public void sendPacketToAuthorizedPK(String publicKey, Packet packet) throws ProtocolException {
public void sendPacketToAuthorizedPK(String publicKey, Packet packet, Client exclude) throws ProtocolException {
Set<Client> clients = this.clientIndexer.getClients(ECIAuthentificate.class, "publicKey", publicKey);
if(clients == null){
/**
@@ -77,12 +78,55 @@ public class ClientManager {
continue;
}
/**
* Отправляем пакет каждому клиенту с таким публичным ключом (то есть всем его авторизованным сессиям/устройствам)
* Отправляем пакет каждому клиенту с таким публичным ключом (то есть всем его авторизованным сессиям/устройствам),
* исключая клиента exclude
*/
if(exclude != null && client.equals(exclude)){
/**
* Этот клиент является исключением, он не должен получать этот пакет
*/
continue;
}
client.send(packet);
}
}
/**
* Отправить пакет ВСЕМ АВТОРИЗОВАННЫМ клиентам с публичным ключом publicKey
* @param publicKey публичный ключ получателя
* @param packet пакет для отправки
* @throws ProtocolException если произошла ошибка при отправке пакета клиенту
*/
public void sendPacketToAuthorizedPK(String publicKey, Packet packet) throws ProtocolException {
this.sendPacketToAuthorizedPK(publicKey, packet, null);
}
/**
* Отправить пакет всем клиентам с публичными ключами из списка publicKeys
* @param publicKeys список публичных ключей получателей
* @param packet пакет для отправки
* @param exclude клиент, который не должен получать этот пакет, может быть null
* @throws ProtocolException если произошла ошибка при отправке пакета клиенту
*/
public void sendPacketToAuthorizedPK(List<String> publicKeys, Packet packet, Client exclude) throws ProtocolException {
for(String publicKey : publicKeys){
this.sendPacketToAuthorizedPK(publicKey, packet, exclude);
}
}
/**
* Отправить пакет всем клиентам с публичными ключами из списка publicKeys
* @param publicKeys список публичных ключей получателей
* @param packet пакет для отправки
* @throws ProtocolException если произошла ошибка при отправке пакета клиенту
*/
public void sendPacketToAuthorizedPK(List<String> publicKeys, Packet packet) throws ProtocolException {
for(String publicKey : publicKeys){
this.sendPacketToAuthorizedPK(publicKey, packet, null);
}
}
/**
* Отправить пакет всем клиентам с публичными ключом как у client, кроме клиента client, который является отправителем и не должен получать этот пакет
* @param client клиент
@@ -111,18 +155,6 @@ public class ClientManager {
}
}
/**
* Отправить пакет всем клиентам с публичными ключами из списка publicKeys
* @param publicKeys список публичных ключей получателей
* @param packet пакет для отправки
* @throws ProtocolException если произошла ошибка при отправке пакета клиенту
*/
public void sendPacketToAuthorizedPK(List<String> publicKeys, Packet packet) throws ProtocolException {
for(String publicKey : publicKeys){
this.sendPacketToAuthorizedPK(publicKey, packet);
}
}
/**
* Получить список клиентов по публичному ключу (get PublicKey clients), могут быть неавторизованные клиенты
* @param publicKey публичный ключ клиента

View File

@@ -3,8 +3,7 @@ package im.rosetta.client.tags;
import java.util.HashMap;
import java.util.Map;
import im.rosetta.packet.runtime.HandshakeStage;
import im.rosetta.network.enums.HandshakeStage;
import io.orprotocol.client.ECITag;
/**

View File

@@ -1,40 +1,51 @@
package im.rosetta.database.entity;
import im.rosetta.database.CreateUpdateEntity;
import java.util.ArrayList;
import java.util.List;
import im.rosetta.database.CreateUpdateEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "devices", indexes = {
@Index(name = "idx_public_key", columnList = "publicKey, deviceId", unique = true)
})
public class Device extends CreateUpdateEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "publicKey", nullable = false)
private String publicKey;
@Column(name = "deviceId", nullable = false)
private String deviceId;
@Column(name = "deviceName", nullable = false)
private String deviceName;
@Column(name = "deviceOs", nullable = false)
private String deviceOs;
/**
* Время завершения сессии устройства
*/
@Column(name = "syncTime", nullable = true, columnDefinition = "bigint default 0")
private Long syncTime;
@OneToMany(mappedBy = "device", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<PushToken> tokens = new ArrayList<>();
public Long getId() {
return id;
}
@@ -59,6 +70,10 @@ public class Device extends CreateUpdateEntity {
return syncTime;
}
public List<PushToken> getTokens() {
return tokens;
}
public void setSyncTime(Long syncTime) {
this.syncTime = syncTime;
}
@@ -79,4 +94,24 @@ public class Device extends CreateUpdateEntity {
this.deviceOs = deviceOs;
}
public void setTokens(List<PushToken> tokens) {
this.tokens = tokens;
}
public void addToken(PushToken token) {
if (token == null) {
return;
}
this.tokens.add(token);
token.setDevice(this);
}
public void removeToken(PushToken token) {
if (token == null) {
return;
}
this.tokens.remove(token);
token.setDevice(null);
}
}

View File

@@ -0,0 +1,85 @@
package im.rosetta.database.entity;
import im.rosetta.database.CreateUpdateEntity;
import im.rosetta.packet.runtime.TokenType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
@Entity
@Table(
name = "device_tokens",
uniqueConstraints = {
@UniqueConstraint(name = "uq_device_token", columnNames = {"device_id", "type", "token"})
},
indexes = {
@Index(name = "idx_device_token_type", columnList = "type"),
@Index(name = "idx_device_token_token", columnList = "token")
}
)
public class PushToken extends CreateUpdateEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "device_id", nullable = false)
private Device device;
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false, length = 32)
private TokenType type;
@Column(name = "token", nullable = false, columnDefinition = "TEXT")
private String token;
public Long getId() {
return id;
}
public Device getDevice() {
return device;
}
public TokenType getType() {
return type;
}
public String getToken() {
return token;
}
public void setDevice(Device device) {
this.device = device;
}
public void setType(TokenType type) {
this.type = type;
}
public void setToken(String token) {
this.token = token;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PushToken pushToken = (PushToken) o;
if (!device.equals(pushToken.device)) return false;
if (type != pushToken.type) return false;
return token.equals(pushToken.token);
}
}

View File

@@ -1,10 +1,8 @@
package im.rosetta.database.entity;
import im.rosetta.database.CreateUpdateEntity;
import im.rosetta.database.converters.StringListConverter;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@@ -12,9 +10,6 @@ import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.Table;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "users", indexes = {
@Index(name = "idx_users_publickey", columnList = "publicKey", unique = true)
@@ -40,10 +35,6 @@ public class User extends CreateUpdateEntity {
@Column(name = "publicKey", nullable = false, unique = true)
private String publicKey;
@Convert(converter = StringListConverter.class)
@Column(name = "notificationsTokens", nullable = false, columnDefinition = "TEXT")
private List<String> notificationsTokens = new ArrayList<>();
public Long getId() {
return id;
@@ -89,12 +80,4 @@ public class User extends CreateUpdateEntity {
this.verified = verified;
}
public List<String> getNotificationsTokens() {
return notificationsTokens;
}
public void setNotificationsTokens(List<String> notificationsTokens) {
this.notificationsTokens = notificationsTokens;
}
}

View File

@@ -0,0 +1,59 @@
package im.rosetta.database.repository;
import java.util.List;
import org.hibernate.Session;
import im.rosetta.database.HibernateUtil;
import im.rosetta.database.Repository;
import im.rosetta.database.entity.Device;
import im.rosetta.database.entity.PushToken;
public class PushTokenRepository extends Repository<PushToken> {
public PushTokenRepository() {
super(PushToken.class);
}
/**
* Найти все токены для заданного публичного ключа
* @param publicKey публичный ключ пользователя
* @return список токенов для заданного публичного ключа
*/
public List<PushToken> findTokens(String publicKey) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("SELECT pt FROM PushToken pt JOIN pt.device d WHERE d.publicKey = :publicKey", PushToken.class)
.setParameter("publicKey", publicKey)
.getResultList();
}
}
/**
* Найти все токены для заданного списка публичных ключей
* @param publicKeys список публичных ключей пользователей
* @return список токенов для заданного списка публичных ключей
*/
public List<PushToken> findTokens(List<String> publicKeys) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("SELECT pt FROM PushToken pt JOIN pt.device d WHERE d.publicKey IN :publicKeys", PushToken.class)
.setParameter("publicKeys", publicKeys)
.getResultList();
}
}
/**
* Найти токен для заданного устройства и токена
* @param device устройство, которому принадлежит токен
* @param token токен, который нужно найти
* @return токен для заданного устройства и токена, или null, если такой токен не найден
*/
public PushToken findToken(Device device, String token){
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("SELECT pt FROM PushToken pt WHERE pt.device = :device AND pt.token = :token", PushToken.class)
.setParameter("device", device)
.setParameter("token", token)
.uniqueResult();
}
}
}

View File

@@ -1,11 +1,16 @@
package im.rosetta.executors;
import java.util.List;
import im.rosetta.Failures;
import im.rosetta.client.tags.ECIAuthentificate;
import im.rosetta.database.entity.User;
import im.rosetta.database.repository.UserRepository;
import im.rosetta.database.entity.Device;
import im.rosetta.database.entity.PushToken;
import im.rosetta.database.repository.DeviceRepository;
import im.rosetta.database.repository.PushTokenRepository;
import im.rosetta.packet.Packet16PushNotification;
import im.rosetta.service.services.UserService;
import im.rosetta.packet.runtime.NetworkNotificationAction;
import im.rosetta.service.services.DeviceService;
import io.orprotocol.ProtocolException;
import io.orprotocol.client.Client;
@@ -13,8 +18,9 @@ import io.orprotocol.packet.PacketExecutor;
public class Executor16PushNotification extends PacketExecutor<Packet16PushNotification> {
private final UserRepository userRepository = new UserRepository();
private final UserService userService = new UserService(userRepository);
private final DeviceRepository deviceRepository = new DeviceRepository();
private final DeviceService deviceService = new DeviceService(deviceRepository);
private final PushTokenRepository pushTokenRepository = new PushTokenRepository();
@Override
public void onPacketReceived(Packet16PushNotification packet, Client client) throws Exception, ProtocolException {
@@ -33,15 +39,50 @@ public class Executor16PushNotification extends PacketExecutor<Packet16PushNotif
*/
return;
}
User user = userService.fromClient(client);
switch (packet.getAction()) {
case SUBSCRIBE:
userService.subscribeToPushNotifications(user, notificationToken);
break;
case UNSUBSCRIBE:
userService.unsubscribeFromPushNotifications(user, notificationToken);
break;
Device device = this.findDevice(eciAuthentificate.getPublicKey(), packet.getDeviceId());
if(device == null){
/**
* Устройство не найдено, значит оно не верифицировано
*/
client.disconnect();
return;
}
PushToken pushToken = this.pushTokenRepository.findToken(device, notificationToken);
if(packet.getAction() == NetworkNotificationAction.SUBSCRIBE && pushToken == null){
/**
* Подписка на токен только если токен еще не подписан
*/
PushToken token = new PushToken();
token.setToken(notificationToken);
token.setDevice(device);
token.setType(packet.getTokenType());
this.pushTokenRepository.save(token);
}
if(packet.getAction() == NetworkNotificationAction.UNSUBSCRIBE && pushToken != null){
/**
* Отписка от токена только если токен уже подписан
*/
this.pushTokenRepository.delete(pushToken);
}
}
private Device findDevice(String publicKey, String deviceId) {
List<Device> devices = this.deviceService.getDevicesByPK(publicKey);
if(devices.size() == 0){
/**
* У пользователя нет устройств, значит текущее устройство верифицировано
* такого быть не может, это избыточная проверка
*/
return null;
}
for(Device device : devices){
if(device.getDeviceId().equals(deviceId)){
return device;
}
}
return null;
}
}

View File

@@ -1,10 +1,19 @@
package im.rosetta.executors;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import im.rosetta.Failures;
import im.rosetta.calls.CallManager;
import im.rosetta.calls.CallSession;
import im.rosetta.client.ClientManager;
import im.rosetta.client.tags.ECIAuthentificate;
import im.rosetta.packet.Packet26SignalPeer;
import im.rosetta.packet.runtime.NetworkSignalType;
import im.rosetta.service.dispatch.push.PushNotifyDispatcher;
import im.rosetta.service.dispatch.runtime.PushType;
import im.rosetta.service.services.ForwardUnitService;
import io.g365sfu.Room;
import io.orprotocol.ProtocolException;
@@ -18,62 +27,196 @@ public class Executor26SignalPeer extends PacketExecutor<Packet26SignalPeer> {
private ClientManager clientManager;
private ForwardUnitService fus;
private PushNotifyDispatcher pushNotifyDispatcher = new PushNotifyDispatcher();
/**
* Сигналы, которые может выполнять только авторизованный пользователь,
* все сигналы, которые не входят в этот перечень, будут доступны для
* исполнения без авторизации.
*/
private Set<NetworkSignalType> authentificatedTypes = new HashSet<>(){{
add(NetworkSignalType.CALL);
}};
public Executor26SignalPeer(ClientManager clientManager, ForwardUnitService fus) {
/**
* Менеджер звонков, который реализует весь необхоимый функционал для управления звонками,
* например проверку занятости пользователя, и тд
*/
private CallManager callManager;
public Executor26SignalPeer(ClientManager clientManager, ForwardUnitService fus, CallManager callManager) {
this.clientManager = clientManager;
this.fus = fus;
this.callManager = callManager;
}
@Override
public void onPacketReceived(Packet26SignalPeer packet, Client client) throws Exception, ProtocolException {
String src = packet.getSrc();
String dst = packet.getDst();
ECIAuthentificate eciAuthentificate = client.getTag(ECIAuthentificate.class);
if (eciAuthentificate == null || !eciAuthentificate.hasAuthorized()) {
NetworkSignalType type = packet.getSignalType();
if ((eciAuthentificate == null || !eciAuthentificate.hasAuthorized())
&& this.authentificatedTypes.contains(type)) {
/**
* Если клиент не авторизован, то мы не будем обрабатывать его сигналы на анициализацию звонка
* Если клиент не авторизован, то мы не будем обрабатывать его сигналы на инициализацию звонка и создание комнаты
* и просто отключим его от сервера.
*/
client.disconnect(Failures.HANDSHAKE_NOT_COMPLETED);
return;
}
NetworkSignalType type = packet.getSignalType();
if(src != null && !src.equals(eciAuthentificate.getPublicKey()) && authentificatedTypes.contains(type)) {
/**
* Если src в пакете не совпадает с авторизованным PK клиента, то это может означать, что клиент пытается
* отправить сигнал от другого пользователя, отключаем его от сервера.
*/
client.disconnect(Failures.DATA_MISSMATCH);
return;
}
if(type == NetworkSignalType.CALL) {
/**
* Инициируется звонок от src к dst, проверяем, что dst не занят другим звонком, если занят, то отправляем сигнал END_CALL_BECAUSE_BUSY обратно src
*/
Room room = this.fus.getRoomByParticipantId(packet.getDst());
if(room != null) {
if(this.callManager.isBusy(dst) || this.callManager.isBusy(src)) {
/**
* Получатель сигнала уже находится в другой комнате, значит он занят другим звонком, отправляем сигнал END_CALL_BECAUSE_BUSY обратно src
*/
Packet26SignalPeer responsePacket = new Packet26SignalPeer();
responsePacket.setSignalType(NetworkSignalType.END_CALL_BECAUSE_BUSY);
this.clientManager.sendPacketToAuthorizedPK(packet.getSrc(), responsePacket);
client.send(responsePacket);
return;
}
}
if(type == NetworkSignalType.CREATE_ROOM){
/**
* Создается комната для звонка
* Генерируем CallID и JoinToken
*/
Room room = this.fus.createRoom();
room.addParticipant(packet.getSrc());
room.addParticipant(packet.getDst());
packet.setRoomId(room.getRoomId());
String callId = UUID.randomUUID().toString();
String joinToken = UUID.randomUUID().toString();
packet.setJoinToken(joinToken);
packet.setCallId(callId);
/**
* Результат создания комнаты транслируем обоим участникам, чтобы они могли начать обмен WebRTC SDP, и тд
* Создаем сессию звонка и добавляем в нее звонящего
*/
this.clientManager.sendPacketToAuthorizedPK(packet.getSrc(), packet);
this.clientManager.sendPacketToAuthorizedPK(packet.getDst(), packet);
CallSession session = this.callManager.createCall(callId, joinToken);
session.joinCall(src, client);
/**
* Добавляем dst в ringing, чтобы пометить, что ему поступает звонок
*/
session.addRinging(dst);
/**
* Получатель сигнала не занят, отправляем ему пуш уведомление о входящем звонке и сигнал CALL для инициализации звонка
*/
pushNotifyDispatcher.sendPush(dst, new HashMap<>(){{
put("type", PushType.CALL);
put("dialog", src);
put("callId", callId);
put("joinToken", joinToken);
}});
/**
* Отправляем сигнал CALL всем авторизованным устройствам вызываемого абонента
*/
this.clientManager.sendPacketToAuthorizedPK(dst, packet);
return;
}
/**
* TODO: Проверка на существование получателя
*/
this.clientManager.sendPacketToAuthorizedPK(packet.getDst(), packet);
/**
* TODO: Высокоприоритетный пуш для сигналов звонков, чтобы мобильные устройства могли показать
* интерфейс входящего звонка, даже если приложение находится в фоне
*/
if(type == NetworkSignalType.ACCEPT){
String callId = packet.getCallId();
String joinToken = packet.getJoinToken();
CallSession session = this.callManager.getCallSession(callId, joinToken);
if(session == null) {
/**
* Сессии звонка нет
*/
client.disconnect(Failures.NO_CALL_SESSION);
return;
}
if(!session.isValidSource(src)) {
/**
* Клиент не состоит в сессии звонка, отключаем его от сервера, так как он отправляет некорректные данные
*/
client.disconnect(Failures.DATA_MISSMATCH);
return;
}
Room room = this.fus.createRoom();
session.setRoom(room);
session.joinCall(src, client);
for(String participant : session.clients.keySet()) {
room.addParticipant(participant);
}
session.sendPacket(packet, client);
/**
* Сбрасываем вызов на всех остальных устройствах пользователя, который принимает звонок,
* чтобы он не смог принять или отклонить звонок с другого устройства
*/
Packet26SignalPeer endCallOtherDevices = new Packet26SignalPeer();
endCallOtherDevices.setSignalType(NetworkSignalType.END_CALL);
this.clientManager.sendPacketToAuthorizedPK(src, endCallOtherDevices, client);
return;
}
if(type == NetworkSignalType.KEY_EXCHANGE){
/**
* Ретранслируем ключи в рамках сессии
*/
CallSession session = this.callManager.getCallSession(client);
if(session == null) {
/**
* Сессии звонка нет
*/
client.disconnect(Failures.NO_CALL_SESSION);
return;
}
/**
* Обмениваемся ключами в рамках сессии, ретранслируя их всем участникам сессии, кроме отправителя
*/
session.sendPacket(packet, client);
return;
}
if(type == NetworkSignalType.END_CALL) {
/**
* Ретранслируем сигнал окончания звонка всем участникам сессии, кроме отправителя, и удаляем сессию
*/
/**
* Сначала получаем сессию по сокету отправителя пакета, если не находим, то пробуем найти сессию по callId и joinToken из пакета, если не находим,
* то отключаем клиента от сервера, так как он отправляет некорректные данные
*/
CallSession session = this.callManager.getCallSession(client);
if(session == null) {
String callId = packet.getCallId();
String joinToken = packet.getJoinToken();
session = this.callManager.getCallSession(callId, joinToken);
}
if(session == null) {
/**
* Сессии звонка нет, скорее всего она была удалена при обрыве RTC Peer Connection,
* при срабатывании RTCPeerConnection::close на клиенте раньше, чем клиент отправил сигнал END_CALL
*/
return;
}
/**
* Отправляем сигнал окончания звонка всем участникам сессии, кроме отправителя
*/
session.sendPacket(packet, client);
/**
* Отправляем пакет вызываемым (ringing) пользователям (которые еще не в сессии)
*/
this.callManager.sendPacketToRinging(session, packet);
/**
* Удаляем сессию из активных сессий звонков
*/
this.callManager.removeSession(session);
return;
}
if(type == NetworkSignalType.ACTIVE) {
/**
* Клиент сообщил, что прошел стадию обмена ключами и звонок активен
*/
CallSession session = this.callManager.getCallSession(client);
if(session == null) {
/**
* Сессии звонка нет
*/
client.disconnect(Failures.NO_CALL_SESSION);
return;
}
session.sendPacket(packet, null);
}
}
}

View File

@@ -1,10 +1,10 @@
package im.rosetta.executors;
import im.rosetta.Failures;
import im.rosetta.client.tags.ECIAuthentificate;
import im.rosetta.calls.CallManager;
import im.rosetta.calls.CallSession;
import im.rosetta.packet.Packet27WebRTC;
import im.rosetta.packet.runtime.NetworkWebRTCType;
import im.rosetta.service.services.ForwardUnitService;
import io.g365sfu.Room;
import io.orprotocol.ProtocolException;
import io.orprotocol.client.Client;
@@ -12,35 +12,42 @@ import io.orprotocol.packet.PacketExecutor;
public class Executor27WebRTC extends PacketExecutor<Packet27WebRTC> {
private ForwardUnitService fus;
private CallManager callManager;
public Executor27WebRTC(ForwardUnitService fus) {
this.fus = fus;
public Executor27WebRTC(CallManager callManager) {
this.callManager = callManager;
}
@Override
public void onPacketReceived(Packet27WebRTC packet, Client client) throws Exception, ProtocolException {
ECIAuthentificate eciAuthentificate = client.getTag(ECIAuthentificate.class);
if(eciAuthentificate == null || !eciAuthentificate.hasAuthorized()) {
/**
* Получаем, в какой сессии находится этот сокет
*/
CallSession session = this.callManager.getCallSession(client);
if(session == null) {
/**
* Если клиент не авторизован, то мы не будем обрабатывать его сигналы на инициализацию звонка
* и просто отключим его от сервера.
* Если сессия не найдена, то мы не будем обрабатывать сигналы для звонка
*/
client.disconnect(Failures.HANDSHAKE_NOT_COMPLETED);
return;
}
String publicKey = eciAuthentificate.getPublicKey();
/**
* Так как в комнатах Participants это публичные ключи пользователей, то мы можем
* найти комнату, в которой находится пользователь, по его публичному ключу
*/
Room room = this.fus.getRoomByParticipantId(publicKey);
Room room = session.getRoom();
if(room == null) {
/**
* Если комната не найдена, то мы не будем обрабатывать сигналы для звонка
* и просто отключим клиента от сервера.
* Звонок еще не активен, а значит комнаты еще нет. Нельзя обменяться WebRTC сигналами пока комнаты еще нет.
*/
return;
}
/**
* Получаем публичный ключ, которым представился клиент, в рамках сессии звонка.
* Мы не делаем это через ECIAuthentificate, так как в рамках звонка клиент может не быть авторизован, но при этом он уже находится в сессии звонка, и мы можем идентифицировать его по публичному ключу,
* который он указал при присоединении к звонку используя joinToken.
* Так что, несмотря на то, что клиент может быть не авторизован, мы все равно можем достоверно знать его публичный ключ
*/
String publicKey = session.getPublicKey(client);
if(publicKey == null) {
/**
* Избыточная проверка, так как если клиент находится в сессии, то он должен быть в списке клиентов сессии,
* но на всякий случай проверим это, чтобы избежать возможных ошибок
*/
client.disconnect(Failures.DATA_MISSMATCH);
return;

View File

@@ -2,8 +2,6 @@ package im.rosetta.executors;
import java.util.ArrayList;
import im.rosetta.Failures;
import im.rosetta.client.tags.ECIAuthentificate;
import im.rosetta.packet.Packet28IceServers;
import im.rosetta.service.services.ForwardUnitService;
import io.orprotocol.ProtocolException;
@@ -20,15 +18,6 @@ public class Executor28IceServers extends PacketExecutor<Packet28IceServers> {
@Override
public void onPacketReceived(Packet28IceServers packet, Client client) throws Exception, ProtocolException {
ECIAuthentificate eciAuthentificate = client.getTag(ECIAuthentificate.class);
if(eciAuthentificate == null || !eciAuthentificate.hasAuthorized()) {
/**
* Если клиент не авторизован, то мы не будем обрабатывать его запрос на получение ICE серверов
* и просто отключим его от сервера.
*/
client.disconnect(Failures.HANDSHAKE_NOT_COMPLETED);
return;
}
/**
* Берем TURN сервера и отправляем их клиенту
*/

View File

@@ -13,9 +13,9 @@ import im.rosetta.event.EventManager;
import im.rosetta.event.events.handshake.HandshakeCompletedEvent;
import im.rosetta.event.events.handshake.HandshakeDeviceConfirmEvent;
import im.rosetta.event.events.handshake.HandshakeFailedEvent;
import im.rosetta.packet.Packet0Handshake;
import im.rosetta.packet.Packet9DeviceNew;
import im.rosetta.packet.runtime.HandshakeStage;
import im.rosetta.network.enums.HandshakeStage;
import im.rosetta.network.packet.PacketDeviceNew;
import im.rosetta.network.packet.PacketHandshake;
import im.rosetta.service.services.BufferService;
import im.rosetta.service.services.DeviceService;
@@ -25,7 +25,7 @@ import io.orprotocol.lock.Lock;
import io.orprotocol.packet.PacketExecutor;
import io.orprotocol.packet.PacketManager;
public class Executor0Handshake extends PacketExecutor<Packet0Handshake> {
public class ExecutorHandshake extends PacketExecutor<PacketHandshake> {
private final UserRepository userRepository = new UserRepository();
private final DeviceRepository deviceRepository = new DeviceRepository();
@@ -35,7 +35,7 @@ public class Executor0Handshake extends PacketExecutor<Packet0Handshake> {
private final BufferRepository bufferRepository = new BufferRepository();
private final BufferService bufferService;
public Executor0Handshake(EventManager eventManager, ClientManager clientManager, PacketManager packetManager) {
public ExecutorHandshake(EventManager eventManager, ClientManager clientManager, PacketManager packetManager) {
this.eventManager = eventManager;
this.clientManager = clientManager;
this.bufferService = new BufferService(bufferRepository, packetManager);
@@ -43,7 +43,7 @@ public class Executor0Handshake extends PacketExecutor<Packet0Handshake> {
@Override
@Lock(lockFor = "publicKey")
public void onPacketReceived(Packet0Handshake handshake, Client client) throws ProtocolException {
public void onPacketReceived(PacketHandshake handshake, Client client) throws ProtocolException {
String publicKey = handshake.getPublicKey();
String privateKey = handshake.getPrivateKey();
String deviceId = handshake.getDeviceId();
@@ -180,7 +180,7 @@ public class Executor0Handshake extends PacketExecutor<Packet0Handshake> {
/**
* Уведомляем все авторизованные устройства пользователя о том, что нужно подтвердить новое устройство
*/
Packet9DeviceNew newDevicePacket = new Packet9DeviceNew();
PacketDeviceNew newDevicePacket = new PacketDeviceNew();
newDevicePacket.setDeviceId(deviceId);
newDevicePacket.setDeviceName(deviceName);
newDevicePacket.setDeviceOs(deviceOs);

View File

@@ -9,16 +9,16 @@ import im.rosetta.Failures;
import im.rosetta.client.tags.ECIAuthentificate;
import im.rosetta.database.entity.User;
import im.rosetta.database.repository.UserRepository;
import im.rosetta.packet.Packet1UserInfo;
import im.rosetta.packet.Packet2Result;
import im.rosetta.packet.runtime.ResultCode;
import im.rosetta.network.enums.ResultCode;
import im.rosetta.network.packet.PacketResult;
import im.rosetta.network.packet.PacketUserInfo;
import im.rosetta.service.services.UserService;
import io.orprotocol.ProtocolException;
import io.orprotocol.client.Client;
import io.orprotocol.packet.PacketExecutor;
public class Executor1UserInfo extends PacketExecutor<Packet1UserInfo> {
public class ExecutorUserInfo extends PacketExecutor<PacketUserInfo> {
private final UserRepository userRepository = new UserRepository();
private final UserService userService = new UserService(userRepository);
@@ -32,11 +32,12 @@ public class Executor1UserInfo extends PacketExecutor<Packet1UserInfo> {
"deleted",
"safety",
"secure",
"rosettasafe"
"rosettasafe",
"rosettadev1"
));
@Override
public void onPacketReceived(Packet1UserInfo packet, Client client) throws Exception, ProtocolException {
public void onPacketReceived(PacketUserInfo packet, Client client) throws Exception, ProtocolException {
ECIAuthentificate eciAuthentificate = client.getTag(ECIAuthentificate.class);
String username = packet.getUsername();
String title = packet.getTitle();
@@ -64,7 +65,7 @@ public class Executor1UserInfo extends PacketExecutor<Packet1UserInfo> {
/**
* Это имя пользователя уже занято, отправляем клиенту ошибку
*/
Packet2Result result = new Packet2Result();
PacketResult result = new PacketResult();
result.setResultCode(ResultCode.USERNAME_TAKEN);
client.send(result);
return;
@@ -73,7 +74,7 @@ public class Executor1UserInfo extends PacketExecutor<Packet1UserInfo> {
/**
* Не удалось сменить username, отправляем клиенту ошибку
*/
Packet2Result result = new Packet2Result();
PacketResult result = new PacketResult();
result.setResultCode(ResultCode.INVALID);
client.send(result);
return;
@@ -84,7 +85,7 @@ public class Executor1UserInfo extends PacketExecutor<Packet1UserInfo> {
/**
* Не удалось сменить title, отправляем клиенту ошибку
*/
Packet2Result result = new Packet2Result();
PacketResult result = new PacketResult();
result.setResultCode(ResultCode.INVALID);
client.send(result);
return;
@@ -93,7 +94,7 @@ public class Executor1UserInfo extends PacketExecutor<Packet1UserInfo> {
/**
* Отправляем клиенту успешный результат
*/
Packet2Result result = new Packet2Result();
PacketResult result = new PacketResult();
result.setResultCode(ResultCode.SUCCESS);
client.send(result);
}

View File

@@ -0,0 +1,116 @@
package im.rosetta.network;
import im.rosetta.network.packet.PacketHandshake;
import im.rosetta.network.packet.PacketUserInfo;
import im.rosetta.network.packet.PacketResult;
import im.rosetta.network.packet.PacketSearch;
import im.rosetta.network.packet.PacketOnlineSubscribe;
import im.rosetta.network.packet.PacketOnlineState;
import im.rosetta.network.packet.PacketMessage;
import im.rosetta.network.packet.PacketRead;
import im.rosetta.network.packet.PacketDelivery;
import im.rosetta.network.packet.PacketDeviceNew;
import im.rosetta.network.packet.PacketRequestUpdate;
import im.rosetta.network.packet.PacketTypeing;
import im.rosetta.network.packet.PacketRequestTransport;
import im.rosetta.network.packet.PacketPushNotification;
import im.rosetta.network.packet.PacketGroupCreate;
import im.rosetta.network.packet.PacketGroupInfo;
import im.rosetta.network.packet.PacketGroupInviteInfo;
import im.rosetta.network.packet.PacketGroupJoin;
import im.rosetta.network.packet.PacketGroupLeave;
import im.rosetta.network.packet.PacketGroupBan;
import im.rosetta.network.packet.PacketDeviceList;
import im.rosetta.network.packet.PacketDeviceResolve;
import im.rosetta.network.packet.PacketSync;
import im.rosetta.network.packet.PacketSignalPeer;
import im.rosetta.network.packet.PacketWebRTC;
import im.rosetta.network.packet.PacketIceServers;
import io.orprotocol.packet.PacketManager;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class RccGeneratedPacketRegistry {
public static final int PACKET_HANDSHAKE_ID = 0;
public static final int PACKET_USER_INFO_ID = 1;
public static final int PACKET_RESULT_ID = 2;
public static final int PACKET_SEARCH_ID = 3;
public static final int PACKET_ONLINE_SUBSCRIBE_ID = 4;
public static final int PACKET_ONLINE_STATE_ID = 5;
public static final int PACKET_MESSAGE_ID = 6;
public static final int PACKET_READ_ID = 7;
public static final int PACKET_DELIVERY_ID = 8;
public static final int PACKET_DEVICE_NEW_ID = 9;
public static final int PACKET_REQUEST_UPDATE_ID = 10;
public static final int PACKET_TYPEING_ID = 11;
public static final int PACKET_REQUEST_TRANSPORT_ID = 15;
public static final int PACKET_PUSH_NOTIFICATION_ID = 16;
public static final int PACKET_GROUP_CREATE_ID = 17;
public static final int PACKET_GROUP_INFO_ID = 18;
public static final int PACKET_GROUP_INVITE_INFO_ID = 19;
public static final int PACKET_GROUP_JOIN_ID = 20;
public static final int PACKET_GROUP_LEAVE_ID = 21;
public static final int PACKET_GROUP_BAN_ID = 22;
public static final int PACKET_DEVICE_LIST_ID = 23;
public static final int PACKET_DEVICE_RESOLVE_ID = 24;
public static final int PACKET_SYNC_ID = 25;
public static final int PACKET_SIGNAL_PEER_ID = 26;
public static final int PACKET_WEB_RTC_ID = 27;
public static final int PACKET_ICE_SERVERS_ID = 28;
private RccGeneratedPacketRegistry() {}
public static void registerAll(PacketManager manager) {
manager.registerPacket(PACKET_HANDSHAKE_ID, PacketHandshake.class);
manager.registerCodec(PACKET_HANDSHAKE_ID, new im.rosetta.network.codec.PacketHandshakeCodec());
manager.registerPacket(PACKET_USER_INFO_ID, PacketUserInfo.class);
manager.registerCodec(PACKET_USER_INFO_ID, new im.rosetta.network.codec.PacketUserInfoCodec());
manager.registerPacket(PACKET_RESULT_ID, PacketResult.class);
manager.registerCodec(PACKET_RESULT_ID, new im.rosetta.network.codec.PacketResultCodec());
manager.registerPacket(PACKET_SEARCH_ID, PacketSearch.class);
manager.registerCodec(PACKET_SEARCH_ID, new im.rosetta.network.codec.PacketSearchCodec());
manager.registerPacket(PACKET_ONLINE_SUBSCRIBE_ID, PacketOnlineSubscribe.class);
manager.registerCodec(PACKET_ONLINE_SUBSCRIBE_ID, new im.rosetta.network.codec.PacketOnlineSubscribeCodec());
manager.registerPacket(PACKET_ONLINE_STATE_ID, PacketOnlineState.class);
manager.registerCodec(PACKET_ONLINE_STATE_ID, new im.rosetta.network.codec.PacketOnlineStateCodec());
manager.registerPacket(PACKET_MESSAGE_ID, PacketMessage.class);
manager.registerCodec(PACKET_MESSAGE_ID, new im.rosetta.network.codec.PacketMessageCodec());
manager.registerPacket(PACKET_READ_ID, PacketRead.class);
manager.registerCodec(PACKET_READ_ID, new im.rosetta.network.codec.PacketReadCodec());
manager.registerPacket(PACKET_DELIVERY_ID, PacketDelivery.class);
manager.registerCodec(PACKET_DELIVERY_ID, new im.rosetta.network.codec.PacketDeliveryCodec());
manager.registerPacket(PACKET_DEVICE_NEW_ID, PacketDeviceNew.class);
manager.registerCodec(PACKET_DEVICE_NEW_ID, new im.rosetta.network.codec.PacketDeviceNewCodec());
manager.registerPacket(PACKET_REQUEST_UPDATE_ID, PacketRequestUpdate.class);
manager.registerCodec(PACKET_REQUEST_UPDATE_ID, new im.rosetta.network.codec.PacketRequestUpdateCodec());
manager.registerPacket(PACKET_TYPEING_ID, PacketTypeing.class);
manager.registerCodec(PACKET_TYPEING_ID, new im.rosetta.network.codec.PacketTypeingCodec());
manager.registerPacket(PACKET_REQUEST_TRANSPORT_ID, PacketRequestTransport.class);
manager.registerCodec(PACKET_REQUEST_TRANSPORT_ID, new im.rosetta.network.codec.PacketRequestTransportCodec());
manager.registerPacket(PACKET_PUSH_NOTIFICATION_ID, PacketPushNotification.class);
manager.registerCodec(PACKET_PUSH_NOTIFICATION_ID, new im.rosetta.network.codec.PacketPushNotificationCodec());
manager.registerPacket(PACKET_GROUP_CREATE_ID, PacketGroupCreate.class);
manager.registerCodec(PACKET_GROUP_CREATE_ID, new im.rosetta.network.codec.PacketGroupCreateCodec());
manager.registerPacket(PACKET_GROUP_INFO_ID, PacketGroupInfo.class);
manager.registerCodec(PACKET_GROUP_INFO_ID, new im.rosetta.network.codec.PacketGroupInfoCodec());
manager.registerPacket(PACKET_GROUP_INVITE_INFO_ID, PacketGroupInviteInfo.class);
manager.registerCodec(PACKET_GROUP_INVITE_INFO_ID, new im.rosetta.network.codec.PacketGroupInviteInfoCodec());
manager.registerPacket(PACKET_GROUP_JOIN_ID, PacketGroupJoin.class);
manager.registerCodec(PACKET_GROUP_JOIN_ID, new im.rosetta.network.codec.PacketGroupJoinCodec());
manager.registerPacket(PACKET_GROUP_LEAVE_ID, PacketGroupLeave.class);
manager.registerCodec(PACKET_GROUP_LEAVE_ID, new im.rosetta.network.codec.PacketGroupLeaveCodec());
manager.registerPacket(PACKET_GROUP_BAN_ID, PacketGroupBan.class);
manager.registerCodec(PACKET_GROUP_BAN_ID, new im.rosetta.network.codec.PacketGroupBanCodec());
manager.registerPacket(PACKET_DEVICE_LIST_ID, PacketDeviceList.class);
manager.registerCodec(PACKET_DEVICE_LIST_ID, new im.rosetta.network.codec.PacketDeviceListCodec());
manager.registerPacket(PACKET_DEVICE_RESOLVE_ID, PacketDeviceResolve.class);
manager.registerCodec(PACKET_DEVICE_RESOLVE_ID, new im.rosetta.network.codec.PacketDeviceResolveCodec());
manager.registerPacket(PACKET_SYNC_ID, PacketSync.class);
manager.registerCodec(PACKET_SYNC_ID, new im.rosetta.network.codec.PacketSyncCodec());
manager.registerPacket(PACKET_SIGNAL_PEER_ID, PacketSignalPeer.class);
manager.registerCodec(PACKET_SIGNAL_PEER_ID, new im.rosetta.network.codec.PacketSignalPeerCodec());
manager.registerPacket(PACKET_WEB_RTC_ID, PacketWebRTC.class);
manager.registerCodec(PACKET_WEB_RTC_ID, new im.rosetta.network.codec.PacketWebRTCCodec());
manager.registerPacket(PACKET_ICE_SERVERS_ID, PacketIceServers.class);
manager.registerCodec(PACKET_ICE_SERVERS_ID, new im.rosetta.network.codec.PacketIceServersCodec());
}
}

View File

@@ -0,0 +1,90 @@
package im.rosetta.network.codec;
import java.util.ArrayList;
import java.util.List;
import io.orprotocol.ProtocolException;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.types.Attachment;
import im.rosetta.network.enums.AttachmentType;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class AttachmentCodec {
private static final int F_ID = 1;
private static final int F_BLOB = 2;
private static final int F_TYPE = 3;
private static final int F_PREVIEW = 4;
private static final int F_TRANSPORT = 5;
private AttachmentCodec() {}
public static Attachment decode(byte[] raw, int version) throws ProtocolException {
if (raw == null) {
return null;
}
TlvReader reader = new TlvReader(raw);
Attachment model = new Attachment();
if (version >= 1) {
model.id = reader.getString(F_ID);
}
if (version >= 1) {
model.blob = reader.getString(F_BLOB);
}
if (version >= 1) {
model.type = AttachmentType.fromCode(reader.getInt32(F_TYPE), version);
}
if (version >= 1) {
model.preview = reader.getString(F_PREVIEW);
}
if (version >= 1) {
model.transport = AttachmentTransportCodec.decode(reader.getBytes(F_TRANSPORT), version);
}
return model;
}
public static byte[] encode(Attachment model, int version) throws ProtocolException {
if (model == null) {
return null;
}
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (model.id != null) writer.writeString(F_ID, model.id);
}
if (version >= 1) {
if (model.blob != null) writer.writeString(F_BLOB, model.blob);
}
if (version >= 1) {
if (model.type != null) { model.type.requireSupportedInVersion(version); writer.writeInt32(F_TYPE, model.type.getCode()); }
}
if (version >= 1) {
if (model.preview != null) writer.writeString(F_PREVIEW, model.preview);
}
if (version >= 1) {
if (model.transport != null) writer.writeBytes(F_TRANSPORT, AttachmentTransportCodec.encode(model.transport, version));
}
return writer.toByteArray();
}
public static List<Attachment> decodeList(List<byte[]> raws, int version) throws ProtocolException {
List<Attachment> out = new ArrayList<>();
if (raws == null) {
return out;
}
for (byte[] raw : raws) {
out.add(decode(raw, version));
}
return out;
}
public static List<byte[]> encodeList(List<Attachment> values, int version) throws ProtocolException {
List<byte[]> out = new ArrayList<>();
if (values == null) {
return out;
}
for (Attachment value : values) {
out.add(encode(value, version));
}
return out;
}
}

View File

@@ -0,0 +1,68 @@
package im.rosetta.network.codec;
import java.util.ArrayList;
import java.util.List;
import io.orprotocol.ProtocolException;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.types.AttachmentTransport;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class AttachmentTransportCodec {
private static final int F_TRANSPORT_TAG = 1;
private static final int F_TRANSPORT_SERVER = 2;
private AttachmentTransportCodec() {}
public static AttachmentTransport decode(byte[] raw, int version) throws ProtocolException {
if (raw == null) {
return null;
}
TlvReader reader = new TlvReader(raw);
AttachmentTransport model = new AttachmentTransport();
if (version >= 1) {
model.transportTag = reader.getString(F_TRANSPORT_TAG);
}
if (version >= 1) {
model.transportServer = reader.getString(F_TRANSPORT_SERVER);
}
return model;
}
public static byte[] encode(AttachmentTransport model, int version) throws ProtocolException {
if (model == null) {
return null;
}
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (model.transportTag != null) writer.writeString(F_TRANSPORT_TAG, model.transportTag);
}
if (version >= 1) {
if (model.transportServer != null) writer.writeString(F_TRANSPORT_SERVER, model.transportServer);
}
return writer.toByteArray();
}
public static List<AttachmentTransport> decodeList(List<byte[]> raws, int version) throws ProtocolException {
List<AttachmentTransport> out = new ArrayList<>();
if (raws == null) {
return out;
}
for (byte[] raw : raws) {
out.add(decode(raw, version));
}
return out;
}
public static List<byte[]> encodeList(List<AttachmentTransport> values, int version) throws ProtocolException {
List<byte[]> out = new ArrayList<>();
if (values == null) {
return out;
}
for (AttachmentTransport value : values) {
out.add(encode(value, version));
}
return out;
}
}

View File

@@ -0,0 +1,91 @@
package im.rosetta.network.codec;
import java.util.ArrayList;
import java.util.List;
import io.orprotocol.ProtocolException;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.types.NetworkDevice;
import im.rosetta.network.enums.DeviceSolution;
import im.rosetta.network.enums.NetworkStatus;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class NetworkDeviceCodec {
private static final int F_NETWORK_STATUS = 1;
private static final int F_DEVICE_NAME = 2;
private static final int F_DEVICE_OS = 3;
private static final int F_DEVICE_ID = 4;
private static final int F_DEVICE_SOLUTION = 5;
private NetworkDeviceCodec() {}
public static NetworkDevice decode(byte[] raw, int version) throws ProtocolException {
if (raw == null) {
return null;
}
TlvReader reader = new TlvReader(raw);
NetworkDevice model = new NetworkDevice();
if (version >= 1) {
model.networkStatus = NetworkStatus.fromCode(reader.getInt32(F_NETWORK_STATUS), version);
}
if (version >= 1) {
model.deviceName = reader.getString(F_DEVICE_NAME);
}
if (version >= 1) {
model.deviceOs = reader.getString(F_DEVICE_OS);
}
if (version >= 1) {
model.deviceId = reader.getString(F_DEVICE_ID);
}
if (version >= 1) {
model.deviceSolution = DeviceSolution.fromCode(reader.getInt32(F_DEVICE_SOLUTION), version);
}
return model;
}
public static byte[] encode(NetworkDevice model, int version) throws ProtocolException {
if (model == null) {
return null;
}
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (model.networkStatus != null) { model.networkStatus.requireSupportedInVersion(version); writer.writeInt32(F_NETWORK_STATUS, model.networkStatus.getCode()); }
}
if (version >= 1) {
if (model.deviceName != null) writer.writeString(F_DEVICE_NAME, model.deviceName);
}
if (version >= 1) {
if (model.deviceOs != null) writer.writeString(F_DEVICE_OS, model.deviceOs);
}
if (version >= 1) {
if (model.deviceId != null) writer.writeString(F_DEVICE_ID, model.deviceId);
}
if (version >= 1) {
if (model.deviceSolution != null) { model.deviceSolution.requireSupportedInVersion(version); writer.writeInt32(F_DEVICE_SOLUTION, model.deviceSolution.getCode()); }
}
return writer.toByteArray();
}
public static List<NetworkDevice> decodeList(List<byte[]> raws, int version) throws ProtocolException {
List<NetworkDevice> out = new ArrayList<>();
if (raws == null) {
return out;
}
for (byte[] raw : raws) {
out.add(decode(raw, version));
}
return out;
}
public static List<byte[]> encodeList(List<NetworkDevice> values, int version) throws ProtocolException {
List<byte[]> out = new ArrayList<>();
if (values == null) {
return out;
}
for (NetworkDevice value : values) {
out.add(encode(value, version));
}
return out;
}
}

View File

@@ -0,0 +1,69 @@
package im.rosetta.network.codec;
import java.util.ArrayList;
import java.util.List;
import io.orprotocol.ProtocolException;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.types.PKNetworkStatus;
import im.rosetta.network.enums.NetworkStatus;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class PKNetworkStatusCodec {
private static final int F_PUBLIC_KEY = 1;
private static final int F_NETWORK_STATUS = 2;
private PKNetworkStatusCodec() {}
public static PKNetworkStatus decode(byte[] raw, int version) throws ProtocolException {
if (raw == null) {
return null;
}
TlvReader reader = new TlvReader(raw);
PKNetworkStatus model = new PKNetworkStatus();
if (version >= 1) {
model.publicKey = reader.getString(F_PUBLIC_KEY);
}
if (version >= 1) {
model.networkStatus = NetworkStatus.fromCode(reader.getInt32(F_NETWORK_STATUS), version);
}
return model;
}
public static byte[] encode(PKNetworkStatus model, int version) throws ProtocolException {
if (model == null) {
return null;
}
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (model.publicKey != null) writer.writeString(F_PUBLIC_KEY, model.publicKey);
}
if (version >= 1) {
if (model.networkStatus != null) { model.networkStatus.requireSupportedInVersion(version); writer.writeInt32(F_NETWORK_STATUS, model.networkStatus.getCode()); }
}
return writer.toByteArray();
}
public static List<PKNetworkStatus> decodeList(List<byte[]> raws, int version) throws ProtocolException {
List<PKNetworkStatus> out = new ArrayList<>();
if (raws == null) {
return out;
}
for (byte[] raw : raws) {
out.add(decode(raw, version));
}
return out;
}
public static List<byte[]> encodeList(List<PKNetworkStatus> values, int version) throws ProtocolException {
List<byte[]> out = new ArrayList<>();
if (values == null) {
return out;
}
for (PKNetworkStatus value : values) {
out.add(encode(value, version));
}
return out;
}
}

View File

@@ -0,0 +1,40 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketDelivery;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketDeliveryCodec implements Codec<PacketDelivery> {
private static final int F_MESSAGE_ID = 1;
private static final int F_TO_PUBLIC_KEY = 2;
@Override
public PacketDelivery decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketDelivery packet = new PacketDelivery();
if (version >= 1) {
packet.messageId = reader.getString(F_MESSAGE_ID);
}
if (version >= 1) {
packet.toPublicKey = reader.getString(F_TO_PUBLIC_KEY);
}
return packet;
}
@Override
public byte[] encode(PacketDelivery packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.messageId != null) writer.writeString(F_MESSAGE_ID, packet.messageId);
}
if (version >= 1) {
if (packet.toPublicKey != null) writer.writeString(F_TO_PUBLIC_KEY, packet.toPublicKey);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketDeviceList;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketDeviceListCodec implements Codec<PacketDeviceList> {
private static final int F_DEVICES = 1;
@Override
public PacketDeviceList decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketDeviceList packet = new PacketDeviceList();
if (version >= 1) {
packet.devices = NetworkDeviceCodec.decodeList(reader.getBytesList(F_DEVICES), version);
}
return packet;
}
@Override
public byte[] encode(PacketDeviceList packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.devices != null) writer.writeBytesList(F_DEVICES, NetworkDeviceCodec.encodeList(packet.devices, version));
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,54 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketDeviceNew;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketDeviceNewCodec implements Codec<PacketDeviceNew> {
private static final int F_IP_ADDRESS = 1;
private static final int F_DEVICE_ID = 2;
private static final int F_DEVICE_NAME = 3;
private static final int F_DEVICE_OS = 4;
@Override
public PacketDeviceNew decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketDeviceNew packet = new PacketDeviceNew();
if (version >= 1) {
packet.ipAddress = reader.getString(F_IP_ADDRESS);
}
if (version >= 1) {
packet.deviceId = reader.getString(F_DEVICE_ID);
}
if (version >= 1) {
packet.deviceName = reader.getString(F_DEVICE_NAME);
}
if (version >= 1) {
packet.deviceOs = reader.getString(F_DEVICE_OS);
}
return packet;
}
@Override
public byte[] encode(PacketDeviceNew packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.ipAddress != null) writer.writeString(F_IP_ADDRESS, packet.ipAddress);
}
if (version >= 1) {
if (packet.deviceId != null) writer.writeString(F_DEVICE_ID, packet.deviceId);
}
if (version >= 1) {
if (packet.deviceName != null) writer.writeString(F_DEVICE_NAME, packet.deviceName);
}
if (version >= 1) {
if (packet.deviceOs != null) writer.writeString(F_DEVICE_OS, packet.deviceOs);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,41 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketDeviceResolve;
import im.rosetta.network.enums.DeviceSolution;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketDeviceResolveCodec implements Codec<PacketDeviceResolve> {
private static final int F_DEVICE_ID = 1;
private static final int F_SOLUTION = 2;
@Override
public PacketDeviceResolve decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketDeviceResolve packet = new PacketDeviceResolve();
if (version >= 1) {
packet.deviceId = reader.getString(F_DEVICE_ID);
}
if (version >= 1) {
packet.solution = DeviceSolution.fromCode(reader.getInt32(F_SOLUTION), version);
}
return packet;
}
@Override
public byte[] encode(PacketDeviceResolve packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.deviceId != null) writer.writeString(F_DEVICE_ID, packet.deviceId);
}
if (version >= 1) {
if (packet.solution != null) { packet.solution.requireSupportedInVersion(version); writer.writeInt32(F_SOLUTION, packet.solution.getCode()); }
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,40 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketGroupBan;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketGroupBanCodec implements Codec<PacketGroupBan> {
private static final int F_GROUP_ID = 1;
private static final int F_PUBLIC_KEY = 2;
@Override
public PacketGroupBan decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketGroupBan packet = new PacketGroupBan();
if (version >= 1) {
packet.groupId = reader.getString(F_GROUP_ID);
}
if (version >= 1) {
packet.publicKey = reader.getString(F_PUBLIC_KEY);
}
return packet;
}
@Override
public byte[] encode(PacketGroupBan packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.groupId != null) writer.writeString(F_GROUP_ID, packet.groupId);
}
if (version >= 1) {
if (packet.publicKey != null) writer.writeString(F_PUBLIC_KEY, packet.publicKey);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketGroupCreate;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketGroupCreateCodec implements Codec<PacketGroupCreate> {
private static final int F_GROUP_ID = 1;
@Override
public PacketGroupCreate decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketGroupCreate packet = new PacketGroupCreate();
if (version >= 1) {
packet.groupId = reader.getString(F_GROUP_ID);
}
return packet;
}
@Override
public byte[] encode(PacketGroupCreate packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.groupId != null) writer.writeString(F_GROUP_ID, packet.groupId);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,40 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketGroupInfo;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketGroupInfoCodec implements Codec<PacketGroupInfo> {
private static final int F_GROUP_ID = 1;
private static final int F_MEMBERS_PKS = 2;
@Override
public PacketGroupInfo decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketGroupInfo packet = new PacketGroupInfo();
if (version >= 1) {
packet.groupId = reader.getString(F_GROUP_ID);
}
if (version >= 1) {
packet.membersPKs = reader.getStringList(F_MEMBERS_PKS);
}
return packet;
}
@Override
public byte[] encode(PacketGroupInfo packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.groupId != null) writer.writeString(F_GROUP_ID, packet.groupId);
}
if (version >= 1) {
if (packet.membersPKs != null) writer.writeStringList(F_MEMBERS_PKS, packet.membersPKs);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,48 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketGroupInviteInfo;
import im.rosetta.network.enums.GroupStatus;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketGroupInviteInfoCodec implements Codec<PacketGroupInviteInfo> {
private static final int F_GROUP_ID = 1;
private static final int F_MEMBERS_COUNT = 2;
private static final int F_STATUS = 3;
@Override
public PacketGroupInviteInfo decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketGroupInviteInfo packet = new PacketGroupInviteInfo();
if (version >= 1) {
packet.groupId = reader.getString(F_GROUP_ID);
}
if (version >= 1) {
packet.membersCount = reader.getInt32(F_MEMBERS_COUNT);
}
if (version >= 1) {
packet.status = GroupStatus.fromCode(reader.getInt32(F_STATUS), version);
}
return packet;
}
@Override
public byte[] encode(PacketGroupInviteInfo packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.groupId != null) writer.writeString(F_GROUP_ID, packet.groupId);
}
if (version >= 1) {
if (packet.membersCount != null) writer.writeInt32(F_MEMBERS_COUNT, packet.membersCount);
}
if (version >= 1) {
if (packet.status != null) { packet.status.requireSupportedInVersion(version); writer.writeInt32(F_STATUS, packet.status.getCode()); }
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,48 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketGroupJoin;
import im.rosetta.network.enums.GroupStatus;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketGroupJoinCodec implements Codec<PacketGroupJoin> {
private static final int F_GROUP_ID = 1;
private static final int F_STATUS = 2;
private static final int F_GROUP_STRING = 3;
@Override
public PacketGroupJoin decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketGroupJoin packet = new PacketGroupJoin();
if (version >= 1) {
packet.groupId = reader.getString(F_GROUP_ID);
}
if (version >= 1) {
packet.status = GroupStatus.fromCode(reader.getInt32(F_STATUS), version);
}
if (version >= 1) {
packet.groupString = reader.getString(F_GROUP_STRING);
}
return packet;
}
@Override
public byte[] encode(PacketGroupJoin packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.groupId != null) writer.writeString(F_GROUP_ID, packet.groupId);
}
if (version >= 1) {
if (packet.status != null) { packet.status.requireSupportedInVersion(version); writer.writeInt32(F_STATUS, packet.status.getCode()); }
}
if (version >= 1) {
if (packet.groupString != null) writer.writeString(F_GROUP_STRING, packet.groupString);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketGroupLeave;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketGroupLeaveCodec implements Codec<PacketGroupLeave> {
private static final int F_GROUP_ID = 1;
@Override
public PacketGroupLeave decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketGroupLeave packet = new PacketGroupLeave();
if (version >= 1) {
packet.groupId = reader.getString(F_GROUP_ID);
}
return packet;
}
@Override
public byte[] encode(PacketGroupLeave packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.groupId != null) writer.writeString(F_GROUP_ID, packet.groupId);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,83 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketHandshake;
import im.rosetta.network.enums.HandshakeStage;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketHandshakeCodec implements Codec<PacketHandshake> {
private static final int F_PUBLIC_KEY = 1;
private static final int F_PRIVATE_KEY = 2;
private static final int F_PROTOCOL_VERSION = 3;
private static final int F_HEARTBEAT_INTERVAL = 4;
private static final int F_DEVICE_ID = 5;
private static final int F_DEVICE_NAME = 6;
private static final int F_DEVICE_OS = 7;
private static final int F_HANDSHAKE_STAGE = 8;
@Override
public PacketHandshake decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketHandshake packet = new PacketHandshake();
if (version >= 1) {
packet.publicKey = reader.getString(F_PUBLIC_KEY);
}
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
if (version >= 1) {
packet.protocolVersion = reader.getInt32(F_PROTOCOL_VERSION);
}
if (version >= 1) {
packet.heartbeatInterval = reader.getInt32(F_HEARTBEAT_INTERVAL);
}
if (version >= 1) {
packet.deviceId = reader.getString(F_DEVICE_ID);
}
if (version >= 1) {
packet.deviceName = reader.getString(F_DEVICE_NAME);
}
if (version >= 1) {
packet.deviceOs = reader.getString(F_DEVICE_OS);
}
if (version >= 1) {
packet.handshakeStage = HandshakeStage.fromCode(reader.getInt32(F_HANDSHAKE_STAGE), version);
}
return packet;
}
@Override
public byte[] encode(PacketHandshake packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.publicKey != null) writer.writeString(F_PUBLIC_KEY, packet.publicKey);
}
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
if (version >= 1) {
if (packet.protocolVersion != null) writer.writeInt32(F_PROTOCOL_VERSION, packet.protocolVersion);
}
if (version >= 1) {
if (packet.heartbeatInterval != null) writer.writeInt32(F_HEARTBEAT_INTERVAL, packet.heartbeatInterval);
}
if (version >= 1) {
if (packet.deviceId != null) writer.writeString(F_DEVICE_ID, packet.deviceId);
}
if (version >= 1) {
if (packet.deviceName != null) writer.writeString(F_DEVICE_NAME, packet.deviceName);
}
if (version >= 1) {
if (packet.deviceOs != null) writer.writeString(F_DEVICE_OS, packet.deviceOs);
}
if (version >= 1) {
if (packet.handshakeStage != null) { packet.handshakeStage.requireSupportedInVersion(version); writer.writeInt32(F_HANDSHAKE_STAGE, packet.handshakeStage.getCode()); }
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketIceServers;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketIceServersCodec implements Codec<PacketIceServers> {
private static final int F_ICE_SERVERS = 1;
@Override
public PacketIceServers decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketIceServers packet = new PacketIceServers();
if (version >= 1) {
packet.iceServers = RTCIceServerCodec.decodeList(reader.getBytesList(F_ICE_SERVERS), version);
}
return packet;
}
@Override
public byte[] encode(PacketIceServers packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.iceServers != null) writer.writeBytesList(F_ICE_SERVERS, RTCIceServerCodec.encodeList(packet.iceServers, version));
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,89 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketMessage;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketMessageCodec implements Codec<PacketMessage> {
private static final int F_FROM_PUBLIC_KEY = 1;
private static final int F_TO_PUBLIC_KEY = 2;
private static final int F_PRIVATE_KEY = 3;
private static final int F_CONTENT = 4;
private static final int F_CHACHA_KEY = 5;
private static final int F_TIMESTAMP = 6;
private static final int F_MESSAGE_ID = 7;
private static final int F_ATTACHMENTS = 8;
private static final int F_AES_CHACHA_KEY = 9;
@Override
public PacketMessage decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketMessage packet = new PacketMessage();
if (version >= 1) {
packet.fromPublicKey = reader.getString(F_FROM_PUBLIC_KEY);
}
if (version >= 1) {
packet.toPublicKey = reader.getString(F_TO_PUBLIC_KEY);
}
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
if (version >= 1) {
packet.content = reader.getString(F_CONTENT);
}
if (version >= 1) {
packet.chachaKey = reader.getString(F_CHACHA_KEY);
}
if (version >= 1) {
packet.timestamp = reader.getInt64(F_TIMESTAMP);
}
if (version >= 1) {
packet.messageId = reader.getString(F_MESSAGE_ID);
}
if (version >= 1) {
packet.attachments = AttachmentCodec.decodeList(reader.getBytesList(F_ATTACHMENTS), version);
}
if (version >= 1) {
packet.aesChachaKey = reader.getString(F_AES_CHACHA_KEY);
}
return packet;
}
@Override
public byte[] encode(PacketMessage packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.fromPublicKey != null) writer.writeString(F_FROM_PUBLIC_KEY, packet.fromPublicKey);
}
if (version >= 1) {
if (packet.toPublicKey != null) writer.writeString(F_TO_PUBLIC_KEY, packet.toPublicKey);
}
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
if (version >= 1) {
if (packet.content != null) writer.writeString(F_CONTENT, packet.content);
}
if (version >= 1) {
if (packet.chachaKey != null) writer.writeString(F_CHACHA_KEY, packet.chachaKey);
}
if (version >= 1) {
if (packet.timestamp != null) writer.writeInt64(F_TIMESTAMP, packet.timestamp);
}
if (version >= 1) {
if (packet.messageId != null) writer.writeString(F_MESSAGE_ID, packet.messageId);
}
if (version >= 1) {
if (packet.attachments != null) writer.writeBytesList(F_ATTACHMENTS, AttachmentCodec.encodeList(packet.attachments, version));
}
if (version >= 1) {
if (packet.aesChachaKey != null) writer.writeString(F_AES_CHACHA_KEY, packet.aesChachaKey);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketOnlineState;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketOnlineStateCodec implements Codec<PacketOnlineState> {
private static final int F_PK_NETWORK_STATUSES = 1;
@Override
public PacketOnlineState decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketOnlineState packet = new PacketOnlineState();
if (version >= 1) {
packet.pkNetworkStatuses = PKNetworkStatusCodec.decodeList(reader.getBytesList(F_PK_NETWORK_STATUSES), version);
}
return packet;
}
@Override
public byte[] encode(PacketOnlineState packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.pkNetworkStatuses != null) writer.writeBytesList(F_PK_NETWORK_STATUSES, PKNetworkStatusCodec.encodeList(packet.pkNetworkStatuses, version));
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,40 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketOnlineSubscribe;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketOnlineSubscribeCodec implements Codec<PacketOnlineSubscribe> {
private static final int F_PRIVATE_KEY = 1;
private static final int F_PUBLIC_KEYS = 2;
@Override
public PacketOnlineSubscribe decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketOnlineSubscribe packet = new PacketOnlineSubscribe();
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
if (version >= 1) {
packet.publicKeys = reader.getStringList(F_PUBLIC_KEYS);
}
return packet;
}
@Override
public byte[] encode(PacketOnlineSubscribe packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
if (version >= 1) {
if (packet.publicKeys != null) writer.writeStringList(F_PUBLIC_KEYS, packet.publicKeys);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,56 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketPushNotification;
import im.rosetta.network.enums.NotificationAction;
import im.rosetta.network.enums.TokenType;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketPushNotificationCodec implements Codec<PacketPushNotification> {
private static final int F_NOTIFICATION_TOKEN = 1;
private static final int F_ACTION = 2;
private static final int F_TOKEN_TYPE = 3;
private static final int F_DEVICE_ID = 4;
@Override
public PacketPushNotification decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketPushNotification packet = new PacketPushNotification();
if (version >= 1) {
packet.notificationToken = reader.getString(F_NOTIFICATION_TOKEN);
}
if (version >= 1) {
packet.action = NotificationAction.fromCode(reader.getInt32(F_ACTION), version);
}
if (version >= 1) {
packet.tokenType = TokenType.fromCode(reader.getInt32(F_TOKEN_TYPE), version);
}
if (version >= 1) {
packet.deviceId = reader.getString(F_DEVICE_ID);
}
return packet;
}
@Override
public byte[] encode(PacketPushNotification packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.notificationToken != null) writer.writeString(F_NOTIFICATION_TOKEN, packet.notificationToken);
}
if (version >= 1) {
if (packet.action != null) { packet.action.requireSupportedInVersion(version); writer.writeInt32(F_ACTION, packet.action.getCode()); }
}
if (version >= 1) {
if (packet.tokenType != null) { packet.tokenType.requireSupportedInVersion(version); writer.writeInt32(F_TOKEN_TYPE, packet.tokenType.getCode()); }
}
if (version >= 1) {
if (packet.deviceId != null) writer.writeString(F_DEVICE_ID, packet.deviceId);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,47 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketRead;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketReadCodec implements Codec<PacketRead> {
private static final int F_FROM_PUBLIC_KEY = 1;
private static final int F_TO_PUBLIC_KEY = 2;
private static final int F_PRIVATE_KEY = 3;
@Override
public PacketRead decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketRead packet = new PacketRead();
if (version >= 1) {
packet.fromPublicKey = reader.getString(F_FROM_PUBLIC_KEY);
}
if (version >= 1) {
packet.toPublicKey = reader.getString(F_TO_PUBLIC_KEY);
}
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
return packet;
}
@Override
public byte[] encode(PacketRead packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.fromPublicKey != null) writer.writeString(F_FROM_PUBLIC_KEY, packet.fromPublicKey);
}
if (version >= 1) {
if (packet.toPublicKey != null) writer.writeString(F_TO_PUBLIC_KEY, packet.toPublicKey);
}
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketRequestTransport;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketRequestTransportCodec implements Codec<PacketRequestTransport> {
private static final int F_SERVER = 1;
@Override
public PacketRequestTransport decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketRequestTransport packet = new PacketRequestTransport();
if (version >= 1) {
packet.server = reader.getString(F_SERVER);
}
return packet;
}
@Override
public byte[] encode(PacketRequestTransport packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.server != null) writer.writeString(F_SERVER, packet.server);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketRequestUpdate;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketRequestUpdateCodec implements Codec<PacketRequestUpdate> {
private static final int F_SERVER = 1;
@Override
public PacketRequestUpdate decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketRequestUpdate packet = new PacketRequestUpdate();
if (version >= 1) {
packet.server = reader.getString(F_SERVER);
}
return packet;
}
@Override
public byte[] encode(PacketRequestUpdate packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.server != null) writer.writeString(F_SERVER, packet.server);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,34 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketResult;
import im.rosetta.network.enums.ResultCode;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketResultCodec implements Codec<PacketResult> {
private static final int F_RESULT_CODE = 1;
@Override
public PacketResult decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketResult packet = new PacketResult();
if (version >= 1) {
packet.resultCode = ResultCode.fromCode(reader.getInt32(F_RESULT_CODE), version);
}
return packet;
}
@Override
public byte[] encode(PacketResult packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.resultCode != null) { packet.resultCode.requireSupportedInVersion(version); writer.writeInt32(F_RESULT_CODE, packet.resultCode.getCode()); }
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,47 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketSearch;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketSearchCodec implements Codec<PacketSearch> {
private static final int F_PRIVATE_KEY = 1;
private static final int F_SEARCH = 2;
private static final int F_SEARCH_INFO = 3;
@Override
public PacketSearch decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketSearch packet = new PacketSearch();
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
if (version >= 1) {
packet.search = reader.getString(F_SEARCH);
}
if (version >= 1) {
packet.searchInfo = SearchInfoCodec.decodeList(reader.getBytesList(F_SEARCH_INFO), version);
}
return packet;
}
@Override
public byte[] encode(PacketSearch packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
if (version >= 1) {
if (packet.search != null) writer.writeString(F_SEARCH, packet.search);
}
if (version >= 1) {
if (packet.searchInfo != null) writer.writeBytesList(F_SEARCH_INFO, SearchInfoCodec.encodeList(packet.searchInfo, version));
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,69 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketSignalPeer;
import im.rosetta.network.enums.SignalType;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketSignalPeerCodec implements Codec<PacketSignalPeer> {
private static final int F_SRC = 1;
private static final int F_DST = 2;
private static final int F_SHARED_PUBLIC = 3;
private static final int F_SIGNAL_TYPE = 4;
private static final int F_CALL_ID = 5;
private static final int F_JOIN_TOKEN = 6;
@Override
public PacketSignalPeer decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketSignalPeer packet = new PacketSignalPeer();
if (version >= 1) {
packet.src = reader.getString(F_SRC);
}
if (version >= 1) {
packet.dst = reader.getString(F_DST);
}
if (version >= 1) {
packet.sharedPublic = reader.getString(F_SHARED_PUBLIC);
}
if (version >= 1) {
packet.signalType = SignalType.fromCode(reader.getInt32(F_SIGNAL_TYPE), version);
}
if (version >= 1) {
packet.callId = reader.getString(F_CALL_ID);
}
if (version >= 1) {
packet.joinToken = reader.getString(F_JOIN_TOKEN);
}
return packet;
}
@Override
public byte[] encode(PacketSignalPeer packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.src != null) writer.writeString(F_SRC, packet.src);
}
if (version >= 1) {
if (packet.dst != null) writer.writeString(F_DST, packet.dst);
}
if (version >= 1) {
if (packet.sharedPublic != null) writer.writeString(F_SHARED_PUBLIC, packet.sharedPublic);
}
if (version >= 1) {
if (packet.signalType != null) { packet.signalType.requireSupportedInVersion(version); writer.writeInt32(F_SIGNAL_TYPE, packet.signalType.getCode()); }
}
if (version >= 1) {
if (packet.callId != null) writer.writeString(F_CALL_ID, packet.callId);
}
if (version >= 1) {
if (packet.joinToken != null) writer.writeString(F_JOIN_TOKEN, packet.joinToken);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,41 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketSync;
import im.rosetta.network.enums.SyncStatus;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketSyncCodec implements Codec<PacketSync> {
private static final int F_SYNC_STATUS = 1;
private static final int F_TIMESTAMP = 2;
@Override
public PacketSync decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketSync packet = new PacketSync();
if (version >= 1) {
packet.syncStatus = SyncStatus.fromCode(reader.getInt32(F_SYNC_STATUS), version);
}
if (version >= 1) {
packet.timestamp = reader.getInt64(F_TIMESTAMP);
}
return packet;
}
@Override
public byte[] encode(PacketSync packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.syncStatus != null) { packet.syncStatus.requireSupportedInVersion(version); writer.writeInt32(F_SYNC_STATUS, packet.syncStatus.getCode()); }
}
if (version >= 1) {
if (packet.timestamp != null) writer.writeInt64(F_TIMESTAMP, packet.timestamp);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,47 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketTypeing;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketTypeingCodec implements Codec<PacketTypeing> {
private static final int F_FROM_PUBLIC_KEY = 1;
private static final int F_TO_PUBLIC_KEY = 2;
private static final int F_PRIVATE_KEY = 3;
@Override
public PacketTypeing decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketTypeing packet = new PacketTypeing();
if (version >= 1) {
packet.fromPublicKey = reader.getString(F_FROM_PUBLIC_KEY);
}
if (version >= 1) {
packet.toPublicKey = reader.getString(F_TO_PUBLIC_KEY);
}
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
return packet;
}
@Override
public byte[] encode(PacketTypeing packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.fromPublicKey != null) writer.writeString(F_FROM_PUBLIC_KEY, packet.fromPublicKey);
}
if (version >= 1) {
if (packet.toPublicKey != null) writer.writeString(F_TO_PUBLIC_KEY, packet.toPublicKey);
}
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,47 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketUserInfo;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketUserInfoCodec implements Codec<PacketUserInfo> {
private static final int F_PRIVATE_KEY = 1;
private static final int F_USERNAME = 2;
private static final int F_TITLE = 3;
@Override
public PacketUserInfo decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketUserInfo packet = new PacketUserInfo();
if (version >= 1) {
packet.privateKey = reader.getString(F_PRIVATE_KEY);
}
if (version >= 1) {
packet.username = reader.getString(F_USERNAME);
}
if (version >= 1) {
packet.title = reader.getString(F_TITLE);
}
return packet;
}
@Override
public byte[] encode(PacketUserInfo packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.privateKey != null) writer.writeString(F_PRIVATE_KEY, packet.privateKey);
}
if (version >= 1) {
if (packet.username != null) writer.writeString(F_USERNAME, packet.username);
}
if (version >= 1) {
if (packet.title != null) writer.writeString(F_TITLE, packet.title);
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,41 @@
package im.rosetta.network.codec;
import io.orprotocol.ProtocolException;
import io.orprotocol.buffer.Buffer;
import io.orprotocol.codec.Codec;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.packet.PacketWebRTC;
import im.rosetta.network.enums.WebRTCType;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class PacketWebRTCCodec implements Codec<PacketWebRTC> {
private static final int F_SDP_OR_CANDIDATE = 1;
private static final int F_TYPE = 2;
@Override
public PacketWebRTC decode(Buffer data, int version) throws ProtocolException {
byte[] payload = data.readBytes(data.remaining());
TlvReader reader = new TlvReader(payload);
PacketWebRTC packet = new PacketWebRTC();
if (version >= 1) {
packet.sdpOrCandidate = reader.getString(F_SDP_OR_CANDIDATE);
}
if (version >= 1) {
packet.type = WebRTCType.fromCode(reader.getInt32(F_TYPE), version);
}
return packet;
}
@Override
public byte[] encode(PacketWebRTC packet, int version) throws ProtocolException {
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (packet.sdpOrCandidate != null) writer.writeString(F_SDP_OR_CANDIDATE, packet.sdpOrCandidate);
}
if (version >= 1) {
if (packet.type != null) { packet.type.requireSupportedInVersion(version); writer.writeInt32(F_TYPE, packet.type.getCode()); }
}
return writer.toByteArray();
}
}

View File

@@ -0,0 +1,82 @@
package im.rosetta.network.codec;
import java.util.ArrayList;
import java.util.List;
import io.orprotocol.ProtocolException;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.types.RTCIceServer;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class RTCIceServerCodec {
private static final int F_URL = 1;
private static final int F_USERNAME = 2;
private static final int F_CREDENTIAL = 3;
private static final int F_TRANSPORT = 4;
private RTCIceServerCodec() {}
public static RTCIceServer decode(byte[] raw, int version) throws ProtocolException {
if (raw == null) {
return null;
}
TlvReader reader = new TlvReader(raw);
RTCIceServer model = new RTCIceServer();
if (version >= 1) {
model.url = reader.getString(F_URL);
}
if (version >= 1) {
model.username = reader.getString(F_USERNAME);
}
if (version >= 1) {
model.credential = reader.getString(F_CREDENTIAL);
}
if (version >= 1) {
model.transport = reader.getString(F_TRANSPORT);
}
return model;
}
public static byte[] encode(RTCIceServer model, int version) throws ProtocolException {
if (model == null) {
return null;
}
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (model.url != null) writer.writeString(F_URL, model.url);
}
if (version >= 1) {
if (model.username != null) writer.writeString(F_USERNAME, model.username);
}
if (version >= 1) {
if (model.credential != null) writer.writeString(F_CREDENTIAL, model.credential);
}
if (version >= 1) {
if (model.transport != null) writer.writeString(F_TRANSPORT, model.transport);
}
return writer.toByteArray();
}
public static List<RTCIceServer> decodeList(List<byte[]> raws, int version) throws ProtocolException {
List<RTCIceServer> out = new ArrayList<>();
if (raws == null) {
return out;
}
for (byte[] raw : raws) {
out.add(decode(raw, version));
}
return out;
}
public static List<byte[]> encodeList(List<RTCIceServer> values, int version) throws ProtocolException {
List<byte[]> out = new ArrayList<>();
if (values == null) {
return out;
}
for (RTCIceServer value : values) {
out.add(encode(value, version));
}
return out;
}
}

View File

@@ -0,0 +1,90 @@
package im.rosetta.network.codec;
import java.util.ArrayList;
import java.util.List;
import io.orprotocol.ProtocolException;
import io.orprotocol.tlv.read.TlvReader;
import io.orprotocol.tlv.write.TlvWriter;
import im.rosetta.network.types.SearchInfo;
import im.rosetta.network.enums.NetworkStatus;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public final class SearchInfoCodec {
private static final int F_USERNAME = 1;
private static final int F_TITLE = 2;
private static final int F_PUBLIC_KEY = 3;
private static final int F_VERIFIED = 4;
private static final int F_NETWORK_STATUS = 5;
private SearchInfoCodec() {}
public static SearchInfo decode(byte[] raw, int version) throws ProtocolException {
if (raw == null) {
return null;
}
TlvReader reader = new TlvReader(raw);
SearchInfo model = new SearchInfo();
if (version >= 1) {
model.username = reader.getString(F_USERNAME);
}
if (version >= 1) {
model.title = reader.getString(F_TITLE);
}
if (version >= 1) {
model.publicKey = reader.getString(F_PUBLIC_KEY);
}
if (version >= 1) {
model.verified = reader.getInt32(F_VERIFIED);
}
if (version >= 1) {
model.networkStatus = NetworkStatus.fromCode(reader.getInt32(F_NETWORK_STATUS), version);
}
return model;
}
public static byte[] encode(SearchInfo model, int version) throws ProtocolException {
if (model == null) {
return null;
}
TlvWriter writer = new TlvWriter();
if (version >= 1) {
if (model.username != null) writer.writeString(F_USERNAME, model.username);
}
if (version >= 1) {
if (model.title != null) writer.writeString(F_TITLE, model.title);
}
if (version >= 1) {
if (model.publicKey != null) writer.writeString(F_PUBLIC_KEY, model.publicKey);
}
if (version >= 1) {
if (model.verified != null) writer.writeInt32(F_VERIFIED, model.verified);
}
if (version >= 1) {
if (model.networkStatus != null) { model.networkStatus.requireSupportedInVersion(version); writer.writeInt32(F_NETWORK_STATUS, model.networkStatus.getCode()); }
}
return writer.toByteArray();
}
public static List<SearchInfo> decodeList(List<byte[]> raws, int version) throws ProtocolException {
List<SearchInfo> out = new ArrayList<>();
if (raws == null) {
return out;
}
for (byte[] raw : raws) {
out.add(decode(raw, version));
}
return out;
}
public static List<byte[]> encodeList(List<SearchInfo> values, int version) throws ProtocolException {
List<byte[]> out = new ArrayList<>();
if (values == null) {
return out;
}
for (SearchInfo value : values) {
out.add(encode(value, version));
}
return out;
}
}

View File

@@ -0,0 +1,61 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum AttachmentType {
IMAGE(0),
MESSAGES(1),
FILE(2),
AVATAR(3),
CALL(4),
VOICE(5),
VIDEO_CIRCLE(6);
private final Integer code;
AttachmentType(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static AttachmentType fromCode(int code) {
return switch (code) {
case 0 -> IMAGE;
case 1 -> MESSAGES;
case 2 -> FILE;
case 3 -> AVATAR;
case 4 -> CALL;
case 5 -> VOICE;
case 6 -> VIDEO_CIRCLE;
default -> throw new IllegalArgumentException("Unknown AttachmentType code: " + code);
};
}
public static AttachmentType fromCode(int code, int version) {
AttachmentType value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported AttachmentType code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case IMAGE -> true;
case MESSAGES -> true;
case FILE -> true;
case AVATAR -> true;
case CALL -> true;
case VOICE -> true;
case VIDEO_CIRCLE -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported AttachmentType value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,46 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum DeviceSolution {
ACCEPT(0),
DECLINE(1);
private final Integer code;
DeviceSolution(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static DeviceSolution fromCode(int code) {
return switch (code) {
case 0 -> ACCEPT;
case 1 -> DECLINE;
default -> throw new IllegalArgumentException("Unknown DeviceSolution code: " + code);
};
}
public static DeviceSolution fromCode(int code, int version) {
DeviceSolution value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported DeviceSolution code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case ACCEPT -> true;
case DECLINE -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported DeviceSolution value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,52 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum GroupStatus {
JOINED(0),
INVALID(1),
NOT_JOINED(2),
BANNED(3);
private final Integer code;
GroupStatus(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static GroupStatus fromCode(int code) {
return switch (code) {
case 0 -> JOINED;
case 1 -> INVALID;
case 2 -> NOT_JOINED;
case 3 -> BANNED;
default -> throw new IllegalArgumentException("Unknown GroupStatus code: " + code);
};
}
public static GroupStatus fromCode(int code, int version) {
GroupStatus value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported GroupStatus code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case JOINED -> true;
case INVALID -> true;
case NOT_JOINED -> true;
case BANNED -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported GroupStatus value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,46 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum HandshakeStage {
COMPLETED(0),
NEED_DEVICE_VERIFICATION(1);
private final Integer code;
HandshakeStage(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static HandshakeStage fromCode(int code) {
return switch (code) {
case 0 -> COMPLETED;
case 1 -> NEED_DEVICE_VERIFICATION;
default -> throw new IllegalArgumentException("Unknown HandshakeStage code: " + code);
};
}
public static HandshakeStage fromCode(int code, int version) {
HandshakeStage value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported HandshakeStage code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case COMPLETED -> true;
case NEED_DEVICE_VERIFICATION -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported HandshakeStage value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,46 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum NetworkStatus {
ONLINE(0),
OFFLINE(1);
private final Integer code;
NetworkStatus(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static NetworkStatus fromCode(int code) {
return switch (code) {
case 0 -> ONLINE;
case 1 -> OFFLINE;
default -> throw new IllegalArgumentException("Unknown NetworkStatus code: " + code);
};
}
public static NetworkStatus fromCode(int code, int version) {
NetworkStatus value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported NetworkStatus code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case ONLINE -> true;
case OFFLINE -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported NetworkStatus value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,46 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum NotificationAction {
SUBSCRIBE(0),
UNSUBSCRIBE(1);
private final Integer code;
NotificationAction(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static NotificationAction fromCode(int code) {
return switch (code) {
case 0 -> SUBSCRIBE;
case 1 -> UNSUBSCRIBE;
default -> throw new IllegalArgumentException("Unknown NotificationAction code: " + code);
};
}
public static NotificationAction fromCode(int code, int version) {
NotificationAction value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported NotificationAction code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case SUBSCRIBE -> true;
case UNSUBSCRIBE -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported NotificationAction value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,52 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum ResultCode {
SUCCESS(0),
ERROR(1),
INVALID(2),
USERNAME_TAKEN(3);
private final Integer code;
ResultCode(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static ResultCode fromCode(int code) {
return switch (code) {
case 0 -> SUCCESS;
case 1 -> ERROR;
case 2 -> INVALID;
case 3 -> USERNAME_TAKEN;
default -> throw new IllegalArgumentException("Unknown ResultCode code: " + code);
};
}
public static ResultCode fromCode(int code, int version) {
ResultCode value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported ResultCode code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case SUCCESS -> true;
case ERROR -> true;
case INVALID -> true;
case USERNAME_TAKEN -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported ResultCode value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,67 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum SignalType {
CALL(0),
KEY_EXCHANGE(1),
ACTIVE_CALL(2),
END_CALL(3),
ACTIVE(4),
END_CALL_BECAUSE_PEER_DISCONNECTED(5),
END_CALL_BECAUSE_BUSY(6),
ACCEPT(7),
RINGING_TIMEOUT(8);
private final Integer code;
SignalType(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static SignalType fromCode(int code) {
return switch (code) {
case 0 -> CALL;
case 1 -> KEY_EXCHANGE;
case 2 -> ACTIVE_CALL;
case 3 -> END_CALL;
case 4 -> ACTIVE;
case 5 -> END_CALL_BECAUSE_PEER_DISCONNECTED;
case 6 -> END_CALL_BECAUSE_BUSY;
case 7 -> ACCEPT;
case 8 -> RINGING_TIMEOUT;
default -> throw new IllegalArgumentException("Unknown SignalType code: " + code);
};
}
public static SignalType fromCode(int code, int version) {
SignalType value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported SignalType code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case CALL -> true;
case KEY_EXCHANGE -> true;
case ACTIVE_CALL -> true;
case END_CALL -> true;
case ACTIVE -> true;
case END_CALL_BECAUSE_PEER_DISCONNECTED -> true;
case END_CALL_BECAUSE_BUSY -> true;
case ACCEPT -> true;
case RINGING_TIMEOUT -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported SignalType value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,49 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum SyncStatus {
NOT_NEEDED(0),
BATCH_START(1),
BATCH_END(2);
private final Integer code;
SyncStatus(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static SyncStatus fromCode(int code) {
return switch (code) {
case 0 -> NOT_NEEDED;
case 1 -> BATCH_START;
case 2 -> BATCH_END;
default -> throw new IllegalArgumentException("Unknown SyncStatus code: " + code);
};
}
public static SyncStatus fromCode(int code, int version) {
SyncStatus value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported SyncStatus code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case NOT_NEEDED -> true;
case BATCH_START -> true;
case BATCH_END -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported SyncStatus value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,46 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum TokenType {
FCM(0),
VoIPApns(1);
private final Integer code;
TokenType(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static TokenType fromCode(int code) {
return switch (code) {
case 0 -> FCM;
case 1 -> VoIPApns;
default -> throw new IllegalArgumentException("Unknown TokenType code: " + code);
};
}
public static TokenType fromCode(int code, int version) {
TokenType value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported TokenType code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case FCM -> true;
case VoIPApns -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported TokenType value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,49 @@
package im.rosetta.network.enums;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public enum WebRTCType {
OFFER(0),
ANSWER(1),
ICE_CANDIDATE(2);
private final Integer code;
WebRTCType(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public static WebRTCType fromCode(int code) {
return switch (code) {
case 0 -> OFFER;
case 1 -> ANSWER;
case 2 -> ICE_CANDIDATE;
default -> throw new IllegalArgumentException("Unknown WebRTCType code: " + code);
};
}
public static WebRTCType fromCode(int code, int version) {
WebRTCType value = fromCode(code);
if (!value.isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported WebRTCType code " + code + " for version " + version);
}
return value;
}
public boolean isSupportedInVersion(int version) {
return switch (this) {
case OFFER -> true;
case ANSWER -> true;
case ICE_CANDIDATE -> true;
};
}
public void requireSupportedInVersion(int version) {
if (!isSupportedInVersion(version)) {
throw new IllegalArgumentException("Unsupported WebRTCType value " + this + " for version " + version);
}
}
}

View File

@@ -0,0 +1,24 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketDelivery extends Packet {
public String messageId;
public String toPublicKey;
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getToPublicKey() {
return toPublicKey;
}
public void setToPublicKey(String toPublicKey) {
this.toPublicKey = toPublicKey;
}
}

View File

@@ -0,0 +1,17 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.types.NetworkDevice;
public class PacketDeviceList extends Packet {
public java.util.List<NetworkDevice> devices;
public java.util.List<NetworkDevice> getDevices() {
return devices;
}
public void setDevices(java.util.List<NetworkDevice> devices) {
this.devices = devices;
}
}

View File

@@ -0,0 +1,42 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketDeviceNew extends Packet {
public String ipAddress;
public String deviceId;
public String deviceName;
public String deviceOs;
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceOs() {
return deviceOs;
}
public void setDeviceOs(String deviceOs) {
this.deviceOs = deviceOs;
}
}

View File

@@ -0,0 +1,26 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.DeviceSolution;
public class PacketDeviceResolve extends Packet {
public String deviceId;
public DeviceSolution solution;
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public DeviceSolution getSolution() {
return solution;
}
public void setSolution(DeviceSolution solution) {
this.solution = solution;
}
}

View File

@@ -0,0 +1,24 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketGroupBan extends Packet {
public String groupId;
public String publicKey;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
}

View File

@@ -0,0 +1,15 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketGroupCreate extends Packet {
public String groupId;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
}

View File

@@ -0,0 +1,24 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketGroupInfo extends Packet {
public String groupId;
public java.util.List<String> membersPKs;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public java.util.List<String> getMembersPKs() {
return membersPKs;
}
public void setMembersPKs(java.util.List<String> membersPKs) {
this.membersPKs = membersPKs;
}
}

View File

@@ -0,0 +1,35 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.GroupStatus;
public class PacketGroupInviteInfo extends Packet {
public String groupId;
public Integer membersCount;
public GroupStatus status;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Integer getMembersCount() {
return membersCount;
}
public void setMembersCount(Integer membersCount) {
this.membersCount = membersCount;
}
public GroupStatus getStatus() {
return status;
}
public void setStatus(GroupStatus status) {
this.status = status;
}
}

View File

@@ -0,0 +1,35 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.GroupStatus;
public class PacketGroupJoin extends Packet {
public String groupId;
public GroupStatus status;
public String groupString;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public GroupStatus getStatus() {
return status;
}
public void setStatus(GroupStatus status) {
this.status = status;
}
public String getGroupString() {
return groupString;
}
public void setGroupString(String groupString) {
this.groupString = groupString;
}
}

View File

@@ -0,0 +1,15 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketGroupLeave extends Packet {
public String groupId;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
}

View File

@@ -0,0 +1,80 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.HandshakeStage;
public class PacketHandshake extends Packet {
public String publicKey;
public String privateKey;
public Integer protocolVersion;
public Integer heartbeatInterval;
public String deviceId;
public String deviceName;
public String deviceOs;
public HandshakeStage handshakeStage;
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public Integer getProtocolVersion() {
return protocolVersion;
}
public void setProtocolVersion(Integer protocolVersion) {
this.protocolVersion = protocolVersion;
}
public Integer getHeartbeatInterval() {
return heartbeatInterval;
}
public void setHeartbeatInterval(Integer heartbeatInterval) {
this.heartbeatInterval = heartbeatInterval;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceOs() {
return deviceOs;
}
public void setDeviceOs(String deviceOs) {
this.deviceOs = deviceOs;
}
public HandshakeStage getHandshakeStage() {
return handshakeStage;
}
public void setHandshakeStage(HandshakeStage handshakeStage) {
this.handshakeStage = handshakeStage;
}
}

View File

@@ -0,0 +1,17 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.types.RTCIceServer;
public class PacketIceServers extends Packet {
public java.util.List<RTCIceServer> iceServers;
public java.util.List<RTCIceServer> getIceServers() {
return iceServers;
}
public void setIceServers(java.util.List<RTCIceServer> iceServers) {
this.iceServers = iceServers;
}
}

View File

@@ -0,0 +1,89 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.types.Attachment;
public class PacketMessage extends Packet {
public String fromPublicKey;
public String toPublicKey;
public String privateKey;
public String content;
public String chachaKey;
public Long timestamp;
public String messageId;
public java.util.List<Attachment> attachments;
public String aesChachaKey;
public String getFromPublicKey() {
return fromPublicKey;
}
public void setFromPublicKey(String fromPublicKey) {
this.fromPublicKey = fromPublicKey;
}
public String getToPublicKey() {
return toPublicKey;
}
public void setToPublicKey(String toPublicKey) {
this.toPublicKey = toPublicKey;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getChachaKey() {
return chachaKey;
}
public void setChachaKey(String chachaKey) {
this.chachaKey = chachaKey;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public java.util.List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(java.util.List<Attachment> attachments) {
this.attachments = attachments;
}
public String getAesChachaKey() {
return aesChachaKey;
}
public void setAesChachaKey(String aesChachaKey) {
this.aesChachaKey = aesChachaKey;
}
}

View File

@@ -0,0 +1,17 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.types.PKNetworkStatus;
public class PacketOnlineState extends Packet {
public java.util.List<PKNetworkStatus> pkNetworkStatuses;
public java.util.List<PKNetworkStatus> getPkNetworkStatuses() {
return pkNetworkStatuses;
}
public void setPkNetworkStatuses(java.util.List<PKNetworkStatus> pkNetworkStatuses) {
this.pkNetworkStatuses = pkNetworkStatuses;
}
}

View File

@@ -0,0 +1,24 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketOnlineSubscribe extends Packet {
public String privateKey;
public java.util.List<String> publicKeys;
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public java.util.List<String> getPublicKeys() {
return publicKeys;
}
public void setPublicKeys(java.util.List<String> publicKeys) {
this.publicKeys = publicKeys;
}
}

View File

@@ -0,0 +1,45 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.NotificationAction;
import im.rosetta.network.enums.TokenType;
public class PacketPushNotification extends Packet {
public String notificationToken;
public NotificationAction action;
public TokenType tokenType;
public String deviceId;
public String getNotificationToken() {
return notificationToken;
}
public void setNotificationToken(String notificationToken) {
this.notificationToken = notificationToken;
}
public NotificationAction getAction() {
return action;
}
public void setAction(NotificationAction action) {
this.action = action;
}
public TokenType getTokenType() {
return tokenType;
}
public void setTokenType(TokenType tokenType) {
this.tokenType = tokenType;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketRead extends Packet {
public String fromPublicKey;
public String toPublicKey;
public String privateKey;
public String getFromPublicKey() {
return fromPublicKey;
}
public void setFromPublicKey(String fromPublicKey) {
this.fromPublicKey = fromPublicKey;
}
public String getToPublicKey() {
return toPublicKey;
}
public void setToPublicKey(String toPublicKey) {
this.toPublicKey = toPublicKey;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
}

View File

@@ -0,0 +1,15 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketRequestTransport extends Packet {
public String server;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
}

View File

@@ -0,0 +1,15 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketRequestUpdate extends Packet {
public String server;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
}

View File

@@ -0,0 +1,17 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.ResultCode;
public class PacketResult extends Packet {
public ResultCode resultCode;
public ResultCode getResultCode() {
return resultCode;
}
public void setResultCode(ResultCode resultCode) {
this.resultCode = resultCode;
}
}

View File

@@ -0,0 +1,35 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.types.SearchInfo;
public class PacketSearch extends Packet {
public String privateKey;
public String search;
public java.util.List<SearchInfo> searchInfo;
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public java.util.List<SearchInfo> getSearchInfo() {
return searchInfo;
}
public void setSearchInfo(java.util.List<SearchInfo> searchInfo) {
this.searchInfo = searchInfo;
}
}

View File

@@ -0,0 +1,62 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.SignalType;
public class PacketSignalPeer extends Packet {
public String src;
public String dst;
public String sharedPublic;
public SignalType signalType;
public String callId;
public String joinToken;
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDst() {
return dst;
}
public void setDst(String dst) {
this.dst = dst;
}
public String getSharedPublic() {
return sharedPublic;
}
public void setSharedPublic(String sharedPublic) {
this.sharedPublic = sharedPublic;
}
public SignalType getSignalType() {
return signalType;
}
public void setSignalType(SignalType signalType) {
this.signalType = signalType;
}
public String getCallId() {
return callId;
}
public void setCallId(String callId) {
this.callId = callId;
}
public String getJoinToken() {
return joinToken;
}
public void setJoinToken(String joinToken) {
this.joinToken = joinToken;
}
}

View File

@@ -0,0 +1,26 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.SyncStatus;
public class PacketSync extends Packet {
public SyncStatus syncStatus;
public Long timestamp;
public SyncStatus getSyncStatus() {
return syncStatus;
}
public void setSyncStatus(SyncStatus syncStatus) {
this.syncStatus = syncStatus;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketTypeing extends Packet {
public String fromPublicKey;
public String toPublicKey;
public String privateKey;
public String getFromPublicKey() {
return fromPublicKey;
}
public void setFromPublicKey(String fromPublicKey) {
this.fromPublicKey = fromPublicKey;
}
public String getToPublicKey() {
return toPublicKey;
}
public void setToPublicKey(String toPublicKey) {
this.toPublicKey = toPublicKey;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
}

View File

@@ -0,0 +1,33 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
public class PacketUserInfo extends Packet {
public String privateKey;
public String username;
public String title;
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@@ -0,0 +1,26 @@
package im.rosetta.network.packet;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import io.orprotocol.packet.Packet;
import im.rosetta.network.enums.WebRTCType;
public class PacketWebRTC extends Packet {
public String sdpOrCandidate;
public WebRTCType type;
public String getSdpOrCandidate() {
return sdpOrCandidate;
}
public void setSdpOrCandidate(String sdpOrCandidate) {
this.sdpOrCandidate = sdpOrCandidate;
}
public WebRTCType getType() {
return type;
}
public void setType(WebRTCType type) {
this.type = type;
}
}

View File

@@ -0,0 +1,52 @@
package im.rosetta.network.types;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import im.rosetta.network.enums.AttachmentType;
public class Attachment {
public String id;
public String blob;
public AttachmentType type;
public String preview;
public AttachmentTransport transport;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBlob() {
return blob;
}
public void setBlob(String blob) {
this.blob = blob;
}
public AttachmentType getType() {
return type;
}
public void setType(AttachmentType type) {
this.type = type;
}
public String getPreview() {
return preview;
}
public void setPreview(String preview) {
this.preview = preview;
}
public AttachmentTransport getTransport() {
return transport;
}
public void setTransport(AttachmentTransport transport) {
this.transport = transport;
}
}

View File

@@ -0,0 +1,23 @@
package im.rosetta.network.types;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class AttachmentTransport {
public String transportTag;
public String transportServer;
public String getTransportTag() {
return transportTag;
}
public void setTransportTag(String transportTag) {
this.transportTag = transportTag;
}
public String getTransportServer() {
return transportServer;
}
public void setTransportServer(String transportServer) {
this.transportServer = transportServer;
}
}

View File

@@ -1,29 +1,15 @@
package im.rosetta.packet.runtime;
package im.rosetta.network.types;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import im.rosetta.network.enums.DeviceSolution;
import im.rosetta.network.enums.NetworkStatus;
/**
* Обозначает подключенное к аккаунту устройство, с которого
* был произведен вход в систему.
*/
public class NetworkDevice {
private NetworkStatus networkStatus;
private String deviceName;
private String deviceOs;
private String deviceId;
private DeviceSolution deviceSolution;
public NetworkDevice() {
}
public NetworkDevice(NetworkStatus networkStatus, String deviceName, String deviceOs, String deviceId,
DeviceSolution deviceSolution) {
this.networkStatus = networkStatus;
this.deviceName = deviceName;
this.deviceOs = deviceOs;
this.deviceId = deviceId;
this.deviceSolution = deviceSolution;
}
public NetworkStatus networkStatus;
public String deviceName;
public String deviceOs;
public String deviceId;
public DeviceSolution deviceSolution;
public NetworkStatus getNetworkStatus() {
return networkStatus;
@@ -64,5 +50,4 @@ public class NetworkDevice {
public void setDeviceSolution(DeviceSolution deviceSolution) {
this.deviceSolution = deviceSolution;
}
}

View File

@@ -1,21 +1,12 @@
package im.rosetta.packet.runtime;
package im.rosetta.network.types;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import im.rosetta.network.enums.NetworkStatus;
/**
* Сущность для обозначения статуса сети
* пользователя по публичному ключу
*/
public class PKNetworkStatus {
public String publicKey;
public NetworkStatus networkStatus;
public PKNetworkStatus() {}
public PKNetworkStatus(String publicKey, NetworkStatus networkStatus) {
this.publicKey = publicKey;
this.networkStatus = networkStatus;
}
public String getPublicKey() {
return publicKey;
}
@@ -31,5 +22,4 @@ public class PKNetworkStatus {
public void setNetworkStatus(NetworkStatus networkStatus) {
this.networkStatus = networkStatus;
}
}

View File

@@ -0,0 +1,41 @@
package im.rosetta.network.types;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
public class RTCIceServer {
public String url;
public String username;
public String credential;
public String transport;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public String getTransport() {
return transport;
}
public void setTransport(String transport) {
this.transport = transport;
}
}

View File

@@ -0,0 +1,52 @@
package im.rosetta.network.types;
// Auto-generated by RCC (Rosetta Code Compiler). Do not edit manually.
import im.rosetta.network.enums.NetworkStatus;
public class SearchInfo {
public String username;
public String title;
public String publicKey;
public Integer verified;
public NetworkStatus networkStatus;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public Integer getVerified() {
return verified;
}
public void setVerified(Integer verified) {
this.verified = verified;
}
public NetworkStatus getNetworkStatus() {
return networkStatus;
}
public void setNetworkStatus(NetworkStatus networkStatus) {
this.networkStatus = networkStatus;
}
}

View File

@@ -1,156 +0,0 @@
package im.rosetta.packet;
import im.rosetta.packet.runtime.HandshakeStage;
import io.orprotocol.Stream;
import io.orprotocol.packet.Packet;
/**
* Пакет хэндшейка между клиентом и сервером.
* Используется для установления соединения и подтверждения от сервера что клиент
* тот за кого себя выдает.
*
* Протокол таблица:
* 0 - packetId (int16)
* 1 - privateKey (string)
* 2 - publicKey (string)
* 3 - protocolVersion (int8)
* 4 - heartbeatInterval (int8)
* 5 - deviceId (string)
* 6 - deviceName (string)
* 7 - deviceOs (string)
* 8 - handshakeStage (int8)
*/
public class Packet0Handshake extends Packet {
/**
* Публичный и приватный ключи клиента
*/
private String publicKey;
/**
* Приватный ключ клиента
* Это не совсем приватный ключ, а лишь необратимо зашифрованная его версия
* для идентификации клиента на сервере.
*/
private String privateKey;
/**
* Версия протокола клиента
*/
private int protocolVersion = 1;
/**
* Интервал отправки heartbeat пакетов в секундах
*/
private int heartbeatInterval = 15;
/**
* Минимальная информация об устройстве клиента
*/
private String deviceId;
private String deviceName;
private String deviceOs;
/**
* Стадия рукопожатия
* 0 - COMPLETED
* 1 - NEED_DEVICE_VERIFICATION
*/
private HandshakeStage handshakeStage = HandshakeStage.COMPLETED;
@Override
public Stream write() {
Stream stream = new Stream();
stream.writeInt16(this.packetId);
stream.writeString(this.privateKey);
stream.writeString(this.publicKey);
stream.writeInt8(this.protocolVersion);
stream.writeInt8(this.heartbeatInterval);
stream.writeString(this.deviceId);
stream.writeString(this.deviceName);
stream.writeString(this.deviceOs);
stream.writeInt8(this.handshakeStage.getCode());
return stream;
}
@Override
public void read(Stream stream) {
this.privateKey = stream.readString();
this.publicKey = stream.readString();
this.protocolVersion = stream.readInt8();
this.heartbeatInterval = stream.readInt8();
String deviceId = stream.readString();
String deviceName = stream.readString();
String deviceOs = stream.readString();
this.deviceId = deviceId;
this.deviceName = deviceName;
this.deviceOs = deviceOs;
this.handshakeStage = HandshakeStage.fromCode(
stream.readInt8()
);
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
public int getProtocolVersion() {
return protocolVersion;
}
public int getHeartbeatInterval() {
return heartbeatInterval;
}
public String getDeviceId() {
return deviceId;
}
public String getDeviceName() {
return deviceName;
}
public String getDeviceOs() {
return deviceOs;
}
public HandshakeStage getHandshakeStage() {
return handshakeStage;
}
public void setHandshakeStage(HandshakeStage handshakeStage) {
this.handshakeStage = handshakeStage;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public void setDeviceOs(String deviceOs) {
this.deviceOs = deviceOs;
}
public void setHeartbeatInterval(int heartbeatInterval) {
this.heartbeatInterval = heartbeatInterval;
}
public void setProtocolVersion(int protocolVersion) {
this.protocolVersion = protocolVersion;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
}

View File

@@ -1,14 +0,0 @@
package im.rosetta.packet;
import im.rosetta.packet.base.PacketBaseServer;
/**
* Получает сервер обновления
*/
public class Packet10RequestUpdate extends PacketBaseServer {
/**
* Пустой пакет, так как он наследник PacketBaseServer
* который всегда имеет одну структуру.
* Смотреть PacketBaseServer для реализации
*/
}

View File

@@ -1,29 +0,0 @@
package im.rosetta.packet;
import im.rosetta.packet.base.PacketBaseDialog;
import io.orprotocol.Stream;
/**
* Пакет отвечающий за индикацию печати в диалогах
*/
public class Packet11Typeing extends PacketBaseDialog {
@Override
public void read(Stream stream) {
this.privateKey = stream.readString();
this.fromPublicKey = stream.readString();
this.toPublicKey = stream.readString();
}
@Override
public Stream write() {
Stream stream = new Stream();
stream.writeInt16(this.packetId);
stream.writeString(this.privateKey);
stream.writeString(this.fromPublicKey);
stream.writeString(this.toPublicKey);
return stream;
}
}

View File

@@ -1,16 +0,0 @@
package im.rosetta.packet;
import im.rosetta.packet.base.PacketBaseServer;
/**
* Пакет отправляется клиентом для запроса транспортного сервера, строка в этот момент клиентом
* не заполняется, а уже обратно сервер заполняет строку и записывает туда транспортный сервер
* чтобы клиент мог отправлять вложения на него
*/
public class Packet15RequestTransport extends PacketBaseServer {
/**
* Пустой пакет, так как он наследник PacketBaseServer
* который всегда имеет одну структуру.
* Смотреть PacketBaseServer для реализации
*/
}

Some files were not shown because too many files have changed in this diff Show More