mirror of
https://github.com/jwdeveloper/TikTokLiveJava.git
synced 2026-02-27 08:49:40 -05:00
Compare commits
170 Commits
develop-1-
...
develop-1.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e1ab35a60 | ||
|
|
cef4972f37 | ||
|
|
713c90a271 | ||
|
|
71853db5cc | ||
|
|
ef90d4cd58 | ||
|
|
dad4048bc0 | ||
|
|
9ba049d37a | ||
|
|
f7d657371b | ||
|
|
eea691a5aa | ||
|
|
a249ac0cdd | ||
|
|
b82c7184b3 | ||
|
|
29631ac468 | ||
|
|
15c642297c | ||
|
|
d3004d76c1 | ||
|
|
3ae73072ff | ||
|
|
9c5f97157a | ||
|
|
ea847bb883 | ||
|
|
45bac053b9 | ||
|
|
8cb647f27a | ||
|
|
ffbd67eef4 | ||
|
|
e923f3fad7 | ||
|
|
faa1185b97 | ||
|
|
ead954dd27 | ||
|
|
e37b30ff12 | ||
|
|
7a5c00d99a | ||
|
|
407f51fa73 | ||
|
|
8581df7f49 | ||
|
|
3e52523644 | ||
|
|
3387986ced | ||
|
|
0fcac60cbe | ||
|
|
63dd8c20ac | ||
|
|
b809bb6cda | ||
|
|
a68eaba5a1 | ||
|
|
0252b9a42f | ||
|
|
1b2a8bad93 | ||
|
|
6b22154c82 | ||
|
|
965816e846 | ||
|
|
6b6e82cd93 | ||
|
|
c93c3144ff | ||
|
|
12c64e1c67 | ||
|
|
5794ff2a57 | ||
|
|
d471e87dd7 | ||
|
|
c89bcad894 | ||
|
|
c9a84c39df | ||
|
|
c1105f1324 | ||
|
|
243ce9bc94 | ||
|
|
4f141edb1a | ||
|
|
359a1508c7 | ||
|
|
bbfa7b410b | ||
|
|
6da40927d0 | ||
|
|
4d97fd9157 | ||
|
|
1ba51476d1 | ||
|
|
9ee5c89f64 | ||
|
|
ffabf098c0 | ||
|
|
7468fc2385 | ||
|
|
abbb557881 | ||
|
|
19c513afe6 | ||
|
|
283024a1d4 | ||
|
|
a0ac9e6d79 | ||
|
|
2385d1e75e | ||
|
|
c9c7f62d4a | ||
|
|
35ef95096d | ||
|
|
46bcfd6eb8 | ||
|
|
38b66395cb | ||
|
|
46e75dec1a | ||
|
|
749cfcf4a6 | ||
|
|
039f2b6a0b | ||
|
|
1a1860e35d | ||
|
|
8a4248daa3 | ||
|
|
ff5310f5bf | ||
|
|
9ddec45740 | ||
|
|
8a7b9e801b | ||
|
|
7b4590d0a1 | ||
|
|
2555edd86f | ||
|
|
a805844522 | ||
|
|
9da96b4417 | ||
|
|
12cf9e641b | ||
|
|
6bfa0b7745 | ||
|
|
cf9b882391 | ||
|
|
913d473442 | ||
|
|
72092bb56b | ||
|
|
b6247feb32 | ||
|
|
0dd952a7fb | ||
|
|
af4f2b4510 | ||
|
|
2c12b71e99 | ||
|
|
bc3386d21e | ||
|
|
4801de58cb | ||
|
|
548a585e90 | ||
|
|
2667f04a1c | ||
|
|
0a857594ea | ||
|
|
b0593ba95c | ||
|
|
c23faffcde | ||
|
|
f7a92d5015 | ||
|
|
6a42da9ecb | ||
|
|
1308b86567 | ||
|
|
20ba88c0ac | ||
|
|
77533ea4be | ||
|
|
3231924f8f | ||
|
|
ea525470e2 | ||
|
|
b0bf4ac606 | ||
|
|
0b9f1570d0 | ||
|
|
7a4c7fecbd | ||
|
|
0ae9068858 | ||
|
|
8905958207 | ||
|
|
c12f3cc4dc | ||
|
|
7402899f52 | ||
|
|
1b8b150d61 | ||
|
|
b2305b7bed | ||
|
|
7b911838a2 | ||
|
|
e44cb71869 | ||
|
|
af8c689417 | ||
|
|
81ac92fb33 | ||
|
|
34a78b5435 | ||
|
|
534cb7906d | ||
|
|
0bb8edfe5c | ||
|
|
4979c1b27a | ||
|
|
f7c8ffdaa5 | ||
|
|
c1fda687d3 | ||
|
|
05c49c4545 | ||
|
|
7d36f36cee | ||
|
|
f8a716429d | ||
|
|
fee805f0ea | ||
|
|
1733102aff | ||
|
|
89f54d5976 | ||
|
|
39055b5f3a | ||
|
|
cd9e9ead85 | ||
|
|
5a2d2d23f0 | ||
|
|
3eed982d6b | ||
|
|
385560de3a | ||
|
|
2e37b6627b | ||
|
|
c4f0d63b43 | ||
|
|
15550ed703 | ||
|
|
c7d84218f2 | ||
|
|
1ecd192539 | ||
|
|
d6c0d50ac3 | ||
|
|
b4997da0a8 | ||
|
|
82990665b8 | ||
|
|
155b47977d | ||
|
|
3e262773a4 | ||
|
|
89fbeb848b | ||
|
|
aa99c5929b | ||
|
|
4dd866c6cc | ||
|
|
0d384f0fdc | ||
|
|
3832db111e | ||
|
|
46d5f15d3f | ||
|
|
4f3ec1c6d9 | ||
|
|
31075e5f09 | ||
|
|
33a3f7afb8 | ||
|
|
6c888c5d5b | ||
|
|
214aa3b1ff | ||
|
|
3f2c9083d5 | ||
|
|
450014759c | ||
|
|
790f568244 | ||
|
|
e3e0d8a88e | ||
|
|
e0136d0f3b | ||
|
|
dd5ccbfb7f | ||
|
|
110a4fab4c | ||
|
|
69a2a6a338 | ||
|
|
530551763c | ||
|
|
ca1827853a | ||
|
|
ea8c740faa | ||
|
|
1977cbe8dc | ||
|
|
c3a48c4d70 | ||
|
|
2c51844fd9 | ||
|
|
8ff4236452 | ||
|
|
7817aeb652 | ||
|
|
788653484f | ||
|
|
6cebbf891d | ||
|
|
cc32648988 | ||
|
|
4c797724d3 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,10 +1,11 @@
|
||||
backend-infrastructure/.aws-sam
|
||||
|
||||
# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode
|
||||
|
||||
.db
|
||||
# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode
|
||||
*.db
|
||||
### Linux ###
|
||||
*~
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<artifactId>TikTokLiveJava</artifactId>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<version>1.0.2-Release</version>
|
||||
<version>1.4.0-Release</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>API</artifactId>
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
|
||||
@Data
|
||||
public class ClientSettings {
|
||||
/**
|
||||
* Timeout for Connections
|
||||
*/
|
||||
private Duration timeout;
|
||||
|
||||
/**
|
||||
* ISO-Language for Client
|
||||
*/
|
||||
|
||||
private String clientLanguage;
|
||||
|
||||
/**
|
||||
* Whether to Retry if Connection Fails
|
||||
*/
|
||||
private boolean retryOnConnectionFailure;
|
||||
|
||||
|
||||
/**
|
||||
* Before retrying connect, wait for select amount of time
|
||||
*/
|
||||
private Duration retryConnectionTimeout;
|
||||
|
||||
/**
|
||||
* Whether to handle Events received from Room when Connecting
|
||||
*/
|
||||
private boolean handleExistingEvents;
|
||||
|
||||
/**
|
||||
* Whether to print Logs to Console
|
||||
*/
|
||||
|
||||
private boolean printToConsole;
|
||||
/**
|
||||
* LoggingLevel for Logs
|
||||
*/
|
||||
private Level logLevel;
|
||||
|
||||
|
||||
/**
|
||||
* Optional: Use it if you need to change TikTok live hostname in builder
|
||||
*/
|
||||
private String hostName;
|
||||
|
||||
|
||||
/**
|
||||
* Parameters used in requests to TikTok api
|
||||
*/
|
||||
private Map<String, Object> clientParameters;
|
||||
|
||||
|
||||
/*
|
||||
* Optional: Sometimes not every messages from chat are send to TikTokLiveJava to fix this issue you can set sessionId
|
||||
* documentation how to obtain sessionId https://github.com/isaackogan/TikTok-Live-Connector#send-chat-messages
|
||||
*/
|
||||
private String sessionId;
|
||||
|
||||
/*
|
||||
* Optional: By default roomID is fetched before connect to live, but you can set it manually
|
||||
*
|
||||
*/
|
||||
private String roomId;
|
||||
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface TikTokEventHandler
|
||||
public @interface TikTokEventObserver
|
||||
{
|
||||
|
||||
}
|
||||
@@ -20,18 +20,17 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.tools.collector.tables;
|
||||
package io.github.jwdeveloper.tiktok.data.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Value;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Data
|
||||
public class TikTokResponseModel
|
||||
@AllArgsConstructor
|
||||
public class MessageMetaData
|
||||
{
|
||||
private Integer id;
|
||||
|
||||
private String hostName;
|
||||
|
||||
private String response;
|
||||
|
||||
private String createdAt;
|
||||
private Duration handlingTime;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.dto;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
import java.net.*;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ProxyData
|
||||
{
|
||||
private final String address;
|
||||
private final int port;
|
||||
|
||||
public static ProxyData map(String string) {
|
||||
if (string == null || string.isBlank())
|
||||
throw new IllegalArgumentException("Provided address cannot be null or empty!");
|
||||
int portIndex = string.lastIndexOf(':');
|
||||
try {
|
||||
String address = string.substring(0, portIndex);
|
||||
int port = Integer.parseInt(string.substring(portIndex+1));
|
||||
|
||||
// Port validation
|
||||
if (port < 0 || port > 65535)
|
||||
throw new IndexOutOfBoundsException("Port out of range: "+port);
|
||||
|
||||
// IP Validation
|
||||
InetAddress res = InetAddress.getByName(address);
|
||||
|
||||
return new ProxyData(address, port);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException("Port must be a valid integer!");
|
||||
} catch (UnknownHostException e) {
|
||||
throw new IllegalArgumentException("Address must be valid IPv4, IPv6, or domain name!");
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyData clone() {
|
||||
return new ProxyData(address, port);
|
||||
}
|
||||
|
||||
public InetSocketAddress toSocketAddress() {
|
||||
return new InetSocketAddress(address, port);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Data
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class CustomEvent extends TikTokHeaderEvent {
|
||||
private final User user;
|
||||
private final String title;
|
||||
|
||||
public CustomEvent(User user, String title) {
|
||||
this.user = user;
|
||||
this.title = title;
|
||||
}
|
||||
}
|
||||
@@ -47,11 +47,23 @@ public class TikTokCommentEvent extends TikTokHeaderEvent {
|
||||
|
||||
public TikTokCommentEvent(WebcastChatMessage msg) {
|
||||
super(msg.getCommon());
|
||||
user = User.map(msg.getUser());
|
||||
user = User.map(msg.getUser(), msg.getUserIdentity());
|
||||
text = msg.getContent();
|
||||
visibleToSender = msg.getVisibleToSender();
|
||||
getUserLanguage = msg.getContentLanguage();
|
||||
mentionedUser = User.map(msg.getAtUser(),msg.getUserIdentity());
|
||||
mentionedUser = User.map(msg.getAtUser());
|
||||
pictures = msg.getEmotesListList().stream().map(e -> Picture.map(e.getEmote().getImage())).toList();
|
||||
}
|
||||
|
||||
|
||||
public static TikTokCommentEvent of(String userName, String message) {
|
||||
var builder = WebcastChatMessage.newBuilder();
|
||||
builder.setUser(io.github.jwdeveloper.tiktok.messages.data.User.newBuilder()
|
||||
.setNickname(userName)
|
||||
.build());
|
||||
builder.setContentLanguage("en");
|
||||
builder.setVisibleToSender(true);
|
||||
builder.setContent(message);
|
||||
return new TikTokCommentEvent(builder.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ package io.github.jwdeveloper.tiktok.data.events;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* Triggered when the connection gets disconnected. In that case you can call connect() again to have a reconnect logic.
|
||||
@@ -32,4 +32,12 @@ import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Control)
|
||||
public class TikTokDisconnectedEvent extends TikTokLiveClientEvent {
|
||||
}
|
||||
@Getter private final String reason;
|
||||
public TikTokDisconnectedEvent(String reason) {
|
||||
this.reason = reason.isBlank() ? "None" : reason;
|
||||
}
|
||||
|
||||
public TikTokDisconnectedEvent() {
|
||||
this("None");
|
||||
}
|
||||
}
|
||||
@@ -34,18 +34,10 @@ import java.util.List;
|
||||
@Getter
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokLinkEvent extends TikTokHeaderEvent {
|
||||
private final String token;
|
||||
|
||||
private User user;
|
||||
|
||||
private final List<User> otherUsers;
|
||||
|
||||
public TikTokLinkEvent(WebcastLinkMessage msg) {
|
||||
super(msg.getCommon());
|
||||
token = msg.getToken();
|
||||
if (msg.getUser().getUser().hasUser()) {
|
||||
user = new User(msg.getUser().getUser().getUser());
|
||||
}
|
||||
otherUsers = msg.getUser().getOtherUsersList().stream().map(e -> new User(e.getUser())).toList();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,17 +20,13 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
package io.github.jwdeveloper.tiktok.data.events;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TrackedUser
|
||||
{
|
||||
List<TikTokEvent> getInvokedEvents();
|
||||
List<Gift> getGifs();
|
||||
User getUserData();
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokLiveUnpausedEvent extends TikTokEvent {
|
||||
}
|
||||
@@ -26,7 +26,9 @@ import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.UserAttribute;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastMemberMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSubNotifyMessage;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
@@ -35,15 +37,26 @@ import lombok.Getter;
|
||||
@Getter
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokSubscribeEvent extends TikTokHeaderEvent {
|
||||
private User user;
|
||||
private final User user;
|
||||
|
||||
public TikTokSubscribeEvent(WebcastMemberMessage msg) {
|
||||
super(msg.getCommon());
|
||||
|
||||
if(msg.hasUser())
|
||||
{
|
||||
user = new User(msg.getUser());
|
||||
public TikTokSubscribeEvent(WebcastMemberMessage msg) {
|
||||
super(msg.getCommon());
|
||||
user = User.map(msg.getUser());
|
||||
user.addAttribute(UserAttribute.Subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
public TikTokSubscribeEvent(WebcastSubNotifyMessage msg) {
|
||||
super(msg.getCommon());
|
||||
user = User.map(msg.getUser());
|
||||
user.addAttribute(UserAttribute.Subscriber);
|
||||
}
|
||||
|
||||
public static TikTokSubscribeEvent of(String userName) {
|
||||
return new TikTokSubscribeEvent(WebcastMemberMessage.newBuilder()
|
||||
.setUser(io.github.jwdeveloper.tiktok.messages.data.User.newBuilder()
|
||||
.setNickname(userName)
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,17 +20,18 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
package io.github.jwdeveloper.tiktok.data.events.control;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface UserManager
|
||||
/**
|
||||
* Triggered when client is connecting to live is successfully established.
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Control)
|
||||
public class TikTokConnectingEvent extends TikTokLiveClientEvent
|
||||
{
|
||||
TrackedUser observeUser(User user);
|
||||
|
||||
TrackedUser getTrackedUser(Long id);
|
||||
|
||||
List<TrackedUser> getTrackedUsers();
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.control;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.*;
|
||||
import lombok.*;
|
||||
|
||||
/**
|
||||
* Triggered before the connection is established.
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Control)
|
||||
public class TikTokPreConnectionEvent extends TikTokLiveClientEvent
|
||||
{
|
||||
@Getter private final LiveUserData.Response userData;
|
||||
@Getter private final LiveData.Response roomData;
|
||||
@Getter @Setter boolean cancelConnection = false;
|
||||
|
||||
public TikTokPreConnectionEvent(LiveUserData.Response userData, LiveData.Response liveData) {
|
||||
this.userData = userData;
|
||||
this.roomData = liveData;
|
||||
}
|
||||
}
|
||||
@@ -22,10 +22,10 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.gift;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftSendType;
|
||||
import io.github.jwdeveloper.tiktok.annotations.*;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import lombok.Getter;
|
||||
|
||||
@@ -33,23 +33,34 @@ import lombok.Getter;
|
||||
/**
|
||||
* Triggered every time gift is sent
|
||||
*
|
||||
* @see GiftSendType it has 3 states
|
||||
* @see GiftComboStateType it has 3 states
|
||||
*
|
||||
* <p>Example when user sends gift with combo</p>
|
||||
* <p>>Combo: 1 -> comboState = GiftSendType.Begin</p>
|
||||
* <p>Combo: 4 -> comboState = GiftSendType.Active</p>
|
||||
* <p>Combo: 8 -> comboState = GiftSendType.Active</p>
|
||||
* <p>Combo: 12 -> comboState = GiftSendType.Finsihed</p>
|
||||
*
|
||||
* <p>
|
||||
* Remember if comboState is Finsihed both TikTokGiftComboEvent and TikTokGiftEvent event gets triggered
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
@Getter
|
||||
public class TikTokGiftComboEvent extends TikTokGiftEvent {
|
||||
private final GiftSendType comboState;
|
||||
private final GiftComboStateType comboState;
|
||||
|
||||
public TikTokGiftComboEvent(Gift gift, WebcastGiftMessage msg, GiftSendType comboState) {
|
||||
super(gift, msg);
|
||||
public TikTokGiftComboEvent(Gift gift, User host, WebcastGiftMessage msg, GiftComboStateType comboState) {
|
||||
super(gift, host, msg);
|
||||
this.comboState = comboState;
|
||||
}
|
||||
}
|
||||
|
||||
public static TikTokGiftComboEvent of(Gift gift, int combo, GiftComboStateType comboState) {
|
||||
return new TikTokGiftComboEvent(
|
||||
gift,
|
||||
new User(0L, "Test", new Picture("")),
|
||||
WebcastGiftMessage
|
||||
.newBuilder()
|
||||
.setComboCount(combo)
|
||||
.build(),
|
||||
comboState);
|
||||
}
|
||||
}
|
||||
@@ -23,31 +23,53 @@
|
||||
package io.github.jwdeveloper.tiktok.data.events.gift;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.annotations.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftSendType;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import lombok.Getter;
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* Triggered when user sends gifts that has
|
||||
* no combo (most of expensive gifts)
|
||||
* or if combo has finished
|
||||
* no combo (most of expensive gifts)
|
||||
* or if combo has finished
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
@Getter
|
||||
public class TikTokGiftEvent extends TikTokHeaderEvent {
|
||||
private final Gift gift;
|
||||
private final User user;
|
||||
private final User toUser;
|
||||
private final int combo;
|
||||
public TikTokGiftEvent(Gift gift, WebcastGiftMessage msg) {
|
||||
|
||||
public TikTokGiftEvent(Gift gift, User liveHost, WebcastGiftMessage msg) {
|
||||
super(msg.getCommon());
|
||||
this.gift = gift;
|
||||
user = User.map(msg.getUser(), msg.getUserIdentity());
|
||||
if (msg.getToUser().getNickname().isEmpty()) {
|
||||
toUser = liveHost;
|
||||
} else {
|
||||
toUser = User.map(msg.getToUser());
|
||||
}
|
||||
combo = msg.getComboCount();
|
||||
}
|
||||
}
|
||||
|
||||
public TikTokGiftEvent(Gift gift) {
|
||||
this.gift = gift;
|
||||
user = new User(0L, "sender", new Picture(""));
|
||||
toUser = new User(0L, "receiver", new Picture(""));
|
||||
combo = 1;
|
||||
}
|
||||
|
||||
|
||||
public static TikTokGiftEvent of(Gift gift) {
|
||||
return new TikTokGiftEvent(gift);
|
||||
}
|
||||
|
||||
public static TikTokGiftEvent of(String name, int id, int diamonds) {
|
||||
return TikTokGiftEvent.of(new Gift(id, name, diamonds, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.http.HttpData;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@EventMeta(eventType = EventType.Debug)
|
||||
public class TikTokHttpResponseEvent extends TikTokEvent
|
||||
{
|
||||
String url;
|
||||
|
||||
HttpData response;
|
||||
|
||||
HttpData request;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@EventMeta(eventType = EventType.Debug)
|
||||
public class TikTokRoomDataResponseEvent extends TikTokEvent
|
||||
{
|
||||
private final LiveData.Response liveData;
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.room;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.UserAttribute;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.RoomMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLiveIntroMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastRoomMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSystemMessage;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokRoomEvent extends TikTokHeaderEvent
|
||||
{
|
||||
private User hostUser;
|
||||
private String hostLanguage;
|
||||
private final String welcomeMessage;
|
||||
|
||||
public TikTokRoomEvent(WebcastRoomMessage msg) {
|
||||
super(msg.getCommon());
|
||||
welcomeMessage = msg.getContent();
|
||||
}
|
||||
|
||||
public TikTokRoomEvent(RoomMessage msg) {
|
||||
super(msg.getCommon());
|
||||
welcomeMessage = msg.getContent();
|
||||
}
|
||||
|
||||
public TikTokRoomEvent(WebcastSystemMessage msg) {
|
||||
super(msg.getCommon());
|
||||
welcomeMessage = msg.getMessage();
|
||||
}
|
||||
|
||||
public TikTokRoomEvent(WebcastLiveIntroMessage msg) {
|
||||
super(msg.getCommon());
|
||||
hostUser = User.map(msg.getHost());
|
||||
hostUser.addAttribute(UserAttribute.LiveHost);
|
||||
welcomeMessage = msg.getContent();
|
||||
hostLanguage = msg.getLanguage();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.room;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomInfo;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
|
||||
/*
|
||||
Triggered when LiveRoomInfo got updated such as likes, viewers, ranking ....
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokRoomInfoEvent extends TikTokEvent
|
||||
{
|
||||
LiveRoomInfo roomInfo;
|
||||
}
|
||||
@@ -24,8 +24,10 @@ package io.github.jwdeveloper.tiktok.data.events.social;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokSubscribeEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastMemberMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSocialMessage;
|
||||
import lombok.Value;
|
||||
|
||||
@@ -45,4 +47,12 @@ public class TikTokFollowEvent extends TikTokHeaderEvent
|
||||
totalFollowers = msg.getFollowCount();
|
||||
}
|
||||
|
||||
public static TikTokFollowEvent of(String userName)
|
||||
{
|
||||
return new TikTokFollowEvent(WebcastSocialMessage.newBuilder()
|
||||
.setUser(io.github.jwdeveloper.tiktok.messages.data.User.newBuilder()
|
||||
.setNickname(userName)
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLikeMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastMemberMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSocialMessage;
|
||||
import lombok.Getter;
|
||||
@@ -47,4 +48,13 @@ public class TikTokJoinEvent extends TikTokHeaderEvent {
|
||||
user = User.map(msg.getUser());
|
||||
totalUsers = msg.getMemberCount();
|
||||
}
|
||||
|
||||
public static TikTokJoinEvent of(String userName)
|
||||
{
|
||||
return new TikTokJoinEvent(WebcastMemberMessage.newBuilder()
|
||||
.setUser(io.github.jwdeveloper.tiktok.messages.data.User.newBuilder()
|
||||
.setNickname(userName)
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,4 +57,15 @@ public class TikTokLikeEvent extends TikTokHeaderEvent
|
||||
likes = msg.getCount();
|
||||
totalLikes = msg.getTotal();
|
||||
}
|
||||
|
||||
public static TikTokLikeEvent of(String userName, int likes)
|
||||
{
|
||||
return new TikTokLikeEvent(WebcastLikeMessage.newBuilder()
|
||||
.setCount(likes)
|
||||
.setTotal(likes)
|
||||
.setUser(io.github.jwdeveloper.tiktok.messages.data.User.newBuilder()
|
||||
.setNickname(userName)
|
||||
.build())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,9 @@ package io.github.jwdeveloper.tiktok.data.events.websocket;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.dto.MessageMetaData;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
@@ -34,22 +36,32 @@ import java.time.Duration;
|
||||
|
||||
|
||||
/**
|
||||
* Triggered every time a protobuf encoded webcast message arrives. You can deserialize the binary object depending on the use case.
|
||||
* Triggered every time TikTok sends data. Data incoming as protobuf message.
|
||||
* You can deserialize the binary object depending on the use case.
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@EventMeta(eventType = EventType.Debug)
|
||||
public class TikTokWebsocketMessageEvent extends TikTokEvent
|
||||
{
|
||||
private TikTokEvent event;
|
||||
public class TikTokWebsocketMessageEvent extends TikTokEvent {
|
||||
|
||||
/*
|
||||
* Original message that is coming from TikTok
|
||||
* message.method - Name of message type, for example "WebcastGiftMessage"
|
||||
* message.payload - Bytes array that contains actual data of message.
|
||||
* Example of parsing, WebcastGiftMessage giftMessage = WebcastGiftMessage.parseFrom(message.getPayload());
|
||||
*/
|
||||
private WebcastResponse.Message message;
|
||||
|
||||
private MetaData metaData;
|
||||
/*
|
||||
* TikTokLiveJava event that was created from TikTok message data
|
||||
* Example: TikTokGiftEvent
|
||||
*/
|
||||
private TikTokEvent event;
|
||||
|
||||
/*
|
||||
* Metadata information about mapping message to event, such as time and stuff
|
||||
*/
|
||||
private MessageMetaData metaData;
|
||||
|
||||
|
||||
@Value
|
||||
public static class MetaData
|
||||
{
|
||||
Duration handlingTime;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,4 +39,9 @@ public class TikTokWebsocketUnhandledMessageEvent extends TikTokUnhandledEvent<W
|
||||
public TikTokWebsocketUnhandledMessageEvent(WebcastResponse.Message data) {
|
||||
super(data);
|
||||
}
|
||||
|
||||
public WebcastResponse.Message getMessage()
|
||||
{
|
||||
return this.getData();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,15 +28,10 @@ import lombok.Getter;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.*;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
|
||||
public class Picture {
|
||||
|
||||
@Getter
|
||||
@@ -49,7 +44,6 @@ public class Picture {
|
||||
}
|
||||
|
||||
public static Picture map(io.github.jwdeveloper.tiktok.messages.data.Image profilePicture) {
|
||||
|
||||
var index = profilePicture.getUrlListCount() - 1;
|
||||
if (index < 0) {
|
||||
return new Picture("");
|
||||
@@ -74,12 +68,11 @@ public class Picture {
|
||||
return CompletableFuture.supplyAsync(this::downloadImage);
|
||||
}
|
||||
|
||||
private BufferedImage download(String urlString)
|
||||
{
|
||||
if(urlString.isEmpty())
|
||||
{
|
||||
private BufferedImage download(String urlString) {
|
||||
if (urlString.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var baos = new ByteArrayOutputStream();
|
||||
try (var is = new URL(urlString).openStream()) {
|
||||
var byteChunk = new byte[4096];
|
||||
@@ -103,4 +96,9 @@ public class Picture {
|
||||
public static Picture Empty() {
|
||||
return new Picture("");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Picture{link='" + link + "', image=" + image + "}";
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,4 @@ public class Badge {
|
||||
public static Badge empty() {
|
||||
return new Badge();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -24,19 +24,22 @@ package io.github.jwdeveloper.tiktok.data.models.badges;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class CombineBadge extends Badge {
|
||||
private final Picture picture;
|
||||
private final String text;
|
||||
private final String subText;
|
||||
|
||||
|
||||
public CombineBadge(BadgeStruct.CombineBadge combineBadge) {
|
||||
|
||||
picture = Picture.map(combineBadge.getIcon());
|
||||
text = combineBadge.getText().getDefaultPattern();
|
||||
subText = combineBadge.getStr();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CombineBadge{picture=" + picture +", text='" + text + "', subText='" + subText + "'}";
|
||||
}
|
||||
}
|
||||
@@ -24,12 +24,18 @@ package io.github.jwdeveloper.tiktok.data.models.badges;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class PictureBadge extends Badge {
|
||||
|
||||
private final Picture picture;
|
||||
public PictureBadge(BadgeStruct.ImageBadge imageBadge) {
|
||||
|
||||
public PictureBadge(BadgeStruct.ImageBadge imageBadge) {
|
||||
picture = Picture.map(imageBadge.getImage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PictureBadge{picture=" + picture + "}";
|
||||
}
|
||||
}
|
||||
@@ -23,12 +23,18 @@
|
||||
package io.github.jwdeveloper.tiktok.data.models.badges;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class StringBadge extends Badge {
|
||||
private final String text;
|
||||
|
||||
public String text;
|
||||
public StringBadge(BadgeStruct.StringBadge stringBadge) {
|
||||
|
||||
this.text = stringBadge.getStr();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "StringBadge{text='" + text + "'}";
|
||||
}
|
||||
}
|
||||
@@ -23,13 +23,18 @@
|
||||
package io.github.jwdeveloper.tiktok.data.models.badges;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
|
||||
import lombok.Getter;
|
||||
|
||||
public class TextBadge extends Badge
|
||||
{
|
||||
@Getter
|
||||
public class TextBadge extends Badge {
|
||||
private final String text;
|
||||
|
||||
public TextBadge(BadgeStruct.TextBadge textBadge)
|
||||
{
|
||||
public TextBadge(BadgeStruct.TextBadge textBadge) {
|
||||
this.text = textBadge.getDefaultPattern();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TextBadge{text='" + text + "'}";
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.models.chest;
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -22,19 +22,16 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.models.gifts;
|
||||
|
||||
public enum GiftSendType
|
||||
{
|
||||
//TODO it should be called GiftComboStateType
|
||||
public enum GiftComboStateType {
|
||||
Finished,
|
||||
Begin,
|
||||
Active;
|
||||
|
||||
|
||||
public static GiftSendType fromNumber(long number)
|
||||
{
|
||||
public static GiftComboStateType fromNumber(long number) {
|
||||
return switch ((int) number) {
|
||||
case 0 -> GiftSendType.Finished;
|
||||
case 1, 2, 4 -> GiftSendType.Active;
|
||||
default -> GiftSendType.Finished;
|
||||
case 1, 2, 4 -> GiftComboStateType.Active;
|
||||
default -> GiftComboStateType.Finished;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.models.http;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.*;
|
||||
|
||||
@Data
|
||||
public class HttpData {
|
||||
String url;
|
||||
String method;
|
||||
Map<String, List<String>> headers = new TreeMap<>();
|
||||
Map<String, String> parameters = new TreeMap<>();
|
||||
int status;
|
||||
String body = "";
|
||||
|
||||
|
||||
public static HttpData map(HttpRequest request) {
|
||||
var data = new HttpData();
|
||||
data.setUrl(request.uri().getPath());
|
||||
data.setMethod(request.method());
|
||||
data.setParameters(extractQueryParams(request.uri()));
|
||||
data.setStatus(200);
|
||||
if (request.bodyPublisher().isPresent()) {
|
||||
data.setBody(request.bodyPublisher().get().toString());
|
||||
}
|
||||
data.setHeaders(Collections.unmodifiableMap(request.headers().map()));
|
||||
return data;
|
||||
}
|
||||
|
||||
public static HttpData map(HttpResponse<String> response) {
|
||||
var data = new HttpData();
|
||||
data.setUrl(response.uri().getPath());
|
||||
data.setMethod(response.request().method());
|
||||
data.setParameters(extractQueryParams(response.uri()));
|
||||
data.setStatus(200);
|
||||
data.setBody(response.body());
|
||||
data.setHeaders(Collections.unmodifiableMap(response.headers().map()));
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
private static Map<String, String> extractQueryParams(URI uri) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
String query = uri.getQuery();
|
||||
if (query != null && !query.isEmpty()) {
|
||||
for (String param : query.split("&")) {
|
||||
String[] keyValue = param.split("=");
|
||||
if (keyValue.length > 1) {
|
||||
params.put(keyValue[0], keyValue[1]);
|
||||
} else {
|
||||
params.put(keyValue[0], ""); // Empty value for parameter without explicit value
|
||||
}
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
}
|
||||
@@ -43,11 +43,12 @@ public class User {
|
||||
private long followers;
|
||||
private List<Badge> badges;
|
||||
@Getter(AccessLevel.NONE)
|
||||
private Set<UserAttribute> attributes;
|
||||
private final Set<UserAttribute> attributes = new HashSet<>();
|
||||
|
||||
public List<UserAttribute> getAttributes() {
|
||||
return attributes.stream().toList();
|
||||
}
|
||||
|
||||
public boolean hasAttribute(UserAttribute userFlag) {
|
||||
return attributes.contains(userFlag);
|
||||
}
|
||||
@@ -104,14 +105,28 @@ public class User {
|
||||
this.following = following;
|
||||
this.followers = followers;
|
||||
this.badges = badges;
|
||||
this.attributes = new HashSet<>();
|
||||
}
|
||||
|
||||
public User(Long id,
|
||||
String name,
|
||||
String profileName,
|
||||
Picture picture,
|
||||
long following,
|
||||
long followers,
|
||||
List<Badge> badges) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.profileName = profileName;
|
||||
this.picture = picture;
|
||||
this.following = following;
|
||||
this.followers = followers;
|
||||
this.badges = badges;
|
||||
}
|
||||
|
||||
public User(Long userId,
|
||||
String nickName) {
|
||||
this.id = userId;
|
||||
this.name = nickName;
|
||||
this.attributes = new HashSet<>();
|
||||
}
|
||||
|
||||
public User(Long userId,
|
||||
@@ -194,4 +209,4 @@ public class User {
|
||||
0,
|
||||
List.of(Badge.empty()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,29 +20,29 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.events_generator;
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class EventGeneratorSettings
|
||||
public class GiftsData
|
||||
{
|
||||
private String inputDictionary;
|
||||
|
||||
private String outputDictionary;
|
||||
private List<String> ignoredFiles = new ArrayList<>();
|
||||
|
||||
private String prefix;
|
||||
|
||||
private String endFix;
|
||||
|
||||
private boolean isTikTokEvent;
|
||||
|
||||
public void addIgnoredClass(String name)
|
||||
@Getter
|
||||
public final class Request
|
||||
{
|
||||
ignoredFiles.add(name);
|
||||
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static final class Response
|
||||
{
|
||||
private String json;
|
||||
private List<Gift> gifts;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
|
||||
public class LiveConnectionData {
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Request {
|
||||
private String roomId;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Response {
|
||||
private String websocketCookies;
|
||||
private URI websocketUrl;
|
||||
private WebcastResponse webcastResponse;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
public class LiveData {
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Request {
|
||||
private String roomId;
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public static class Response {
|
||||
private String json;
|
||||
private LiveStatus liveStatus;
|
||||
private String title;
|
||||
private int likes;
|
||||
private int viewers;
|
||||
private int totalViewers;
|
||||
private boolean ageRestricted;
|
||||
private User host;
|
||||
private LiveType liveType;
|
||||
public Response() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public enum LiveStatus {
|
||||
HostNotFound,
|
||||
HostOnline,
|
||||
HostOffline,
|
||||
}
|
||||
|
||||
public enum LiveType {
|
||||
SOLO,
|
||||
BOX,
|
||||
BATTLE,
|
||||
CO_HOST
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
public class LiveUserData {
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Request {
|
||||
private String userName;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Response {
|
||||
private String json;
|
||||
private UserStatus userStatus;
|
||||
private String roomId;
|
||||
private long startedAtTimeStamp;
|
||||
|
||||
public boolean isLiveOnline() {
|
||||
return userStatus == LiveUserData.UserStatus.Live || userStatus == LiveUserData.UserStatus.LivePaused;
|
||||
}
|
||||
|
||||
public boolean isHostNameValid() {
|
||||
return userStatus != LiveUserData.UserStatus.NotFound;
|
||||
}
|
||||
}
|
||||
|
||||
public enum UserStatus {
|
||||
NotFound,
|
||||
Offline,
|
||||
LivePaused,
|
||||
Live,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.settings;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
|
||||
public class HttpClientSettings {
|
||||
|
||||
@Getter
|
||||
final Map<String, Object> params;
|
||||
|
||||
@Getter
|
||||
final Map<String, String> headers;
|
||||
|
||||
@Getter
|
||||
final Map<String, String> cookies;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
ProxyClientSettings proxyClientSettings;
|
||||
|
||||
@Getter
|
||||
Consumer<HttpClient.Builder> onClientCreating;
|
||||
|
||||
@Getter
|
||||
Consumer<HttpRequest.Builder> onRequestCreating;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
Duration timeout;
|
||||
|
||||
public HttpClientSettings() {
|
||||
this.params = new TreeMap<>();
|
||||
this.headers = new HashMap<>();
|
||||
this.cookies = new HashMap<>();
|
||||
this.timeout = Duration.ofSeconds(2);
|
||||
this.proxyClientSettings = new ProxyClientSettings();
|
||||
this.onClientCreating = (x) -> {
|
||||
};
|
||||
this.onRequestCreating = (x) -> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param consumer Use to configure proxy settings for http client
|
||||
*/
|
||||
public void configureProxy(Consumer<ProxyClientSettings> consumer) {
|
||||
proxyClientSettings.setEnabled(true);
|
||||
consumer.accept(proxyClientSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param onRequestCreating Every time new Http request in created this method will be triggered
|
||||
* use to modify request
|
||||
*/
|
||||
public void onRequestCreating(Consumer<HttpRequest.Builder> onRequestCreating) {
|
||||
this.onRequestCreating = onRequestCreating;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param onClientCreating Every time new instance of Http client request in created this method will be triggered
|
||||
* use to modify http client
|
||||
*/
|
||||
public void onClientCreating(Consumer<HttpClient.Builder> onClientCreating) {
|
||||
this.onClientCreating = onClientCreating;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpClientSettings clone() {
|
||||
|
||||
var newSettings = new HttpClientSettings();
|
||||
newSettings.setTimeout(this.getTimeout());
|
||||
newSettings.onRequestCreating(this.onRequestCreating);
|
||||
newSettings.onClientCreating(this.onClientCreating);
|
||||
newSettings.getHeaders().putAll(new TreeMap<>(this.headers));
|
||||
newSettings.getCookies().putAll(new TreeMap<>(this.cookies));
|
||||
newSettings.getParams().putAll(new TreeMap<>(this.params));
|
||||
newSettings.proxyClientSettings = this.proxyClientSettings;
|
||||
|
||||
return newSettings;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,9 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
package io.github.jwdeveloper.tiktok.data.settings;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
@@ -28,45 +30,100 @@ import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class Constants {
|
||||
|
||||
/**
|
||||
* Web-URL for TikTok
|
||||
*/
|
||||
public static final String TIKTOK_URL_WEB = "https://www.tiktok.com/";
|
||||
/**
|
||||
* WebCast-BaseURL for TikTok
|
||||
*/
|
||||
public static final String TIKTOK_URL_WEBCAST = "https://webcast.tiktok.com/webcast/";
|
||||
/**
|
||||
* Signing API by Isaac Kogan
|
||||
* https://github-wiki-see.page/m/isaackogan/TikTokLive/wiki/All-About-Signatures
|
||||
*/
|
||||
public static final String TIKTOK_SIGN_API = "https://tiktok.eulerstream.com/webcast/sign_url";
|
||||
|
||||
/**
|
||||
* Default TimeOut for Connections
|
||||
*/
|
||||
public static final int DEFAULT_TIMEOUT = 20;
|
||||
@Data
|
||||
public class LiveClientSettings {
|
||||
|
||||
|
||||
/**
|
||||
* Default Settings for Client
|
||||
* TODO: give better description
|
||||
* <p>
|
||||
* sets client in the offline mode, so it do not connects to TikTok servers
|
||||
* it makes sense to use it when you are testing client with your custom events
|
||||
*/
|
||||
public static ClientSettings DefaultClientSettings() {
|
||||
var clientSettings = new ClientSettings();
|
||||
clientSettings.setTimeout(Duration.ofSeconds(DEFAULT_TIMEOUT));
|
||||
private boolean offline;
|
||||
|
||||
/**
|
||||
* TODO: give better description
|
||||
* <p>
|
||||
* Determines if gifts data is downloaded before TikTokLive starts,
|
||||
* when `false` then client.giftManager() does not contain initial gifts
|
||||
*/
|
||||
private boolean fetchGifts = true;
|
||||
|
||||
/**
|
||||
* ISO-Language for Client
|
||||
*/
|
||||
private String clientLanguage;
|
||||
|
||||
/**
|
||||
* Whether to Retry if Connection Fails
|
||||
*/
|
||||
private boolean retryOnConnectionFailure;
|
||||
|
||||
/**
|
||||
* Before retrying connect, wait for select amount of time
|
||||
*/
|
||||
private Duration retryConnectionTimeout;
|
||||
|
||||
/**
|
||||
* Whether to print Logs to Console
|
||||
*/
|
||||
private boolean printToConsole = true;
|
||||
|
||||
/**
|
||||
* LoggingLevel for Logs
|
||||
*/
|
||||
private Level logLevel;
|
||||
|
||||
/**
|
||||
* Optional: Use it if you need to change TikTok live hostname in builder
|
||||
*/
|
||||
private String hostName;
|
||||
|
||||
/**
|
||||
* Parameters used in requests to TikTok api
|
||||
*/
|
||||
private HttpClientSettings httpSettings;
|
||||
|
||||
/**
|
||||
* Interval of time in milliseconds between pings to TikTok
|
||||
* @apiNote Min: 250 (0.25 seconds), Default: 5000 (5 seconds)
|
||||
*/
|
||||
private long pingInterval = 5000;
|
||||
|
||||
/**
|
||||
* Optional: Sometimes not every messages from chat are send to TikTokLiveJava to fix this issue you can set sessionId
|
||||
* @see <a href="https://github.com/isaackogan/TikTok-Live-Connector#send-chat-messages">Documentation: How to obtain sessionId</a>
|
||||
*/
|
||||
private String sessionId;
|
||||
|
||||
/**
|
||||
* Optional: By default roomID is fetched before connect to live, but you can set it manually
|
||||
*/
|
||||
private String roomId;
|
||||
|
||||
/**
|
||||
* Optional: API Key for increased limit to signing server
|
||||
*/
|
||||
private String apiKey;
|
||||
|
||||
public static LiveClientSettings createDefault() {
|
||||
var httpSettings = new HttpClientSettings();
|
||||
httpSettings.getParams().putAll(DefaultClientParams());
|
||||
httpSettings.getHeaders().putAll(DefaultRequestHeaders());
|
||||
httpSettings.setTimeout(Duration.ofSeconds(3));
|
||||
|
||||
var clientSettings = new LiveClientSettings();
|
||||
clientSettings.setClientLanguage("en-US");
|
||||
clientSettings.setHandleExistingEvents(true);
|
||||
clientSettings.setRetryOnConnectionFailure(false);
|
||||
clientSettings.setRetryConnectionTimeout(Duration.ofSeconds(1));
|
||||
clientSettings.setPrintToConsole(false);
|
||||
clientSettings.setLogLevel(Level.ALL);
|
||||
clientSettings.setClientParameters(Constants.DefaultClientParams());
|
||||
|
||||
clientSettings.setHttpSettings(httpSettings);
|
||||
return clientSettings;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Default Parameters for HTTP-Request
|
||||
*/
|
||||
@@ -105,26 +162,24 @@ public class Constants {
|
||||
clientParams.put("webcast_sdk_version", "1.3.0");
|
||||
clientParams.put("update_version_code", "1.3.0");
|
||||
|
||||
|
||||
return clientParams;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Default Headers for HTTP-Request
|
||||
*/
|
||||
public static Map<String, String> DefaultRequestHeaders() {
|
||||
var headers = new HashMap<String, String>();
|
||||
|
||||
headers.put("authority","www.tiktok.com");
|
||||
headers.put("Connection", "keep-alive");
|
||||
headers.put("authority", "www.tiktok.com");
|
||||
headers.put("Cache-Control", "max-age=0");
|
||||
headers.put("Accept", "text/html,application/json,application/protobuf");
|
||||
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36");
|
||||
headers.put("Referer", "https://www.tiktok.com/");
|
||||
headers.put("Origin", "https://www.tiktok.com");
|
||||
headers.put("Accept-Language", "en-US,en; q=0.9");
|
||||
headers.put("Accept-Encoding", "gzip, deflate");
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.settings;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.dto.ProxyData;
|
||||
import lombok.*;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProxyClientSettings implements Iterator<ProxyData>
|
||||
{
|
||||
private boolean enabled, autoDiscard = true, fallback = true;
|
||||
private Rotation rotation = Rotation.CONSECUTIVE;
|
||||
private final List<ProxyData> proxyList = new ArrayList<>();
|
||||
private int index = -1;
|
||||
private Proxy.Type type = Proxy.Type.DIRECT;
|
||||
private Consumer<ProxyData> onProxyUpdated = x -> {};
|
||||
|
||||
public boolean addProxy(String addressPort) {
|
||||
return proxyList.add(ProxyData.map(addressPort));
|
||||
}
|
||||
|
||||
public boolean addProxy(String address, int port) {
|
||||
return addProxy(new InetSocketAddress(address, port));
|
||||
}
|
||||
|
||||
public boolean addProxy(InetSocketAddress inetAddress) {
|
||||
return proxyList.add(new ProxyData(inetAddress.getHostString(), inetAddress.getPort()));
|
||||
}
|
||||
|
||||
public void addProxies(List<String> list) {
|
||||
list.forEach(this::addProxy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return !proxyList.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProxyData next() {
|
||||
var nextProxy = switch (rotation)
|
||||
{
|
||||
case CONSECUTIVE -> {
|
||||
index = (index+1) % proxyList.size();
|
||||
yield proxyList.get(index).clone();
|
||||
}
|
||||
case RANDOM -> {
|
||||
index = new Random().nextInt(proxyList.size());
|
||||
yield proxyList.get(index).clone();
|
||||
}
|
||||
case NONE -> {
|
||||
index = Math.max(index, 0);
|
||||
yield proxyList.get(index).clone();
|
||||
}
|
||||
};
|
||||
onProxyUpdated.accept(nextProxy);
|
||||
return nextProxy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
proxyList.remove(index);
|
||||
}
|
||||
|
||||
public void setIndex(int index) {
|
||||
if (index == 0 && proxyList.isEmpty())
|
||||
this.index = 0;
|
||||
else {
|
||||
if (index < 0 || index >= proxyList.size())
|
||||
throw new IndexOutOfBoundsException("Index " + index + " exceeds list of size: " + proxyList.size());
|
||||
this.index = index;
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyClientSettings clone()
|
||||
{
|
||||
ProxyClientSettings settings = new ProxyClientSettings();
|
||||
settings.setEnabled(enabled);
|
||||
settings.setRotation(rotation);
|
||||
settings.setIndex(index);
|
||||
settings.setType(type);
|
||||
settings.setOnProxyUpdated(onProxyUpdated);
|
||||
proxyList.forEach(proxyData -> settings.addProxy(proxyData.getAddress(), proxyData.getPort()));
|
||||
return settings;
|
||||
}
|
||||
|
||||
public enum Rotation
|
||||
{
|
||||
/** Rotate addresses consecutively, from proxy 0 -> 1 -> 2 -> ...etc. */
|
||||
CONSECUTIVE,
|
||||
/** Rotate addresses randomly, from proxy 0 -> 69 -> 420 -> 1 -> ...etc. */
|
||||
RANDOM,
|
||||
/** Don't rotate addresses at all, pin to the indexed address. */
|
||||
NONE
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@
|
||||
package io.github.jwdeveloper.tiktok.exceptions;
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* Happens while bad response from Http request to TikTok
|
||||
*/
|
||||
public class TikTokLiveRequestException extends TikTokLiveException
|
||||
@@ -46,4 +46,4 @@ public class TikTokLiveRequestException extends TikTokLiveException
|
||||
public TikTokLiveRequestException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,15 +26,20 @@ package io.github.jwdeveloper.tiktok.exceptions;
|
||||
/**
|
||||
* Happens when incoming data from TikTok can not be mapped to TikTokEvent's
|
||||
*/
|
||||
public class TikTokMessageMappingException extends TikTokLiveException
|
||||
{
|
||||
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, Throwable throwable)
|
||||
{
|
||||
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + " to class " + outputClass.getSimpleName(),throwable);
|
||||
public class TikTokMessageMappingException extends TikTokLiveException {
|
||||
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, Throwable throwable) {
|
||||
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + " to class " + outputClass.getSimpleName(), throwable);
|
||||
}
|
||||
|
||||
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, String message)
|
||||
{
|
||||
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + " to class " + outputClass.getSimpleName()+": "+message);
|
||||
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, String message) {
|
||||
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + " to class " + outputClass.getSimpleName() + ": " + message);
|
||||
}
|
||||
|
||||
public TikTokMessageMappingException(Class<?> inputClazz, String message, Throwable throwable) {
|
||||
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + ": " + message, throwable);
|
||||
}
|
||||
|
||||
public TikTokMessageMappingException(String message, Throwable throwable) {
|
||||
super( message, throwable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,33 +20,30 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
package io.github.jwdeveloper.tiktok.exceptions;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class TikTokCookieJar {
|
||||
private final Map<String, String> cookies;
|
||||
public TikTokCookieJar() {
|
||||
cookies = new HashMap<>();
|
||||
/*
|
||||
* Happens while bad response from http proxy request to TikTok
|
||||
*/
|
||||
public class TikTokProxyRequestException extends TikTokLiveException
|
||||
{
|
||||
public TikTokProxyRequestException() {
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
return cookies.get(key);
|
||||
public TikTokProxyRequestException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public void set(String key, String value) {
|
||||
cookies.put(key, value);
|
||||
public TikTokProxyRequestException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public String parseCookies()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
for(var entry : cookies.entrySet())
|
||||
{
|
||||
sb.append(entry.getKey()).append("=").append(entry.getValue()).append(";");
|
||||
}
|
||||
return sb.toString();
|
||||
public TikTokProxyRequestException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
|
||||
public TikTokProxyRequestException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -20,41 +20,26 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.utils;
|
||||
package io.github.jwdeveloper.tiktok.exceptions;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
|
||||
public class CancelationToken
|
||||
public class TikTokSignServerException extends TikTokLiveRequestException
|
||||
{
|
||||
private boolean isCanceled =false;
|
||||
|
||||
public void cancel()
|
||||
{
|
||||
isCanceled =true;
|
||||
public TikTokSignServerException() {
|
||||
}
|
||||
|
||||
public boolean isCancel()
|
||||
{
|
||||
|
||||
return isCanceled;
|
||||
public TikTokSignServerException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public void throwIfCancel()
|
||||
{
|
||||
if(!isCanceled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
throw new TikTokLiveException("Token requested cancelation");
|
||||
public TikTokSignServerException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public boolean isNotCancel()
|
||||
{
|
||||
return !isCancel();
|
||||
public TikTokSignServerException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public static CancelationToken create()
|
||||
{
|
||||
return new CancelationToken();
|
||||
public TikTokSignServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.requests.GiftsData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
|
||||
|
||||
public interface LiveHttpClient
|
||||
{
|
||||
/**
|
||||
* @return list of gifts that are available in your country
|
||||
*/
|
||||
GiftsData.Response fetchGiftsData();
|
||||
|
||||
|
||||
/**
|
||||
* Returns information about user that is having a livestream
|
||||
* @param userName name of user
|
||||
* @return {@link LiveUserData.Response}
|
||||
*/
|
||||
default LiveUserData.Response fetchLiveUserData(String userName) {
|
||||
return fetchLiveUserData(new LiveUserData.Request(userName));
|
||||
}
|
||||
|
||||
LiveUserData.Response fetchLiveUserData(LiveUserData.Request request);
|
||||
|
||||
/**
|
||||
* @param roomId can be obtained from browsers cookies or by invoked fetchLiveUserData
|
||||
* @return {@link LiveData.Response}
|
||||
*/
|
||||
default LiveData.Response fetchLiveData(String roomId) {
|
||||
return fetchLiveData(new LiveData.Request(roomId));
|
||||
}
|
||||
|
||||
LiveData.Response fetchLiveData(LiveData.Request request);
|
||||
|
||||
/**
|
||||
* @param roomId can be obtained from browsers cookies or by invoked fetchLiveUserData
|
||||
* @return {@link LiveConnectionData.Response}
|
||||
*/
|
||||
default LiveConnectionData.Response fetchLiveConnectionData(String roomId) {
|
||||
return fetchLiveConnectionData(new LiveConnectionData.Request(roomId));
|
||||
}
|
||||
|
||||
LiveConnectionData.Response fetchLiveConnectionData(LiveConnectionData.Request request);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public interface GiftsManager {
|
||||
|
||||
/**
|
||||
* You can create and attach your own custom gift to manager
|
||||
*
|
||||
* @param gift
|
||||
*/
|
||||
void attachGift(Gift gift);
|
||||
|
||||
/**
|
||||
* You can create and attach your own custom gift to manager
|
||||
*
|
||||
* @param gifts
|
||||
*/
|
||||
void attachGiftsList(List<Gift> gifts);
|
||||
|
||||
/**
|
||||
* finds gift by name
|
||||
* When gift not found return Gift.UNDEFINED;
|
||||
*
|
||||
* @param name gift name
|
||||
*/
|
||||
Gift getByName(String name);
|
||||
|
||||
/**
|
||||
* finds gift by id
|
||||
* When gift not found return Gift.UNDEFINED;
|
||||
*
|
||||
* @param giftId giftId
|
||||
*/
|
||||
Gift getById(int giftId);
|
||||
|
||||
|
||||
/**
|
||||
* finds gift by filter
|
||||
* When gift not found return Gift.UNDEFINED;
|
||||
*/
|
||||
Gift getByFilter(Predicate<Gift> filter);
|
||||
|
||||
List<Gift> getManyByFilter(Predicate<Gift> filter);
|
||||
|
||||
/**
|
||||
* @return list of all gifts
|
||||
*/
|
||||
List<Gift> toList();
|
||||
|
||||
|
||||
/**
|
||||
* @return list of all map of all gifts where Integer is gift Id
|
||||
*/
|
||||
Map<Integer, Gift> toMap();
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.listener.ListenersManager;
|
||||
import io.github.jwdeveloper.tiktok.listener.TikTokEventListener;
|
||||
|
||||
@@ -55,10 +56,24 @@ public interface LiveClient {
|
||||
void disconnect();
|
||||
|
||||
|
||||
/**
|
||||
* Use to manually invoke event
|
||||
*/
|
||||
void publishEvent(TikTokEvent event);
|
||||
|
||||
|
||||
/**
|
||||
* @param webcastMessageName name of TikTok protocol-buffer message
|
||||
* @param payloadBase64 protocol-buffer message bytes payload
|
||||
*/
|
||||
void publishMessage(String webcastMessageName, String payloadBase64);
|
||||
|
||||
void publishMessage(String webcastMessageName, byte[] payload);
|
||||
|
||||
/**
|
||||
* Get information about gifts
|
||||
*/
|
||||
GiftManager getGiftManager();
|
||||
GiftsManager getGiftManager();
|
||||
|
||||
/**
|
||||
* Gets the current room info from TikTok API including streamer info, room status and statistics.
|
||||
|
||||
@@ -22,14 +22,32 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.RankingUser;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.models.ConnectionState;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface LiveRoomInfo
|
||||
{
|
||||
/**
|
||||
*
|
||||
* @return get current count of viewers of live
|
||||
*/
|
||||
int getViewersCount();
|
||||
|
||||
/**
|
||||
*
|
||||
* @return get total current count of viewers since beginning of live
|
||||
*/
|
||||
int getTotalViewersCount();
|
||||
int getLikesCount();
|
||||
long getStartTime();
|
||||
boolean isAgeRestricted();
|
||||
String getRoomId();
|
||||
String getHostName();
|
||||
String getTitle();
|
||||
User getHostUser();
|
||||
List<RankingUser> getUsersRanking();
|
||||
ConnectionState getConnectionState();
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,11 @@ package io.github.jwdeveloper.tiktok.live.builder;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.envelop.TikTokChestEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.control.TikTokPreConnectionEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftComboEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomUserInfoEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.http.TikTokHttpResponseEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomInfoEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
|
||||
@@ -40,58 +40,148 @@ import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketUnhandl
|
||||
|
||||
public interface EventsBuilder<T> {
|
||||
|
||||
T onRoom(EventConsumer<TikTokRoomEvent> event);
|
||||
|
||||
T onRoomUserInfo(EventConsumer<TikTokRoomUserInfoEvent> event);
|
||||
|
||||
T onComment(EventConsumer<TikTokCommentEvent> event);
|
||||
|
||||
T onWebsocketMessage(EventConsumer<TikTokWebsocketMessageEvent> event);
|
||||
|
||||
T onWebsocketResponse(EventConsumer<TikTokWebsocketResponseEvent> event);
|
||||
|
||||
T onWebsocketUnhandledMessage(EventConsumer<TikTokWebsocketUnhandledMessageEvent> event);
|
||||
/**
|
||||
* Invoked whenever specified event is triggered
|
||||
*
|
||||
* @param eventClass event class
|
||||
* @param action action
|
||||
*/
|
||||
<E extends TikTokEvent> T onEvent(Class<E> eventClass, EventConsumer<E> action);
|
||||
|
||||
|
||||
/**
|
||||
* Invoked whenever any event is triggered
|
||||
*
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onEvent(EventConsumer<TikTokEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked when information about room (live) got updated such as viewer count, etc..
|
||||
*
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onRoomInfo(EventConsumer<TikTokRoomInfoEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked when someone send message to chat
|
||||
*
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onComment(EventConsumer<TikTokCommentEvent> action);
|
||||
|
||||
|
||||
T onGiftCombo(EventConsumer<TikTokGiftComboEvent> event);
|
||||
T onGift(EventConsumer<TikTokGiftEvent> event);
|
||||
/**
|
||||
* Invoked when TikTokLiveJava makes http request and getting response
|
||||
*
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onHttpResponse(EventConsumer<TikTokHttpResponseEvent> action);
|
||||
|
||||
T onQuestion(EventConsumer<TikTokQuestionEvent> event);
|
||||
/**
|
||||
* Invoked when TikTok protocolBuffer data "message" was successfully mapped to event
|
||||
* events contains protocol-buffer "Message" and TikTokLiveJava "Event"
|
||||
*
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onWebsocketMessage(EventConsumer<TikTokWebsocketMessageEvent> action);
|
||||
|
||||
T onSubscribe(EventConsumer<TikTokSubscribeEvent> event);
|
||||
/**
|
||||
* Invoked when there was not found event mapper for TikTok protocolBuffer data "message"
|
||||
*
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onWebsocketUnhandledMessage(EventConsumer<TikTokWebsocketUnhandledMessageEvent> action);
|
||||
|
||||
T onFollow(EventConsumer<TikTokFollowEvent> event);
|
||||
|
||||
T onLike(EventConsumer<TikTokLikeEvent> event);
|
||||
|
||||
T onEmote(EventConsumer<TikTokEmoteEvent> event);
|
||||
|
||||
T onJoin(EventConsumer<TikTokJoinEvent> event);
|
||||
|
||||
T onShare(EventConsumer<TikTokShareEvent> event);
|
||||
T onUnhandledSocial(EventConsumer<TikTokUnhandledSocialEvent> event);
|
||||
|
||||
// T onChest(EventConsumer<TikTokChestEvent> event);
|
||||
|
||||
T onLivePaused(EventConsumer<TikTokLivePausedEvent> event);
|
||||
|
||||
T onLiveEnded(EventConsumer<TikTokLiveEndedEvent> event);
|
||||
|
||||
T onConnected(EventConsumer<TikTokConnectedEvent> event);
|
||||
|
||||
T onReconnecting(EventConsumer<TikTokReconnectingEvent> event);
|
||||
|
||||
T onDisconnected(EventConsumer<TikTokDisconnectedEvent> event);
|
||||
|
||||
T onError(EventConsumer<TikTokErrorEvent> event);
|
||||
T onEvent(EventConsumer<TikTokEvent> event);
|
||||
/**
|
||||
* Invoked every time TikTok sends protocolBuffer data to websocket
|
||||
* Response contains list of messages that are later mapped to events
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onWebsocketResponse(EventConsumer<TikTokWebsocketResponseEvent> action);
|
||||
|
||||
|
||||
/**
|
||||
* Invoked for gifts that has no combo, or when combo finishes
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onGift(EventConsumer<TikTokGiftEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked for gifts that has combo options such as roses
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onGiftCombo(EventConsumer<TikTokGiftComboEvent> action);
|
||||
|
||||
|
||||
T onQuestion(EventConsumer<TikTokQuestionEvent> action);
|
||||
|
||||
T onSubscribe(EventConsumer<TikTokSubscribeEvent> action);
|
||||
|
||||
T onFollow(EventConsumer<TikTokFollowEvent> action);
|
||||
|
||||
T onLike(EventConsumer<TikTokLikeEvent> action);
|
||||
|
||||
T onEmote(EventConsumer<TikTokEmoteEvent> action);
|
||||
|
||||
T onJoin(EventConsumer<TikTokJoinEvent> action);
|
||||
|
||||
T onShare(EventConsumer<TikTokShareEvent> action);
|
||||
|
||||
T onLivePaused(EventConsumer<TikTokLivePausedEvent> action);
|
||||
|
||||
T onLiveUnpaused(EventConsumer<TikTokLiveUnpausedEvent> action);
|
||||
|
||||
T onLiveEnded(EventConsumer<TikTokLiveEndedEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked when client has been successfully connected to live
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onConnected(EventConsumer<TikTokConnectedEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked before client has been successfully connected to live
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onPreConnection(EventConsumer<TikTokPreConnectionEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked when client tries to reconnect
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onReconnecting(EventConsumer<TikTokReconnectingEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked when client disconnected
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onDisconnected(EventConsumer<TikTokDisconnectedEvent> action);
|
||||
|
||||
/**
|
||||
* Invoked when exception was throed inside client or event handler
|
||||
* @param action
|
||||
* @return
|
||||
*/
|
||||
T onError(EventConsumer<TikTokErrorEvent> action);
|
||||
|
||||
|
||||
// TODO Figure out how those events works
|
||||
// T onChest(EventConsumer<TikTokChestEvent> event);
|
||||
|
||||
//T onLinkMicFanTicket(TikTokEventConsumer<TikTokLinkMicFanTicketEvent> event);
|
||||
|
||||
//T onEnvelope(TikTokEventConsumer<TikTokEnvelopeEvent> event);
|
||||
@@ -133,6 +223,4 @@ public interface EventsBuilder<T> {
|
||||
//T onLinkMicBattle(TikTokEventConsumer<TikTokLinkMicBattleEvent> event);
|
||||
|
||||
//T onUnhandledControl(TikTokEventConsumer<TikTokUnhandledControlEvent> event);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -22,21 +22,59 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live.builder;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.listener.TikTokEventListener;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokMapper;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface LiveClientBuilder extends EventsBuilder<LiveClientBuilder> {
|
||||
LiveClientBuilder configure(Consumer<ClientSettings> consumer);
|
||||
|
||||
/**
|
||||
* This method is triggered after default mappings are registered
|
||||
* It could be used to OVERRIDE behaviour of mappings and implement custom behaviour
|
||||
*
|
||||
* Be aware if for example you override WebcastGiftEvent, onGiftEvent() will not be working
|
||||
*
|
||||
* @param onCustomMappings lambda method
|
||||
* @return
|
||||
*/
|
||||
LiveClientBuilder onMapping(Consumer<TikTokMapper> onCustomMappings);
|
||||
|
||||
|
||||
/**
|
||||
* Configuration of client settings
|
||||
* @see LiveClientSettings
|
||||
* @param onConfigure
|
||||
* @return
|
||||
*/
|
||||
LiveClientBuilder configure(Consumer<LiveClientSettings> onConfigure);
|
||||
|
||||
/**
|
||||
* @see TikTokEventListener
|
||||
* Adding events listener class, its fancy way to register events without using lamda method
|
||||
* but actual method in class that implements TikTokEventListener
|
||||
* @return
|
||||
*/
|
||||
LiveClientBuilder addListener(TikTokEventListener listener);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return LiveClient object
|
||||
*/
|
||||
LiveClient build();
|
||||
|
||||
/**
|
||||
*
|
||||
* @return LiveClient object and connects to TikTok live
|
||||
*/
|
||||
LiveClient buildAndConnect();
|
||||
|
||||
/**
|
||||
*
|
||||
* @return LiveClient object and connects to TikTok live asynchronously
|
||||
*/
|
||||
CompletableFuture<LiveClient> buildAndConnectAsync();
|
||||
}
|
||||
|
||||
@@ -20,36 +20,39 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.room;
|
||||
package io.github.jwdeveloper.tiktok.mappers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.RankingUser;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastRoomUserSeqMessage;
|
||||
import lombok.Getter;
|
||||
import com.google.protobuf.GeneratedMessageV3;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.MappingAction;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.function.Function;
|
||||
|
||||
|
||||
|
||||
@Getter
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokRoomUserInfoEvent extends TikTokHeaderEvent {
|
||||
private final int totalUsers;
|
||||
public interface TikTokMapper {
|
||||
|
||||
/**
|
||||
* Only top 5 users in ranking has detailed data
|
||||
* rest has only ID
|
||||
* * if mapper is not found for messageName, TikTokLiveException is thrown
|
||||
*
|
||||
* @param messageName
|
||||
* @return TikTokMapperModel
|
||||
*/
|
||||
private final List<RankingUser> usersRanking;
|
||||
public TikTokRoomUserInfoEvent(WebcastRoomUserSeqMessage msg) {
|
||||
super(msg.getCommon());
|
||||
totalUsers = msg.getTotalUser();
|
||||
usersRanking = msg.getRanksListList().stream().map(RankingUser::new)
|
||||
.sorted((ru1, ru2) -> Integer.compare(ru2.getScore(), ru1.getScore()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
TikTokMapperModel forMessage(String messageName);
|
||||
|
||||
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName);
|
||||
|
||||
TikTokMapperModel forMessage(String mapperName, MappingAction<MappingResult> onMapping);
|
||||
|
||||
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, MappingAction<MappingResult> onMapping);
|
||||
|
||||
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, Function<byte[], TikTokEvent> onMapping);
|
||||
|
||||
TikTokMapperModel forAnyMessage();
|
||||
|
||||
|
||||
boolean isRegistered(String mapperName);
|
||||
|
||||
<T extends GeneratedMessageV3> boolean isRegistered(Class<T> mapperName);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.mappers;
|
||||
|
||||
import com.google.protobuf.GeneratedMessageV3;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokMessageMappingException;
|
||||
import io.github.jwdeveloper.tiktok.utils.ProtoBufferObject;
|
||||
|
||||
public interface TikTokMapperHelper {
|
||||
|
||||
/**
|
||||
* @param bytes protocol buffer data bytes
|
||||
* @param messageClass class that we want to serialize bytes to
|
||||
* @param <T> @messageClass must be class that is made by protocol buffer
|
||||
* @return object of type @messageClass
|
||||
*/
|
||||
<T extends GeneratedMessageV3> T bytesToWebcastObject(byte[] bytes, Class<T> messageClass);
|
||||
|
||||
/**
|
||||
* @param bytes protocol buffer data bytes
|
||||
* @param messageName class that we want to serialize bytes to
|
||||
* @return protocol buffer objects if class for @messageName has been found
|
||||
* @throws TikTokMessageMappingException if there is no suitable class for messageName
|
||||
*/
|
||||
Object bytesToWebcastObject(byte[] bytes, String messageName);
|
||||
|
||||
|
||||
/**
|
||||
* @param messageName checks wheaten TikTokLiveJava has class representation for certain protocol-buffer message name
|
||||
* @return false if class is not found
|
||||
*/
|
||||
boolean isMessageHasProtoClass(String messageName);
|
||||
|
||||
/**
|
||||
* @param bytes protocol buffer data bytes
|
||||
* @return tree structure of protocol buffer object
|
||||
* @see ProtoBufferObject
|
||||
*/
|
||||
ProtoBufferObject bytesToProtoBufferStructure(byte[] bytes);
|
||||
|
||||
/**
|
||||
* Converts object to json
|
||||
*
|
||||
* @param obj any object
|
||||
* @return pretty formatted json
|
||||
*/
|
||||
String toJson(Object obj);
|
||||
}
|
||||
@@ -20,44 +20,39 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
package io.github.jwdeveloper.tiktok.mappers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.AfterMappingAction;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.MappingAction;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface GiftManager {
|
||||
public interface TikTokMapperModel {
|
||||
|
||||
/**
|
||||
* In case you can't find your gift in Gift enum. You can register gift
|
||||
* manually here to make it detected while TikTokGiftEvent
|
||||
*
|
||||
* @param id gift's id
|
||||
* @param name gift's name
|
||||
* @param diamondCost diamond cost
|
||||
* @return
|
||||
* @return name of websocket message that this mapper is mapping from
|
||||
*/
|
||||
Gift registerGift(int id, String name, int diamondCost, Picture picture);
|
||||
|
||||
String getSourceMessageName();
|
||||
|
||||
/**
|
||||
* @param action Input bytes from websocket, you can modify it and returns different bytes
|
||||
*/
|
||||
TikTokMapperModel onBeforeMapping(MappingAction<byte[]> action);
|
||||
|
||||
/**
|
||||
* @param action Input bytes from websocket. As output returns list of tiktok live events
|
||||
*/
|
||||
TikTokMapperModel onMapping(MappingAction<MappingResult> action);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param giftId
|
||||
* @return
|
||||
* @param action You can modify output list of TikTokLive events
|
||||
* @see AfterMappingAction
|
||||
*/
|
||||
Gift findById(int giftId);
|
||||
|
||||
/**
|
||||
*
|
||||
* @param giftName
|
||||
* @return
|
||||
*/
|
||||
Gift findByName(String giftName);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return all gifts
|
||||
*/
|
||||
List<Gift> getGifts();
|
||||
TikTokMapperModel onAfterMapping(Function<MappingResult, List<TikTokEvent>> action);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.mappers.data;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface AfterMappingAction {
|
||||
/**
|
||||
* @param source object that was used as source to create events
|
||||
* @param events list of events prepared before, could be modified or changed
|
||||
* @return list of events that will be invoked
|
||||
*/
|
||||
List<TikTokEvent> onAfterMapping(Object source, List<TikTokEvent> events);
|
||||
}
|
||||
@@ -20,16 +20,19 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
package io.github.jwdeveloper.tiktok.mappers.data;
|
||||
|
||||
import java.util.Map;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokMapperHelper;
|
||||
|
||||
public interface TikTokHttpRequest {
|
||||
TikTokHttpRequest setQueries(Map<String, Object> queries);
|
||||
@FunctionalInterface
|
||||
public interface MappingAction<T> {
|
||||
|
||||
TikTokHttpRequest setHeader(String key, String value);
|
||||
String get(String url);
|
||||
|
||||
String post(String url);
|
||||
/**
|
||||
* @param inputBytes incoming bytes from TikTok server. The represents protocol buffer message that was send to client
|
||||
* @param messageName name of protocol buffer message
|
||||
* @param mapperHelper utils and helper methods that can be use to debbug/display/deserialize protocol buffer data
|
||||
* @return
|
||||
*/
|
||||
T onMapping(byte[] inputBytes, String messageName, TikTokMapperHelper mapperHelper);
|
||||
|
||||
}
|
||||
@@ -20,31 +20,34 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.events_generator;
|
||||
package io.github.jwdeveloper.tiktok.mappers.data;
|
||||
|
||||
import lombok.Data;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CSharpClassInfo
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public class MappingResult
|
||||
{
|
||||
private String className;
|
||||
private List<FieldInfo> fields = new ArrayList<>();
|
||||
private List<ConstructorInfo> constructors = new ArrayList<>();
|
||||
|
||||
public void addField(String type, String fields)
|
||||
{
|
||||
this.fields.add(new FieldInfo(type,fields));
|
||||
Object source;
|
||||
|
||||
List<TikTokEvent> events;
|
||||
|
||||
String message;
|
||||
|
||||
public static MappingResult of(Object source) {
|
||||
return new MappingResult(source, List.of(),"");
|
||||
}
|
||||
|
||||
public void addConstructor(List<FieldInfo> arguments)
|
||||
{
|
||||
this.constructors.add(new ConstructorInfo(arguments));
|
||||
public static MappingResult of(Object source, List<TikTokEvent> events) {
|
||||
return new MappingResult(source, events,"");
|
||||
}
|
||||
|
||||
public record FieldInfo(String type, String name){};
|
||||
|
||||
public record ConstructorInfo(List<FieldInfo> arguemtns){};
|
||||
public static MappingResult of(Object source,TikTokEvent events) {
|
||||
return new MappingResult(source, List.of(events),"");
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,10 @@ package io.github.jwdeveloper.tiktok.utils;
|
||||
import com.google.gson.ExclusionStrategy;
|
||||
import com.google.gson.FieldAttributes;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import io.github.jwdeveloper.tiktok.data.dto.MessageMetaData;
|
||||
|
||||
import java.awt.*;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class JsonUtil {
|
||||
@@ -34,13 +36,25 @@ public class JsonUtil {
|
||||
return new GsonBuilder()
|
||||
.addSerializationExclusionStrategy(new ExclusionStrategy() {
|
||||
@Override
|
||||
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
|
||||
public boolean shouldSkipField(FieldAttributes fieldAttributes)
|
||||
{
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldSkipClass(Class<?> aClass) {
|
||||
return aClass.equals(Image.class);
|
||||
public boolean shouldSkipClass(Class<?> aClass)
|
||||
{
|
||||
if(aClass.equals(Image.class))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if(aClass.equals(MessageMetaData.class))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.disableHtmlEscaping()
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.utils;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class ProtoBufferFileGenerator {
|
||||
|
||||
|
||||
public static String generate(ProtoBufferObject protoBuffObj, String name) {
|
||||
|
||||
var sb = new StringBuilder();
|
||||
var offset = 2;
|
||||
sb.append("message ").append(name).append(" { \n");
|
||||
|
||||
var objects = new TreeMap<String, ProtoBufferObject>();
|
||||
var objectCounter = 0;
|
||||
for (var entry : protoBuffObj.getFields().entrySet()) {
|
||||
var index = entry.getKey();
|
||||
var field = entry.getValue();
|
||||
var fieldName = field.type.toLowerCase() + "Value";
|
||||
var value = field.value;
|
||||
if (field.value instanceof ProtoBufferObject object) {
|
||||
fieldName += objectCounter;
|
||||
value = "";
|
||||
objects.put(fieldName,object);
|
||||
objectCounter++;
|
||||
|
||||
}
|
||||
for (var i = 0; i < offset; i++) {
|
||||
sb.append(" ");
|
||||
}
|
||||
sb.append(field.type).append(" ").append(fieldName)
|
||||
.append(" ")
|
||||
.append("=")
|
||||
.append(" ")
|
||||
.append(index)
|
||||
.append(";")
|
||||
.append(" //")
|
||||
.append(value)
|
||||
.append("\n");
|
||||
}
|
||||
sb.append(" \n");
|
||||
for(var object : objects.entrySet())
|
||||
{
|
||||
var structure = generate(object.getValue(),object.getKey());
|
||||
sb.append(structure);
|
||||
}
|
||||
|
||||
|
||||
sb.append(" \n");
|
||||
sb.append("} \n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,12 +22,32 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.utils;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface JsonIgnore {
|
||||
}
|
||||
public class ProtoBufferJsonGenerator {
|
||||
public static JsonObject genratejson(ProtoBufferObject protoBuffObj) {
|
||||
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
for (var entry : protoBuffObj.getFields().entrySet()) {
|
||||
var fieldName = entry.getKey() + "_" + entry.getValue().type;
|
||||
if (entry.getValue().value instanceof ProtoBufferObject protoObj)
|
||||
{
|
||||
JsonObject childJson = genratejson(protoObj);
|
||||
jsonObject.add(fieldName, childJson);
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = entry.getValue().value.toString();
|
||||
jsonObject.addProperty(fieldName, value);
|
||||
}
|
||||
|
||||
return jsonObject;
|
||||
}
|
||||
|
||||
public static String generate(ProtoBufferObject protoBufferObject) {
|
||||
var json = genratejson(protoBufferObject);
|
||||
var gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
return gson.toJson(json);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.utils;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class ProtoBufferObject {
|
||||
@Getter
|
||||
private final Map<Integer, ProtoBufferField> fields;
|
||||
|
||||
public ProtoBufferObject() {
|
||||
this.fields = new TreeMap<>();
|
||||
}
|
||||
|
||||
public Object getField(int index)
|
||||
{
|
||||
return fields.get(index);
|
||||
}
|
||||
|
||||
public void addField(int index, String type, Object value) {
|
||||
fields.put(index, new ProtoBufferField(type, value));
|
||||
}
|
||||
|
||||
public void addField(int index, ProtoBufferField value) {
|
||||
fields.put(index, value);
|
||||
}
|
||||
|
||||
|
||||
public String toProtoFile()
|
||||
{
|
||||
return ProtoBufferFileGenerator.generate(this,"UnknownMessage");
|
||||
}
|
||||
|
||||
public String toJson()
|
||||
{
|
||||
return ProtoBufferJsonGenerator.generate(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return toString(0, true);
|
||||
}
|
||||
|
||||
public String toString(int offset ,boolean nested) {
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.append("\n");
|
||||
for (var entry : fields.entrySet()) {
|
||||
var index = entry.getKey();
|
||||
var field = entry.getValue();
|
||||
|
||||
for(var i =0;i<offset;i++)
|
||||
{
|
||||
sb.append(" ");
|
||||
}
|
||||
sb.append(index).append(" ")
|
||||
.append(field.type).append(" ");
|
||||
|
||||
var value = field.value;
|
||||
if (value instanceof ProtoBufferObject child) {
|
||||
sb.append(child.toString(offset+2,nested));
|
||||
} else {
|
||||
sb.append(entry.getValue().value);
|
||||
}
|
||||
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@AllArgsConstructor
|
||||
public class ProtoBufferField {
|
||||
public String type;
|
||||
|
||||
public Object value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.utils;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.protobuf.UnknownFieldSet;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
public class ProtocolUtils {
|
||||
public static String toBase64(byte[] bytes) {
|
||||
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
public static String toBase64(WebcastResponse.Message bytes) {
|
||||
return Base64.getEncoder().encodeToString(bytes.toByteArray());
|
||||
}
|
||||
|
||||
|
||||
public static byte[] fromBase64(String base64) {
|
||||
|
||||
return Base64.getDecoder().decode(base64);
|
||||
}
|
||||
|
||||
public static ProtoBufferObject getProtocolBufferStructure(byte[] bytes) {
|
||||
|
||||
try {
|
||||
var files = UnknownFieldSet.parseFrom(bytes);
|
||||
var protoBufferObject = new ProtoBufferObject();
|
||||
createStructure(files, protoBufferObject);
|
||||
return protoBufferObject;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createStructure(UnknownFieldSet unknownFieldSet, ProtoBufferObject root) throws InvalidProtocolBufferException {
|
||||
for (var entry : unknownFieldSet.asMap().entrySet()) {
|
||||
var objectValue = entry.getValue();
|
||||
var type = "undefind";
|
||||
Object value = null;
|
||||
var index = entry.getKey();
|
||||
if (!objectValue.getLengthDelimitedList().isEmpty()) {
|
||||
var nestedObject = new ProtoBufferObject();
|
||||
for (var str : objectValue.getLengthDelimitedList()) {
|
||||
try {
|
||||
var nestedFieldsSet = UnknownFieldSet.parseFrom(str);
|
||||
createStructure(nestedFieldsSet, nestedObject);
|
||||
} catch (Exception e)
|
||||
{
|
||||
type = "string";
|
||||
value = str.toStringUtf8();
|
||||
}
|
||||
}
|
||||
if (value != null) {
|
||||
root.addField(index, "string", value);
|
||||
} else {
|
||||
root.addField(index, "object", nestedObject);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!objectValue.getFixed32List().isEmpty()) {
|
||||
type = "Fixed32List";
|
||||
value = objectValue.getFixed32List();
|
||||
}
|
||||
|
||||
if (!objectValue.getFixed64List().isEmpty()) {
|
||||
type = "Fixed64List";
|
||||
value = objectValue.getFixed64List();
|
||||
}
|
||||
|
||||
if (!objectValue.getGroupList().isEmpty()) {
|
||||
type = "getGroupList";
|
||||
value = objectValue.getGroupList();
|
||||
}
|
||||
|
||||
if (!objectValue.getVarintList().isEmpty()) {
|
||||
type = "int";
|
||||
value = objectValue.getVarintList().get(0);
|
||||
}
|
||||
|
||||
root.addField(index, type, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static WebcastResponse.Message fromBase64ToMessage(String base64) throws InvalidProtocolBufferException {
|
||||
var bytes = fromBase64(base64);
|
||||
return WebcastResponse.Message.parseFrom(bytes);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -22,11 +22,11 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.websocket;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
|
||||
public interface SocketClient {
|
||||
void start(WebcastResponse webcastResponse, LiveClient tikTokLiveClient);
|
||||
|
||||
void start(LiveConnectionData.Response webcastResponse, LiveClient tikTokLiveClient);
|
||||
void stop();
|
||||
}
|
||||
|
||||
@@ -64,8 +64,8 @@ message Text {
|
||||
string stringValue = 11;
|
||||
oneof textPieceType
|
||||
{
|
||||
TextPieceUser userValue = 21;
|
||||
TextPieceGift giftValue = 22;
|
||||
TextPieceUser userValue = 21;
|
||||
TextPieceGift giftValue = 22;
|
||||
}
|
||||
TextPiecePatternRef patternRefValue = 24;
|
||||
}
|
||||
@@ -155,7 +155,7 @@ message BadgeStruct {
|
||||
|
||||
message ProfileCardPanel {
|
||||
bool useNewProfileCardStyle = 1;
|
||||
// BadgeTextPosition badgeTextPosition = 2; // Enum
|
||||
// BadgeTextPosition badgeTextPosition = 2; // Enum
|
||||
ProjectionConfig projectionConfig = 3;
|
||||
ProfileContent profileContent = 4;
|
||||
}
|
||||
@@ -973,4 +973,567 @@ message FanTicketRoomNoticeContent {
|
||||
int64 MatchId = 3;
|
||||
int64 EventTime = 4;
|
||||
string FanTicketIconUrl = 5;
|
||||
}
|
||||
|
||||
message LinkerAcceptNoticeContent {
|
||||
int64 fromUserId = 1;
|
||||
int64 fromRoomId = 2;
|
||||
int64 toUserId = 3;
|
||||
}
|
||||
|
||||
message LinkerCancelContent {
|
||||
int64 fromUserId = 1;
|
||||
int64 toUserId = 2;
|
||||
int64 cancelType = 3;
|
||||
int64 actionId = 4;
|
||||
}
|
||||
|
||||
message ListUser {
|
||||
User user = 1;
|
||||
int64 linkmicId = 2;
|
||||
string linkmicIdStr = 3;
|
||||
int64 linkStatus = 4; // Enum
|
||||
LinkType linkType = 5; // Enum
|
||||
int32 userPosition = 6;
|
||||
int32 silenceStatus = 7; // Enum
|
||||
int64 modifyTime = 8;
|
||||
int64 linkerId = 9;
|
||||
int32 roleType = 10; // Enum
|
||||
|
||||
enum LinkType {
|
||||
LINK_UNKNOWN = 0;
|
||||
AUDIO = 1;
|
||||
VIDEO = 2;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//it is just empty
|
||||
message LinkerCloseContent {
|
||||
|
||||
}
|
||||
|
||||
message LinkerCreateContent {
|
||||
int64 ownerId = 1;
|
||||
int64 ownerRoomId = 2;
|
||||
int64 linkType = 3;
|
||||
}
|
||||
|
||||
|
||||
|
||||
message LinkerEnterContent {
|
||||
repeated ListUser linkedUsersList = 1;
|
||||
int32 anchorMultiLiveEnum = 2; // Enum
|
||||
LinkmicUserSettingInfo anchorSettingInfo = 3;;
|
||||
}
|
||||
|
||||
message LinkerInviteContent {
|
||||
int64 fromUserId = 1;
|
||||
int64 fromRoomId = 2;
|
||||
string toRtcExtInfo = 3;
|
||||
bool rtcJoinChannel = 4;
|
||||
int64 vendor = 5;
|
||||
string secFromUserId = 6;
|
||||
string toLinkmicIdStr = 7;
|
||||
User fromUser = 8;
|
||||
int64 requiredMicIdx = 9;
|
||||
}
|
||||
|
||||
message LinkerKickOutContent {
|
||||
int64 fromUserId = 1;
|
||||
KickoutReason kickoutReason = 2; // Enum
|
||||
}
|
||||
|
||||
message LinkerLeaveContent {
|
||||
int64 userId = 1;
|
||||
string linkmicIdStr = 2;
|
||||
int64 sendLeaveUid = 3;
|
||||
int64 leaveReason = 4;
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerLinkedListChangeContent {
|
||||
|
||||
}
|
||||
//Empty
|
||||
message CohostListChangeContent {
|
||||
}
|
||||
|
||||
|
||||
message LinkerListChangeContent {
|
||||
repeated ListUser linkedUsersList = 1;
|
||||
repeated ListUser appliedUsersList = 2;
|
||||
repeated ListUser connectingUsersList = 3;
|
||||
}
|
||||
|
||||
message LinkerMediaChangeContent {
|
||||
int64 op = 1; // Enum
|
||||
int64 toUserId = 2;
|
||||
int64 anchorId = 3;
|
||||
int64 roomId = 4;
|
||||
int64 changeScene = 5; // Enum
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerMicIdxUpdateContent {
|
||||
|
||||
}
|
||||
|
||||
|
||||
message LinkerMuteContent {
|
||||
int64 userId = 1;
|
||||
int64 status = 2; // Enum
|
||||
}
|
||||
|
||||
message LinkerRandomMatchContent {
|
||||
User user = 1;
|
||||
int64 roomId = 2;
|
||||
int64 inviteType = 3;
|
||||
string matchId = 4;
|
||||
int64 innerChannelId = 5;
|
||||
}
|
||||
|
||||
message LinkerReplyContent {
|
||||
int64 fromUserId = 1;
|
||||
int64 fromRoomId = 2;
|
||||
LinkmicInfo fromUserLinkmicInfo = 3;
|
||||
int64 toUserId = 4;
|
||||
LinkmicInfo toUserLinkmicInfo = 5;
|
||||
int64 linkType = 6;
|
||||
int64 replyStatus = 7;
|
||||
LinkerSetting linkerSetting = 8;
|
||||
User fromUser = 9;
|
||||
User toUser = 10;
|
||||
|
||||
message LinkmicInfo {
|
||||
string accessKey = 1;
|
||||
int64 linkMicId = 2;
|
||||
bool joinable = 3;
|
||||
int32 confluenceType = 4;
|
||||
string rtcExtInfo = 5;
|
||||
string rtcAppId = 6;
|
||||
string rtcAppSign = 7;
|
||||
string linkmicIdStr = 8;
|
||||
int64 vendor = 9;
|
||||
}
|
||||
}
|
||||
|
||||
message LinkerSetting {
|
||||
int64 MaxMemberLimit = 1;
|
||||
int64 LinkType = 2;
|
||||
int64 Scene = 3;
|
||||
int64 OwnerUserId = 4;
|
||||
int64 OwnerRoomId = 5;
|
||||
int64 Vendor = 6;
|
||||
}
|
||||
|
||||
message LinkerSysKickOutContent {
|
||||
int64 userId = 1;
|
||||
string linkmicIdStr = 2;
|
||||
}
|
||||
|
||||
message LinkmicUserToastContent {
|
||||
int64 userId = 1;
|
||||
int64 roomId = 2;
|
||||
Text displayText = 3;
|
||||
}
|
||||
|
||||
message LinkerUpdateUserContent {
|
||||
int64 fromUserId = 1;
|
||||
int64 toUserId = 2;
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerUpdateUserSettingContent {
|
||||
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerWaitingListChangeContent {
|
||||
|
||||
}
|
||||
|
||||
|
||||
message LinkmicUserSettingInfo {
|
||||
int64 userId = 1;
|
||||
int64 layout = 2; // @warning Enum not found, should be Layout
|
||||
int64 fixMicNum = 3; // @warning Enum not found, should be FixMicNum
|
||||
int64 allowRequestFromUser = 4; // @warning Enum not found, should be AllowRequestFromUser
|
||||
int64 allowRequestFromFollowerOnly = 5; // @warning Enum not found, should be AllowRequestFromFollowerOnly
|
||||
LinkmicApplierSortSetting applierSortSetting = 7; // Enum
|
||||
}
|
||||
|
||||
|
||||
message Player {
|
||||
int64 roomId = 1;
|
||||
int64 userId = 2;
|
||||
}
|
||||
|
||||
message AllListUser {
|
||||
repeated LinkLayerListUser linkedList = 2;
|
||||
repeated LinkLayerListUser appliedList = 3;
|
||||
repeated LinkLayerListUser invitedList = 4;
|
||||
repeated LinkLayerListUser readyList = 5;
|
||||
}
|
||||
|
||||
message LinkLayerListUser {
|
||||
User user = 1;
|
||||
int64 linkmicId = 2;
|
||||
Position pos = 3;
|
||||
int64 linkedTimeNano = 4;
|
||||
string appVersion = 5;
|
||||
int64 magicNumber1 = 7;
|
||||
}
|
||||
|
||||
message Position {
|
||||
int32 type = 1;
|
||||
LinkPosition link = 2;
|
||||
}
|
||||
|
||||
message LinkPosition {
|
||||
int32 position = 1;
|
||||
int32 opt = 2;
|
||||
}
|
||||
|
||||
message GroupPlayer {
|
||||
int64 channelId = 1;
|
||||
User user = 2;
|
||||
}
|
||||
|
||||
message DSLConfig {
|
||||
int32 sceneVersion = 1;
|
||||
string layoutId = 2;
|
||||
}
|
||||
|
||||
message GroupChannelAllUser {
|
||||
int64 groupChannelId = 1;
|
||||
repeated GroupChannelUser userList = 2;
|
||||
}
|
||||
|
||||
message GroupChannelUser {
|
||||
int64 channelId = 1;
|
||||
GroupStatus status = 2; // Enum
|
||||
TextType type = 3; // Enum
|
||||
AllListUser allUser = 4;
|
||||
int64 joinTime = 5;
|
||||
int64 linkedTime = 6;
|
||||
GroupPlayer ownerUser = 7;
|
||||
}
|
||||
|
||||
message RTCExtraInfo {
|
||||
RTCEngineConfig liveRtcEngineConfig = 1;
|
||||
repeated RTCLiveVideoParam liveRtcVideoParamList = 2;
|
||||
RTCBitrateMap rtcBitrateMap = 3;
|
||||
int32 rtcFps = 4;
|
||||
string rtcBusinessId = 8;
|
||||
int32 interactClientType = 10;
|
||||
|
||||
message RTCEngineConfig {
|
||||
string rtcAppId = 1;
|
||||
string rtcUserId = 2;
|
||||
string rtcToken = 3;
|
||||
int64 rtcChannelId = 4;
|
||||
}
|
||||
|
||||
message RTCLiveVideoParam {
|
||||
int32 strategyId = 1;
|
||||
RTCVideoParam params = 2;
|
||||
}
|
||||
|
||||
message RTCVideoParam {
|
||||
int32 width = 1;
|
||||
int32 height = 2;
|
||||
int32 fps = 3;
|
||||
int32 bitrateKbps = 4;
|
||||
}
|
||||
|
||||
message RTCBitrateMap {
|
||||
int32 xx1 = 1;
|
||||
int32 xx2 = 2;
|
||||
int32 xx3 = 3;
|
||||
int32 xx4 = 4;
|
||||
}
|
||||
}
|
||||
|
||||
message CreateChannelContent {
|
||||
Player owner = 1;
|
||||
string ownerLinkMicId = 2;
|
||||
}
|
||||
|
||||
message ListChangeContent {
|
||||
TextType type = 1; // Enum
|
||||
AllListUser list = 2;
|
||||
}
|
||||
|
||||
message MultiLiveContent {
|
||||
InviteBizContent inviteBizContent = 2;
|
||||
ReplyBizContent replyBizContent = 3;
|
||||
PermitBizContent permitBizContent = 4;
|
||||
KickOutBizContent kickOutBizContent = 6;
|
||||
|
||||
|
||||
message InviteBizContent {
|
||||
LinkmicUserSettingInfo anchorSettingInfo = 1;
|
||||
int64 inviteSource = 2; // @warning Enum not found, should be InviteSource
|
||||
User operatorUserInfo = 3;
|
||||
int64 operatorLinkAdminType = 4; // @warning Enum not found, should be OperatorLinkAdminType
|
||||
User inviteeUserInfo = 5;
|
||||
}
|
||||
|
||||
|
||||
message ReplyBizContent {
|
||||
int32 linkType = 1;
|
||||
int32 isTurnOffInvitation = 2;
|
||||
User replyUserInfo = 3;
|
||||
}
|
||||
|
||||
message PermitBizContent {
|
||||
LinkmicUserSettingInfo anchorSettingInfo = 1;
|
||||
int64 expireTimestamp = 2;
|
||||
User operatorUserInfo = 3;
|
||||
int64 operatorLinkAdminType = 4; // @warning Enum not found, should be OperatorLinkAdminType
|
||||
}
|
||||
|
||||
message KickOutBizContent {
|
||||
User operatorUserInfo = 1;
|
||||
int64 operatorLinkAdminType = 2; // @warning Enum not found, should be OperatorLinkAdminType
|
||||
User kickPlayerUserInfo = 3;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
message InviteContent {
|
||||
Player invitor = 1;
|
||||
RTCExtraInfo inviteeRtcExtInfo = 2;
|
||||
string invitorLinkMicId = 3;
|
||||
string inviteeLinkMicId = 4;
|
||||
bool isOwner = 5;
|
||||
Position pos = 6;
|
||||
DSLConfig dsl = 7;
|
||||
User invitee = 8;
|
||||
User operator = 9;
|
||||
}
|
||||
|
||||
|
||||
// @ApplyContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message ApplyContent {
|
||||
Player applier = 1;
|
||||
string applierLinkMicId = 2;
|
||||
}
|
||||
|
||||
|
||||
// @PermitApplyContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message PermitApplyContent {
|
||||
Player permiter = 1;
|
||||
string permiterLinkMicId = 2;
|
||||
Position applierPos = 3;
|
||||
ReplyStatus replyStatus = 4; // Enum
|
||||
DSLConfig dsl = 5;
|
||||
User applier = 6;
|
||||
User operator = 7;
|
||||
string applierLinkMicId = 8;
|
||||
}
|
||||
|
||||
|
||||
// @ReplyInviteContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message ReplyInviteContent {
|
||||
Player invitee = 1;
|
||||
ReplyStatus replyStatus = 2; // Enum
|
||||
string inviteeLinkMicId = 3;
|
||||
Position inviteePos = 4;
|
||||
Player inviteOperatorUser = 5;
|
||||
}
|
||||
|
||||
|
||||
// @KickOutContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message KickOutContent {
|
||||
Player offliner = 1;
|
||||
KickoutReason kickoutReason = 2; // Enum
|
||||
}
|
||||
|
||||
|
||||
// @CancelApplyContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message CancelApplyContent {
|
||||
Player applier = 1;
|
||||
string applierLinkMicId = 2;
|
||||
}
|
||||
|
||||
|
||||
// @CancelInviteContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message CancelInviteContent {
|
||||
Player invitor = 1;
|
||||
string invitorLinkMicId = 2;
|
||||
string inviteeLinkMicId = 3;
|
||||
int64 inviteSeqId = 4;
|
||||
Player invitee = 5;
|
||||
}
|
||||
|
||||
|
||||
// @LeaveContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message LeaveContent {
|
||||
Player leaver = 1;
|
||||
int64 leaveReason = 2;
|
||||
}
|
||||
|
||||
|
||||
// @FinishChannelContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message FinishChannelContent {
|
||||
Player owner = 1;
|
||||
int64 finishReason = 2;
|
||||
}
|
||||
|
||||
|
||||
// @JoinDirectContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message JoinDirectContent {
|
||||
LinkLayerListUser joiner = 1;
|
||||
AllListUser allUsers = 2;
|
||||
}
|
||||
|
||||
|
||||
// @LeaveJoinGroupContent
|
||||
// proto.webcast.im
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message LeaveJoinGroupContent {
|
||||
GroupPlayer operator = 1;
|
||||
int64 groupChannelId = 2;
|
||||
string leaveSource = 3;
|
||||
}
|
||||
|
||||
|
||||
// @PermitJoinGroupContent
|
||||
// proto.webcast.im
|
||||
message PermitJoinGroupContent {
|
||||
GroupPlayer approver = 1;
|
||||
AgreeStatus agreeStatus = 2; // Enum
|
||||
TextType type = 3; // Enum
|
||||
repeated RTCExtraInfo groupExtInfoList = 4;
|
||||
GroupChannelAllUser groupUser = 5;
|
||||
}
|
||||
|
||||
|
||||
// @CancelJoinGroupContent
|
||||
// proto.webcast.im
|
||||
message CancelJoinGroupContent {
|
||||
repeated GroupPlayer leaverList = 1;
|
||||
GroupPlayer operator = 2;
|
||||
TextType type = 3; // Enum
|
||||
}
|
||||
|
||||
|
||||
|
||||
message P2PGroupChangeContent {
|
||||
repeated RTCExtraInfo groupExtInfoList = 1;
|
||||
GroupChannelAllUser groupUser = 2;
|
||||
}
|
||||
|
||||
|
||||
message BusinessContent {
|
||||
int64 overLength = 1;
|
||||
MultiLiveContent multiLiveContent = 100;
|
||||
CohostContent cohostContent = 200;
|
||||
|
||||
message CohostContent {
|
||||
JoinGroupBizContent joinGroupBizContent = 1;
|
||||
|
||||
}
|
||||
|
||||
message JoinGroupBizContent {
|
||||
int32 fromRoomAgeRestricted = 1;
|
||||
Tag fromTag = 2;
|
||||
PerceptionDialogInfo dialog = 3;
|
||||
PunishEventInfo punishInfo = 4;
|
||||
JoinGroupMessageExtra joinGroupMsgExtra = 101;
|
||||
}
|
||||
|
||||
message Tag {
|
||||
int32 tagType = 1;
|
||||
string tagValue = 2;
|
||||
string tagText = 3;
|
||||
}
|
||||
|
||||
message PerceptionDialogInfo {
|
||||
int64 iconType = 1; // @warning Enum not found, should be IconType
|
||||
Text title = 2;
|
||||
Text subTitle = 3;
|
||||
Text adviceActionText = 4;
|
||||
Text defaultActionText = 5;
|
||||
string violationDetailUrl = 6;
|
||||
int32 scene = 7;
|
||||
int64 targetUserId = 8;
|
||||
int64 targetRoomId = 9;
|
||||
int64 countDownTime = 10;
|
||||
bool showFeedback = 11;
|
||||
repeated PerceptionFeedbackOption feedbackOptionsList = 12;
|
||||
int64 policyTip = 13;
|
||||
}
|
||||
|
||||
message PerceptionFeedbackOption {
|
||||
int64 id = 1;
|
||||
string contentKey = 2;
|
||||
}
|
||||
|
||||
message JoinGroupMessageExtra {
|
||||
int64 sourceType = 1;
|
||||
RivalExtra extra = 2;
|
||||
repeated RivalExtra otherUsersList = 3;
|
||||
|
||||
|
||||
// @RivalExtra
|
||||
// proto.webcast.im.JoinGroupMessageExtra
|
||||
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
|
||||
message RivalExtra {
|
||||
int64 userCount = 4;
|
||||
Image avatarThumb = 5;
|
||||
string displayId = 6;
|
||||
AuthenticationInfo authenticationInfo = 7;
|
||||
string nickname = 8;
|
||||
int64 followStatus = 9;
|
||||
Hashtag hashtag = 10;
|
||||
TopHostInfo topHostInfo = 11;
|
||||
int64 userId = 12;
|
||||
bool isBestTeammate = 13;
|
||||
|
||||
message AuthenticationInfo {
|
||||
string customVerify = 1;
|
||||
string enterpriseVerifyReason = 2;
|
||||
Image authenticationBadge = 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
message Hashtag {
|
||||
int64 id = 1;
|
||||
string title = 2;
|
||||
Image image = 3;
|
||||
HashtagNamespace namespace = 4; // Enum
|
||||
}
|
||||
|
||||
message TopHostInfo {
|
||||
string rankType = 1;
|
||||
int64 topIndex = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message JoinGroupContent {
|
||||
GroupChannelAllUser groupUser = 1;
|
||||
GroupPlayer joinUser = 2;
|
||||
TextType type = 3; // Enum
|
||||
}
|
||||
@@ -25,6 +25,85 @@ enum EmotePrivateType {
|
||||
EMOTE_PRIVATE_TYPE_SUB_WAVE = 1;
|
||||
}
|
||||
|
||||
enum TextType {
|
||||
DISPLAY_TEXT = 0;
|
||||
CONTENT = 1;
|
||||
}
|
||||
|
||||
enum LinkmicApplierSortSetting {
|
||||
LINKMIC_APPLIER_SORT_SETTING_NONE = 0;
|
||||
LINKMIC_APPLIER_SORT_SETTING_BY_GIFT_SCORE = 1;
|
||||
}
|
||||
|
||||
enum HashtagNamespace {
|
||||
GLOBAL = 0;
|
||||
GAMING = 1;
|
||||
}
|
||||
|
||||
enum AgreeStatus {
|
||||
AGREE_UNKNOWN = 0;
|
||||
AGREE = 1;
|
||||
REJECT = 2;
|
||||
}
|
||||
|
||||
enum KickoutReason {
|
||||
KICKOUT_REASON_UNKNOWN = 0;
|
||||
KICKOUT_REASON_FIRST_FRAME_TIMEOUT = 1;
|
||||
KICKOUT_REASON_BY_HOST = 2;
|
||||
KICKOUT_REASON_RTC_LOST_CONNECTION = 3;
|
||||
KICKOUT_REASON_BY_PUNISH = 4;
|
||||
KICKOUT_REASON_BY_ADMIN = 5;
|
||||
KICKOUT_REASON_HOST_REMOVE_ALL_GUESTS = 6;
|
||||
}
|
||||
|
||||
|
||||
enum GroupStatus {
|
||||
GROUP_STATUS_UNKNOWN = 0;
|
||||
GROUP_STATUS_WAITING = 1;
|
||||
GROUP_STATUS_LINKED = 3;
|
||||
}
|
||||
|
||||
enum BusinessCase {
|
||||
BUSINESS_NOT_SET = 0;
|
||||
APPLY_BIZ_CONTENT = 1;
|
||||
INVITE_BIZ_CONTENT = 2;
|
||||
REPLY_BIZ_CONTENT = 3;
|
||||
PERMIT_BIZ_CONTENT = 4;
|
||||
JOIN_DIRECT_BIZ_CONTENT = 5;
|
||||
KICK_OUT_BIZ_CONTENT = 6;
|
||||
LIST_CHANGE_BIZ_CONTENT = 11;
|
||||
MULTI_LIVE_CONTENT = 100;
|
||||
COHOST_CONTENT = 200;
|
||||
}
|
||||
|
||||
enum ReplyStatus {
|
||||
REPLY_STATUS_UNKNOWN = 0;
|
||||
REPLY_STATUS_AGREE = 1;
|
||||
REPLY_STATUS_REFUSE_PERSONALLY = 2;
|
||||
REPLY_STATUS_REFUSE_TYPE_NOT_SUPPORT = 3;
|
||||
REPLY_STATUS_REFUSE_PROCESSING_INVITATION = 4;
|
||||
REPLY_STATUS_REFUSE_BY_TIMEOUT = 5;
|
||||
REPLY_STATUS_REFUSE_EXCEPTION = 6;
|
||||
REPLY_STATUS_REFUSE_SYSTEM_NOT_SUPPORTED = 7;
|
||||
REPLY_STATUS_REFUSE_SUBTYPE_DIFFERENCE = 8;
|
||||
REPLY_STATUS_REFUSE_IN_MICROOM = 9;
|
||||
REPLY_STATUS_REFUSE_NOT_LOAD_PLUGIN = 10;
|
||||
REPLY_STATUS_REFUSE_IN_MULTI_GUEST = 11;
|
||||
REPLY_STATUS_REFUSE_PAUSE_LIVE = 12;
|
||||
REPLY_STATUS_REFUSE_OPEN_CAMERA_DIALOG_SHOWING = 13;
|
||||
REPLY_STATUS_REFUSE_DRAW_GUESSING = 14;
|
||||
REPLY_STATUS_REFUSE_RANDOM_MATCHING = 15;
|
||||
REPLY_STATUS_REFUSE_IN_MATCH_PROCESSING = 16;
|
||||
REPLY_STATUS_REFUSE_IN_MICROOM_FOR_MULTI_COHOST = 17;
|
||||
REPLY_STATUS_REFUSE_COHOST_FINISHED = 18;
|
||||
REPLY_STATUS_REFUSE_NOT_CONNECTED = 19;
|
||||
REPLY_STATUS_REFUSE_LINKMIC_FULL = 20;
|
||||
REPLY_STATUS_REFUSE_ARC_INCOMPATIBLE = 21;
|
||||
REPLY_STATUS_REFUSE_PROCESSING_OTHER_INVITE = 22;
|
||||
REPLY_STATUS_REFUSE_PROCESSING_OTHER_APPLY = 23;
|
||||
REPLY_STATUS_REFUSE_IN_ANCHOR_COHOST = 24;
|
||||
REPLY_STATUS_REFUSE_TOPIC_PAIRING = 25;
|
||||
}
|
||||
|
||||
enum SubscribeType {
|
||||
SUBSCRIBETYPE_ONCE = 0;
|
||||
@@ -68,6 +147,7 @@ enum MemberMessageAction {
|
||||
enum ControlAction {
|
||||
ControlActionUNKNOWN = 0;
|
||||
STREAM_PAUSED = 1; // Stream Paused by Host
|
||||
STREAM_UNPAUSED = 2;
|
||||
STREAM_ENDED = 3; // Stream Ended by Host
|
||||
}
|
||||
|
||||
@@ -135,4 +215,80 @@ enum EnvelopeDisplay
|
||||
EnvelopeDisplayUnknown = 0;
|
||||
EnvelopeDisplayNew = 1;
|
||||
EnvelopeDisplayHide = 2;
|
||||
}
|
||||
|
||||
|
||||
enum CommonContentCase {
|
||||
COMMON_CONTENT_NOT_SET = 0;
|
||||
CREATE_CHANNEL_CONTENT = 100;
|
||||
LIST_CHANGE_CONTENT = 102;
|
||||
INVITE_CONTENT = 103;
|
||||
APPLY_CONTENT = 104;
|
||||
PERMIT_APPLY_CONTENT = 105;
|
||||
REPLY_INVITE_CONTENT = 106;
|
||||
KICK_OUT_CONTENT = 107;
|
||||
CANCEL_APPLY_CONTENT = 108;
|
||||
CANCEL_INVITE_CONTENT = 109;
|
||||
LEAVE_CONTENT = 110;
|
||||
FINISH_CONTENT = 111;
|
||||
JOIN_DIRECT_CONTENT = 112;
|
||||
JOIN_GROUP_CONTENT = 113;
|
||||
PERMIT_GROUP_CONTENT = 114;
|
||||
CANCEL_GROUP_CONTENT = 115;
|
||||
LEAVE_GROUP_CONTENT = 116;
|
||||
P2P_GROUP_CHANGE_CONTENT = 117;
|
||||
GROUP_CHANGE_CONTENT = 118;
|
||||
}
|
||||
|
||||
|
||||
enum LinkMessageType {
|
||||
TPYE_LINKER_UNKNOWN = 0;
|
||||
TYPE_LINKER_CREATE = 1;
|
||||
TYPE_LINKER_CLOSE = 2;
|
||||
TYPE_LINKER_INVITE = 3;
|
||||
TYPE_LINKER_APPLY = 4;
|
||||
TYPE_LINKER_REPLY = 5;
|
||||
TPYE_LINKER_ENTER = 6;
|
||||
TPYE_LINKER_LEAVE = 7;
|
||||
TYPE_LINKER_PERMIT = 8;
|
||||
TPYE_LINKER_CANCEL_INVITE = 9;
|
||||
TYPE_LINKER_WAITING_LIST_CHANGE = 10;
|
||||
TYPE_LINKER_LINKED_LIST_CHANGE = 11;
|
||||
TYPE_LINKER_UPDATE_USER = 12;
|
||||
TPYE_LINKER_KICK_OUT = 13;
|
||||
TPYE_LINKER_CANCEL_APPLY = 14;
|
||||
TYPE_LINKER_MUTE = 15;
|
||||
TYPE_LINKER_MATCH = 16;
|
||||
TYPE_LINKER_UPDATE_USER_SETTING = 17;
|
||||
TYPE_LINKER_MIC_IDX_UPDATE = 18;
|
||||
TYPE_LINKER_LEAVE_V2 = 19;
|
||||
TYPE_LINKER_WAITING_LIST_CHANGE_V2 = 20;
|
||||
TYPE_LINKER_LINKED_LIST_CHANGE_V2 = 21;
|
||||
TYPE_LINKER_COHOST_LIST_CHANGE = 22;
|
||||
TYPE_LINKER_MEDIA_CHANGE = 23;
|
||||
TYPE_LINKER_ACCEPT_NOTICE = 24;
|
||||
TPYE_LINKER_SYS_KICK_OUT = 101;
|
||||
TPYE_LINKMIC_USER_TOAST = 102;
|
||||
}
|
||||
|
||||
enum MessageType {
|
||||
MESSAGETYPE_SUBSUCCESS = 0;
|
||||
MESSAGETYPE_ANCHORREMINDER = 1;
|
||||
MESSAGETYPE_ENTERROOMEXPIRESOON = 2;
|
||||
MESSAGETYPE_SUBGOALCREATETOANCHOR = 3;
|
||||
MESSAGETYPE_SUBGOALCOMPLETETOAUDIENCE = 4;
|
||||
MESSAGETYPE_SUBGOALCOMPLETETOANCHOR = 5;
|
||||
MESSAGETYPE_SUBGIFTTIKTOK2USERNOTICE = 6;
|
||||
MESSAGETYPE_SUBGIFTTIKTOK2ANCHORNOTICE = 7;
|
||||
MESSAGETYPE_SUBGIFTTRECEIVESENDNOTICE = 8;
|
||||
MESSAGETYPE_SUBGIFTSENDSUCCEEDROOMMESSAGE = 9;
|
||||
MESSAGETYPE_SUBGIFTSENDSUCCEEDANCHORNOTICE = 10;
|
||||
MESSAGETYPE_SUBGIFTLOWVERSIONUPGRADENOTICE = 11;
|
||||
MESSAGETYPE_SUBGIFTUSERBUYAUTHNOTICE = 12;
|
||||
}
|
||||
|
||||
enum Scene {
|
||||
SCENE_UNKNOWN = 0;
|
||||
SCENE_CO_HOST = 2;
|
||||
SCENE_MULTI_LIVE = 4;
|
||||
}
|
||||
@@ -18,17 +18,13 @@ message WebcastPushFrame {
|
||||
uint64 LogId = 2;
|
||||
uint64 Service = 3;
|
||||
uint64 Method = 4;
|
||||
map<string,string> headers = 5;
|
||||
map<string, string> headers = 5;
|
||||
string PayloadEncoding = 6;
|
||||
string PayloadType = 7;
|
||||
bytes Payload = 8;
|
||||
|
||||
}
|
||||
|
||||
message WebcastWebsocketAck {
|
||||
uint64 Id = 1;
|
||||
string Type = 2;
|
||||
}
|
||||
|
||||
|
||||
//@WebcastResponse
|
||||
@@ -81,6 +77,13 @@ message WebcastGiftMessage {
|
||||
bool isFirstSent = 25;
|
||||
string orderId = 28;
|
||||
UserIdentity userIdentity = 32;
|
||||
UserGiftReciever userGiftReciever = 23;
|
||||
|
||||
message UserGiftReciever
|
||||
{
|
||||
int64 userId = 1;
|
||||
string deviceName = 10;
|
||||
}
|
||||
|
||||
message GiftIMPriority {
|
||||
repeated int64 queueSizesList = 1;
|
||||
@@ -177,6 +180,8 @@ message WebcastCaptionMessage {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Comment sent by User
|
||||
//@WebcastChatMessage
|
||||
message WebcastChatMessage {
|
||||
@@ -195,7 +200,7 @@ message WebcastChatMessage {
|
||||
int32 quickChatScene = 16;
|
||||
int32 communityFlaggedStatus = 17;
|
||||
UserIdentity UserIdentity = 18;
|
||||
map<int32,string> CommentQualityScores = 19;
|
||||
map<int32, string> CommentQualityScores = 19;
|
||||
|
||||
// @EmoteWithIndex
|
||||
// proto.webcast.im.ChatMessage
|
||||
@@ -275,14 +280,14 @@ message WebcastGoalUpdateMessage {
|
||||
int64 contributorId = 4;
|
||||
Image contributorAvatar = 5;
|
||||
string contributorDisplayId = 6;
|
||||
// SubGoal contributeSubgoal = 7;
|
||||
// SubGoal contributeSubgoal = 7;
|
||||
int64 contributeCount = 9;
|
||||
int64 contributeScore = 10;
|
||||
int64 giftRepeatCount = 11;
|
||||
string contributorIdStr = 12;
|
||||
bool pin = 13;
|
||||
bool unpin = 14;
|
||||
// GoalPinInfo pinInfo = 15;
|
||||
// GoalPinInfo pinInfo = 15;
|
||||
}
|
||||
|
||||
// Message related to Chat-moderation?
|
||||
@@ -346,7 +351,7 @@ message WebcastSocialMessage {
|
||||
message WebcastSubNotifyMessage {
|
||||
Common common = 1;
|
||||
User user = 2;
|
||||
// ExhibitionType exhibitionType = 3; // Enum
|
||||
// ExhibitionType exhibitionType = 3; // Enum
|
||||
int64 subMonth = 4;
|
||||
SubscribeType subscribeType = 5; // Enum
|
||||
OldSubscribeStatus oldSubscribeStatus = 6; // Enum
|
||||
@@ -440,7 +445,7 @@ message WebcastMemberMessage {
|
||||
//@WebcastPollMessage
|
||||
message WebcastPollMessage {
|
||||
Common common = 1;
|
||||
int32 messageType = 2;
|
||||
MessageType messageType = 2;
|
||||
int64 pollId = 3;
|
||||
PollStartContent startContent = 4;
|
||||
PollEndContent endContent = 5;
|
||||
@@ -505,6 +510,9 @@ message WebcastHourlyRankMessage {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//<Battles>
|
||||
|
||||
//@WebcastLinkMicArmies
|
||||
message WebcastLinkMicArmies {
|
||||
Common common = 1;
|
||||
@@ -521,6 +529,45 @@ message WebcastLinkMicArmies {
|
||||
uint32 data4 = 12;
|
||||
uint32 data5 = 13;
|
||||
}
|
||||
//@WebcastLinkMicBattlePunishFinish
|
||||
message WebcastLinkMicBattlePunishFinish {
|
||||
Common Header = 1;
|
||||
uint64 Id1 = 2;
|
||||
uint64 Timestamp = 3;
|
||||
uint32 Data4 = 4;
|
||||
uint64 Id2 = 5;
|
||||
LinkMicBattlePunishFinishData Data6 = 6;
|
||||
|
||||
message LinkMicBattlePunishFinishData {
|
||||
uint64 Id2 = 1; // Same as Id2 in outer object (loser?)
|
||||
uint64 Timestamp = 2;
|
||||
uint32 Data3 = 3;
|
||||
uint64 Id1 = 4; // Same as Id1 in outer object (winner?)
|
||||
uint32 Data5 = 5;
|
||||
uint32 Data6 = 6;
|
||||
uint32 Data8 = 8;
|
||||
}
|
||||
}
|
||||
|
||||
//@WebcastLinkmicBattleTaskMessage
|
||||
message WebcastLinkmicBattleTaskMessage {
|
||||
Common Header = 1;
|
||||
uint32 Data2 = 2;
|
||||
LinkmicBattleTaskData Data3 = 3;
|
||||
LinkmicBattleTaskData2 Data5 = 5;
|
||||
|
||||
message LinkmicBattleTaskData {
|
||||
BattleTaskData Data1 = 1;
|
||||
}
|
||||
message BattleTaskData {
|
||||
uint32 Data1 = 1;
|
||||
}
|
||||
|
||||
message LinkmicBattleTaskData2 {
|
||||
uint32 Data1 = 1;
|
||||
uint32 Data2 = 2;
|
||||
}
|
||||
}
|
||||
|
||||
//@WebcastLinkMicBattle
|
||||
message WebcastLinkMicBattle {
|
||||
@@ -570,11 +617,10 @@ message WebcastLinkMicFanTicketMethod {
|
||||
Common common = 1;
|
||||
FanTicketRoomNoticeContent FanTicketRoomNotice = 2;
|
||||
}
|
||||
|
||||
//@WebcastLinkMicMethod
|
||||
message WebcastLinkMicMethod {
|
||||
Common common = 1;
|
||||
int64 messageType = 2;
|
||||
MessageType messageType = 2;
|
||||
string accessKey = 3;
|
||||
int64 anchorLinkmicId = 4;
|
||||
int64 userId = 5;
|
||||
@@ -588,6 +634,8 @@ message WebcastLinkMicMethod {
|
||||
int64 inviteUid = 13;
|
||||
}
|
||||
|
||||
//<Battles>
|
||||
|
||||
//@WebcastLiveIntroMessage
|
||||
message WebcastLiveIntroMessage {
|
||||
Common common = 1;
|
||||
@@ -630,7 +678,7 @@ message WebcastMsgDetectMessage {
|
||||
bool detectP2PMsg = 3;
|
||||
bool detectRoomMsg = 4;
|
||||
bool httpOptimize = 5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//@WebcastOecLiveShoppingMessage
|
||||
@@ -681,39 +729,63 @@ message WebcastSystemMessage {
|
||||
//@WebcastLinkMessage
|
||||
message WebcastLinkMessage {
|
||||
Common common = 1;
|
||||
uint32 data1 = 2;
|
||||
uint64 data2 = 3;
|
||||
uint32 data3 = 4;
|
||||
LinkMessageData data = 18;
|
||||
LinkMessageUserContainer user = 20;
|
||||
string token = 200;
|
||||
|
||||
message LinkMessageData {
|
||||
DataContainer data = 1; // index 1 is an Id
|
||||
}
|
||||
|
||||
message LinkMessageUserContainer {
|
||||
LinkMessageUser user = 1;
|
||||
repeated LinkMessageUser otherUsers = 2;
|
||||
|
||||
message LinkMessageUser {
|
||||
User user = 1;
|
||||
uint64 timeStamp = 2;
|
||||
uint32 data1 = 4;
|
||||
string idString = 5;
|
||||
uint32 data2 = 7;
|
||||
}
|
||||
}
|
||||
LinkMessageType MessageType = 2;
|
||||
int64 LinkerId = 3;
|
||||
Scene Scene = 4;
|
||||
LinkerInviteContent InviteContent = 5;
|
||||
LinkerReplyContent ReplyContent = 6;
|
||||
LinkerCreateContent CreateContent = 7;
|
||||
LinkerCloseContent CloseContent = 8;
|
||||
LinkerEnterContent EnterContent = 9;
|
||||
LinkerLeaveContent LeaveContent = 10;
|
||||
LinkerCancelContent CancelContent = 11;
|
||||
LinkerKickOutContent KickOutContent = 12;
|
||||
LinkerLinkedListChangeContent LinkedListChangeContent = 13;
|
||||
LinkerUpdateUserContent UpdateUserContent = 14;
|
||||
LinkerWaitingListChangeContent WaitingListChangeContent = 15;
|
||||
LinkerMuteContent MuteContent = 16;
|
||||
LinkerRandomMatchContent RandomMatchContent = 17;
|
||||
LinkerUpdateUserSettingContent UpdateUserSettingContent = 18;
|
||||
LinkerMicIdxUpdateContent MicIdxUpdateContent = 19;
|
||||
LinkerListChangeContent ListChangeContent = 20;
|
||||
CohostListChangeContent CohostListChangeContent = 21;
|
||||
LinkerMediaChangeContent MediaChangeContent = 22;
|
||||
LinkerAcceptNoticeContent ReplyAcceptNoticeContent = 23;
|
||||
LinkerSysKickOutContent SysKickOutContent = 101;
|
||||
LinkmicUserToastContent UserToastContent = 102;
|
||||
string extra = 200;
|
||||
int64 expireTimestamp = 201;
|
||||
string transferExtra = 202;
|
||||
}
|
||||
|
||||
//@WebcastLinkLayerMessage
|
||||
|
||||
// @WebcastLinkLayerMessage
|
||||
message WebcastLinkLayerMessage {
|
||||
Common common = 1;
|
||||
LinkLayerMessageType messageType = 2;
|
||||
MessageType messageType = 2; // Enum
|
||||
int64 channelId = 3;
|
||||
Scene scene = 4; // Enum
|
||||
CreateChannelContent createChannelContent = 100;
|
||||
ListChangeContent listChangeContent = 102;
|
||||
InviteContent inviteContent = 103;
|
||||
ApplyContent applyContent = 104;
|
||||
PermitApplyContent permitApplyContent = 105;
|
||||
ReplyInviteContent replyInviteContent = 106;
|
||||
KickOutContent kickOutContent = 107;
|
||||
CancelApplyContent cancelApplyContent = 108;
|
||||
CancelInviteContent cancelInviteContent = 109;
|
||||
LeaveContent leaveContent = 110;
|
||||
FinishChannelContent finishContent = 111;
|
||||
JoinDirectContent joinDirectContent = 112;
|
||||
JoinGroupContent joinGroupContent = 113;
|
||||
PermitJoinGroupContent permitGroupContent = 114;
|
||||
CancelJoinGroupContent cancelGroupContent = 115;
|
||||
LeaveJoinGroupContent leaveGroupContent = 116;
|
||||
P2PGroupChangeContent p2pGroupChangeContent = 117;
|
||||
BusinessContent businessContent = 200;
|
||||
}
|
||||
|
||||
|
||||
// @RoomVerifyMessage
|
||||
message RoomVerifyMessage {
|
||||
Common common = 1;
|
||||
int32 action = 2;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<artifactId>TikTokLiveJava</artifactId>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<version>1.0.2-Release</version>
|
||||
<version>1.4.0-Release</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<dependency>
|
||||
<groupId>org.java-websocket</groupId>
|
||||
<artifactId>Java-WebSocket</artifactId>
|
||||
<version>1.5.4</version>
|
||||
<version>1.5.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
|
||||
@@ -23,68 +23,91 @@
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokDataChecker;
|
||||
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftsManager;
|
||||
import io.github.jwdeveloper.tiktok.http.LiveHttpClient;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftsManager;
|
||||
import io.github.jwdeveloper.tiktok.live.builder.LiveClientBuilder;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class TikTokLive
|
||||
{
|
||||
public class TikTokLive {
|
||||
|
||||
/**
|
||||
* Example: https://www.tiktok.com/@dostawcavideo - hostName would be 'dostawcavideo'
|
||||
*
|
||||
* @param hostName profile name of Tiktok user could be found in profile link
|
||||
* example: https://www.tiktok.com/@dostawcavideo hostName would be dostawcavideo
|
||||
* @return LiveClientBuilder
|
||||
*/
|
||||
public static LiveClientBuilder newClient(String hostName)
|
||||
{
|
||||
public static LiveClientBuilder newClient(String hostName) {
|
||||
return new TikTokLiveClientBuilder(hostName);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Example: https://www.tiktok.com/@dostawcavideo - hostName would be 'dostawcavideo'
|
||||
*
|
||||
* @param hostName profile name of Tiktok user could be found in profile link
|
||||
* example: https://www.tiktok.com/@dostawcavideo hostName would be dostawcavideo
|
||||
* @return true if live is Online, false if is offline
|
||||
*/
|
||||
public static boolean isLiveOnline(String hostName)
|
||||
{
|
||||
return new TikTokDataChecker().isOnline(hostName);
|
||||
public static boolean isLiveOnline(String hostName) {
|
||||
return requests().fetchLiveUserData(hostName).isLiveOnline();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Example: https://www.tiktok.com/@dostawcavideo - hostName would be 'dostawcavideo'
|
||||
*
|
||||
* @param hostName profile name of Tiktok user could be found in profile link
|
||||
* example: https://www.tiktok.com/@dostawcavideo hostName would be dostawcavideo
|
||||
* @return true if live is Online, false if is offline
|
||||
*/
|
||||
public static CompletableFuture<Boolean> isLiveOnlineAsync(String hostName)
|
||||
{
|
||||
return new TikTokDataChecker().isOnlineAsync(hostName);
|
||||
public static CompletableFuture<Boolean> isLiveOnlineAsync(String hostName) {
|
||||
return CompletableFuture.supplyAsync(() -> isLiveOnline(hostName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: https://www.tiktok.com/@dostawcavideo - hostName would be 'dostawcavideo'
|
||||
*
|
||||
* @param hostName profile name of Tiktok user could be found in profile link
|
||||
* example: https://www.tiktok.com/@dostawcavideo hostName would be dostawcavideo
|
||||
* @return true is hostName name is valid and exists, false if not
|
||||
*/
|
||||
public static boolean isHostNameValid(String hostName)
|
||||
{
|
||||
return new TikTokDataChecker().isHostNameValid(hostName);
|
||||
public static boolean isHostNameValid(String hostName) {
|
||||
return requests().fetchLiveUserData(hostName).isHostNameValid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: https://www.tiktok.com/@dostawcavideo - hostName would be 'dostawcavideo'
|
||||
*
|
||||
* @param hostName profile name of Tiktok user could be found in profile link
|
||||
* example: https://www.tiktok.com/@dostawcavideo hostName would be dostawcavideo
|
||||
* @return true is hostName name is valid and exists, false if not
|
||||
*/
|
||||
public static CompletableFuture<Boolean> isHostNameValidAsync(String hostName)
|
||||
{
|
||||
return new TikTokDataChecker().isHostNameValidAsync(hostName);
|
||||
public static CompletableFuture<Boolean> isHostNameValidAsync(String hostName) {
|
||||
return CompletableFuture.supplyAsync(() -> isHostNameValid(hostName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use to get some data from TikTok about users are lives
|
||||
*
|
||||
* @return LiveHttpClient
|
||||
*/
|
||||
public static LiveHttpClient requests() {
|
||||
return new TikTokLiveHttpClient();
|
||||
}
|
||||
|
||||
|
||||
//I don't like it, but it is reasonable for now
|
||||
private static GiftsManager giftsManager;
|
||||
|
||||
/**
|
||||
* Fetch gifts from endpoint and returns GiftManager
|
||||
*
|
||||
* @return GiftsManager
|
||||
*/
|
||||
public static GiftsManager gifts() {
|
||||
if (giftsManager == null) {
|
||||
synchronized (GiftsManager.class) {
|
||||
giftsManager = new TikTokGiftsManager(requests().fetchGiftsData().getGifts());
|
||||
}
|
||||
}
|
||||
return giftsManager;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -22,48 +22,59 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokDisconnectedEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokErrorEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokReconnectingEvent;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveOfflineHostException;
|
||||
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftManager;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokApiService;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.control.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.http.TikTokRoomDataResponseEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomInfoEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.*;
|
||||
import io.github.jwdeveloper.tiktok.http.LiveHttpClient;
|
||||
import io.github.jwdeveloper.tiktok.listener.ListenersManager;
|
||||
import io.github.jwdeveloper.tiktok.listener.TikTokListenersManager;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftsManager;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import io.github.jwdeveloper.tiktok.models.ConnectionState;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.websocket.SocketClient;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TikTokLiveClient implements LiveClient {
|
||||
private final TikTokRoomInfo liveRoomInfo;
|
||||
private final TikTokGiftManager tikTokGiftManager;
|
||||
private final TikTokApiService apiService;
|
||||
private final LiveHttpClient httpClient;
|
||||
private final SocketClient webSocketClient;
|
||||
private final TikTokEventObserver tikTokEventHandler;
|
||||
private final ClientSettings clientSettings;
|
||||
private final TikTokLiveEventHandler tikTokEventHandler;
|
||||
private final LiveClientSettings clientSettings;
|
||||
private final TikTokListenersManager listenersManager;
|
||||
private final Logger logger;
|
||||
private final GiftsManager giftsManager;
|
||||
private final TikTokLiveMessageHandler messageHandler;
|
||||
|
||||
public TikTokLiveClient(TikTokRoomInfo tikTokLiveMeta,
|
||||
TikTokApiService tikTokApiService,
|
||||
SocketClient webSocketClient,
|
||||
TikTokGiftManager tikTokGiftManager,
|
||||
TikTokEventObserver tikTokEventHandler,
|
||||
ClientSettings clientSettings,
|
||||
TikTokListenersManager listenersManager,
|
||||
Logger logger) {
|
||||
public TikTokLiveClient(
|
||||
TikTokLiveMessageHandler messageHandler,
|
||||
GiftsManager giftsManager,
|
||||
TikTokRoomInfo tikTokLiveMeta,
|
||||
LiveHttpClient tiktokHttpClient,
|
||||
SocketClient webSocketClient,
|
||||
TikTokLiveEventHandler tikTokEventHandler,
|
||||
LiveClientSettings clientSettings,
|
||||
TikTokListenersManager listenersManager,
|
||||
Logger logger) {
|
||||
this.messageHandler = messageHandler;
|
||||
this.giftsManager = giftsManager;
|
||||
this.liveRoomInfo = tikTokLiveMeta;
|
||||
this.tikTokGiftManager = tikTokGiftManager;
|
||||
this.apiService = tikTokApiService;
|
||||
this.httpClient = tiktokHttpClient;
|
||||
this.webSocketClient = webSocketClient;
|
||||
this.tikTokEventHandler = tikTokEventHandler;
|
||||
this.clientSettings = clientSettings;
|
||||
@@ -73,17 +84,15 @@ public class TikTokLiveClient implements LiveClient {
|
||||
|
||||
|
||||
public void connectAsync(Consumer<LiveClient> onConnection) {
|
||||
CompletableFuture.supplyAsync(() ->
|
||||
{
|
||||
CompletableFuture.runAsync(() -> {
|
||||
connect();
|
||||
onConnection.accept(this);
|
||||
return this;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public CompletableFuture<LiveClient> connectAsync() {
|
||||
return CompletableFuture.supplyAsync(() ->
|
||||
{
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
connect();
|
||||
return this;
|
||||
});
|
||||
@@ -92,8 +101,7 @@ public class TikTokLiveClient implements LiveClient {
|
||||
public void connect() {
|
||||
try {
|
||||
tryConnect();
|
||||
} catch (TikTokLiveException e)
|
||||
{
|
||||
} catch (TikTokLiveException e) {
|
||||
setState(ConnectionState.DISCONNECTED);
|
||||
tikTokEventHandler.publish(this, new TikTokErrorEvent(e));
|
||||
tikTokEventHandler.publish(this, new TikTokDisconnectedEvent());
|
||||
@@ -108,46 +116,99 @@ public class TikTokLiveClient implements LiveClient {
|
||||
this.connect();
|
||||
}
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.info("Unhandled exception report this bug to github https://github.com/jwdeveloper/TikTokLiveJava/issues");
|
||||
this.disconnect();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (!liveRoomInfo.hasConnectionState(ConnectionState.CONNECTED)) {
|
||||
return;
|
||||
}
|
||||
webSocketClient.stop();
|
||||
setState(ConnectionState.DISCONNECTED);
|
||||
}
|
||||
|
||||
public void tryConnect() {
|
||||
if (liveRoomInfo.hasConnectionState(ConnectionState.CONNECTED))
|
||||
if (!liveRoomInfo.hasConnectionState(ConnectionState.DISCONNECTED)) {
|
||||
throw new TikTokLiveException("Already connected");
|
||||
if (liveRoomInfo.hasConnectionState(ConnectionState.CONNECTING))
|
||||
throw new TikTokLiveException("Already connecting");
|
||||
}
|
||||
|
||||
setState(ConnectionState.CONNECTING);
|
||||
tikTokEventHandler.publish(this, new TikTokConnectingEvent());
|
||||
var userDataRequest = new LiveUserData.Request(liveRoomInfo.getHostName());
|
||||
var userData = httpClient.fetchLiveUserData(userDataRequest);
|
||||
liveRoomInfo.setStartTime(userData.getStartedAtTimeStamp());
|
||||
liveRoomInfo.setRoomId(userData.getRoomId());
|
||||
|
||||
apiService.updateSessionId();
|
||||
if (userData.getUserStatus() == LiveUserData.UserStatus.Offline)
|
||||
throw new TikTokLiveOfflineHostException("User is offline: " + liveRoomInfo.getHostName());
|
||||
|
||||
if (clientSettings.getRoomId() != null) {
|
||||
liveRoomInfo.setRoomId(clientSettings.getRoomId());
|
||||
logger.info("Using roomID from settings: " + clientSettings.getRoomId());
|
||||
} else {
|
||||
var roomId = apiService.fetchRoomId(liveRoomInfo.getHostName());
|
||||
liveRoomInfo.setRoomId(roomId);
|
||||
}
|
||||
if (userData.getUserStatus() == LiveUserData.UserStatus.NotFound)
|
||||
throw new TikTokLiveOfflineHostException("User not found: " + liveRoomInfo.getHostName());
|
||||
|
||||
var liveDataRequest = new LiveData.Request(userData.getRoomId());
|
||||
var liveData = httpClient.fetchLiveData(liveDataRequest);
|
||||
|
||||
var roomData = apiService.fetchRoomInfo();
|
||||
if (roomData.getStatus() != LiveRoomMeta.LiveRoomStatus.HostOnline) {
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for Host name could not be found. Is the Host online?");
|
||||
}
|
||||
if (liveData.isAgeRestricted())
|
||||
throw new TikTokLiveException("Livestream for " + liveRoomInfo.getHostName() + " is 18+ or age restricted!");
|
||||
|
||||
if (liveData.getLiveStatus() == LiveData.LiveStatus.HostNotFound)
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for " + liveRoomInfo.getHostName() + " could not be found.");
|
||||
|
||||
if (liveData.getLiveStatus() == LiveData.LiveStatus.HostOffline)
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for " + liveRoomInfo.getHostName() + " not found, is the Host offline?");
|
||||
|
||||
tikTokEventHandler.publish(this, new TikTokRoomDataResponseEvent(liveData));
|
||||
|
||||
liveRoomInfo.setTitle(liveData.getTitle());
|
||||
liveRoomInfo.setViewersCount(liveData.getViewers());
|
||||
liveRoomInfo.setTotalViewersCount(liveData.getTotalViewers());
|
||||
liveRoomInfo.setAgeRestricted(liveData.isAgeRestricted());
|
||||
liveRoomInfo.setHost(liveData.getHost());
|
||||
|
||||
var preconnectEvent = new TikTokPreConnectionEvent(userData, liveData);
|
||||
tikTokEventHandler.publish(this, preconnectEvent);
|
||||
if (preconnectEvent.isCancelConnection())
|
||||
throw new TikTokLiveException("TikTokPreConnectionEvent cancelled connection!");
|
||||
|
||||
var liveConnectionRequest = new LiveConnectionData.Request(userData.getRoomId());
|
||||
var liveConnectionData = httpClient.fetchLiveConnectionData(liveConnectionRequest);
|
||||
webSocketClient.start(liveConnectionData, this);
|
||||
|
||||
var clientData = apiService.fetchClientData();
|
||||
webSocketClient.start(clientData, this);
|
||||
setState(ConnectionState.CONNECTED);
|
||||
tikTokEventHandler.publish(this, new TikTokRoomInfoEvent(liveRoomInfo));
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (liveRoomInfo.hasConnectionState(ConnectionState.DISCONNECTED)) {
|
||||
return;
|
||||
}
|
||||
setState(ConnectionState.DISCONNECTED);
|
||||
webSocketClient.stop();
|
||||
}
|
||||
|
||||
private void setState(ConnectionState connectionState) {
|
||||
logger.info("TikTokLive client state: " + connectionState.name());
|
||||
liveRoomInfo.setConnectionState(connectionState);
|
||||
}
|
||||
|
||||
public void publishEvent(TikTokEvent event) {
|
||||
tikTokEventHandler.publish(this, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishMessage(String webcastMessageName, String payloadBase64) {
|
||||
this.publishMessage(webcastMessageName, Base64.getDecoder().decode(payloadBase64));
|
||||
}
|
||||
@Override
|
||||
public void publishMessage(String webcastMessageName, byte[] payload) {
|
||||
|
||||
var builder = WebcastResponse.Message.newBuilder();
|
||||
builder.setMethod(webcastMessageName);
|
||||
builder.setPayload(ByteString.copyFrom(payload));
|
||||
var message = builder.build();
|
||||
messageHandler.handleSingleMessage(this, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GiftsManager getGiftManager() {
|
||||
return giftsManager;
|
||||
}
|
||||
|
||||
public LiveRoomInfo getRoomInfo() {
|
||||
return liveRoomInfo;
|
||||
@@ -162,16 +223,4 @@ public class TikTokLiveClient implements LiveClient {
|
||||
public Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GiftManager getGiftManager() {
|
||||
return tikTokGiftManager;
|
||||
}
|
||||
|
||||
|
||||
private void setState(ConnectionState connectionState) {
|
||||
logger.info("TikTokLive client state: " + connectionState.name());
|
||||
liveRoomInfo.setConnectionState(connectionState);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -22,121 +22,89 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.common.LoggerFactory;
|
||||
import io.github.jwdeveloper.tiktok.data.events.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.control.TikTokPreConnectionEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.envelop.TikTokChestEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftComboEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.http.TikTokHttpResponseEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomPinEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomUserInfoEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokShareEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketMessageEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketResponseEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketUnhandledMessageEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.*;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftManager;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandlerRegistration;
|
||||
import io.github.jwdeveloper.tiktok.handlers.events.TikTokGiftEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokApiService;
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokCookieJar;
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokHttpClient;
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokHttpRequestFactory;
|
||||
import io.github.jwdeveloper.tiktok.listener.TikTokEventListener;
|
||||
import io.github.jwdeveloper.tiktok.listener.TikTokListenersManager;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.live.builder.EventConsumer;
|
||||
import io.github.jwdeveloper.tiktok.live.builder.LiveClientBuilder;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokGenericEventMapper;
|
||||
import io.github.jwdeveloper.tiktok.utils.ConsoleColors;
|
||||
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftsManager;
|
||||
import io.github.jwdeveloper.tiktok.http.HttpClientFactory;
|
||||
import io.github.jwdeveloper.tiktok.listener.*;
|
||||
import io.github.jwdeveloper.tiktok.live.*;
|
||||
import io.github.jwdeveloper.tiktok.live.builder.*;
|
||||
import io.github.jwdeveloper.tiktok.mappers.*;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
|
||||
import io.github.jwdeveloper.tiktok.mappers.handlers.*;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.*;
|
||||
import io.github.jwdeveloper.tiktok.websocket.TikTokWebSocketClient;
|
||||
import io.github.jwdeveloper.tiktok.websocket.TikTokWebSocketOfflineClient;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.logging.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
|
||||
protected final ClientSettings clientSettings;
|
||||
protected final Logger logger;
|
||||
protected final TikTokEventObserver tikTokEventHandler;
|
||||
protected final LiveClientSettings clientSettings;
|
||||
protected final TikTokLiveEventHandler eventHandler;
|
||||
protected final List<TikTokEventListener> listeners;
|
||||
protected Consumer<TikTokMapper> onCustomMappings;
|
||||
protected Logger logger;
|
||||
protected GiftsManager giftsManager;
|
||||
|
||||
public TikTokLiveClientBuilder(String userName) {
|
||||
this.tikTokEventHandler = new TikTokEventObserver();
|
||||
this.clientSettings = Constants.DefaultClientSettings();
|
||||
this.clientSettings = LiveClientSettings.createDefault();
|
||||
this.clientSettings.setHostName(userName);
|
||||
this.logger = Logger.getLogger(TikTokLive.class.getSimpleName() + " " + userName);
|
||||
this.eventHandler = new TikTokLiveEventHandler();
|
||||
this.listeners = new ArrayList<>();
|
||||
this.onCustomMappings = (e) -> {
|
||||
};
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder configure(Consumer<ClientSettings> consumer) {
|
||||
consumer.accept(clientSettings);
|
||||
public LiveClientBuilder onMapping(Consumer<TikTokMapper> onCustomMappings) {
|
||||
this.onCustomMappings = onCustomMappings;
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder configure(Consumer<LiveClientSettings> onConfigure) {
|
||||
onConfigure.accept(clientSettings);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder addListener(TikTokEventListener listener) {
|
||||
listeners.add(listener);
|
||||
if (listener != null)
|
||||
listeners.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
protected void validate() {
|
||||
if (clientSettings.getClientLanguage() == null || clientSettings.getClientLanguage().isEmpty())
|
||||
clientSettings.setClientLanguage("en");
|
||||
|
||||
if (clientSettings.getTimeout() == null) {
|
||||
clientSettings.setTimeout(Duration.ofSeconds(Constants.DEFAULT_TIMEOUT));
|
||||
}
|
||||
|
||||
if (clientSettings.getClientLanguage() == null || clientSettings.getClientLanguage().equals("")) {
|
||||
clientSettings.setClientLanguage(Constants.DefaultClientSettings().getClientLanguage());
|
||||
}
|
||||
|
||||
|
||||
if (clientSettings.getHostName() == null || clientSettings.getHostName().equals("")) {
|
||||
if (clientSettings.getHostName() == null || clientSettings.getHostName().isEmpty())
|
||||
throw new TikTokLiveException("HostName can not be null");
|
||||
}
|
||||
|
||||
if (clientSettings.getHostName().startsWith("@"))
|
||||
{
|
||||
clientSettings.setHostName(clientSettings.getHostName().substring(1));
|
||||
}
|
||||
|
||||
|
||||
var params = clientSettings.getClientParameters();
|
||||
params.put("app_language", clientSettings.getClientLanguage());
|
||||
params.put("webcast_language", clientSettings.getClientLanguage());
|
||||
|
||||
|
||||
var handler = new ConsoleHandler();
|
||||
handler.setFormatter(new Formatter() {
|
||||
@Override
|
||||
public String format(LogRecord record) {
|
||||
var sb = new StringBuilder();
|
||||
sb.append(ConsoleColors.GREEN).append("[").append(record.getLoggerName()).append("] ");
|
||||
sb.append(ConsoleColors.GREEN).append("[").append(record.getLevel()).append("]: ");
|
||||
sb.append(ConsoleColors.WHITE_BRIGHT).append(record.getMessage());
|
||||
sb.append(ConsoleColors.RESET).append("\n");
|
||||
return sb.toString();
|
||||
}
|
||||
});
|
||||
logger.setUseParentHandlers(false);
|
||||
logger.addHandler(handler);
|
||||
|
||||
logger.setLevel(clientSettings.getLogLevel());
|
||||
|
||||
if (clientSettings.isPrintToConsole() && clientSettings.getLogLevel() == Level.OFF) {
|
||||
logger.setLevel(Level.ALL);
|
||||
}
|
||||
|
||||
if (clientSettings.getPingInterval() < 250)
|
||||
throw new TikTokLiveException("Minimum allowed ping interval is 250 millseconds");
|
||||
|
||||
var httpSettings = clientSettings.getHttpSettings();
|
||||
httpSettings.getParams().put("app_language", clientSettings.getClientLanguage());
|
||||
httpSettings.getParams().put("webcast_language", clientSettings.getClientLanguage());
|
||||
|
||||
this.logger = LoggerFactory.create(clientSettings.getHostName(), clientSettings);
|
||||
this.giftsManager = clientSettings.isFetchGifts() ? TikTokLive.gifts() : new TikTokGiftsManager(List.of());
|
||||
}
|
||||
|
||||
public LiveClient build() {
|
||||
@@ -145,37 +113,125 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
var tiktokRoomInfo = new TikTokRoomInfo();
|
||||
tiktokRoomInfo.setHostName(clientSettings.getHostName());
|
||||
|
||||
var listenerManager = new TikTokListenersManager(listeners, tikTokEventHandler);
|
||||
var cookieJar = new TikTokCookieJar();
|
||||
var requestFactory = new TikTokHttpRequestFactory(cookieJar);
|
||||
var apiClient = new TikTokHttpClient(cookieJar, requestFactory);
|
||||
var apiService = new TikTokApiService(apiClient, logger, clientSettings);
|
||||
var giftManager = new TikTokGiftManager(logger);
|
||||
var eventMapper = new TikTokGenericEventMapper();
|
||||
var giftHandler = new TikTokGiftEventHandler(giftManager);
|
||||
var listenerManager = new TikTokListenersManager(listeners, eventHandler);
|
||||
|
||||
var webResponseHandler = new TikTokMessageHandlerRegistration(tikTokEventHandler,
|
||||
var httpClientFactory = new HttpClientFactory(clientSettings);
|
||||
|
||||
var liveHttpClient = clientSettings.isOffline() ?
|
||||
new TikTokLiveHttpOfflineClient() :
|
||||
new TikTokLiveHttpClient(httpClientFactory, clientSettings);
|
||||
|
||||
var eventsMapper = createMapper(giftsManager, tiktokRoomInfo);
|
||||
var messageHandler = new TikTokLiveMessageHandler(eventHandler, eventsMapper);
|
||||
|
||||
var webSocketClient = clientSettings.isOffline() ?
|
||||
new TikTokWebSocketOfflineClient(eventHandler) :
|
||||
new TikTokWebSocketClient(
|
||||
clientSettings,
|
||||
messageHandler,
|
||||
eventHandler);
|
||||
|
||||
return new TikTokLiveClient(
|
||||
messageHandler,
|
||||
giftsManager,
|
||||
tiktokRoomInfo,
|
||||
eventMapper,
|
||||
giftHandler
|
||||
);
|
||||
|
||||
var webSocketClient = new TikTokWebSocketClient(logger,
|
||||
cookieJar,
|
||||
clientSettings,
|
||||
webResponseHandler,
|
||||
tikTokEventHandler);
|
||||
|
||||
return new TikTokLiveClient(tiktokRoomInfo,
|
||||
apiService,
|
||||
liveHttpClient,
|
||||
webSocketClient,
|
||||
giftManager,
|
||||
tikTokEventHandler,
|
||||
eventHandler,
|
||||
clientSettings,
|
||||
listenerManager,
|
||||
logger);
|
||||
}
|
||||
|
||||
public TikTokLiveMapper createMapper(GiftsManager giftsManager, TikTokRoomInfo roomInfo) {
|
||||
|
||||
|
||||
var eventMapper = new TikTokGenericEventMapper();
|
||||
var mapper = new TikTokLiveMapper(new TikTokLiveMapperHelper(eventMapper));
|
||||
|
||||
//ConnectionEvents events
|
||||
var commonHandler = new TikTokCommonEventHandler();
|
||||
var giftHandler = new TikTokGiftEventHandler(giftsManager, roomInfo);
|
||||
var roomInfoHandler = new TikTokRoomInfoEventHandler(roomInfo);
|
||||
var socialHandler = new TikTokSocialMediaEventHandler(roomInfo);
|
||||
|
||||
|
||||
mapper.forMessage(WebcastControlMessage.class, commonHandler::handleWebcastControlMessage);
|
||||
|
||||
//Room status events
|
||||
mapper.forMessage(WebcastLiveIntroMessage.class, roomInfoHandler::handleIntro);
|
||||
mapper.forMessage(WebcastRoomUserSeqMessage.class, roomInfoHandler::handleUserRanking);
|
||||
mapper.forMessage(WebcastCaptionMessage.class, (inputBytes, messageName, mapperHelper) ->
|
||||
{
|
||||
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastCaptionMessage.class);
|
||||
return MappingResult.of(messageObject, new TikTokCaptionEvent(messageObject));
|
||||
});
|
||||
|
||||
|
||||
//User Interactions events
|
||||
mapper.forMessage(WebcastChatMessage.class, (inputBytes, messageName, mapperHelper) ->
|
||||
{
|
||||
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastChatMessage.class);
|
||||
return MappingResult.of(messageObject, new TikTokCommentEvent(messageObject));
|
||||
});
|
||||
mapper.forMessage(WebcastSubNotifyMessage.class, (inputBytes, messageName, mapperHelper) ->
|
||||
{
|
||||
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastSubNotifyMessage.class);
|
||||
return MappingResult.of(messageObject, new TikTokSubscribeEvent(messageObject));
|
||||
});
|
||||
mapper.forMessage(WebcastEmoteChatMessage.class, (inputBytes, messageName, mapperHelper) ->
|
||||
{
|
||||
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastEmoteChatMessage.class);
|
||||
return MappingResult.of(messageObject, new TikTokEmoteEvent(messageObject));
|
||||
});
|
||||
mapper.forMessage(WebcastQuestionNewMessage.class, (inputBytes, messageName, mapperHelper) ->
|
||||
{
|
||||
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastQuestionNewMessage.class);
|
||||
return MappingResult.of(messageObject, new TikTokQuestionEvent(messageObject));
|
||||
});
|
||||
|
||||
mapper.forMessage(WebcastLikeMessage.class, roomInfoHandler::handleLike);
|
||||
mapper.forMessage(WebcastGiftMessage.class, giftHandler::handleGifts);
|
||||
mapper.forMessage(WebcastSocialMessage.class, socialHandler::handle);
|
||||
mapper.forMessage(WebcastMemberMessage.class, roomInfoHandler::handleMemberMessage);
|
||||
|
||||
|
||||
//Host Interaction events
|
||||
mapper.forMessage(WebcastPollMessage.class, commonHandler::handlePollEvent);
|
||||
mapper.forMessage(WebcastRoomPinMessage.class, commonHandler::handlePinMessage);
|
||||
mapper.forMessage(WebcastChatMessage.class, (inputBytes, messageName, mapperHelper) ->
|
||||
{
|
||||
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastChatMessage.class);
|
||||
return MappingResult.of(messageObject, new TikTokCommentEvent(messageObject));
|
||||
});
|
||||
|
||||
|
||||
//LinkMic events
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicArmies.class, TikTokLinkMicArmiesEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
|
||||
|
||||
//Rank events
|
||||
// mapper.webcastObjectToConstructor(WebcastRankTextMessage.class, TikTokRankTextEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastHourlyRankMessage.class, TikTokRankUpdateEvent.class);
|
||||
|
||||
//Others events
|
||||
// mapper.webcastObjectToConstructor(WebcastInRoomBannerMessage.class, TikTokInRoomBannerEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastMsgDetectMessage.class, TikTokDetectEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastBarrageMessage.class, TikTokBarrageEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastUnauthorizedMemberMessage.class, TikTokUnauthorizedMemberEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastOecLiveShoppingMessage.class, TikTokShopEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastImDeleteMessage.class, TikTokIMDeleteEvent.class);
|
||||
// mapper.bytesToEvents(WebcastEnvelopeMessage.class, commonHandler::handleEnvelop);
|
||||
|
||||
|
||||
onCustomMappings.accept(mapper);
|
||||
return mapper;
|
||||
}
|
||||
|
||||
|
||||
public LiveClient buildAndConnect() {
|
||||
var client = build();
|
||||
client.connect();
|
||||
@@ -186,264 +242,256 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
return build().connectAsync();
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onUnhandledSocial(
|
||||
EventConsumer<TikTokUnhandledSocialEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokUnhandledSocialEvent.class, event);
|
||||
public TikTokLiveClientBuilder onUnhandledSocial(EventConsumer<TikTokUnhandledSocialEvent> event) {
|
||||
eventHandler.subscribe(TikTokUnhandledSocialEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
// @Override
|
||||
public LiveClientBuilder onChest(EventConsumer<TikTokChestEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokChestEvent.class, event);
|
||||
eventHandler.subscribe(TikTokChestEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLinkMicFanTicket(
|
||||
EventConsumer<TikTokLinkMicFanTicketEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLinkMicFanTicketEvent.class, event);
|
||||
public TikTokLiveClientBuilder onLinkMicFanTicket(EventConsumer<TikTokLinkMicFanTicketEvent> event) {
|
||||
eventHandler.subscribe(TikTokLinkMicFanTicketEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onEnvelope(EventConsumer<TikTokEnvelopeEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokEnvelopeEvent.class, event);
|
||||
eventHandler.subscribe(TikTokEnvelopeEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onShop(EventConsumer<TikTokShopEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokShopEvent.class, event);
|
||||
eventHandler.subscribe(TikTokShopEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onDetect(
|
||||
EventConsumer<TikTokDetectEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokDetectEvent.class, event);
|
||||
public TikTokLiveClientBuilder onDetect(EventConsumer<TikTokDetectEvent> event) {
|
||||
eventHandler.subscribe(TikTokDetectEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLinkLayer(
|
||||
EventConsumer<TikTokLinkLayerEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLinkLayerEvent.class, event);
|
||||
public TikTokLiveClientBuilder onLinkLayer(EventConsumer<TikTokLinkLayerEvent> event) {
|
||||
eventHandler.subscribe(TikTokLinkLayerEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onConnected(EventConsumer<TikTokConnectedEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokConnectedEvent.class, event);
|
||||
eventHandler.subscribe(TikTokConnectedEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onPreConnection(EventConsumer<TikTokPreConnectionEvent> event) {
|
||||
eventHandler.subscribe(TikTokPreConnectionEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onCaption(EventConsumer<TikTokCaptionEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokCaptionEvent.class, event);
|
||||
eventHandler.subscribe(TikTokCaptionEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onQuestion(EventConsumer<TikTokQuestionEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokQuestionEvent.class, event);
|
||||
eventHandler.subscribe(TikTokQuestionEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onRoomPin(
|
||||
EventConsumer<TikTokRoomPinEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokRoomPinEvent.class, event);
|
||||
public TikTokLiveClientBuilder onRoomPin(EventConsumer<TikTokRoomPinEvent> event) {
|
||||
eventHandler.subscribe(TikTokRoomPinEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onRoom(EventConsumer<TikTokRoomEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokRoomEvent.class, event);
|
||||
@Override
|
||||
public <E extends TikTokEvent> LiveClientBuilder onEvent(Class<E> eventClass, EventConsumer<E> event) {
|
||||
eventHandler.subscribe(eventClass, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokLiveClientBuilder onRoomInfo(EventConsumer<TikTokRoomInfoEvent> event) {
|
||||
eventHandler.subscribe(TikTokRoomInfoEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLivePaused(EventConsumer<TikTokLivePausedEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLivePausedEvent.class, event);
|
||||
eventHandler.subscribe(TikTokLivePausedEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokLiveClientBuilder onLiveUnpaused(EventConsumer<TikTokLiveUnpausedEvent> event) {
|
||||
eventHandler.subscribe(TikTokLiveUnpausedEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLike(EventConsumer<TikTokLikeEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLikeEvent.class, event);
|
||||
eventHandler.subscribe(TikTokLikeEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLink(EventConsumer<TikTokLinkEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLinkEvent.class, event);
|
||||
eventHandler.subscribe(TikTokLinkEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onBarrage(
|
||||
EventConsumer<TikTokBarrageEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokBarrageEvent.class, event);
|
||||
public TikTokLiveClientBuilder onBarrage(EventConsumer<TikTokBarrageEvent> event) {
|
||||
eventHandler.subscribe(TikTokBarrageEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public TikTokLiveClientBuilder onGift(EventConsumer<TikTokGiftEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokGiftEvent.class, event);
|
||||
eventHandler.subscribe(TikTokGiftEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onGiftCombo(EventConsumer<TikTokGiftComboEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokGiftComboEvent.class, event);
|
||||
eventHandler.subscribe(TikTokGiftComboEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public TikTokLiveClientBuilder onLinkMicArmies(
|
||||
EventConsumer<TikTokLinkMicArmiesEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLinkMicArmiesEvent.class, event);
|
||||
public TikTokLiveClientBuilder onLinkMicArmies(EventConsumer<TikTokLinkMicArmiesEvent> event) {
|
||||
eventHandler.subscribe(TikTokLinkMicArmiesEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onEmote(EventConsumer<TikTokEmoteEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokEmoteEvent.class, event);
|
||||
eventHandler.subscribe(TikTokEmoteEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onUnauthorizedMember(
|
||||
EventConsumer<TikTokUnauthorizedMemberEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokUnauthorizedMemberEvent.class, event);
|
||||
public TikTokLiveClientBuilder onUnauthorizedMember(EventConsumer<TikTokUnauthorizedMemberEvent> event) {
|
||||
eventHandler.subscribe(TikTokUnauthorizedMemberEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onInRoomBanner(
|
||||
EventConsumer<TikTokInRoomBannerEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokInRoomBannerEvent.class, event);
|
||||
public TikTokLiveClientBuilder onInRoomBanner(EventConsumer<TikTokInRoomBannerEvent> event) {
|
||||
eventHandler.subscribe(TikTokInRoomBannerEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLinkMicMethod(
|
||||
EventConsumer<TikTokLinkMicMethodEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLinkMicMethodEvent.class, event);
|
||||
public TikTokLiveClientBuilder onLinkMicMethod(EventConsumer<TikTokLinkMicMethodEvent> event) {
|
||||
eventHandler.subscribe(TikTokLinkMicMethodEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onSubscribe(EventConsumer<TikTokSubscribeEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokSubscribeEvent.class, event);
|
||||
eventHandler.subscribe(TikTokSubscribeEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onPoll(EventConsumer<TikTokPollEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokPollEvent.class, event);
|
||||
eventHandler.subscribe(TikTokPollEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onFollow(EventConsumer<TikTokFollowEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokFollowEvent.class, event);
|
||||
eventHandler.subscribe(TikTokFollowEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onRoomUserInfo(
|
||||
EventConsumer<TikTokRoomUserInfoEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokRoomUserInfoEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public TikTokLiveClientBuilder onComment(EventConsumer<TikTokCommentEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokCommentEvent.class, event);
|
||||
eventHandler.subscribe(TikTokCommentEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveClientBuilder onHttpResponse(EventConsumer<TikTokHttpResponseEvent> action) {
|
||||
eventHandler.subscribe(TikTokHttpResponseEvent.class, action);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onGoalUpdate(EventConsumer<TikTokGoalUpdateEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokGoalUpdateEvent.class, event);
|
||||
eventHandler.subscribe(TikTokGoalUpdateEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onRankUpdate(EventConsumer<TikTokRankUpdateEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokRankUpdateEvent.class, event);
|
||||
eventHandler.subscribe(TikTokRankUpdateEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onIMDelete(EventConsumer<TikTokIMDeleteEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokIMDeleteEvent.class, event);
|
||||
eventHandler.subscribe(TikTokIMDeleteEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLiveEnded(EventConsumer<TikTokLiveEndedEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLiveEndedEvent.class, event);
|
||||
eventHandler.subscribe(TikTokLiveEndedEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onError(EventConsumer<TikTokErrorEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokErrorEvent.class, event);
|
||||
eventHandler.subscribe(TikTokErrorEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public TikTokLiveClientBuilder onJoin(EventConsumer<TikTokJoinEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokJoinEvent.class, event);
|
||||
eventHandler.subscribe(TikTokJoinEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onRankText(EventConsumer<TikTokRankTextEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokRankTextEvent.class, event);
|
||||
eventHandler.subscribe(TikTokRankTextEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onShare(EventConsumer<TikTokShareEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokShareEvent.class, event);
|
||||
eventHandler.subscribe(TikTokShareEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onUnhandledMember(
|
||||
EventConsumer<TikTokUnhandledMemberEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokUnhandledMemberEvent.class, event);
|
||||
public TikTokLiveClientBuilder onUnhandledMember(EventConsumer<TikTokUnhandledMemberEvent> event) {
|
||||
eventHandler.subscribe(TikTokUnhandledMemberEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onSubNotify(EventConsumer<TikTokSubNotifyEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokSubNotifyEvent.class, event);
|
||||
eventHandler.subscribe(TikTokSubNotifyEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onLinkMicBattle(
|
||||
EventConsumer<TikTokLinkMicBattleEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLinkMicBattleEvent.class, event);
|
||||
public TikTokLiveClientBuilder onLinkMicBattle(EventConsumer<TikTokLinkMicBattleEvent> event) {
|
||||
eventHandler.subscribe(TikTokLinkMicBattleEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onDisconnected(
|
||||
EventConsumer<TikTokDisconnectedEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokDisconnectedEvent.class, event);
|
||||
public TikTokLiveClientBuilder onDisconnected(EventConsumer<TikTokDisconnectedEvent> event) {
|
||||
eventHandler.subscribe(TikTokDisconnectedEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onUnhandledControl(
|
||||
EventConsumer<TikTokUnhandledControlEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokUnhandledControlEvent.class, event);
|
||||
public TikTokLiveClientBuilder onUnhandledControl(EventConsumer<TikTokUnhandledControlEvent> event) {
|
||||
eventHandler.subscribe(TikTokUnhandledControlEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokLiveClientBuilder onEvent(EventConsumer<TikTokEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokEvent.class, event);
|
||||
eventHandler.subscribe(TikTokEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokLiveClientBuilder onWebsocketResponse(EventConsumer<TikTokWebsocketResponseEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokWebsocketResponseEvent.class, event);
|
||||
eventHandler.subscribe(TikTokWebsocketResponseEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokLiveClientBuilder onWebsocketMessage(EventConsumer<TikTokWebsocketMessageEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokWebsocketMessageEvent.class, event);
|
||||
eventHandler.subscribe(TikTokWebsocketMessageEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokLiveClientBuilder onWebsocketUnhandledMessage(EventConsumer<TikTokWebsocketUnhandledMessageEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokWebsocketUnhandledMessageEvent.class, event);
|
||||
eventHandler.subscribe(TikTokWebsocketUnhandledMessageEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokLiveClientBuilder onReconnecting(EventConsumer<TikTokReconnectingEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokReconnectingEvent.class, event);
|
||||
eventHandler.subscribe(TikTokReconnectingEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -20,7 +20,7 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.handlers;
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.live.builder.EventConsumer;
|
||||
@@ -31,10 +31,10 @@ import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class TikTokEventObserver {
|
||||
public class TikTokLiveEventHandler {
|
||||
private final Map<Class<?>, Set<EventConsumer>> events;
|
||||
|
||||
public TikTokEventObserver() {
|
||||
public TikTokLiveEventHandler() {
|
||||
events = new HashMap<>();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.github.jwdeveloper.tiktok.common.*;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.*;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.*;
|
||||
import io.github.jwdeveloper.tiktok.http.*;
|
||||
import io.github.jwdeveloper.tiktok.http.mappers.*;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TikTokLiveHttpClient implements LiveHttpClient
|
||||
{
|
||||
/**
|
||||
* <a href="https://github-wiki-see.page/m/isaackogan/TikTokLive/wiki/All-About-Signatures">Signing API by Isaac Kogan</a>
|
||||
*/
|
||||
private static final String TIKTOK_SIGN_API = "https://tiktok.eulerstream.com/webcast/fetch";
|
||||
private static final String TIKTOK_URL_WEB = "https://www.tiktok.com/";
|
||||
private static final String TIKTOK_URL_WEBCAST = "https://webcast.tiktok.com/webcast/";
|
||||
public static final String TIKTOK_GIFTS_URL = "https://raw.githubusercontent.com/TikTok-LIVE-Private/GiftsGenerator/master/page/public/gifts.json";
|
||||
public static final int TIKTOK_AGE_RESTRICTED_CODE = 4003110;
|
||||
|
||||
private final HttpClientFactory httpFactory;
|
||||
private final LiveClientSettings clientSettings;
|
||||
private final LiveUserDataMapper liveUserDataMapper;
|
||||
private final LiveDataMapper liveDataMapper;
|
||||
private final GiftsDataMapper giftsDataMapper;
|
||||
private final Logger logger;
|
||||
|
||||
public TikTokLiveHttpClient(HttpClientFactory factory, LiveClientSettings settings) {
|
||||
this.httpFactory = factory;
|
||||
this.clientSettings = settings;
|
||||
this.logger = LoggerFactory.create("HttpClient", clientSettings);
|
||||
liveUserDataMapper = new LiveUserDataMapper();
|
||||
liveDataMapper = new LiveDataMapper();
|
||||
giftsDataMapper = new GiftsDataMapper();
|
||||
}
|
||||
|
||||
public TikTokLiveHttpClient() {
|
||||
this(new HttpClientFactory(LiveClientSettings.createDefault()), LiveClientSettings.createDefault());
|
||||
}
|
||||
|
||||
public GiftsData.Response fetchGiftsData() {
|
||||
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
|
||||
if (proxyClientSettings.isEnabled()) {
|
||||
while (proxyClientSettings.hasNext()) {
|
||||
try {
|
||||
return getGiftsData();
|
||||
} catch (TikTokProxyRequestException ignored) {}
|
||||
}
|
||||
}
|
||||
return getGiftsData();
|
||||
}
|
||||
|
||||
public GiftsData.Response getGiftsData() {
|
||||
var result = httpFactory.client(TIKTOK_GIFTS_URL)
|
||||
.build()
|
||||
.toJsonResponse();
|
||||
|
||||
if (result.isFailure())
|
||||
throw new TikTokLiveRequestException("Unable to fetch gifts information's - "+result);
|
||||
|
||||
var json = result.getContent();
|
||||
return giftsDataMapper.map(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveUserData.Response fetchLiveUserData(LiveUserData.Request request) {
|
||||
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
|
||||
if (proxyClientSettings.isEnabled()) {
|
||||
while (proxyClientSettings.hasNext()) {
|
||||
try {
|
||||
return getLiveUserData(request);
|
||||
} catch (TikTokProxyRequestException ignored) {}
|
||||
}
|
||||
}
|
||||
return getLiveUserData(request);
|
||||
}
|
||||
|
||||
public LiveUserData.Response getLiveUserData(LiveUserData.Request request) {
|
||||
var url = TIKTOK_URL_WEB + "api-live/user/room";
|
||||
var result = httpFactory.client(url)
|
||||
.withParam("uniqueId", request.getUserName())
|
||||
.withParam("sourceType", "54")
|
||||
.build()
|
||||
.toJsonResponse();
|
||||
|
||||
if (result.isFailure())
|
||||
throw new TikTokLiveRequestException("Unable to get information's about user - "+result);
|
||||
|
||||
var json = result.getContent();
|
||||
return liveUserDataMapper.map(json, logger);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveData.Response fetchLiveData(LiveData.Request request) {
|
||||
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
|
||||
if (proxyClientSettings.isEnabled()) {
|
||||
while (proxyClientSettings.hasNext()) {
|
||||
try {
|
||||
return getLiveData(request);
|
||||
} catch (TikTokProxyRequestException ignored) {}
|
||||
}
|
||||
}
|
||||
return getLiveData(request);
|
||||
}
|
||||
|
||||
public LiveData.Response getLiveData(LiveData.Request request) {
|
||||
var url = TIKTOK_URL_WEBCAST + "room/info";
|
||||
var result = httpFactory.client(url)
|
||||
.withParam("room_id", request.getRoomId())
|
||||
.build()
|
||||
.toJsonResponse();
|
||||
|
||||
if (result.isFailure())
|
||||
throw new TikTokLiveRequestException("Unable to get info about live room - "+result);
|
||||
|
||||
var json = result.getContent();
|
||||
return liveDataMapper.map(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveConnectionData.Response fetchLiveConnectionData(LiveConnectionData.Request request) {
|
||||
var result = getStartingPayload(request);
|
||||
HttpResponse<byte[]> credentialsResponse = result.getContent(); // Always guaranteed to have response
|
||||
|
||||
try {
|
||||
var resultHeader = ActionResult.of(credentialsResponse.headers().firstValue("x-set-tt-cookie"));
|
||||
if (resultHeader.isFailure()) {
|
||||
logger.warning("SignServer Headers: "+request.getRoomId()+" - "+credentialsResponse.headers().map());
|
||||
throw new TikTokSignServerException("Sign server did not return the x-set-tt-cookie header - "+result);
|
||||
}
|
||||
var websocketCookie = resultHeader.getContent();
|
||||
var webcastResponse = WebcastResponse.parseFrom(credentialsResponse.body());
|
||||
var webSocketUrl = httpFactory
|
||||
.client(webcastResponse.getPushServer())
|
||||
.withParam("room_id", request.getRoomId())
|
||||
.withParam("cursor", webcastResponse.getCursor())
|
||||
.withParam("resp_content_type", "protobuf")
|
||||
.withParam("internal_ext", webcastResponse.getInternalExt())
|
||||
.withParams(webcastResponse.getRouteParamsMapMap())
|
||||
.build()
|
||||
.toUrl();
|
||||
|
||||
return new LiveConnectionData.Response(websocketCookie, webSocketUrl, webcastResponse);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
throw new TikTokSignServerException("Unable to parse websocket credentials response to WebcastResponse - "+result);
|
||||
}
|
||||
}
|
||||
|
||||
private ActionResult<HttpResponse<byte[]>> getStartingPayload(LiveConnectionData.Request request) {
|
||||
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
|
||||
if (proxyClientSettings.isEnabled()) {
|
||||
while (proxyClientSettings.hasNext()) {
|
||||
try {
|
||||
return getByteResponse(request.getRoomId());
|
||||
} catch (TikTokProxyRequestException | TikTokSignServerException ignored) {}
|
||||
}
|
||||
}
|
||||
return getByteResponse(request.getRoomId());
|
||||
}
|
||||
|
||||
private ActionResult<HttpResponse<byte[]>> getByteResponse(String room_id) {
|
||||
HttpClientBuilder builder = httpFactory.client(TIKTOK_SIGN_API)
|
||||
.withParam("client", "ttlive-java")
|
||||
.withParam("uuc", "1")
|
||||
.withParam("room_id", room_id);
|
||||
|
||||
if (clientSettings.getApiKey() != null)
|
||||
builder.withParam("apiKey", clientSettings.getApiKey());
|
||||
|
||||
var result = builder.build().toResponse();
|
||||
|
||||
if (result.isFailure())
|
||||
throw new TikTokSignServerException("Unable to get websocket connection credentials - "+result);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.GiftsData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
|
||||
import io.github.jwdeveloper.tiktok.http.LiveHttpClient;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
public class TikTokLiveHttpOfflineClient implements LiveHttpClient {
|
||||
@Override
|
||||
public GiftsData.Response fetchGiftsData() {
|
||||
return new GiftsData.Response("", List.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveUserData.Response fetchLiveUserData(LiveUserData.Request request) {
|
||||
return new LiveUserData.Response("", LiveUserData.UserStatus.Live, "offline_room_id", 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveData.Response fetchLiveData(LiveData.Request request) {
|
||||
return new LiveData.Response("",
|
||||
LiveData.LiveStatus.HostOnline,
|
||||
"offline live",
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
new User(0L, "offline user", new Picture("")),
|
||||
LiveData.LiveType.SOLO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveConnectionData.Response fetchLiveConnectionData(LiveConnectionData.Request request) {
|
||||
return new LiveConnectionData.Response("",
|
||||
URI.create("https://example.live"),
|
||||
WebcastResponse.newBuilder().build());
|
||||
}
|
||||
}
|
||||
@@ -20,51 +20,32 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.handlers;
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.dto.MessageMetaData;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokErrorEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketMessageEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketResponseEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketUnhandledMessageEvent;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveMessageException;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokGenericEventMapper;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokLiveMapper;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import io.github.jwdeveloper.tiktok.utils.Stopwatch;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class TikTokLiveMessageHandler {
|
||||
|
||||
public abstract class TikTokMessageHandler {
|
||||
private final TikTokLiveEventHandler tikTokEventHandler;
|
||||
private final TikTokLiveMapper mapper;
|
||||
|
||||
private final Map<String, io.github.jwdeveloper.tiktok.handler.TikTokMessageHandler> handlers;
|
||||
private final TikTokEventObserver tikTokEventHandler;
|
||||
protected final TikTokGenericEventMapper mapper;
|
||||
|
||||
public TikTokMessageHandler(TikTokEventObserver tikTokEventHandler, TikTokGenericEventMapper mapper) {
|
||||
handlers = new HashMap<>();
|
||||
public TikTokLiveMessageHandler(TikTokLiveEventHandler tikTokEventHandler, TikTokLiveMapper mapper) {
|
||||
this.tikTokEventHandler = tikTokEventHandler;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
public void registerMapping(Class<?> clazz, Function<byte[], TikTokEvent> func) {
|
||||
handlers.put(clazz.getSimpleName(), messagePayload -> List.of(func.apply(messagePayload)));
|
||||
}
|
||||
|
||||
public void registerMappings(Class<?> clazz, Function<byte[], List<TikTokEvent>> func) {
|
||||
handlers.put(clazz.getSimpleName(), func::apply);
|
||||
}
|
||||
|
||||
public void registerMapping(Class<?> input, Class<?> output) {
|
||||
registerMapping(input, (e) -> mapper.mapToEvent(input, output, e));
|
||||
}
|
||||
|
||||
public void handle(LiveClient client, WebcastResponse webcastResponse) {
|
||||
tikTokEventHandler.publish(client, new TikTokWebsocketResponseEvent(webcastResponse));
|
||||
for (var message : webcastResponse.getMessagesList()) {
|
||||
@@ -77,21 +58,21 @@ public abstract class TikTokMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public void handleSingleMessage(LiveClient client, WebcastResponse.Message message) throws Exception {
|
||||
public void handleSingleMessage(LiveClient client, WebcastResponse.Message message)
|
||||
{
|
||||
var messageClassName = message.getMethod();
|
||||
if (!handlers.containsKey(messageClassName)) {
|
||||
if (!mapper.isRegistered(messageClassName)) {
|
||||
tikTokEventHandler.publish(client, new TikTokWebsocketUnhandledMessageEvent(message));
|
||||
return;
|
||||
}
|
||||
var handler = handlers.get(messageClassName);
|
||||
var stopwatch = new Stopwatch();
|
||||
stopwatch.start();
|
||||
var events = handler.handle(message.getPayload().toByteArray());
|
||||
var events = mapper.handleMapping(messageClassName, message.getPayload().toByteArray());
|
||||
var handlingTimeInMs = stopwatch.stop();
|
||||
var metadata = new TikTokWebsocketMessageEvent.MetaData(Duration.ofNanos(handlingTimeInMs));
|
||||
var metadata = new MessageMetaData(Duration.ofNanos(handlingTimeInMs));
|
||||
|
||||
for (var event : events) {
|
||||
tikTokEventHandler.publish(client, new TikTokWebsocketMessageEvent(event, message, metadata));
|
||||
tikTokEventHandler.publish(client, new TikTokWebsocketMessageEvent(message, event, metadata));
|
||||
tikTokEventHandler.publish(client, event);
|
||||
}
|
||||
}
|
||||
@@ -22,35 +22,52 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.messages.data.User;
|
||||
import io.github.jwdeveloper.tiktok.models.ConnectionState;
|
||||
import io.github.jwdeveloper.tiktok.data.models.RankingUser;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.models.ConnectionState;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class TikTokRoomInfo implements LiveRoomInfo
|
||||
{
|
||||
public class TikTokRoomInfo implements LiveRoomInfo {
|
||||
private String roomId;
|
||||
|
||||
private int likesCount;
|
||||
|
||||
private int viewersCount;
|
||||
|
||||
private int totalViewersCount;
|
||||
|
||||
private long startTime;
|
||||
|
||||
private boolean ageRestricted;
|
||||
|
||||
private User host;
|
||||
|
||||
private Picture picture;
|
||||
|
||||
private String description;
|
||||
private List<RankingUser> usersRanking = new LinkedList<>();
|
||||
|
||||
private String hostName;
|
||||
|
||||
private String title;
|
||||
|
||||
private String language = "en";
|
||||
|
||||
private ConnectionState connectionState = ConnectionState.DISCONNECTED;
|
||||
|
||||
public boolean hasConnectionState(ConnectionState state)
|
||||
{
|
||||
public boolean hasConnectionState(ConnectionState state) {
|
||||
return connectionState == state;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getHostUser() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void updateRanking(List<RankingUser> rankingUsers) {
|
||||
usersRanking.clear();
|
||||
usersRanking.addAll(rankingUsers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package io.github.jwdeveloper.tiktok.common;
|
||||
|
||||
import com.google.gson.*;
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Data
|
||||
public class ActionResult<T> {
|
||||
|
||||
private boolean success = true;
|
||||
private T content;
|
||||
private String message;
|
||||
@Accessors(chain = true, fluent = true)
|
||||
private ActionResult<?> previous;
|
||||
|
||||
protected ActionResult(T object) {
|
||||
this.content = object;
|
||||
}
|
||||
|
||||
protected ActionResult(T object, boolean success) {
|
||||
this(object);
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
protected ActionResult(T object, boolean success, String message) {
|
||||
this(object, success);
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public static <T> ActionResultBuilder<T> of(T content) {
|
||||
return new ActionResultBuilder<>(content);
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> of(Optional<T> optional) {
|
||||
return new ActionResult<>(optional.orElse(null), optional.isPresent());
|
||||
}
|
||||
|
||||
public boolean isFailure() {
|
||||
return !isSuccess();
|
||||
}
|
||||
|
||||
public boolean hasMessage() {
|
||||
return message != null;
|
||||
}
|
||||
|
||||
public boolean hasPrevious() {
|
||||
return previous != null;
|
||||
}
|
||||
|
||||
public boolean hasContent() {
|
||||
return content != null;
|
||||
}
|
||||
|
||||
public <Output> ActionResult<Output> cast(Output output) {
|
||||
return new ActionResult<>(output, this.isSuccess(), this.getMessage());
|
||||
}
|
||||
|
||||
public <Output> ActionResult<Output> cast() {
|
||||
return cast(null);
|
||||
}
|
||||
|
||||
public <U> ActionResult<U> map(Function<? super T, ? extends U> mapper) {
|
||||
return hasContent() ? cast(mapper.apply(content)) : cast();
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> success(T payload, String message) {
|
||||
return new ActionResult<>(payload, true, message);
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> success(T payload) {
|
||||
return success(payload, null);
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> success() {
|
||||
return success(null);
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> failure(T target, String message) {
|
||||
return new ActionResult<>(target, false, message);
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> failure(String message) {
|
||||
return failure(null, message);
|
||||
}
|
||||
|
||||
public static <T> ActionResult<T> failure() {
|
||||
return failure(null);
|
||||
}
|
||||
|
||||
public JsonObject toJson() {
|
||||
JsonObject map = new JsonObject();
|
||||
map.addProperty("success", success);
|
||||
map.add("content", new Gson().toJsonTree(content));
|
||||
map.addProperty("message", message);
|
||||
map.add("previous", hasPrevious() ? previous.toJson() : null);
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ActionResult: "+new Gson().newBuilder().setPrettyPrinting().create().toJson(toJson());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.github.jwdeveloper.tiktok.common;
|
||||
|
||||
import lombok.Setter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ActionResultBuilder<T>
|
||||
{
|
||||
private final T content;
|
||||
private String message;
|
||||
@Setter @Accessors(fluent = true, chain = true)
|
||||
private ActionResult<?> previous;
|
||||
|
||||
public ActionResultBuilder(T content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public ActionResultBuilder<T> message(Object... messages) {
|
||||
this.message = Arrays.stream(messages).map(Object::toString).collect(Collectors.joining(" "));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ActionResult<T> success() {
|
||||
return ActionResult.success(content, message).previous(previous);
|
||||
}
|
||||
|
||||
public ActionResult<T> failure() {
|
||||
return ActionResult.success(content, message).previous(previous);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.github.jwdeveloper.tiktok.common;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.utils.ConsoleColors;
|
||||
|
||||
import java.util.logging.*;
|
||||
|
||||
public class LoggerFactory
|
||||
{
|
||||
public static Logger create(String name, LiveClientSettings settings) {
|
||||
Logger logger = Logger.getLogger(name);
|
||||
if (logger.getHandlers().length == 0) {
|
||||
var handler = new ConsoleHandler();
|
||||
handler.setFormatter(new Formatter()
|
||||
{
|
||||
@Override
|
||||
public String format(LogRecord record) {
|
||||
var sb = new StringBuilder();
|
||||
sb.append(ConsoleColors.GREEN).append("[").append(record.getLoggerName()).append("] ");
|
||||
sb.append(ConsoleColors.GREEN).append("[").append(record.getLevel()).append("]: ");
|
||||
sb.append(ConsoleColors.WHITE_BRIGHT).append(record.getMessage());
|
||||
sb.append(ConsoleColors.RESET).append("\n");
|
||||
return sb.toString();
|
||||
}
|
||||
});
|
||||
logger.setUseParentHandlers(false);
|
||||
logger.addHandler(handler);
|
||||
logger.setLevel(settings.getLogLevel());
|
||||
if (!settings.isPrintToConsole())
|
||||
logger.setLevel(Level.OFF);
|
||||
}
|
||||
return logger;
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.gifts;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TikTokGiftManager implements GiftManager {
|
||||
|
||||
private final Map<Integer, Gift> indexById;
|
||||
private final Map<String, Gift> indexByName;
|
||||
private final Logger logger;
|
||||
|
||||
public TikTokGiftManager(Logger logger)
|
||||
{
|
||||
indexById = new HashMap<>();
|
||||
indexByName = new HashMap<>();
|
||||
this.logger = logger;
|
||||
init();
|
||||
}
|
||||
|
||||
protected void init() {
|
||||
for (var gift : Gift.values()) {
|
||||
indexById.put(gift.getId(), gift);
|
||||
indexByName.put(gift.getName(), gift);
|
||||
}
|
||||
}
|
||||
|
||||
public Gift registerGift(int id, String name, int diamondCost, Picture picture) {
|
||||
try {
|
||||
var constructor = Unsafe.class.getDeclaredConstructors()[0];
|
||||
constructor.setAccessible(true);
|
||||
var unsafe = (Unsafe) constructor.newInstance();
|
||||
Gift enumInstance = (Gift) unsafe.allocateInstance(Gift.class);
|
||||
|
||||
var field = Gift.class.getDeclaredField("id");
|
||||
field.setAccessible(true);
|
||||
field.set(enumInstance, id);
|
||||
|
||||
field = Gift.class.getDeclaredField("name");
|
||||
field.setAccessible(true);
|
||||
field.set(enumInstance, name);
|
||||
|
||||
|
||||
// EnumSet
|
||||
field = Gift.class.getDeclaredField("diamondCost");
|
||||
field.setAccessible(true);
|
||||
field.set(enumInstance, diamondCost);
|
||||
|
||||
field = Gift.class.getDeclaredField("picture");
|
||||
field.setAccessible(true);
|
||||
field.set(enumInstance, picture);
|
||||
|
||||
indexById.put(enumInstance.getId(), enumInstance);
|
||||
indexByName.put(enumInstance.getName(), enumInstance);
|
||||
|
||||
return enumInstance;
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveException("Unable to register gift: " + name + ": " + id);
|
||||
}
|
||||
}
|
||||
|
||||
public Gift findById(int giftId) {
|
||||
if (!indexById.containsKey(giftId)) {
|
||||
return Gift.UNDEFINED;
|
||||
}
|
||||
return indexById.get(giftId);
|
||||
}
|
||||
|
||||
public Gift findByName(String giftName) {
|
||||
if (!indexByName.containsKey(giftName)) {
|
||||
return Gift.UNDEFINED;
|
||||
}
|
||||
return indexByName.get(giftName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Gift> getGifts()
|
||||
{
|
||||
return indexById.values().stream().toList();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.github.jwdeveloper.tiktok.gifts;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftsManager;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TikTokGiftsManager implements GiftsManager {
|
||||
private final Map<Integer, Gift> giftsByIdIndex;
|
||||
|
||||
public TikTokGiftsManager(List<Gift> giftList)
|
||||
{
|
||||
giftsByIdIndex = giftList.stream().collect(Collectors.toConcurrentMap(Gift::getId, e -> e));
|
||||
}
|
||||
|
||||
public void attachGift(Gift gift) {
|
||||
giftsByIdIndex.put(gift.getId(), gift);
|
||||
}
|
||||
|
||||
public void attachGiftsList(List<Gift> gifts) {
|
||||
gifts.forEach(this::attachGift);
|
||||
}
|
||||
|
||||
public Gift getByName(String name) {
|
||||
return getByFilter(e -> e.getName().equalsIgnoreCase(name));
|
||||
}
|
||||
|
||||
public Gift getById(int giftId) {
|
||||
if (!giftsByIdIndex.containsKey(giftId)) {
|
||||
return Gift.UNDEFINED;
|
||||
}
|
||||
|
||||
return giftsByIdIndex.get(giftId);
|
||||
}
|
||||
|
||||
public Gift getByFilter(Predicate<Gift> filter) {
|
||||
return giftsByIdIndex.values()
|
||||
.stream()
|
||||
.filter(filter)
|
||||
.findFirst()
|
||||
.orElseGet(() -> Gift.UNDEFINED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Gift> getManyByFilter(Predicate<Gift> filter) {
|
||||
return giftsByIdIndex.values()
|
||||
.stream()
|
||||
.filter(filter)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<Gift> toList() {
|
||||
return giftsByIdIndex.values().stream().toList();
|
||||
}
|
||||
|
||||
public Map<Integer, Gift> toMap() {
|
||||
return Collections.unmodifiableMap(giftsByIdIndex);
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.handlers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.TikTokRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.data.events.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.envelop.TikTokChestEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEndEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollStartEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollUpdateEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomPinEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomUserInfoEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.social.TikTokShareEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Text;
|
||||
import io.github.jwdeveloper.tiktok.data.models.chest.Chest;
|
||||
import io.github.jwdeveloper.tiktok.handlers.events.TikTokGiftEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokGenericEventMapper;
|
||||
import io.github.jwdeveloper.tiktok.messages.enums.EnvelopeDisplay;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.*;
|
||||
import io.github.jwdeveloper.tiktok.models.SocialTypes;
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class TikTokMessageHandlerRegistration extends TikTokMessageHandler {
|
||||
|
||||
private final TikTokRoomInfo roomInfo;
|
||||
private final TikTokGiftEventHandler giftHandler;
|
||||
private final Pattern socialMediaPattern = Pattern.compile("pm_mt_guidance_viewer_([0-9]+)_share");
|
||||
|
||||
public TikTokMessageHandlerRegistration(TikTokEventObserver tikTokEventHandler,
|
||||
TikTokRoomInfo roomInfo,
|
||||
TikTokGenericEventMapper genericTikTokEventMapper,
|
||||
TikTokGiftEventHandler tikTokGiftEventHandler) {
|
||||
super(tikTokEventHandler, genericTikTokEventMapper);
|
||||
this.giftHandler = tikTokGiftEventHandler;
|
||||
this.roomInfo = roomInfo;
|
||||
init();
|
||||
}
|
||||
|
||||
public void init() {
|
||||
|
||||
//ConnectionEvents events
|
||||
registerMapping(WebcastControlMessage.class, this::handleWebcastControlMessage);
|
||||
registerMapping(WebcastSystemMessage.class, TikTokRoomEvent.class);
|
||||
|
||||
|
||||
//Room status events
|
||||
registerMapping(WebcastLiveIntroMessage.class, TikTokRoomEvent.class);
|
||||
registerMapping(WebcastRoomUserSeqMessage.class, this::handleRoomUserSeqMessage);
|
||||
registerMapping(RoomMessage.class, TikTokRoomEvent.class);
|
||||
registerMapping(WebcastRoomMessage.class, TikTokRoomEvent.class);
|
||||
registerMapping(WebcastCaptionMessage.class, TikTokCaptionEvent.class);
|
||||
|
||||
//User Interactions events
|
||||
registerMapping(WebcastChatMessage.class, TikTokCommentEvent.class);
|
||||
registerMapping(WebcastLikeMessage.class, this::handleLike);
|
||||
registerMappings(WebcastGiftMessage.class, giftHandler::handleGift);
|
||||
registerMapping(WebcastSocialMessage.class, this::handleSocialMedia);
|
||||
registerMapping(WebcastMemberMessage.class, this::handleMemberMessage);
|
||||
|
||||
//Host Interaction events
|
||||
registerMapping(WebcastPollMessage.class, this::handlePollEvent);
|
||||
registerMapping(WebcastRoomPinMessage.class, this::handlePinMessage);
|
||||
registerMapping(WebcastGoalUpdateMessage.class, TikTokGoalUpdateEvent.class);
|
||||
|
||||
//LinkMic events
|
||||
registerMapping(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
|
||||
registerMapping(WebcastLinkMicArmies.class, TikTokLinkMicArmiesEvent.class);
|
||||
registerMapping(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
|
||||
registerMapping(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
|
||||
|
||||
//Rank events
|
||||
registerMapping(WebcastRankTextMessage.class, TikTokRankTextEvent.class);
|
||||
registerMapping(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
|
||||
registerMapping(WebcastHourlyRankMessage.class, TikTokRankUpdateEvent.class);
|
||||
|
||||
//Others events
|
||||
registerMapping(WebcastInRoomBannerMessage.class, TikTokInRoomBannerEvent.class);
|
||||
registerMapping(WebcastMsgDetectMessage.class, TikTokDetectEvent.class);
|
||||
registerMapping(WebcastBarrageMessage.class, TikTokBarrageEvent.class);
|
||||
registerMapping(WebcastUnauthorizedMemberMessage.class, TikTokUnauthorizedMemberEvent.class);
|
||||
registerMapping(WebcastOecLiveShoppingMessage.class, TikTokShopEvent.class);
|
||||
registerMapping(WebcastImDeleteMessage.class, TikTokIMDeleteEvent.class);
|
||||
registerMapping(WebcastQuestionNewMessage.class, TikTokQuestionEvent.class);
|
||||
registerMappings(WebcastEnvelopeMessage.class, this::handleEnvelop);
|
||||
registerMapping(WebcastSubNotifyMessage.class, TikTokSubNotifyEvent.class);
|
||||
registerMapping(WebcastEmoteChatMessage.class, TikTokEmoteEvent.class);
|
||||
}
|
||||
|
||||
|
||||
@SneakyThrows
|
||||
private TikTokEvent handleWebcastControlMessage(byte[] msg) {
|
||||
var message = WebcastControlMessage.parseFrom(msg);
|
||||
return switch (message.getAction()) {
|
||||
case STREAM_PAUSED -> new TikTokLivePausedEvent();
|
||||
case STREAM_ENDED -> new TikTokLiveEndedEvent();
|
||||
default -> new TikTokUnhandledControlEvent(message);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@SneakyThrows
|
||||
private TikTokEvent handleSocialMedia(byte[] msg) {
|
||||
var message = WebcastSocialMessage.parseFrom(msg);
|
||||
|
||||
var socialType = Text.map(message.getCommon().getDisplayText()).getKey();
|
||||
var matcher = socialMediaPattern.matcher(socialType);
|
||||
|
||||
if (matcher.find()) {
|
||||
var value = matcher.group(1);
|
||||
var number = Integer.parseInt(value);
|
||||
return new TikTokShareEvent(message, number);
|
||||
}
|
||||
|
||||
return switch (socialType) {
|
||||
case SocialTypes.LikeType -> new TikTokLikeEvent(message, roomInfo.getLikesCount());
|
||||
case SocialTypes.FollowType -> new TikTokFollowEvent(message);
|
||||
case SocialTypes.ShareType -> new TikTokShareEvent(message);
|
||||
case SocialTypes.JoinType -> new TikTokJoinEvent(message, roomInfo.getViewersCount());
|
||||
default -> new TikTokUnhandledSocialEvent(message);
|
||||
};
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private TikTokEvent handleMemberMessage(byte[] msg) {
|
||||
var message = WebcastMemberMessage.parseFrom(msg);
|
||||
roomInfo.setViewersCount(message.getMemberCount());
|
||||
return switch (message.getAction()) {
|
||||
case JOINED -> new TikTokJoinEvent(message);
|
||||
case SUBSCRIBED -> new TikTokSubscribeEvent(message);
|
||||
default -> new TikTokUnhandledMemberEvent(message);
|
||||
};
|
||||
}
|
||||
|
||||
private TikTokEvent handleRoomUserSeqMessage(byte[] msg) {
|
||||
var event = (TikTokRoomUserInfoEvent) mapper.mapToEvent(WebcastRoomUserSeqMessage.class, TikTokRoomUserInfoEvent.class, msg);
|
||||
roomInfo.setViewersCount(event.getTotalUsers());
|
||||
return event;
|
||||
}
|
||||
|
||||
private TikTokEvent handleLike(byte[] msg) {
|
||||
var event = (TikTokLikeEvent) mapper.mapToEvent(WebcastLikeMessage.class, TikTokLikeEvent.class, msg);
|
||||
roomInfo.setLikesCount(event.getTotalLikes());
|
||||
return event;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private TikTokEvent handlePinMessage(byte[] msg) {
|
||||
var pinMessage = WebcastRoomPinMessage.parseFrom(msg);
|
||||
var chatMessage = WebcastChatMessage.parseFrom(pinMessage.getPinnedMessage());
|
||||
var chatEvent = new TikTokCommentEvent(chatMessage);
|
||||
return new TikTokRoomPinEvent(pinMessage, chatEvent);
|
||||
}
|
||||
|
||||
//TODO Probably not working
|
||||
@SneakyThrows
|
||||
private TikTokEvent handlePollEvent(byte[] msg) {
|
||||
var poolMessage = WebcastPollMessage.parseFrom(msg);
|
||||
return switch (poolMessage.getMessageType()) {
|
||||
case 0 -> new TikTokPollStartEvent(poolMessage);
|
||||
case 1 -> new TikTokPollEndEvent(poolMessage);
|
||||
case 2 -> new TikTokPollUpdateEvent(poolMessage);
|
||||
default -> new TikTokPollEvent(poolMessage);
|
||||
};
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private List<TikTokEvent> handleEnvelop(byte[] data) {
|
||||
var msg = WebcastEnvelopeMessage.parseFrom(data);
|
||||
if (msg.getDisplay() != EnvelopeDisplay.EnvelopeDisplayNew) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
var totalDiamonds = msg.getEnvelopeInfo().getDiamondCount();
|
||||
var totalUsers = msg.getEnvelopeInfo().getPeopleCount();
|
||||
var chest = new Chest(totalDiamonds, totalUsers);
|
||||
|
||||
return List.of(new TikTokChestEvent(chest, msg));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package io.github.jwdeveloper.tiktok.handlers.events;
|
||||
|
||||
public class TikTokChestEventHandler {
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.common.ActionResult;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.HttpClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
import java.net.*;
|
||||
import java.net.http.*;
|
||||
import java.nio.charset.*;
|
||||
import java.util.*;
|
||||
import java.util.regex.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@AllArgsConstructor
|
||||
public class HttpClient {
|
||||
|
||||
protected final HttpClientSettings httpClientSettings;
|
||||
protected final String url;
|
||||
private final Pattern pattern = Pattern.compile("charset=(.*?)(?=&|$)");
|
||||
|
||||
public ActionResult<HttpResponse<byte[]>> toResponse() {
|
||||
var client = prepareClient();
|
||||
var request = prepareGetRequest();
|
||||
try {
|
||||
var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
var result = ActionResult.of(response);
|
||||
return response.statusCode() != 200 ? result.message("HttpResponse Code: ", response.statusCode()).failure() : result.success();
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public ActionResult<String> toJsonResponse() {
|
||||
return toResponse().map(content -> new String(content.body(), charsetFrom(content.headers())));
|
||||
}
|
||||
|
||||
private Charset charsetFrom(HttpHeaders headers) {
|
||||
String type = headers.firstValue("Content-type").orElse("text/html; charset=utf-8");
|
||||
int i = type.indexOf(";");
|
||||
if (i >= 0) type = type.substring(i+1);
|
||||
try {
|
||||
Matcher matcher = pattern.matcher(type);
|
||||
if (!matcher.find())
|
||||
return StandardCharsets.UTF_8;
|
||||
return Charset.forName(matcher.group(1));
|
||||
} catch (Throwable x) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
}
|
||||
|
||||
public ActionResult<byte[]> toBinaryResponse() {
|
||||
return toResponse().map(HttpResponse::body);
|
||||
}
|
||||
|
||||
public URI toUrl() {
|
||||
var stringUrl = prepareUrlWithParameters(url, httpClientSettings.getParams());
|
||||
return URI.create(stringUrl);
|
||||
}
|
||||
|
||||
protected HttpRequest prepareGetRequest() {
|
||||
var requestBuilder = HttpRequest.newBuilder().GET();
|
||||
requestBuilder.uri(toUrl());
|
||||
requestBuilder.timeout(httpClientSettings.getTimeout());
|
||||
httpClientSettings.getHeaders().forEach(requestBuilder::setHeader);
|
||||
|
||||
httpClientSettings.getOnRequestCreating().accept(requestBuilder);
|
||||
return requestBuilder.build();
|
||||
}
|
||||
|
||||
protected java.net.http.HttpClient prepareClient() {
|
||||
var builder = java.net.http.HttpClient.newBuilder()
|
||||
.followRedirects(java.net.http.HttpClient.Redirect.NORMAL)
|
||||
.cookieHandler(new CookieManager())
|
||||
.connectTimeout(httpClientSettings.getTimeout());
|
||||
|
||||
httpClientSettings.getOnClientCreating().accept(builder);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
protected String prepareUrlWithParameters(String url, Map<String, Object> parameters) {
|
||||
if (parameters.isEmpty()) {
|
||||
return url;
|
||||
}
|
||||
|
||||
return url + "?" + parameters.entrySet().stream().map(entry ->
|
||||
{
|
||||
var encodedKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
|
||||
var encodedValue = URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8);
|
||||
return encodedKey + "=" + encodedValue;
|
||||
}).collect(Collectors.joining("&"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.settings.HttpClientSettings;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class HttpClientBuilder {
|
||||
|
||||
private final HttpClientSettings httpClientSettings;
|
||||
private String url;
|
||||
|
||||
public HttpClientBuilder(String url, HttpClientSettings httpClientSettings) {
|
||||
this.httpClientSettings = httpClientSettings;
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public HttpClientBuilder(String url) {
|
||||
httpClientSettings = new HttpClientSettings();
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withHttpClientSettings(Consumer<HttpClientSettings> consumer) {
|
||||
consumer.accept(httpClientSettings);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withCookie(String name, String value) {
|
||||
httpClientSettings.getCookies().put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withHeader(String name, String value) {
|
||||
httpClientSettings.getHeaders().put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withParam(String name, String value) {
|
||||
httpClientSettings.getParams().put(name, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withParams(Map<String, String> parameters) {
|
||||
httpClientSettings.getParams().putAll(parameters);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClientBuilder withHeaders(Map<String, String> headers) {
|
||||
httpClientSettings.getHeaders().putAll(headers);
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClient build() {
|
||||
var proxyClientSettings = httpClientSettings.getProxyClientSettings();
|
||||
if (proxyClientSettings.isEnabled() && proxyClientSettings.hasNext())
|
||||
return new HttpProxyClient(httpClientSettings, url);
|
||||
return new HttpClient(httpClientSettings, url);
|
||||
}
|
||||
}
|
||||
@@ -20,34 +20,25 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.tools.collector.tables;
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.*;
|
||||
|
||||
public class ExceptionInfoModel
|
||||
{
|
||||
private String message;
|
||||
private String stackTrace;
|
||||
public class HttpClientFactory {
|
||||
private final LiveClientSettings liveClientSettings;
|
||||
|
||||
public ExceptionInfoModel(Throwable throwable) {
|
||||
this.message = throwable.getMessage();
|
||||
this.stackTrace = getStackTraceAsString(throwable);
|
||||
public HttpClientFactory(LiveClientSettings liveClientSettings) {
|
||||
this.liveClientSettings = liveClientSettings;
|
||||
}
|
||||
|
||||
public static String getStackTraceAsString(Throwable throwable) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
throwable.printStackTrace(pw);
|
||||
return sw.toString();
|
||||
public HttpClientBuilder client(String url) {
|
||||
return new HttpClientBuilder(url, liveClientSettings.getHttpSettings().clone());
|
||||
}
|
||||
|
||||
// Getters for message and stackTrace
|
||||
public String getMessage() {
|
||||
return message;
|
||||
//Does not contains default httpClientSettings, Params, headers, etd
|
||||
public HttpClientBuilder clientEmpty(String url) {
|
||||
var settings = new HttpClientSettings();
|
||||
settings.setProxyClientSettings(liveClientSettings.getHttpSettings().getProxyClientSettings());
|
||||
return new HttpClientBuilder(url, settings);
|
||||
}
|
||||
|
||||
public String getStackTrace() {
|
||||
return stackTrace;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.common.ActionResult;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.*;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.*;
|
||||
|
||||
import javax.net.ssl.*;
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.net.http.*;
|
||||
import java.net.http.HttpResponse.ResponseInfo;
|
||||
import java.security.*;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class HttpProxyClient extends HttpClient {
|
||||
|
||||
private final ProxyClientSettings proxySettings;
|
||||
|
||||
public HttpProxyClient(HttpClientSettings httpClientSettings, String url) {
|
||||
super(httpClientSettings, url);
|
||||
this.proxySettings = httpClientSettings.getProxyClientSettings();
|
||||
}
|
||||
|
||||
public ActionResult<HttpResponse<byte[]>> toResponse() {
|
||||
return switch (proxySettings.getType()) {
|
||||
case HTTP, DIRECT -> handleHttpProxyRequest();
|
||||
default -> handleSocksProxyRequest();
|
||||
};
|
||||
}
|
||||
|
||||
public ActionResult<HttpResponse<byte[]>> handleHttpProxyRequest() {
|
||||
var builder = java.net.http.HttpClient.newBuilder()
|
||||
.followRedirects(java.net.http.HttpClient.Redirect.NORMAL)
|
||||
.cookieHandler(new CookieManager())
|
||||
.connectTimeout(httpClientSettings.getTimeout());
|
||||
|
||||
while (proxySettings.hasNext()) {
|
||||
try {
|
||||
InetSocketAddress address = proxySettings.next().toSocketAddress();
|
||||
builder.proxy(ProxySelector.of(address));
|
||||
|
||||
httpClientSettings.getOnClientCreating().accept(builder);
|
||||
var client = builder.build();
|
||||
var request = prepareGetRequest();
|
||||
|
||||
var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (response.statusCode() != 200)
|
||||
continue;
|
||||
return ActionResult.success(response);
|
||||
} catch (HttpConnectTimeoutException | ConnectException e) {
|
||||
if (proxySettings.isAutoDiscard())
|
||||
proxySettings.remove();
|
||||
throw new TikTokProxyRequestException(e);
|
||||
} catch (IOException e) {
|
||||
if (e.getMessage().contains("503") && proxySettings.isFallback()) // Indicates proxy protocol is not supported
|
||||
return super.toResponse();
|
||||
throw new TikTokProxyRequestException(e);
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException(e);
|
||||
}
|
||||
}
|
||||
throw new TikTokLiveRequestException("No more proxies available!");
|
||||
}
|
||||
|
||||
private ActionResult<HttpResponse<byte[]>> handleSocksProxyRequest() {
|
||||
try {
|
||||
SSLContext sc = SSLContext.getInstance("SSL");
|
||||
sc.init(null, new TrustManager[]{ new X509TrustManager() {
|
||||
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {}
|
||||
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {}
|
||||
public X509Certificate[] getAcceptedIssuers() { return null; }
|
||||
}}, null);
|
||||
|
||||
URL url = toUrl().toURL();
|
||||
|
||||
if (proxySettings.hasNext()) {
|
||||
try {
|
||||
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxySettings.next().toSocketAddress());
|
||||
|
||||
HttpsURLConnection socksConnection = (HttpsURLConnection) url.openConnection(proxy);
|
||||
socksConnection.setSSLSocketFactory(sc.getSocketFactory());
|
||||
socksConnection.setConnectTimeout(httpClientSettings.getTimeout().toMillisPart());
|
||||
socksConnection.setReadTimeout(httpClientSettings.getTimeout().toMillisPart());
|
||||
|
||||
byte[] body = socksConnection.getInputStream().readAllBytes();
|
||||
|
||||
Map<String, List<String>> headers = socksConnection.getHeaderFields()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.filter(entry -> entry.getKey() != null)
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
|
||||
var responseInfo = createResponseInfo(socksConnection.getResponseCode(), headers);
|
||||
|
||||
var response = createHttpResponse(body, toUrl(), responseInfo);
|
||||
|
||||
return ActionResult.success(response);
|
||||
} catch (IOException e) {
|
||||
if (e.getMessage().contains("503") && proxySettings.isFallback()) // Indicates proxy protocol is not supported
|
||||
return super.toResponse();
|
||||
if (proxySettings.isAutoDiscard())
|
||||
proxySettings.remove();
|
||||
throw new TikTokProxyRequestException(e);
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException(e);
|
||||
}
|
||||
}
|
||||
throw new TikTokLiveRequestException("No more proxies available!");
|
||||
} catch (NoSuchAlgorithmException | MalformedURLException | KeyManagementException e) {
|
||||
// Should never be reached!
|
||||
System.out.println("handleSocksProxyRequest: If you see this, message us on discord!");
|
||||
e.printStackTrace();
|
||||
} catch (TikTokLiveRequestException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return ActionResult.failure();
|
||||
}
|
||||
|
||||
private ResponseInfo createResponseInfo(int code, Map<String, List<String>> headers) {
|
||||
return new ResponseInfo() {
|
||||
@Override
|
||||
public int statusCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders headers() {
|
||||
return HttpHeaders.of(headers, (s, s1) -> s != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.net.http.HttpClient.Version version() {
|
||||
return java.net.http.HttpClient.Version.HTTP_2;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private HttpResponse<byte[]> createHttpResponse(byte[] body,
|
||||
URI uri,
|
||||
ResponseInfo info) {
|
||||
return new HttpResponse<>()
|
||||
{
|
||||
@Override
|
||||
public int statusCode() {
|
||||
return info.statusCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpRequest request() {
|
||||
throw new UnsupportedOperationException("TODO");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<HttpResponse<byte[]>> previousResponse() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders headers() {
|
||||
return info.headers();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] body() {
|
||||
return body;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SSLSession> sslSession() {
|
||||
throw new UnsupportedOperationException("TODO");
|
||||
}
|
||||
|
||||
@Override
|
||||
public URI uri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.net.http.HttpClient.Version version() {
|
||||
return info.version();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpUtils
|
||||
{
|
||||
public static String parseParameters(String url, Map<String,Object> parameters)
|
||||
{
|
||||
var parameterString = "";
|
||||
if (!parameters.isEmpty()) {
|
||||
var builder = new StringBuilder();
|
||||
builder.append("?");
|
||||
var first = false;
|
||||
for (var param : parameters.entrySet()) {
|
||||
|
||||
if (first) {
|
||||
builder.append("&");
|
||||
}
|
||||
builder.append(param.getKey()).append("=").append(param.getValue());
|
||||
first = true;
|
||||
}
|
||||
parameterString = builder.toString();
|
||||
}
|
||||
|
||||
return url+parameterString;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public static String parseParametersEncode(String url, Map<String,Object> parameters)
|
||||
{
|
||||
|
||||
var parameterString = "";
|
||||
if (!parameters.isEmpty()) {
|
||||
var builder = new StringBuilder();
|
||||
builder.append("?");
|
||||
var first = false;
|
||||
for (var param : parameters.entrySet()) {
|
||||
|
||||
if (first) {
|
||||
builder.append("&");
|
||||
}
|
||||
|
||||
final String encodedKey = URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8);
|
||||
final String encodedValue = URLEncoder.encode(param.getValue().toString(), StandardCharsets.UTF_8);
|
||||
builder.append(encodedKey).append("=").append(encodedValue);
|
||||
first = true;
|
||||
}
|
||||
parameterString = builder.toString();
|
||||
}
|
||||
|
||||
return url+parameterString;
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveOfflineHostException;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
|
||||
import io.github.jwdeveloper.tiktok.mappers.LiveRoomMetaMapper;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class TikTokApiService {
|
||||
private final TikTokHttpClient tiktokHttpClient;
|
||||
private final Logger logger;
|
||||
private final ClientSettings clientSettings;
|
||||
|
||||
public TikTokApiService(TikTokHttpClient apiClient, Logger logger, ClientSettings clientSettings) {
|
||||
this.tiktokHttpClient = apiClient;
|
||||
this.logger = logger;
|
||||
this.clientSettings = clientSettings;
|
||||
}
|
||||
|
||||
|
||||
public void updateSessionId() {
|
||||
if (clientSettings.getSessionId() == null) {
|
||||
return;
|
||||
}
|
||||
if (clientSettings.getSessionId().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
tiktokHttpClient.setSessionId(clientSettings.getSessionId());
|
||||
}
|
||||
|
||||
public String fetchRoomId(String userName) {
|
||||
var roomId = fetchRoomIdFromTiktokApi(userName);
|
||||
clientSettings.getClientParameters().put("room_id", roomId);
|
||||
logger.info("RoomID -> " + roomId);
|
||||
return roomId;
|
||||
}
|
||||
|
||||
private String fetchRoomIdFromTikTokPage(String userName)
|
||||
{
|
||||
/* var roomId = RequestChain.<String>create()
|
||||
.then(() -> fetchRoomIdFromTikTokPage(userName))
|
||||
.then(() -> fetchRoomIdFromTiktokApi(userName))
|
||||
.run();*/
|
||||
logger.info("Fetching room ID");
|
||||
String html;
|
||||
try {
|
||||
html = tiktokHttpClient.getLivestreamPage(userName);
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException("Failed to fetch room id from WebCast, see stacktrace for more info.", e);
|
||||
}
|
||||
|
||||
var firstPattern = Pattern.compile("room_id=([0-9]*)");
|
||||
var firstMatcher = firstPattern.matcher(html);
|
||||
var id = "";
|
||||
|
||||
if (firstMatcher.find()) {
|
||||
id = firstMatcher.group(1);
|
||||
} else {
|
||||
var secondPattern = Pattern.compile("\"roomId\":\"([0-9]*)\"");
|
||||
var secondMatcher = secondPattern.matcher(html);
|
||||
|
||||
if (secondMatcher.find()) {
|
||||
id = secondMatcher.group(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (id.isEmpty()) {
|
||||
throw new TikTokLiveOfflineHostException("Unable to fetch room ID, live host could be offline or name is misspelled");
|
||||
}
|
||||
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private String fetchRoomIdFromTiktokApi(String userName) {
|
||||
|
||||
var params = new HashMap<>(clientSettings.getClientParameters());
|
||||
params.put("uniqueId", userName);
|
||||
params.put("sourceType", 54);
|
||||
var roomData = tiktokHttpClient.getJsonFromTikTokApi("api-live/user/room/", params);
|
||||
|
||||
var data = roomData.getAsJsonObject("data");
|
||||
var user =data.getAsJsonObject("user");
|
||||
var roomId = user.get("roomId").getAsString();
|
||||
|
||||
|
||||
return roomId;
|
||||
}
|
||||
|
||||
|
||||
public LiveRoomMeta fetchRoomInfo() {
|
||||
logger.info("Fetching RoomInfo");
|
||||
try {
|
||||
var response = tiktokHttpClient.getJsonFromWebcastApi("room/info/", clientSettings.getClientParameters());
|
||||
var mapper = new LiveRoomMetaMapper();
|
||||
var liveRoomMeta = mapper.map(response);
|
||||
logger.info("RoomInfo status -> " + liveRoomMeta.getStatus());
|
||||
return liveRoomMeta;
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException("Failed to fetch room info from WebCast, see stacktrace for more info.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public WebcastResponse fetchClientData() {
|
||||
|
||||
logger.info("Fetching ClientData");
|
||||
try {
|
||||
var response = tiktokHttpClient.getSigningServerResponse("im/fetch/", clientSettings.getClientParameters());
|
||||
clientSettings.getClientParameters().put("cursor", response.getCursor());
|
||||
clientSettings.getClientParameters().put("internal_ext", response.getInternalExt());
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException("Failed to fetch client data", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class TikTokDataChecker
|
||||
{
|
||||
|
||||
public CompletableFuture<Boolean> isOnlineAsync(String hostName) {
|
||||
return CompletableFuture.supplyAsync(() -> isOnline(hostName));
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> isHostNameValidAsync(String hostName) {
|
||||
return CompletableFuture.supplyAsync(() -> isOnline(hostName));
|
||||
}
|
||||
|
||||
public boolean isOnline(String hostName) {
|
||||
var factory = new TikTokHttpRequestFactory(new TikTokCookieJar());
|
||||
var url = getLiveUrl(hostName);
|
||||
try {
|
||||
var response = factory.get(url);
|
||||
var titleContent = extractTitleContent(response);
|
||||
return isTitleLiveOnline(titleContent);
|
||||
} catch (Exception e)
|
||||
{
|
||||
throw new TikTokLiveRequestException("Unable to make check live online request",e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isHostNameValid(String hostName) {
|
||||
var factory = new TikTokHttpRequestFactory(new TikTokCookieJar());
|
||||
var url = getProfileUrl(hostName);
|
||||
try {
|
||||
var response = factory.get(url);
|
||||
var titleContent = extractTitleContent(response);
|
||||
return isTitleHostNameValid(titleContent, hostName);
|
||||
} catch (Exception e)
|
||||
{
|
||||
throw new TikTokLiveRequestException("Unable to make check host name valid request",e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isTitleLiveOnline(String title) {
|
||||
return title.contains("is LIVE");
|
||||
}
|
||||
|
||||
private boolean isTitleHostNameValid(String title, String hostName)
|
||||
{
|
||||
return title.contains(hostName);
|
||||
}
|
||||
|
||||
private String extractTitleContent(String html) {
|
||||
var regex = "<title\\b[^>]*>(.*?)<\\/title>";
|
||||
var pattern = Pattern.compile(regex);
|
||||
var matcher = pattern.matcher(html);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(1);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private String getLiveUrl(String hostName) {
|
||||
var sb = new StringBuilder();
|
||||
sb.append("https://www.tiktok.com/@");
|
||||
sb.append(hostName);
|
||||
sb.append("/live");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String getProfileUrl(String hostName) {
|
||||
var sb = new StringBuilder();
|
||||
sb.append("https://www.tiktok.com/@");
|
||||
sb.append(hostName);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.github.jwdeveloper.tiktok.Constants;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class TikTokHttpClient {
|
||||
private final TikTokHttpRequestFactory requestFactory;
|
||||
private final TikTokCookieJar tikTokCookieJar;
|
||||
|
||||
public TikTokHttpClient(TikTokCookieJar tikTokCookieJar, TikTokHttpRequestFactory requestFactory) {
|
||||
this.requestFactory = requestFactory;
|
||||
this.tikTokCookieJar = tikTokCookieJar;
|
||||
}
|
||||
|
||||
public void setSessionId(String sessionId)
|
||||
{
|
||||
tikTokCookieJar.set("sessionid", sessionId);
|
||||
tikTokCookieJar.set("sessionid_ss", sessionId);
|
||||
tikTokCookieJar.set("sid_tt", sessionId);
|
||||
}
|
||||
|
||||
|
||||
public String getLivestreamPage(String userName) {
|
||||
|
||||
var url = Constants.TIKTOK_URL_WEB + "@" + userName + "/live/";
|
||||
var get = getRequest(url, null);
|
||||
return get;
|
||||
}
|
||||
|
||||
public JsonObject getJsonFromTikTokApi(String path, Map<String,Object> params)
|
||||
{
|
||||
var get = getRequest(Constants.TIKTOK_URL_WEB + path, params);
|
||||
var json = JsonParser.parseString(get);
|
||||
var jsonObject = json.getAsJsonObject();
|
||||
return jsonObject;
|
||||
}
|
||||
|
||||
public JsonObject getJsonFromWebcastApi(String path, Map<String, Object> parameters) {
|
||||
var get = getRequest(Constants.TIKTOK_URL_WEBCAST + path, parameters);
|
||||
var json = JsonParser.parseString(get);
|
||||
var jsonObject = json.getAsJsonObject();
|
||||
return jsonObject;
|
||||
}
|
||||
|
||||
public WebcastResponse getSigningServerResponse(String path, Map<String, Object> parameters) {
|
||||
var bytes = getSignRequest(Constants.TIKTOK_URL_WEBCAST + path, parameters);
|
||||
try {
|
||||
return WebcastResponse.parseFrom(bytes);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new TikTokLiveRequestException("Unable to deserialize message: "+path,e);
|
||||
}
|
||||
}
|
||||
|
||||
private String postRequest(String url, Map<String, Object> parameters) {
|
||||
if (parameters == null) {
|
||||
parameters = new HashMap<>();
|
||||
}
|
||||
System.out.println("RomMID: "+parameters.get("room_id"));
|
||||
var request = requestFactory.setQueries(parameters);
|
||||
return request.post(url);
|
||||
}
|
||||
|
||||
private String getRequest(String url, Map<String, Object> parameters) {
|
||||
if (parameters == null) {
|
||||
parameters = new HashMap<>();
|
||||
}
|
||||
|
||||
var request = requestFactory.setQueries(parameters);
|
||||
return request.get(url);
|
||||
}
|
||||
private byte[] getSignRequest(String url, Map<String, Object> parameters) {
|
||||
url = getSignedUrl(url, parameters);
|
||||
try {
|
||||
var client = HttpClient.newHttpClient();
|
||||
var request = HttpRequest.newBuilder()
|
||||
.uri(new URI(url))
|
||||
.build();
|
||||
var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
|
||||
var cookies = response.headers().allValues("Set-Cookie");
|
||||
for(var cookie : cookies)
|
||||
{
|
||||
var split = cookie.split(";")[0].split("=");
|
||||
|
||||
|
||||
var key = split[0];
|
||||
var value = split[1];
|
||||
tikTokCookieJar.set(key, value);
|
||||
}
|
||||
|
||||
return response.body();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new TikTokLiveRequestException("Unable to send signature");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String getSignedUrl(String url, Map<String, Object> parameters) {
|
||||
|
||||
var fullUrl = HttpUtils.parseParameters(url,parameters);
|
||||
var signParams = new TreeMap<String,Object>();
|
||||
signParams.put("client", "ttlive-java");
|
||||
signParams.put("uuc", 1);
|
||||
signParams.put("url", fullUrl);
|
||||
|
||||
var request = requestFactory.setQueries(signParams);
|
||||
var content = request.get(Constants.TIKTOK_SIGN_API);
|
||||
|
||||
|
||||
try {
|
||||
var json = JsonParser.parseString(content);
|
||||
var jsonObject = json.getAsJsonObject();
|
||||
var signedUrl = jsonObject.get("signedUrl").getAsString();
|
||||
var userAgent = jsonObject.get("User-Agent").getAsString();
|
||||
|
||||
requestFactory.setAgent(userAgent);
|
||||
return signedUrl;
|
||||
} catch (Exception e) {
|
||||
throw new TikTokLiveRequestException("Insufficient values have been supplied for signing. Likely due to an update. Post an issue on GitHub.", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.Constants;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
import java.net.CookieManager;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class TikTokHttpRequestFactory implements TikTokHttpRequest {
|
||||
private final CookieManager cookieManager;
|
||||
private final Map<String, String> defaultHeaders;
|
||||
private final TikTokCookieJar tikTokCookieJar;
|
||||
private final HttpClient client;
|
||||
private String query;
|
||||
|
||||
public TikTokHttpRequestFactory(TikTokCookieJar tikTokCookieJar) {
|
||||
this.tikTokCookieJar = tikTokCookieJar;
|
||||
this.cookieManager = new CookieManager();
|
||||
defaultHeaders = Constants.DefaultRequestHeaders();
|
||||
client = HttpClient.newBuilder()
|
||||
.cookieHandler(cookieManager)
|
||||
.connectTimeout(Duration.ofSeconds(2))
|
||||
.build();
|
||||
}
|
||||
@SneakyThrows
|
||||
public String get(String url) {
|
||||
var uri = URI.create(url);
|
||||
var requestBuilder = HttpRequest.newBuilder().GET();
|
||||
|
||||
for (var header : defaultHeaders.entrySet())
|
||||
{
|
||||
if(header.getKey().equals("Connection") || header.getKey().equals("Accept-Encoding"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
requestBuilder.setHeader(header.getKey(), header.getValue());
|
||||
}
|
||||
if (query != null) {
|
||||
var baseUri = uri.toString();
|
||||
var requestUri = URI.create(baseUri + "?" + query);
|
||||
requestBuilder.uri(requestUri);
|
||||
}
|
||||
else
|
||||
{
|
||||
requestBuilder.uri(uri);
|
||||
}
|
||||
|
||||
var result = requestBuilder.build();
|
||||
|
||||
return getContent(result);
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public String post(String url) {
|
||||
var uri = URI.create(url);
|
||||
var request = HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(""));
|
||||
for (var header : defaultHeaders.entrySet())
|
||||
{
|
||||
if(header.getKey().equals("Connection"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
request.setHeader(header.getKey(), header.getValue());
|
||||
}
|
||||
request.setHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
|
||||
request.setHeader("Cookie", tikTokCookieJar.parseCookies());
|
||||
|
||||
|
||||
if (query != null) {
|
||||
var baseUri = uri.toString();
|
||||
var requestUri = URI.create(baseUri + "?" + query);
|
||||
request.uri(requestUri);
|
||||
System.out.println(requestUri.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
return getContent(request.build());
|
||||
}
|
||||
|
||||
public TikTokHttpRequest setHeader(String key, String value) {
|
||||
defaultHeaders.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokHttpRequest setAgent(String value) {
|
||||
defaultHeaders.put("User-Agent", value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public TikTokHttpRequest setQueries(Map<String, Object> queries) {
|
||||
if (queries == null)
|
||||
return this;
|
||||
var testMap = new TreeMap<String,Object>(queries);
|
||||
query = String.join("&", testMap.entrySet().stream().map(x ->
|
||||
{
|
||||
var key = x.getKey();
|
||||
var value = "";
|
||||
try {
|
||||
value = URLEncoder.encode(x.getValue().toString(), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return key + "=" + value;
|
||||
}).toList());
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
private String getContent(HttpRequest request) throws Exception {
|
||||
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() == 404) {
|
||||
throw new TikTokLiveRequestException("Request responded with 404 NOT_FOUND");
|
||||
}
|
||||
|
||||
if (response.statusCode() != 200) {
|
||||
throw new TikTokLiveRequestException("Request was unsuccessful " + response.statusCode());
|
||||
}
|
||||
|
||||
var cookies = response.headers().allValues("Set-Cookie");
|
||||
for (var cookie : cookies) {
|
||||
var split = cookie.split(";")[0].split("=");
|
||||
var uri = request.uri();
|
||||
|
||||
|
||||
var key = split[0];
|
||||
var value = split[1];
|
||||
tikTokCookieJar.set(key, value);
|
||||
|
||||
var map = new HashMap<String, List<String>>();
|
||||
map.put(key, List.of(value));
|
||||
cookieManager.put(uri, map);
|
||||
|
||||
}
|
||||
return response.body();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http.mappers;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.GiftsData;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class GiftsDataMapper {
|
||||
public GiftsData.Response map(String json) {
|
||||
var parsedJson = JsonParser.parseString(json);
|
||||
var jsonObject = parsedJson.getAsJsonObject();
|
||||
var gifts = jsonObject.entrySet()
|
||||
.parallelStream()
|
||||
.map(e -> mapSingleGift(e.getValue()))
|
||||
.toList();
|
||||
|
||||
return new GiftsData.Response(json, gifts);
|
||||
}
|
||||
|
||||
|
||||
private Gift mapSingleGift(JsonElement jsonElement) {
|
||||
var jsonObject = jsonElement.getAsJsonObject();
|
||||
|
||||
var id = jsonObject.get("id").getAsInt();
|
||||
var name = jsonObject.get("name").getAsString();
|
||||
var diamondCost = jsonObject.get("diamondCost").getAsInt();
|
||||
var image = jsonObject.get("image").getAsString();
|
||||
return new Gift(id, name, diamondCost, new Picture(image), jsonObject);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http.mappers;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.github.jwdeveloper.tiktok.TikTokLiveHttpClient;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.UserAttribute;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class LiveDataMapper {
|
||||
/**
|
||||
* 0 - Unknown
|
||||
* 1 - ?
|
||||
* 2 - Online
|
||||
* 3 - ?
|
||||
* 4 - Offline
|
||||
*/
|
||||
public LiveData.Response map(String json) {
|
||||
var response = new LiveData.Response();
|
||||
|
||||
response.setJson(json);
|
||||
|
||||
var parsedJson = JsonParser.parseString(json);
|
||||
var jsonObject = parsedJson.getAsJsonObject();
|
||||
|
||||
|
||||
if (!jsonObject.has("data")) {
|
||||
throw new TikTokLiveRequestException("Data section not found in LiveData.Response");
|
||||
}
|
||||
var data = jsonObject.getAsJsonObject("data");
|
||||
|
||||
|
||||
if (data.has("status")) {
|
||||
var status = data.get("status");
|
||||
var statusId = status.getAsInt();
|
||||
var statusValue = switch (statusId) {
|
||||
case 2 -> LiveData.LiveStatus.HostOnline;
|
||||
case 4 -> LiveData.LiveStatus.HostOffline;
|
||||
default -> LiveData.LiveStatus.HostNotFound;
|
||||
};
|
||||
response.setLiveStatus(statusValue);
|
||||
} else if (data.has("prompts") && jsonObject.has("status_code") &&
|
||||
data.get("prompts").getAsString().isEmpty() && jsonObject.get("status_code").isJsonPrimitive()) {
|
||||
response.setAgeRestricted(jsonObject.get("status_code").getAsInt() == TikTokLiveHttpClient.TIKTOK_AGE_RESTRICTED_CODE);
|
||||
} else {
|
||||
response.setLiveStatus(LiveData.LiveStatus.HostNotFound);
|
||||
}
|
||||
|
||||
if (data.has("age_restricted")) {
|
||||
var element = data.getAsJsonObject("age_restricted");
|
||||
var restricted = element.get("restricted").getAsBoolean();
|
||||
response.setAgeRestricted(restricted);
|
||||
}
|
||||
|
||||
if (data.has("title")) {
|
||||
var element = data.get("title");
|
||||
var title = element.getAsString();
|
||||
response.setTitle(title);
|
||||
}
|
||||
|
||||
if (data.has("stats")) {
|
||||
var statsElement = data.getAsJsonObject("stats");
|
||||
var likeElement = statsElement.get("like_count");
|
||||
var likes = likeElement.getAsInt();
|
||||
|
||||
var titalUsersElement = statsElement.get("total_user");
|
||||
var totalUsers = titalUsersElement.getAsInt();
|
||||
|
||||
|
||||
response.setLikes(likes);
|
||||
response.setTotalViewers(totalUsers);
|
||||
}
|
||||
|
||||
if (data.has("user_count")) {
|
||||
var element = data.get("user_count");
|
||||
var viewers = element.getAsInt();
|
||||
response.setViewers(viewers);
|
||||
}
|
||||
|
||||
if (data.has("owner")) {
|
||||
var element = data.getAsJsonObject("owner");
|
||||
var user = getUser(element);
|
||||
response.setHost(user);
|
||||
}
|
||||
|
||||
if (data.has("link_mic")) {
|
||||
var element = data.getAsJsonObject("link_mic");
|
||||
var multi_live = element.get("multi_live_enum").getAsInt();
|
||||
var rival_id = element.get("rival_anchor_id").getAsInt();
|
||||
var battle_scores = element.get("battle_scores").getAsJsonArray();
|
||||
if (multi_live == 1) {
|
||||
if (!battle_scores.isEmpty())
|
||||
response.setLiveType(LiveData.LiveType.BATTLE);
|
||||
else if (rival_id != 0)
|
||||
response.setLiveType(LiveData.LiveType.CO_HOST);
|
||||
else
|
||||
response.setLiveType(LiveData.LiveType.BOX);
|
||||
} else
|
||||
response.setLiveType(LiveData.LiveType.SOLO);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public User getUser(JsonObject jsonElement) {
|
||||
var id = jsonElement.get("id").getAsLong();
|
||||
var name = jsonElement.get("display_id").getAsString();
|
||||
var profileName = jsonElement.get("nickname").getAsString();
|
||||
|
||||
|
||||
var followElement = jsonElement.getAsJsonObject("follow_info");
|
||||
var followers = followElement.get("follower_count").getAsInt();
|
||||
var followingCount = followElement.get("following_count").getAsInt();
|
||||
|
||||
|
||||
var pictureElement = jsonElement.getAsJsonObject("avatar_large");
|
||||
var link = pictureElement.getAsJsonArray("url_list").get(1).getAsString();
|
||||
var picture = new Picture(link);
|
||||
|
||||
var user = new User(id, name, profileName, picture, followers, followingCount, new ArrayList<>());
|
||||
user.addAttribute(UserAttribute.LiveHost);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http.mappers;
|
||||
|
||||
import com.google.gson.*;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class LiveUserDataMapper
|
||||
{
|
||||
public LiveUserData.Response map(String json, Logger logger) {
|
||||
try {
|
||||
var jsonObject = JsonParser.parseString(json).getAsJsonObject();
|
||||
|
||||
var message = jsonObject.get("message").getAsString();
|
||||
|
||||
if (message.equals("params_error")) {
|
||||
throw new TikTokLiveRequestException("fetchRoomIdFromTiktokApi -> Unable to fetch roomID, contact the developer");
|
||||
}
|
||||
if (message.equals("user_not_found")) {
|
||||
return new LiveUserData.Response(json, LiveUserData.UserStatus.NotFound, "", -1);
|
||||
}
|
||||
//live -> status 2
|
||||
//live paused -> 3
|
||||
//not live -> status 4
|
||||
var element = jsonObject.get("data");
|
||||
if (element.isJsonNull()) {
|
||||
return new LiveUserData.Response(json, LiveUserData.UserStatus.NotFound, "", -1);
|
||||
}
|
||||
var data = element.getAsJsonObject();
|
||||
var user = data.getAsJsonObject("user");
|
||||
var roomId = user.get("roomId").getAsString();
|
||||
var status = user.get("status").getAsInt();
|
||||
|
||||
var liveRoom = data.getAsJsonObject("liveRoom");
|
||||
long startTime = liveRoom.get("startTime").getAsLong();
|
||||
|
||||
var statusEnum = switch (status) {
|
||||
case 2 -> LiveUserData.UserStatus.Live;
|
||||
case 3 -> LiveUserData.UserStatus.LivePaused;
|
||||
case 4 -> LiveUserData.UserStatus.Offline;
|
||||
default -> LiveUserData.UserStatus.NotFound;
|
||||
};
|
||||
|
||||
return new LiveUserData.Response(json, statusEnum, roomId, startTime);
|
||||
} catch (JsonSyntaxException e) {
|
||||
logger.warning("Malformed Json: '"+json+"' - Error Message: "+e.getMessage());
|
||||
return new LiveUserData.Response(json, LiveUserData.UserStatus.NotFound, "", -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,11 @@
|
||||
package io.github.jwdeveloper.tiktok.listener;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.TikTokEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.TikTokLiveEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.annotations.TikTokEventObserver;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokEventListenerMethodException;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.live.builder.EventConsumer;
|
||||
|
||||
@@ -37,10 +37,10 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class TikTokListenersManager implements ListenersManager {
|
||||
private final TikTokEventObserver eventObserver;
|
||||
private final TikTokLiveEventHandler eventObserver;
|
||||
private final List<ListenerBindingModel> bindingModels;
|
||||
|
||||
public TikTokListenersManager(List<TikTokEventListener> listeners, TikTokEventObserver tikTokEventHandler) {
|
||||
public TikTokListenersManager(List<TikTokEventListener> listeners, TikTokLiveEventHandler tikTokEventHandler) {
|
||||
this.eventObserver = tikTokEventHandler;
|
||||
this.bindingModels = new ArrayList<>(listeners.size());
|
||||
for (var listener : listeners) {
|
||||
@@ -93,7 +93,7 @@ public class TikTokListenersManager implements ListenersManager {
|
||||
var clazz = listener.getClass();
|
||||
var methods = Arrays.stream(clazz.getDeclaredMethods()).filter(m ->
|
||||
m.getParameterCount() == 2 &&
|
||||
m.isAnnotationPresent(TikTokEventHandler.class)).toList();
|
||||
m.isAnnotationPresent(TikTokEventObserver.class)).toList();
|
||||
var eventsMap = new HashMap<Class<?>, List<EventConsumer<?>>>();
|
||||
for (var method : methods) {
|
||||
var eventClazz = method.getParameterTypes()[1];
|
||||
@@ -111,13 +111,14 @@ public class TikTokListenersManager implements ListenersManager {
|
||||
EventConsumer eventMethodRef = (liveClient, event) ->
|
||||
{
|
||||
try {
|
||||
method.setAccessible(true);
|
||||
method.invoke(listener, liveClient, event);
|
||||
} catch (Exception e) {
|
||||
throw new TikTokEventListenerMethodException(e);
|
||||
}
|
||||
};
|
||||
eventsMap.computeIfAbsent(eventClazz, (a) -> new ArrayList<EventConsumer<?>>()).add(eventMethodRef);
|
||||
eventsMap.computeIfAbsent(eventClazz, (a) -> new ArrayList<>()).add(eventMethodRef);
|
||||
}
|
||||
return new ListenerBindingModel(listener, eventsMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.mappers;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
|
||||
|
||||
public class LiveRoomMetaMapper {
|
||||
/**
|
||||
* 0 - Unknown
|
||||
* 1 - ?
|
||||
* 2 - Online
|
||||
* 3 - ?
|
||||
* 4 - Offline
|
||||
*/
|
||||
public LiveRoomMeta map(JsonObject input) {
|
||||
var liveRoomMeta = new LiveRoomMeta();
|
||||
|
||||
if (!input.has("data")) {
|
||||
return liveRoomMeta;
|
||||
}
|
||||
var data = input.getAsJsonObject("data");
|
||||
|
||||
|
||||
if (data.has("status")) {
|
||||
var status = data.get("status");
|
||||
var statusId = status.getAsInt();
|
||||
var statusValue = switch (statusId) {
|
||||
case 0 -> LiveRoomMeta.LiveRoomStatus.HostNotFound;
|
||||
case 2 -> LiveRoomMeta.LiveRoomStatus.HostOnline;
|
||||
case 4 -> LiveRoomMeta.LiveRoomStatus.HostOffline;
|
||||
default-> LiveRoomMeta.LiveRoomStatus.HostNotFound;
|
||||
};
|
||||
liveRoomMeta.setStatus(statusValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
liveRoomMeta.setStatus(LiveRoomMeta.LiveRoomStatus.HostNotFound);
|
||||
}
|
||||
|
||||
if (data.has("age_restricted")) {
|
||||
var element = data.getAsJsonObject("age_restricted");
|
||||
var restricted = element.get("restricted").getAsBoolean();
|
||||
liveRoomMeta.setAgeRestricted(restricted);
|
||||
}
|
||||
return liveRoomMeta;
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ public class TikTokGenericEventMapper {
|
||||
}
|
||||
}
|
||||
|
||||
private Method getParsingMethod(Class<?> input) throws NoSuchMethodException {
|
||||
public Method getParsingMethod(Class<?> input) throws NoSuchMethodException {
|
||||
if (methodCache.containsKey(input)) {
|
||||
return methodCache.get(input);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user