mirror of
https://github.com/jwdeveloper/TikTokLiveJava.git
synced 2026-02-27 08:49:40 -05:00
Compare commits
131 Commits
1.0.10-Rel
...
1.5.3-Rele
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
786c24d267 | ||
|
|
966d2f65d8 | ||
|
|
7ba7143f5a | ||
|
|
92fde03f2b | ||
|
|
e058290118 | ||
|
|
d25741b229 | ||
|
|
560a8d7c3b | ||
|
|
6178bc25cf | ||
|
|
48d1138754 | ||
|
|
a5320db820 | ||
|
|
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 |
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.9-Release</version>
|
||||
<version>1.5.2-Release</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>API</artifactId>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -47,11 +47,23 @@ public class TikTokCommentEvent extends TikTokHeaderEvent {
|
||||
|
||||
public TikTokCommentEvent(WebcastChatMessage msg) {
|
||||
super(msg.getCommon());
|
||||
user = User.map(msg.getUser(),msg.getUserIdentity());
|
||||
user = User.map(msg.getUser(), msg.getUserIdentity());
|
||||
text = msg.getContent();
|
||||
visibleToSender = msg.getVisibleToSender();
|
||||
getUserLanguage = msg.getContentLanguage();
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -36,10 +36,10 @@ import lombok.Getter;
|
||||
*/
|
||||
@Getter
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokSubscribeEvent extends TikTokHeaderEvent
|
||||
{
|
||||
public class TikTokSubscribeEvent extends TikTokHeaderEvent {
|
||||
private final User user;
|
||||
|
||||
|
||||
public TikTokSubscribeEvent(WebcastMemberMessage msg) {
|
||||
super(msg.getCommon());
|
||||
user = User.map(msg.getUser());
|
||||
@@ -52,4 +52,11 @@ public class TikTokSubscribeEvent extends TikTokHeaderEvent
|
||||
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,24 +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.tools.db.tables;
|
||||
package io.github.jwdeveloper.tiktok.data.events.control;
|
||||
|
||||
import lombok.Data;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
|
||||
@Data
|
||||
public class TikTokDataTable
|
||||
|
||||
/**
|
||||
* Triggered when client is connecting to live is successfully established.
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Control)
|
||||
public class TikTokConnectingEvent extends TikTokLiveClientEvent
|
||||
{
|
||||
private Integer id;
|
||||
|
||||
private String sessionTag;
|
||||
|
||||
private String tiktokUser;
|
||||
|
||||
private String dataType;
|
||||
|
||||
private String dataTypeName;
|
||||
|
||||
private String content;
|
||||
|
||||
private String createdAt;
|
||||
}
|
||||
@@ -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,18 +23,14 @@
|
||||
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.Picture;
|
||||
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.gifts.*;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
|
||||
/**
|
||||
* Triggered when user sends gifts that has
|
||||
@@ -49,11 +45,31 @@ public class TikTokGiftEvent extends TikTokHeaderEvent {
|
||||
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());
|
||||
toUser = new User(msg.getUserGiftReciever().getUserId(), "", "", new Picture(""), 0, 0, new ArrayList<>());
|
||||
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, ""));
|
||||
}
|
||||
}
|
||||
@@ -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.events.http;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
|
||||
@@ -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.tools.collector.api;
|
||||
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;
|
||||
|
||||
public interface DataFilters<T> {
|
||||
T addMessageFilter(Class<? extends com.google.protobuf.GeneratedMessageV3> message);
|
||||
|
||||
T addMessageFilter(String message);
|
||||
|
||||
T addEventFilter(Class<? extends TikTokEvent> event);
|
||||
|
||||
T addEventFilter(String event);
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@EventMeta(eventType = EventType.Debug)
|
||||
public class TikTokRoomDataResponseEvent extends TikTokEvent
|
||||
{
|
||||
private final LiveData.Response liveData;
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 + "'}";
|
||||
}
|
||||
}
|
||||
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
@@ -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.http;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@@ -43,13 +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);
|
||||
}
|
||||
@@ -106,7 +105,6 @@ public class User {
|
||||
this.following = following;
|
||||
this.followers = followers;
|
||||
this.badges = badges;
|
||||
this.attributes = new HashSet<>();
|
||||
}
|
||||
|
||||
public User(Long id,
|
||||
@@ -123,14 +121,12 @@ public class User {
|
||||
this.following = following;
|
||||
this.followers = followers;
|
||||
this.badges = badges;
|
||||
this.attributes = new HashSet<>();
|
||||
}
|
||||
|
||||
public User(Long userId,
|
||||
String nickName) {
|
||||
this.id = userId;
|
||||
this.name = nickName;
|
||||
this.attributes = new HashSet<>();
|
||||
}
|
||||
|
||||
public User(Long userId,
|
||||
@@ -213,4 +209,4 @@ public class User {
|
||||
0,
|
||||
List.of(Badge.empty()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,17 +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.live;
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
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 lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TrackedUser
|
||||
public class GiftsData
|
||||
{
|
||||
List<TikTokEvent> getInvokedEvents();
|
||||
List<Gift> getGifs();
|
||||
User getUserData();
|
||||
@Getter
|
||||
public final class Request
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static final class Response
|
||||
{
|
||||
private String json;
|
||||
private List<Gift> gifts;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,29 +20,28 @@
|
||||
* 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.messages.webcast.WebcastResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
|
||||
@Data
|
||||
public class EventGeneratorSettings
|
||||
{
|
||||
private String inputDictionary;
|
||||
public class LiveConnectionData {
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Request {
|
||||
private String roomId;
|
||||
}
|
||||
|
||||
private String outputDictionary;
|
||||
private List<String> ignoredFiles = new ArrayList<>();
|
||||
|
||||
private String prefix;
|
||||
|
||||
private String endFix;
|
||||
|
||||
private boolean isTikTokEvent;
|
||||
|
||||
public void addIgnoredClass(String name)
|
||||
{
|
||||
ignoredFiles.add(name);
|
||||
@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
|
||||
}
|
||||
}
|
||||
@@ -20,31 +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.events_generator;
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
public class LiveUserData {
|
||||
|
||||
@Data
|
||||
public class CSharpClassInfo
|
||||
{
|
||||
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));
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Request {
|
||||
private String userName;
|
||||
}
|
||||
|
||||
public void addConstructor(List<FieldInfo> arguments)
|
||||
{
|
||||
this.constructors.add(new ConstructorInfo(arguments));
|
||||
@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 record FieldInfo(String type, String name){};
|
||||
|
||||
public record ConstructorInfo(List<FieldInfo> arguemtns){};
|
||||
}
|
||||
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,44 +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.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
|
||||
*/
|
||||
@@ -104,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,17 +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.tools.tester.mockClient;
|
||||
package io.github.jwdeveloper.tiktok.exceptions;
|
||||
|
||||
public class TikTokLiveMock
|
||||
public class TikTokSignServerException extends TikTokLiveRequestException
|
||||
{
|
||||
public static TikTokMockBuilder create(String host)
|
||||
{
|
||||
return new TikTokMockBuilder(host);
|
||||
public TikTokSignServerException() {
|
||||
}
|
||||
|
||||
public static TikTokMockBuilder create()
|
||||
{
|
||||
return create("MockHostName");
|
||||
public TikTokSignServerException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public TikTokSignServerException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public TikTokSignServerException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -20,72 +20,67 @@
|
||||
* 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.live;
|
||||
|
||||
import lombok.Data;
|
||||
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.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@Data
|
||||
public class ClientSettings {
|
||||
/**
|
||||
* Timeout for Connections
|
||||
*/
|
||||
private Duration timeout;
|
||||
public interface GiftsManager {
|
||||
|
||||
/**
|
||||
* 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 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
|
||||
* You can create and attach your own custom gift to manager
|
||||
*
|
||||
* @param gift
|
||||
*/
|
||||
private String roomId;
|
||||
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();
|
||||
}
|
||||
@@ -57,14 +57,23 @@ public interface LiveClient {
|
||||
|
||||
|
||||
/**
|
||||
* You to manually trigger event
|
||||
* Use to manually invoke event
|
||||
*/
|
||||
void publishEvent(TikTokEvent 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.
|
||||
|
||||
@@ -42,6 +42,7 @@ public interface LiveRoomInfo
|
||||
*/
|
||||
int getTotalViewersCount();
|
||||
int getLikesCount();
|
||||
long getStartTime();
|
||||
boolean isAgeRestricted();
|
||||
String getRoomId();
|
||||
String getHostName();
|
||||
@@ -49,4 +50,4 @@ public interface LiveRoomInfo
|
||||
User getHostUser();
|
||||
List<RankingUser> getUsersRanking();
|
||||
ConnectionState getConnectionState();
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ 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.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.http.TikTokHttpResponseEvent;
|
||||
@@ -149,6 +150,13 @@ public interface EventsBuilder<T> {
|
||||
*/
|
||||
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
|
||||
@@ -215,6 +223,4 @@ public interface EventsBuilder<T> {
|
||||
//T onLinkMicBattle(TikTokEventConsumer<TikTokLinkMicBattleEvent> event);
|
||||
|
||||
//T onUnhandledControl(TikTokEventConsumer<TikTokUnhandledControlEvent> event);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -22,15 +22,13 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live.builder;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
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;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface LiveClientBuilder extends EventsBuilder<LiveClientBuilder> {
|
||||
|
||||
@@ -48,11 +46,11 @@ public interface LiveClientBuilder extends EventsBuilder<LiveClientBuilder> {
|
||||
|
||||
/**
|
||||
* Configuration of client settings
|
||||
* @see ClientSettings
|
||||
* @see LiveClientSettings
|
||||
* @param onConfigure
|
||||
* @return
|
||||
*/
|
||||
LiveClientBuilder configure(Consumer<ClientSettings> onConfigure);
|
||||
LiveClientBuilder configure(Consumer<LiveClientSettings> onConfigure);
|
||||
|
||||
/**
|
||||
* @see TikTokEventListener
|
||||
|
||||
@@ -47,6 +47,9 @@ public interface TikTokMapper {
|
||||
|
||||
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, Function<byte[], TikTokEvent> onMapping);
|
||||
|
||||
TikTokMapperModel forAnyMessage();
|
||||
|
||||
|
||||
boolean isRegistered(String mapperName);
|
||||
|
||||
<T extends GeneratedMessageV3> boolean isRegistered(Class<T> mapperName);
|
||||
|
||||
@@ -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.mappers;
|
||||
|
||||
import com.google.protobuf.GeneratedMessageV3;
|
||||
|
||||
@@ -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.mappers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
|
||||
@@ -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.mappers.data;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
|
||||
@@ -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.mappers.data;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokMapperHelper;
|
||||
|
||||
@@ -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.mappers.data;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
|
||||
@@ -36,6 +36,11 @@ public class 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));
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -976,131 +976,146 @@ message FanTicketRoomNoticeContent {
|
||||
}
|
||||
|
||||
message LinkerAcceptNoticeContent {
|
||||
int64 FromUserId = 1;
|
||||
int64 FromRoomId = 2;
|
||||
int64 ToUserId = 3;
|
||||
int64 fromUserId = 1;
|
||||
int64 fromRoomId = 2;
|
||||
int64 toUserId = 3;
|
||||
}
|
||||
|
||||
message LinkerCancelContent {
|
||||
int64 FromUserId = 1;
|
||||
int64 ToUserId = 2;
|
||||
int64 CancelType = 3;
|
||||
int64 ActionId = 4;
|
||||
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;
|
||||
int64 ownerId = 1;
|
||||
int64 ownerRoomId = 2;
|
||||
int64 linkType = 3;
|
||||
}
|
||||
|
||||
|
||||
|
||||
message LinkerEnterContent {
|
||||
repeated User LinkedUsersList = 1;
|
||||
// LinkmicMultiLiveEnum AnchorMultiLiveEnum = 2;
|
||||
// Data.LinkmicUserSettingInfo AnchorSettingInfo = 3;
|
||||
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;
|
||||
map<int64, string> RtcExtInfoMap = 10;
|
||||
//Data.LinkmicMultiLiveEnum AnchorMultiLiveEnum = 11;
|
||||
//Data.LinkmicUserSettingInfo AnchorSettingInfo = 12;
|
||||
string InviterLinkmicIdStr = 13;
|
||||
// InviteTopHostInfo FromTopHostInfo = 16;
|
||||
int64 ActionId = 17;
|
||||
// repeated LinkmicUserInfo LinkedUsersList = 18;
|
||||
// Data.PerceptionDialogInfo Dialog = 19;
|
||||
// Data.PunishEventInfo PunishInfo = 20;
|
||||
int32 FromRoomAgeRestricted = 21;
|
||||
// Data.Tag FromTag = 22;
|
||||
// repeated Data.CohostABTestSetting AbTestSettingList = 23;
|
||||
// Data.LinkerInviteMessageExtra LinkerInviteMsgExtra = 101;
|
||||
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;
|
||||
//LinkMic.KickoutReason KickoutReason = 2;
|
||||
int64 fromUserId = 1;
|
||||
KickoutReason kickoutReason = 2; // Enum
|
||||
}
|
||||
|
||||
message LinkerLeaveContent {
|
||||
int64 UserId = 1;
|
||||
string LinkmicIdStr = 2;
|
||||
int64 SendLeaveUid = 3;
|
||||
int64 LeaveReason = 4;
|
||||
int64 userId = 1;
|
||||
string linkmicIdStr = 2;
|
||||
int64 sendLeaveUid = 3;
|
||||
int64 leaveReason = 4;
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerLinkedListChangeContent {
|
||||
repeated User LinkedUsersList = 1;
|
||||
|
||||
}
|
||||
//Empty
|
||||
message CohostListChangeContent {
|
||||
}
|
||||
|
||||
|
||||
message LinkerListChangeContent {
|
||||
repeated LinkLayerListUser LinkedUsersList = 1;
|
||||
repeated LinkLayerListUser AppliedUsersList = 2;
|
||||
repeated LinkLayerListUser ConnectingUsersList = 3;
|
||||
repeated ListUser linkedUsersList = 1;
|
||||
repeated ListUser appliedUsersList = 2;
|
||||
repeated ListUser connectingUsersList = 3;
|
||||
}
|
||||
|
||||
message LinkerMediaChangeContent {
|
||||
// MicIdxOperation Op = 1;
|
||||
int64 ToUserId = 2;
|
||||
int64 AnchorId = 3;
|
||||
int64 RoomId = 4;
|
||||
// LinkerSceneType ChangeScene = 5;
|
||||
int64 op = 1; // Enum
|
||||
int64 toUserId = 2;
|
||||
int64 anchorId = 3;
|
||||
int64 roomId = 4;
|
||||
int64 changeScene = 5; // Enum
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerMicIdxUpdateContent {
|
||||
LinkerMicIdxUpdateInfo MicIdxUpdateInfo = 1;
|
||||
|
||||
}
|
||||
|
||||
message LinkerMicIdxUpdateInfo {
|
||||
// MicIdxOperation Op = 1;
|
||||
int64 UserId = 2;
|
||||
int64 MicIdx = 3;
|
||||
}
|
||||
|
||||
message LinkerMuteContent {
|
||||
int64 UserId = 1;
|
||||
// Data.MuteStatus Status = 2;
|
||||
int64 userId = 1;
|
||||
int64 status = 2; // Enum
|
||||
}
|
||||
|
||||
message LinkerRandomMatchContent {
|
||||
User User = 1;
|
||||
int64 RoomId = 2;
|
||||
int64 InviteType = 3;
|
||||
string MatchId = 4;
|
||||
int64 InnerChannelId = 5;
|
||||
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;
|
||||
map<int64, string> RtcExtInfoMap = 11;
|
||||
LinkerMicIdxUpdateInfo InviteeMicIdxUpdateInfo = 12;
|
||||
map<int64, int64> ApplierMicIdxInfoMap = 13;
|
||||
// Data.LinkmicMultiLiveEnum AnchorMultiLiveEnum = 14;
|
||||
// Data.LinkmicUserSettingInfo AnchorSettingInfo = 15;
|
||||
int64 ActionId = 16;
|
||||
// repeated LinkmicUserInfo LinkedUsersList = 17;
|
||||
int64 SourceType = 18;
|
||||
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 {
|
||||
@@ -1113,20 +1128,27 @@ message LinkerSetting {
|
||||
}
|
||||
|
||||
message LinkerSysKickOutContent {
|
||||
int64 UserId = 1;
|
||||
string LinkmicIdStr = 2;
|
||||
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;
|
||||
map<string, string> UpdateInfoMap = 3;
|
||||
int64 fromUserId = 1;
|
||||
int64 toUserId = 2;
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerUpdateUserSettingContent {
|
||||
// Data.LinkmicUserSettingInfo UpdateUserSettingInfo = 1;
|
||||
|
||||
}
|
||||
|
||||
//Empty
|
||||
message LinkerWaitingListChangeContent {
|
||||
|
||||
}
|
||||
|
||||
@@ -241,6 +241,35 @@ enum CommonContentCase {
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
|
||||
@@ -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
|
||||
@@ -68,6 +64,7 @@ message WebcastGiftMessage {
|
||||
int32 repeatCount = 5;
|
||||
int32 comboCount = 6;
|
||||
User user = 7;
|
||||
User toUser = 8;
|
||||
int32 repeatEnd = 9;
|
||||
int64 groupId = 11;
|
||||
int64 incomeTaskgifts = 12;
|
||||
@@ -84,8 +81,8 @@ message WebcastGiftMessage {
|
||||
|
||||
message UserGiftReciever
|
||||
{
|
||||
int64 userId =1;
|
||||
string deviceName = 10;
|
||||
int64 userId = 1;
|
||||
string deviceName = 10;
|
||||
}
|
||||
|
||||
message GiftIMPriority {
|
||||
@@ -203,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
|
||||
@@ -283,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?
|
||||
@@ -354,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
|
||||
@@ -681,7 +678,7 @@ message WebcastMsgDetectMessage {
|
||||
bool detectP2PMsg = 3;
|
||||
bool detectRoomMsg = 4;
|
||||
bool httpOptimize = 5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//@WebcastOecLiveShoppingMessage
|
||||
@@ -732,7 +729,7 @@ message WebcastSystemMessage {
|
||||
//@WebcastLinkMessage
|
||||
message WebcastLinkMessage {
|
||||
Common common = 1;
|
||||
MessageType MessageType = 2;
|
||||
LinkMessageType MessageType = 2;
|
||||
int64 LinkerId = 3;
|
||||
Scene Scene = 4;
|
||||
LinkerInviteContent InviteContent = 5;
|
||||
@@ -751,14 +748,14 @@ message WebcastLinkMessage {
|
||||
LinkerUpdateUserSettingContent UpdateUserSettingContent = 18;
|
||||
LinkerMicIdxUpdateContent MicIdxUpdateContent = 19;
|
||||
LinkerListChangeContent ListChangeContent = 20;
|
||||
// CohostListChangeContent CohostListChangeContent = 21;
|
||||
CohostListChangeContent CohostListChangeContent = 21;
|
||||
LinkerMediaChangeContent MediaChangeContent = 22;
|
||||
LinkerAcceptNoticeContent ReplyAcceptNoticeContent = 23;
|
||||
LinkerSysKickOutContent SysKickOutContent = 101;
|
||||
// LinkmicUserToastContent UserToastContent = 102;
|
||||
string Extra = 200;
|
||||
int64 ExpireTimestamp = 201;
|
||||
string TransferExtra = 202;
|
||||
LinkmicUserToastContent UserToastContent = 102;
|
||||
string extra = 200;
|
||||
int64 expireTimestamp = 201;
|
||||
string transferExtra = 202;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<artifactId>TikTokLiveJava</artifactId>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<version>1.0.9-Release</version>
|
||||
<version>1.5.2-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,69 +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,50 +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.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.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.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;
|
||||
@@ -75,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;
|
||||
});
|
||||
@@ -116,54 +123,92 @@ public class TikTokLiveClient implements LiveClient {
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (liveRoomInfo.hasConnectionState(ConnectionState.DISCONNECTED)) {
|
||||
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());
|
||||
|
||||
if (userData.getUserStatus() == LiveUserData.UserStatus.Offline)
|
||||
throw new TikTokLiveOfflineHostException("User is offline: " + liveRoomInfo.getHostName());
|
||||
|
||||
apiService.updateSessionId();
|
||||
if (userData.getUserStatus() == LiveUserData.UserStatus.NotFound)
|
||||
throw new TikTokLiveOfflineHostException("User not found: " + 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);
|
||||
}
|
||||
var liveDataRequest = new LiveData.Request(userData.getRoomId());
|
||||
var liveData = httpClient.fetchLiveData(liveDataRequest);
|
||||
|
||||
if (liveData.isAgeRestricted())
|
||||
throw new TikTokLiveException("Livestream for " + liveRoomInfo.getHostName() + " is 18+ or age restricted!");
|
||||
|
||||
var liveRoomMeta = apiService.fetchRoomInfo();
|
||||
if (liveRoomMeta.getStatus() == LiveRoomMeta.LiveRoomStatus.HostNotFound) {
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for Host name could not be found.");
|
||||
}
|
||||
if (liveRoomMeta.getStatus() == LiveRoomMeta.LiveRoomStatus.HostOffline) {
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for not be found, is the Host offline?");
|
||||
}
|
||||
if (liveData.getLiveStatus() == LiveData.LiveStatus.HostNotFound)
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for " + liveRoomInfo.getHostName() + " could not be found.");
|
||||
|
||||
liveRoomInfo.setTitle(liveRoomMeta.getTitie());
|
||||
liveRoomInfo.setViewersCount(liveRoomMeta.getViewers());
|
||||
liveRoomInfo.setTotalViewersCount(liveRoomMeta.getTotalViewers());
|
||||
liveRoomInfo.setAgeRestricted(liveRoomMeta.isAgeRestricted());
|
||||
liveRoomInfo.setHost(liveRoomMeta.getHost());
|
||||
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;
|
||||
@@ -178,20 +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);
|
||||
}
|
||||
|
||||
public void publishEvent(TikTokEvent event)
|
||||
{
|
||||
tikTokEventHandler.publish(this, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,70 +22,49 @@
|
||||
*/
|
||||
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.TikTokRoomInfoEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomPinEvent;
|
||||
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.TikTokMessageHandler;
|
||||
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.GiftManager;
|
||||
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.mappers.TikTokLiveMapper;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokLiveMapperHelper;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokMapper;
|
||||
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.TikTokCommonEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.mappers.handlers.TikTokGiftEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.mappers.handlers.TikTokRoomInfoEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.mappers.handlers.TikTokSocialMediaEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.mappers.handlers.*;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.*;
|
||||
import io.github.jwdeveloper.tiktok.utils.ConsoleColors;
|
||||
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) -> {
|
||||
};
|
||||
@@ -96,62 +75,36 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public TikTokLiveClientBuilder configure(Consumer<ClientSettings> onConfigure) {
|
||||
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("@")) {
|
||||
if (clientSettings.getHostName().startsWith("@"))
|
||||
clientSettings.setHostName(clientSettings.getHostName().substring(1));
|
||||
}
|
||||
|
||||
if (clientSettings.getPingInterval() < 250)
|
||||
throw new TikTokLiveException("Minimum allowed ping interval is 250 millseconds");
|
||||
|
||||
var params = clientSettings.getClientParameters();
|
||||
params.put("app_language", clientSettings.getClientLanguage());
|
||||
params.put("webcast_language", clientSettings.getClientLanguage());
|
||||
var httpSettings = clientSettings.getHttpSettings();
|
||||
httpSettings.getParams().put("app_language", clientSettings.getClientLanguage());
|
||||
httpSettings.getParams().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()) {
|
||||
logger.setLevel(Level.OFF);
|
||||
}
|
||||
this.logger = LoggerFactory.create(clientSettings.getHostName(), clientSettings);
|
||||
this.giftsManager = clientSettings.isFetchGifts() ? TikTokLive.gifts() : new TikTokGiftsManager(List.of());
|
||||
}
|
||||
|
||||
public LiveClient build() {
|
||||
@@ -160,39 +113,45 @@ 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, tikTokEventHandler);
|
||||
var apiClient = new TikTokHttpClient(cookieJar, requestFactory);
|
||||
var apiService = new TikTokApiService(apiClient, logger, clientSettings);
|
||||
var giftManager = new TikTokGiftManager(logger);
|
||||
var eventsMapper = createMapper(giftManager, tiktokRoomInfo);
|
||||
var messageHandler = new TikTokMessageHandler(tikTokEventHandler, eventsMapper);
|
||||
var listenerManager = new TikTokListenersManager(listeners, eventHandler);
|
||||
|
||||
var httpClientFactory = new HttpClientFactory(clientSettings);
|
||||
|
||||
var webSocketClient = new TikTokWebSocketClient(
|
||||
cookieJar,
|
||||
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,
|
||||
tikTokEventHandler);
|
||||
|
||||
return new TikTokLiveClient(tiktokRoomInfo,
|
||||
apiService,
|
||||
giftsManager,
|
||||
tiktokRoomInfo,
|
||||
liveHttpClient,
|
||||
webSocketClient,
|
||||
giftManager,
|
||||
tikTokEventHandler,
|
||||
eventHandler,
|
||||
clientSettings,
|
||||
listenerManager,
|
||||
logger);
|
||||
}
|
||||
|
||||
public TikTokLiveMapper createMapper(GiftManager giftManager, TikTokRoomInfo roomInfo) {
|
||||
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(giftManager);
|
||||
var giftHandler = new TikTokGiftEventHandler(giftsManager, roomInfo);
|
||||
var roomInfoHandler = new TikTokRoomInfoEventHandler(roomInfo);
|
||||
var socialHandler = new TikTokSocialMediaEventHandler(roomInfo);
|
||||
|
||||
@@ -248,14 +207,14 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
|
||||
|
||||
//LinkMic events
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicArmies.class, TikTokLinkMicArmiesEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
|
||||
|
||||
//Rank events
|
||||
// mapper.webcastObjectToConstructor(WebcastRankTextMessage.class, TikTokRankTextEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastHourlyRankMessage.class, TikTokRankUpdateEvent.class);
|
||||
|
||||
//Others events
|
||||
@@ -263,7 +222,7 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
// 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(WebcastOecLiveShoppingMessage.class, TikTokShopEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastImDeleteMessage.class, TikTokIMDeleteEvent.class);
|
||||
// mapper.bytesToEvents(WebcastEnvelopeMessage.class, commonHandler::handleEnvelop);
|
||||
|
||||
@@ -283,280 +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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends TikTokEvent> LiveClientBuilder onEvent(Class<E> eventClass, EventConsumer<E> event) {
|
||||
tikTokEventHandler.subscribe(eventClass, event);
|
||||
eventHandler.subscribe(eventClass, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public LiveClientBuilder onRoomInfo(EventConsumer<TikTokRoomInfoEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokRoomInfoEvent.class, event);
|
||||
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 LiveClientBuilder onLiveUnpaused(EventConsumer<TikTokLiveUnpausedEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokLiveUnpausedEvent.class, event);
|
||||
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 onComment(EventConsumer<TikTokCommentEvent> event) {
|
||||
tikTokEventHandler.subscribe(TikTokCommentEvent.class, event);
|
||||
eventHandler.subscribe(TikTokCommentEvent.class, event);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LiveClientBuilder onHttpResponse(EventConsumer<TikTokHttpResponseEvent> action) {
|
||||
tikTokEventHandler.subscribe(TikTokHttpResponseEvent.class, 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,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.dto.MessageMetaData;
|
||||
@@ -36,18 +36,16 @@ import io.github.jwdeveloper.tiktok.utils.Stopwatch;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
public class TikTokLiveMessageHandler {
|
||||
|
||||
public class TikTokMessageHandler {
|
||||
|
||||
private final TikTokEventObserver tikTokEventHandler;
|
||||
private final TikTokLiveEventHandler tikTokEventHandler;
|
||||
private final TikTokLiveMapper mapper;
|
||||
|
||||
public TikTokMessageHandler(TikTokEventObserver tikTokEventHandler, TikTokLiveMapper mapper) {
|
||||
public TikTokLiveMessageHandler(TikTokLiveEventHandler tikTokEventHandler, TikTokLiveMapper mapper) {
|
||||
this.tikTokEventHandler = tikTokEventHandler;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
|
||||
public void handle(LiveClient client, WebcastResponse webcastResponse) {
|
||||
tikTokEventHandler.publish(client, new TikTokWebsocketResponseEvent(webcastResponse));
|
||||
for (var message : webcastResponse.getMessagesList()) {
|
||||
@@ -60,7 +58,8 @@ public 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 (!mapper.isRegistered(messageClassName)) {
|
||||
tikTokEventHandler.publish(client, new TikTokWebsocketUnhandledMessageEvent(message));
|
||||
@@ -22,11 +22,10 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
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 io.github.jwdeveloper.tiktok.live.LiveRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.models.ConnectionState;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedList;
|
||||
@@ -42,6 +41,8 @@ public class TikTokRoomInfo implements LiveRoomInfo {
|
||||
|
||||
private int totalViewersCount;
|
||||
|
||||
private long startTime;
|
||||
|
||||
private boolean ageRestricted;
|
||||
|
||||
private User host;
|
||||
@@ -69,5 +70,4 @@ public class TikTokRoomInfo implements LiveRoomInfo {
|
||||
usersRanking.clear();
|
||||
usersRanking.addAll(rankingUsers);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package io.github.jwdeveloper.tiktok.common;
|
||||
|
||||
import com.google.gson.*;
|
||||
import io.github.jwdeveloper.tiktok.http.mappers.*;
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.net.http.*;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Data
|
||||
public class ActionResult<T> {
|
||||
|
||||
private static final Gson gson = new Gson().newBuilder().disableHtmlEscaping()
|
||||
.registerTypeHierarchyAdapter(HttpResponse.class, new HttpResponseJsonMapper())
|
||||
.registerTypeHierarchyAdapter(HttpRequest.class, new HttpRequestJsonMapper())
|
||||
.setPrettyPrinting().create();
|
||||
|
||||
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", gson.toJsonTree(content));
|
||||
map.addProperty("message", message);
|
||||
map.add("previous", hasPrevious() ? previous.toJson() : null);
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ActionResult: "+gson.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);
|
||||
}
|
||||
}
|
||||
@@ -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.db.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,141 +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.GsonBuilder;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.data.dto.TikTokUserInfo;
|
||||
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 userInfo = fetchUserInfoFromTikTokApi(userName);
|
||||
clientSettings.getClientParameters().put("room_id", userInfo.getRoomId());
|
||||
logger.info("RoomID -> " + userInfo.getRoomId());
|
||||
return userInfo.getRoomId();
|
||||
}
|
||||
|
||||
public TikTokUserInfo fetchUserInfoFromTikTokApi(String userName) {
|
||||
|
||||
var params = new HashMap<>(clientSettings.getClientParameters());
|
||||
params.put("uniqueId", userName);
|
||||
params.put("sourceType", 54);
|
||||
JsonObject roomData = null;
|
||||
try {
|
||||
roomData = tiktokHttpClient.getJsonFromTikTokApi("api-live/user/room/", params);
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
throw new TikTokLiveRequestException("Failed to fetch pre connection room information, it happens when TikTok temporary blocks you. Try to connect again in few minutes");
|
||||
}
|
||||
|
||||
var message = roomData.get("message").getAsString();
|
||||
|
||||
if (message.equals("params_error")) {
|
||||
throw new TikTokLiveRequestException("fetchRoomIdFromTiktokApi -> Unable to fetch roomID, contact with developer");
|
||||
}
|
||||
if (message.equals("user_not_found")) {
|
||||
return new TikTokUserInfo(TikTokUserInfo.UserStatus.NotFound, "");
|
||||
}
|
||||
//live -> status 2
|
||||
//live paused -> 3
|
||||
//not live -> status 4
|
||||
var data = roomData.getAsJsonObject("data");
|
||||
var user = data.getAsJsonObject("user");
|
||||
var roomId = user.get("roomId").getAsString();
|
||||
var status = user.get("status").getAsInt();
|
||||
|
||||
var statusEnum = switch (status) {
|
||||
case 2 -> TikTokUserInfo.UserStatus.Live;
|
||||
case 3 -> TikTokUserInfo.UserStatus.LivePaused;
|
||||
case 4 -> TikTokUserInfo.UserStatus.Offline;
|
||||
default -> TikTokUserInfo.UserStatus.NotFound;
|
||||
};
|
||||
|
||||
return new TikTokUserInfo(statusEnum, roomId);
|
||||
}
|
||||
|
||||
|
||||
public LiveRoomMeta fetchRoomInfo() {
|
||||
logger.info("Fetching RoomInfo");
|
||||
try {
|
||||
var response = tiktokHttpClient.getJsonFromWebcastApi("room/info/", clientSettings.getClientParameters());
|
||||
if (!response.has("data")) {
|
||||
var gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
var json = gson.toJson(response);
|
||||
throw new TikTokLiveRequestException("room info response does not contains data field: \n"+ json);
|
||||
}
|
||||
|
||||
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 server, 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 live websocket connection data", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +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.Constants;
|
||||
import io.github.jwdeveloper.tiktok.data.dto.TikTokUserInfo;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.logging.Logger;
|
||||
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 data = getApiService().fetchUserInfoFromTikTokApi(hostName);
|
||||
return data.getUserStatus() == TikTokUserInfo.UserStatus.Live ||
|
||||
data.getUserStatus() == TikTokUserInfo.UserStatus.LivePaused;
|
||||
}
|
||||
|
||||
public boolean isHostNameValid(String hostName) {
|
||||
var data = getApiService().fetchUserInfoFromTikTokApi(hostName);
|
||||
return data.getUserStatus() != TikTokUserInfo.UserStatus.NotFound;
|
||||
}
|
||||
|
||||
public TikTokApiService getApiService() {
|
||||
var jar = new TikTokCookieJar();
|
||||
var factory = new TikTokHttpRequestFactory(jar,new TikTokEventObserver());
|
||||
var client = new TikTokHttpClient(jar, factory);
|
||||
var settings = new ClientSettings();
|
||||
settings.setClientParameters(Constants.DefaultClientParams());
|
||||
var apiService = new TikTokApiService(client, Logger.getGlobal(), settings);
|
||||
return apiService;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<>();
|
||||
}
|
||||
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,171 +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.data.events.http.TikTokHttpResponseEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.http.HttpData;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
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 final TikTokEventObserver eventHandler;
|
||||
private String query;
|
||||
|
||||
public TikTokHttpRequestFactory(TikTokCookieJar tikTokCookieJar, TikTokEventObserver eventHandler) {
|
||||
this.tikTokCookieJar = tikTokCookieJar;
|
||||
this.cookieManager = new CookieManager();
|
||||
this.eventHandler = eventHandler;
|
||||
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);
|
||||
}
|
||||
|
||||
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());
|
||||
|
||||
var event = new TikTokHttpResponseEvent(response.uri().toString(), HttpData.map(request), HttpData.map(response));
|
||||
eventHandler.publish(null, event);
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -20,44 +20,36 @@
|
||||
* 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.http.mappers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
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.List;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public interface GiftManager {
|
||||
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();
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
Gift registerGift(int id, String name, int diamondCost, Picture picture);
|
||||
return new GiftsData.Response(json, gifts);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param giftId
|
||||
* @return
|
||||
*/
|
||||
Gift findById(int giftId);
|
||||
private Gift mapSingleGift(JsonElement jsonElement) {
|
||||
var jsonObject = jsonElement.getAsJsonObject();
|
||||
|
||||
/**
|
||||
*
|
||||
* @param giftName
|
||||
* @return
|
||||
*/
|
||||
Gift findByName(String giftName);
|
||||
|
||||
/**
|
||||
*
|
||||
* @return all gifts
|
||||
*/
|
||||
List<Gift> getGifts();
|
||||
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,21 @@
|
||||
package io.github.jwdeveloper.tiktok.http.mappers;
|
||||
|
||||
import com.google.gson.*;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.net.http.HttpRequest;
|
||||
|
||||
public class HttpRequestJsonMapper implements JsonSerializer<HttpRequest>
|
||||
{
|
||||
@Override
|
||||
public JsonElement serialize(HttpRequest src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
JsonObject object = new JsonObject();
|
||||
object.addProperty("method", src.method());
|
||||
object.add("timeout", context.serialize(src.timeout().toString()));
|
||||
object.addProperty("expectContinue", src.expectContinue());
|
||||
object.add("uri", context.serialize(src.uri()));
|
||||
object.add("version", context.serialize(src.version().toString()));
|
||||
object.add("headers", context.serialize(src.headers().map()));
|
||||
return object;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.github.jwdeveloper.tiktok.http.mappers;
|
||||
|
||||
import com.google.gson.*;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
public class HttpResponseJsonMapper implements JsonSerializer<HttpResponse>
|
||||
{
|
||||
@Override
|
||||
public JsonElement serialize(HttpResponse src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
JsonObject object = new JsonObject();
|
||||
object.addProperty("statusCode", src.statusCode());
|
||||
object.add("request", context.serialize(src.request()));
|
||||
object.add("headers", context.serialize(src.headers().map()));
|
||||
object.add("body", context.serialize(src.body()));
|
||||
object.add("uri", context.serialize(src.uri().toString()));
|
||||
object.add("version", context.serialize(src.version().toString()));
|
||||
return object;
|
||||
}
|
||||
}
|
||||
@@ -20,18 +20,20 @@
|
||||
* 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;
|
||||
package io.github.jwdeveloper.tiktok.http.mappers;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
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.live.LiveRoomMeta;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class LiveRoomMetaMapper {
|
||||
public class LiveDataMapper {
|
||||
/**
|
||||
* 0 - Unknown
|
||||
* 1 - ?
|
||||
@@ -39,38 +41,47 @@ public class LiveRoomMetaMapper {
|
||||
* 3 - ?
|
||||
* 4 - Offline
|
||||
*/
|
||||
public LiveRoomMeta map(JsonObject input) {
|
||||
var liveRoomMeta = new LiveRoomMeta();
|
||||
public LiveData.Response map(String json) {
|
||||
var response = new LiveData.Response();
|
||||
|
||||
if (!input.has("data")) {
|
||||
return liveRoomMeta;
|
||||
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 = input.getAsJsonObject("data");
|
||||
var data = jsonObject.getAsJsonObject("data");
|
||||
|
||||
|
||||
if (data.has("status")) {
|
||||
var status = data.get("status");
|
||||
var statusId = status.getAsInt();
|
||||
var statusValue = switch (statusId) {
|
||||
case 2 -> LiveRoomMeta.LiveRoomStatus.HostOnline;
|
||||
case 4 -> LiveRoomMeta.LiveRoomStatus.HostOffline;
|
||||
default -> LiveRoomMeta.LiveRoomStatus.HostNotFound;
|
||||
case 2 -> LiveData.LiveStatus.HostOnline;
|
||||
case 4 -> LiveData.LiveStatus.HostOffline;
|
||||
default -> LiveData.LiveStatus.HostNotFound;
|
||||
};
|
||||
liveRoomMeta.setStatus(statusValue);
|
||||
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 {
|
||||
liveRoomMeta.setStatus(LiveRoomMeta.LiveRoomStatus.HostNotFound);
|
||||
response.setLiveStatus(LiveData.LiveStatus.HostNotFound);
|
||||
}
|
||||
|
||||
if (data.has("age_restricted")) {
|
||||
var element = data.getAsJsonObject("age_restricted");
|
||||
var restricted = element.get("restricted").getAsBoolean();
|
||||
liveRoomMeta.setAgeRestricted(restricted);
|
||||
response.setAgeRestricted(restricted);
|
||||
}
|
||||
|
||||
if (data.has("title")) {
|
||||
var element = data.get("title");
|
||||
var title = element.getAsString();
|
||||
liveRoomMeta.setTitie(title);
|
||||
response.setTitle(title);
|
||||
}
|
||||
|
||||
if (data.has("stats")) {
|
||||
@@ -82,45 +93,58 @@ public class LiveRoomMetaMapper {
|
||||
var totalUsers = titalUsersElement.getAsInt();
|
||||
|
||||
|
||||
liveRoomMeta.setLikeCount(likes);
|
||||
liveRoomMeta.setTotalViewers(totalUsers);
|
||||
response.setLikes(likes);
|
||||
response.setTotalViewers(totalUsers);
|
||||
}
|
||||
|
||||
if(data.has("user_count"))
|
||||
{
|
||||
if (data.has("user_count")) {
|
||||
var element = data.get("user_count");
|
||||
var viewers = element.getAsInt();
|
||||
liveRoomMeta.setViewers(viewers);
|
||||
response.setViewers(viewers);
|
||||
}
|
||||
|
||||
if(data.has("owner"))
|
||||
{
|
||||
if (data.has("owner")) {
|
||||
var element = data.getAsJsonObject("owner");
|
||||
var user = getUser(element);
|
||||
liveRoomMeta.setHost(user);
|
||||
response.setHost(user);
|
||||
}
|
||||
|
||||
return liveRoomMeta;
|
||||
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)
|
||||
{
|
||||
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 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 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<>());
|
||||
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 | IllegalStateException e) {
|
||||
logger.warning("Malformed Json: '"+json+"' - Error Message: "+e.getMessage());
|
||||
return new LiveUserData.Response(json, LiveUserData.UserStatus.NotFound, "", -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
package io.github.jwdeveloper.tiktok.listener;
|
||||
|
||||
|
||||
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;
|
||||
@@ -36,10 +37,10 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class TikTokListenersManager implements ListenersManager {
|
||||
private final io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver eventObserver;
|
||||
private final TikTokLiveEventHandler eventObserver;
|
||||
private final List<ListenerBindingModel> bindingModels;
|
||||
|
||||
public TikTokListenersManager(List<TikTokEventListener> listeners, io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver tikTokEventHandler) {
|
||||
public TikTokListenersManager(List<TikTokEventListener> listeners, TikTokLiveEventHandler tikTokEventHandler) {
|
||||
this.eventObserver = tikTokEventHandler;
|
||||
this.bindingModels = new ArrayList<>(listeners.size());
|
||||
for (var listener : listeners) {
|
||||
@@ -110,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
package io.github.jwdeveloper.tiktok.mappers;
|
||||
|
||||
import com.google.protobuf.GeneratedMessageV3;
|
||||
import io.github.jwdeveloper.tiktok.TikTokLive;
|
||||
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;
|
||||
@@ -36,10 +37,12 @@ public class TikTokLiveMapper implements TikTokMapper {
|
||||
|
||||
private final Map<String, TikTokLiveMapperModel> mappers;
|
||||
private final TikTokMapperHelper mapperUtils;
|
||||
private final TikTokLiveMapperModel globalMapperModel;
|
||||
|
||||
public TikTokLiveMapper(TikTokMapperHelper mapperUtils) {
|
||||
this.mappers = new HashMap<>();
|
||||
this.mapperUtils = mapperUtils;
|
||||
this.globalMapperModel = new TikTokLiveMapperModel("any message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -76,6 +79,11 @@ public class TikTokLiveMapper implements TikTokMapper {
|
||||
return forMessage(mapperName, (inputBytes, messageName, mapperHelper) -> MappingResult.of(inputBytes, onMapping.apply(inputBytes)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TikTokMapperModel forAnyMessage() {
|
||||
return globalMapperModel;
|
||||
}
|
||||
|
||||
|
||||
public boolean isRegistered(String mapperName) {
|
||||
return mappers.containsKey(mapperName);
|
||||
@@ -84,6 +92,7 @@ public class TikTokLiveMapper implements TikTokMapper {
|
||||
public <T extends GeneratedMessageV3> boolean isRegistered(Class<T> mapperName) {
|
||||
return mappers.containsKey(mapperName.getSimpleName());
|
||||
}
|
||||
|
||||
public List<TikTokEvent> handleMapping(String messageName, byte[] bytes) {
|
||||
if (!isRegistered(messageName)) {
|
||||
return List.of();
|
||||
@@ -91,10 +100,17 @@ public class TikTokLiveMapper implements TikTokMapper {
|
||||
var mapperModel = mappers.get(messageName);
|
||||
|
||||
var inputBytes = mapperModel.getOnBeforeMapping().onMapping(bytes, messageName, mapperUtils);
|
||||
var globalInputBytes = globalMapperModel.getOnBeforeMapping().onMapping(inputBytes, messageName, mapperUtils);
|
||||
|
||||
var mappingResult = mapperModel.getOnMapping().onMapping(inputBytes, messageName, mapperUtils);
|
||||
|
||||
var mappingResult = mapperModel.getOnMapping().onMapping(globalInputBytes, messageName, mapperUtils);
|
||||
|
||||
if (mappingResult == null) {
|
||||
mappingResult = globalMapperModel.getOnMapping().onMapping(globalInputBytes, messageName, mapperUtils);
|
||||
}
|
||||
|
||||
var afterMappingResult = mapperModel.getOnAfterMapping().apply(mappingResult);
|
||||
return afterMappingResult;
|
||||
var globalAfterMappingResult = globalMapperModel.getOnAfterMapping().apply(MappingResult.of(mappingResult.getSource(), afterMappingResult));
|
||||
return globalAfterMappingResult;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.mappers;
|
||||
|
||||
import com.google.protobuf.GeneratedMessageV3;
|
||||
|
||||
@@ -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.mappers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
|
||||
@@ -22,76 +22,76 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.mappers.handlers;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.TikTokRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
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.models.Picture;
|
||||
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.gifts.*;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftsManager;
|
||||
import io.github.jwdeveloper.tiktok.mappers.TikTokMapperHelper;
|
||||
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import lombok.SneakyThrows;
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
|
||||
public class TikTokGiftEventHandler {
|
||||
private final GiftManager giftManager;
|
||||
private final Map<Long, WebcastGiftMessage> giftsMessages;
|
||||
private final TikTokRoomInfo tikTokRoomInfo;
|
||||
|
||||
public TikTokGiftEventHandler(GiftManager giftManager) {
|
||||
this.giftManager = giftManager;
|
||||
private final GiftsManager giftsManager;
|
||||
|
||||
public TikTokGiftEventHandler(GiftsManager giftsManager, TikTokRoomInfo tikTokRoomInfo) {
|
||||
giftsMessages = new HashMap<>();
|
||||
this.tikTokRoomInfo = tikTokRoomInfo;
|
||||
this.giftsManager = giftsManager;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public MappingResult handleGifts(byte[] msg, String name, TikTokMapperHelper helper) {
|
||||
var currentMessage = WebcastGiftMessage.parseFrom(msg);
|
||||
var gifts = handleGift(currentMessage);
|
||||
return MappingResult.of(currentMessage,gifts);
|
||||
return MappingResult.of(currentMessage, gifts);
|
||||
}
|
||||
|
||||
public List<TikTokEvent> handleGift(WebcastGiftMessage currentMessage) {
|
||||
var userId = currentMessage.getUser().getId();
|
||||
var currentType = GiftSendType.fromNumber(currentMessage.getSendType());
|
||||
var currentType = GiftComboStateType.fromNumber(currentMessage.getSendType());
|
||||
var containsPreviousMessage = giftsMessages.containsKey(userId);
|
||||
|
||||
|
||||
//If gift is not streakable just return onGift event
|
||||
if (currentMessage.getGift().getType() != 1) {
|
||||
var comboEvent = getGiftComboEvent(currentMessage, GiftSendType.Finished);
|
||||
var comboEvent = getGiftComboEvent(currentMessage, GiftComboStateType.Finished);
|
||||
var giftEvent = getGiftEvent(currentMessage);
|
||||
return List.of(comboEvent, giftEvent);
|
||||
}
|
||||
|
||||
if (!containsPreviousMessage) {
|
||||
if (currentType == GiftSendType.Finished) {
|
||||
if (currentType == GiftComboStateType.Finished) {
|
||||
return List.of(getGiftEvent(currentMessage));
|
||||
} else {
|
||||
giftsMessages.put(userId, currentMessage);
|
||||
return List.of(getGiftComboEvent(currentMessage, GiftSendType.Begin));
|
||||
return List.of(getGiftComboEvent(currentMessage, GiftComboStateType.Begin));
|
||||
}
|
||||
}
|
||||
|
||||
var previousMessage = giftsMessages.get(userId);
|
||||
var previousType = GiftSendType.fromNumber(previousMessage.getSendType());
|
||||
if (currentType == GiftSendType.Active &&
|
||||
previousType == GiftSendType.Active) {
|
||||
var previousType = GiftComboStateType.fromNumber(previousMessage.getSendType());
|
||||
if (currentType == GiftComboStateType.Active &&
|
||||
previousType == GiftComboStateType.Active) {
|
||||
giftsMessages.put(userId, currentMessage);
|
||||
return List.of(getGiftComboEvent(currentMessage, GiftSendType.Active));
|
||||
return List.of(getGiftComboEvent(currentMessage, GiftComboStateType.Active));
|
||||
}
|
||||
|
||||
|
||||
if (currentType == GiftSendType.Finished &&
|
||||
previousType == GiftSendType.Active) {
|
||||
if (currentType == GiftComboStateType.Finished &&
|
||||
previousType == GiftComboStateType.Active) {
|
||||
giftsMessages.clear();
|
||||
return List.of(
|
||||
getGiftComboEvent(currentMessage, GiftSendType.Finished),
|
||||
getGiftComboEvent(currentMessage, GiftComboStateType.Finished),
|
||||
getGiftEvent(currentMessage));
|
||||
}
|
||||
|
||||
@@ -101,34 +101,48 @@ public class TikTokGiftEventHandler {
|
||||
|
||||
private TikTokGiftEvent getGiftEvent(WebcastGiftMessage message) {
|
||||
var gift = getGiftObject(message);
|
||||
return new TikTokGiftEvent(gift, message);
|
||||
return new TikTokGiftEvent(gift, tikTokRoomInfo.getHost(), message);
|
||||
}
|
||||
|
||||
private TikTokGiftEvent getGiftComboEvent(WebcastGiftMessage message, GiftSendType state) {
|
||||
private TikTokGiftEvent getGiftComboEvent(WebcastGiftMessage message, GiftComboStateType state) {
|
||||
var gift = getGiftObject(message);
|
||||
return new TikTokGiftComboEvent(gift, message, state);
|
||||
return new TikTokGiftComboEvent(gift, tikTokRoomInfo.getHost(), message, state);
|
||||
}
|
||||
|
||||
private Gift getGiftObject(WebcastGiftMessage giftMessage) {
|
||||
var giftId = (int) giftMessage.getGiftId();
|
||||
var gift = giftManager.findById(giftId);
|
||||
var gift = giftsManager.getById(giftId);
|
||||
if (gift == Gift.UNDEFINED)
|
||||
gift = giftsManager.getByName(giftMessage.getGift().getName());
|
||||
if (gift == Gift.UNDEFINED) {
|
||||
gift = giftManager.findByName(giftMessage.getGift().getName());
|
||||
}
|
||||
if (gift == Gift.UNDEFINED) {
|
||||
gift = giftManager.registerGift(
|
||||
giftId,
|
||||
gift = new Gift(giftId,
|
||||
giftMessage.getGift().getName(),
|
||||
giftMessage.getGift().getDiamondCount(),
|
||||
Picture.map(giftMessage.getGift().getImage()));
|
||||
|
||||
giftsManager.attachGift(gift);
|
||||
}
|
||||
|
||||
if (gift.getPicture().getLink().endsWith(".webp")) {
|
||||
if (gift.getPicture().getLink().endsWith(".webp"))
|
||||
{
|
||||
updatePicture(gift, giftMessage);
|
||||
}
|
||||
|
||||
return gift;
|
||||
}
|
||||
|
||||
// TODO-kohlerpop1: I do not think this method is needed for any reason?
|
||||
// TODO response:
|
||||
|
||||
/**
|
||||
* Some generated gifts in JSON file contains .webp image format,
|
||||
* that's bad since java by the defult is not supporing .webp and when URL is
|
||||
* converted to Java.io.Image then image is null
|
||||
*
|
||||
* However, TikTok in GiftWebcast event always has image in .jpg format,
|
||||
* so I take advantage of it and swap .webp url with .jpg url
|
||||
*
|
||||
*/
|
||||
|
||||
private void updatePicture(Gift gift, WebcastGiftMessage webcastGiftMessage) {
|
||||
try {
|
||||
@@ -142,4 +156,4 @@ public class TikTokGiftEventHandler {
|
||||
throw new TikTokLiveException("Unable to update picture in gift: " + gift.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,99 +22,120 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.websocket;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandler;
|
||||
import io.github.jwdeveloper.tiktok.http.HttpUtils;
|
||||
import io.github.jwdeveloper.tiktok.http.TikTokCookieJar;
|
||||
import io.github.jwdeveloper.tiktok.*;
|
||||
import io.github.jwdeveloper.tiktok.data.dto.ProxyData;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.*;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.*;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import org.java_websocket.client.WebSocketClient;
|
||||
|
||||
import java.net.URI;
|
||||
import javax.net.ssl.*;
|
||||
import java.net.Proxy;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.HashMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TikTokWebSocketClient implements SocketClient {
|
||||
private final ClientSettings clientSettings;
|
||||
private final TikTokCookieJar tikTokCookieJar;
|
||||
private final TikTokMessageHandler messageHandler;
|
||||
private final TikTokEventObserver tikTokEventHandler;
|
||||
private final LiveClientSettings clientSettings;
|
||||
private final TikTokLiveMessageHandler messageHandler;
|
||||
private final TikTokLiveEventHandler tikTokEventHandler;
|
||||
private WebSocketClient webSocketClient;
|
||||
private TikTokWebSocketPingingTask pingingTask;
|
||||
|
||||
private final TikTokWebSocketPingingTask pingingTask;
|
||||
private boolean isConnected;
|
||||
|
||||
public TikTokWebSocketClient(
|
||||
TikTokCookieJar tikTokCookieJar,
|
||||
ClientSettings clientSettings,
|
||||
TikTokMessageHandler messageHandler,
|
||||
TikTokEventObserver tikTokEventHandler) {
|
||||
this.tikTokCookieJar = tikTokCookieJar;
|
||||
LiveClientSettings clientSettings,
|
||||
TikTokLiveMessageHandler messageHandler,
|
||||
TikTokLiveEventHandler tikTokEventHandler) {
|
||||
this.clientSettings = clientSettings;
|
||||
this.messageHandler = messageHandler;
|
||||
this.tikTokEventHandler = tikTokEventHandler;
|
||||
isConnected = false;
|
||||
pingingTask = new TikTokWebSocketPingingTask();
|
||||
}
|
||||
|
||||
public void start(WebcastResponse webcastResponse, LiveClient tikTokLiveClient) {
|
||||
@Override
|
||||
public void start(LiveConnectionData.Response connectionData, LiveClient liveClient) {
|
||||
if (isConnected) {
|
||||
stop();
|
||||
}
|
||||
|
||||
if (webcastResponse.getPushServer().isEmpty() || webcastResponse.getRouteParamsMapMap().isEmpty())
|
||||
{
|
||||
throw new TikTokLiveException("Could not find Room");
|
||||
}
|
||||
messageHandler.handle(liveClient, connectionData.getWebcastResponse());
|
||||
|
||||
var headers = new HashMap<String, String>();
|
||||
headers.put("Cookie", connectionData.getWebsocketCookies());
|
||||
webSocketClient = new TikTokWebSocketListener(connectionData.getWebsocketUrl(),
|
||||
headers,
|
||||
clientSettings.getHttpSettings().getTimeout().toMillisPart(),
|
||||
messageHandler,
|
||||
tikTokEventHandler,
|
||||
liveClient);
|
||||
|
||||
// ProxyClientSettings proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
|
||||
// if (proxyClientSettings.isEnabled())
|
||||
// connectProxy(proxyClientSettings);
|
||||
// else
|
||||
connectDefault();
|
||||
}
|
||||
|
||||
private void connectDefault() {
|
||||
try {
|
||||
messageHandler.handle(tikTokLiveClient, webcastResponse);
|
||||
var url = getWebSocketUrl(webcastResponse);
|
||||
webSocketClient = startWebSocket(url, tikTokLiveClient);
|
||||
webSocketClient.connect();
|
||||
|
||||
pingingTask = new TikTokWebSocketPingingTask();
|
||||
pingingTask.run(webSocketClient);
|
||||
pingingTask.run(webSocketClient, clientSettings.getPingInterval());
|
||||
isConnected = true;
|
||||
} catch (Exception e)
|
||||
{
|
||||
} catch (Exception e) {
|
||||
isConnected = false;
|
||||
throw new TikTokLiveException("Failed to connect to the websocket", e);
|
||||
}
|
||||
}
|
||||
|
||||
private URI getWebSocketUrl(WebcastResponse webcastResponse) {
|
||||
var tiktokAccessKey = webcastResponse.getRouteParamsMapMap();
|
||||
|
||||
var parameters = new TreeMap<>(clientSettings.getClientParameters());
|
||||
parameters.putAll(tiktokAccessKey);
|
||||
|
||||
var url = webcastResponse.getPushServer();
|
||||
var parsed = HttpUtils.parseParametersEncode(url, parameters);
|
||||
return URI.create(parsed);
|
||||
public void connectProxy(ProxyClientSettings proxySettings) {
|
||||
try {
|
||||
if (proxySettings.getType() == Proxy.Type.SOCKS) {
|
||||
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);
|
||||
webSocketClient.setSocketFactory(sc.getSocketFactory());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// This will never be thrown.
|
||||
throw new TikTokProxyRequestException("Unable to set Socks proxy SSL instance");
|
||||
}
|
||||
while (proxySettings.hasNext()) {
|
||||
ProxyData proxyData = proxySettings.next();
|
||||
if (!tryProxyConnection(proxySettings, proxyData)) {
|
||||
if (proxySettings.isAutoDiscard())
|
||||
proxySettings.remove();
|
||||
continue;
|
||||
}
|
||||
pingingTask.run(webSocketClient, clientSettings.getPingInterval());
|
||||
isConnected = true;
|
||||
break;
|
||||
}
|
||||
if (!isConnected)
|
||||
throw new TikTokLiveException("Failed to connect to the websocket");
|
||||
}
|
||||
|
||||
private WebSocketClient startWebSocket(URI url, LiveClient liveClient) {
|
||||
var cookie = tikTokCookieJar.parseCookies();
|
||||
var headers = new HashMap<String, String>();
|
||||
headers.put("Cookie", cookie);
|
||||
return new TikTokWebSocketListener(url,
|
||||
headers,
|
||||
3000,
|
||||
messageHandler,
|
||||
tikTokEventHandler,
|
||||
liveClient);
|
||||
public boolean tryProxyConnection(ProxyClientSettings proxySettings, ProxyData proxyData) {
|
||||
try {
|
||||
webSocketClient.setProxy(new Proxy(proxySettings.getType(), proxyData.toSocketAddress()));
|
||||
webSocketClient.connect();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public void stop()
|
||||
{
|
||||
if (isConnected && webSocketClient != null) {
|
||||
|
||||
public void stop() {
|
||||
if (isConnected && webSocketClient != null && webSocketClient.isOpen()) {
|
||||
webSocketClient.closeConnection(0, "");
|
||||
pingingTask.stop();
|
||||
}
|
||||
webSocketClient = null;
|
||||
pingingTask = null;
|
||||
isConnected = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,103 +23,93 @@
|
||||
package io.github.jwdeveloper.tiktok.websocket;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokConnectedEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokDisconnectedEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokErrorEvent;
|
||||
import io.github.jwdeveloper.tiktok.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.*;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokProtocolBufferException;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
|
||||
import io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandler;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastPushFrame;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastWebsocketAck;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.*;
|
||||
import org.java_websocket.client.WebSocketClient;
|
||||
import org.java_websocket.drafts.Draft_6455;
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
|
||||
public class TikTokWebSocketListener extends WebSocketClient {
|
||||
|
||||
private final TikTokMessageHandler messageHandler;
|
||||
private final TikTokEventObserver tikTokEventHandler;
|
||||
private final TikTokLiveMessageHandler messageHandler;
|
||||
private final TikTokLiveEventHandler tikTokEventHandler;
|
||||
private final LiveClient tikTokLiveClient;
|
||||
|
||||
public TikTokWebSocketListener(URI serverUri,
|
||||
Map<String, String> httpHeaders,
|
||||
int connectTimeout,
|
||||
TikTokMessageHandler messageHandler,
|
||||
TikTokEventObserver tikTokEventHandler,
|
||||
TikTokLiveMessageHandler messageHandler,
|
||||
TikTokLiveEventHandler tikTokEventHandler,
|
||||
LiveClient tikTokLiveClient) {
|
||||
super(serverUri, new Draft_6455(), httpHeaders,connectTimeout);
|
||||
super(serverUri, new Draft_6455(), httpHeaders, connectTimeout);
|
||||
this.messageHandler = messageHandler;
|
||||
this.tikTokEventHandler = tikTokEventHandler;
|
||||
this.tikTokLiveClient = tikTokLiveClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(ByteBuffer bytes)
|
||||
{
|
||||
public void onMessage(ByteBuffer bytes) {
|
||||
try {
|
||||
handleBinary(bytes.array());
|
||||
} catch (Exception e) {
|
||||
tikTokEventHandler.publish(tikTokLiveClient, new TikTokErrorEvent(e));
|
||||
}
|
||||
if(isNotClosing())
|
||||
{
|
||||
sendPing();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onOpen(ServerHandshake serverHandshake) {
|
||||
tikTokEventHandler.publish(tikTokLiveClient,new TikTokConnectedEvent());
|
||||
if(isNotClosing())
|
||||
{
|
||||
sendPing();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onClose(int i, String s, boolean b) {
|
||||
tikTokEventHandler.publish(tikTokLiveClient,new TikTokDisconnectedEvent());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception error)
|
||||
{
|
||||
tikTokEventHandler.publish(tikTokLiveClient,new TikTokErrorEvent(error));
|
||||
if(isNotClosing())
|
||||
{
|
||||
if (isNotClosing()) {
|
||||
sendPing();
|
||||
}
|
||||
}
|
||||
|
||||
private void handleBinary(byte[] buffer) {
|
||||
var websocketMessageOptional = getWebcastWebsocketMessage(buffer);
|
||||
if (websocketMessageOptional.isEmpty()) {
|
||||
var websocketPushFrameOptional = getWebcastPushFrame(buffer);
|
||||
if (websocketPushFrameOptional.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
var websocketMessage = websocketMessageOptional.get();
|
||||
var webResponse = getWebResponseMessage(websocketMessage.getPayload());
|
||||
var websocketPushFrame = websocketPushFrameOptional.get();
|
||||
var webcastResponse = getWebResponseMessage(websocketPushFrame.getPayload());
|
||||
|
||||
if(webResponse.getNeedsAck())
|
||||
{
|
||||
//For some reason while send ack id, server get disconnected
|
||||
// sendAckId(webResponse.getFetchInterval());
|
||||
if (webcastResponse.getNeedsAck()) {
|
||||
var pushFrameBuilder = WebcastPushFrame.newBuilder();
|
||||
pushFrameBuilder.setPayloadType("ack");
|
||||
pushFrameBuilder.setLogId(websocketPushFrame.getLogId());
|
||||
pushFrameBuilder.setPayload(webcastResponse.getInternalExtBytes());
|
||||
if (isNotClosing())
|
||||
{
|
||||
this.send(pushFrameBuilder.build().toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
messageHandler.handle(tikTokLiveClient, webResponse);
|
||||
messageHandler.handle(tikTokLiveClient, webcastResponse);
|
||||
}
|
||||
|
||||
private Optional<WebcastPushFrame> getWebcastWebsocketMessage(byte[] buffer) {
|
||||
@Override
|
||||
public void onOpen(ServerHandshake serverHandshake) {
|
||||
tikTokEventHandler.publish(tikTokLiveClient, new TikTokConnectedEvent());
|
||||
if (isNotClosing()) {
|
||||
sendPing();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
tikTokEventHandler.publish(tikTokLiveClient, new TikTokDisconnectedEvent(reason));
|
||||
tikTokLiveClient.disconnect();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception error) {
|
||||
tikTokEventHandler.publish(tikTokLiveClient, new TikTokErrorEvent(error));
|
||||
if (isNotClosing()) {
|
||||
sendPing();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<WebcastPushFrame> getWebcastPushFrame(byte[] buffer) {
|
||||
try {
|
||||
var websocketMessage = WebcastPushFrame.parseFrom(buffer);
|
||||
if (websocketMessage.getPayload().isEmpty()) {
|
||||
@@ -139,28 +129,12 @@ public class TikTokWebSocketListener extends WebSocketClient {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isNotClosing()
|
||||
{
|
||||
private boolean isNotClosing() {
|
||||
return !isClosed() && !isClosing();
|
||||
}
|
||||
|
||||
private void sendAckId(long id) {
|
||||
var serverInfo = WebcastWebsocketAck
|
||||
.newBuilder()
|
||||
.setType("ack")
|
||||
.setId(id)
|
||||
.build();
|
||||
if(isNotClosing())
|
||||
{
|
||||
System.out.println("SEND ICK ID "+id);
|
||||
send(serverInfo.toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onMessage(String s) {
|
||||
|
||||
// System.err.println(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.github.jwdeveloper.tiktok.websocket;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.TikTokLiveEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokConnectedEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokDisconnectedEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
|
||||
public class TikTokWebSocketOfflineClient implements SocketClient {
|
||||
|
||||
private final TikTokLiveEventHandler handler;
|
||||
private LiveClient liveClient;
|
||||
|
||||
public TikTokWebSocketOfflineClient(TikTokLiveEventHandler handler) {
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(LiveConnectionData.Response webcastResponse, LiveClient tikTokLiveClient) {
|
||||
liveClient = tikTokLiveClient;
|
||||
handler.publish(liveClient, new TikTokConnectedEvent());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (liveClient == null) {
|
||||
return;
|
||||
}
|
||||
handler.publish(liveClient, new TikTokDisconnectedEvent());
|
||||
}
|
||||
}
|
||||
@@ -1,81 +1,48 @@
|
||||
/*
|
||||
* 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.websocket;
|
||||
|
||||
import org.java_websocket.WebSocket;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class TikTokWebSocketPingingTask
|
||||
{
|
||||
private Thread thread;
|
||||
private boolean isRunning = false;
|
||||
private final int MIN_TIMEOUT = 5;
|
||||
private final int MAX_TIMEOUT = 100;
|
||||
private final int MAX_TIMEOUT = 250;
|
||||
private final int SLEEP_TIME = 500;
|
||||
|
||||
|
||||
public void run(WebSocket webSocket)
|
||||
public void run(WebSocket webSocket, long pingTaskTime)
|
||||
{
|
||||
stop();
|
||||
thread = new Thread(() ->
|
||||
{
|
||||
pingTask(webSocket);
|
||||
});
|
||||
isRunning =true;
|
||||
thread = new Thread(() -> pingTask(webSocket, pingTaskTime));
|
||||
isRunning = true;
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
if(thread != null)
|
||||
{
|
||||
if (thread != null)
|
||||
thread.interrupt();
|
||||
}
|
||||
isRunning = false;
|
||||
}
|
||||
|
||||
|
||||
private void pingTask(WebSocket webSocket)
|
||||
private void pingTask(WebSocket webSocket, long pingTaskTime)
|
||||
{
|
||||
var random = new Random();
|
||||
while (isRunning)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!webSocket.isOpen())
|
||||
{
|
||||
Thread.sleep(100);
|
||||
while (isRunning) {
|
||||
try {
|
||||
if (!webSocket.isOpen()) {
|
||||
Thread.sleep(SLEEP_TIME);
|
||||
continue;
|
||||
}
|
||||
webSocket.sendPing();
|
||||
|
||||
var timeout = random.nextInt(MAX_TIMEOUT)+MIN_TIMEOUT;
|
||||
Thread.sleep(timeout);
|
||||
Thread.sleep(pingTaskTime+random.nextInt(MAX_TIMEOUT));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
catch (Exception e) {
|
||||
isRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.gifts;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftOld;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -35,38 +35,6 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
public class TikTokGiftManagerTest {
|
||||
|
||||
@InjectMocks
|
||||
TikTokGiftManager giftManager;
|
||||
|
||||
private static final Picture rosePicture = new Picture("https://p19-webcast.tiktokcdn.com/img/maliva/webcast-va/eba3a9bb85c33e017f3648eaf88d7189~tplv-obj.png");
|
||||
|
||||
@Test
|
||||
void registerGift() {
|
||||
var fakeGift = giftManager.registerGift(123, "Fake gift", 123123, rosePicture);
|
||||
var gifts = giftManager.getGifts();
|
||||
var optional = gifts.stream().filter(r -> r == fakeGift).findFirst();
|
||||
Assertions.assertTrue(optional.isPresent());
|
||||
// Assertions.assertNotNull(optional.get().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findById() {
|
||||
var target = giftManager.registerGift(123, "FAKE", 123123, rosePicture);
|
||||
var result = giftManager.findById(target.getId());
|
||||
Assertions.assertEquals(target, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByName() {
|
||||
var target = giftManager.registerGift(123, "FAKE", 123123, rosePicture);
|
||||
var result = giftManager.findByName(target.getName());
|
||||
Assertions.assertEquals(target, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGifts() {
|
||||
Assertions.assertEquals(Gift.values().length, giftManager.getGifts().size());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -22,11 +22,13 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.handlers.events;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.TikTokRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftComboEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftSendType;
|
||||
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftManager;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.GiftComboStateType;
|
||||
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftsManager;
|
||||
import io.github.jwdeveloper.tiktok.mappers.handlers.TikTokGiftEventHandler;
|
||||
import io.github.jwdeveloper.tiktok.messages.data.GiftStruct;
|
||||
import io.github.jwdeveloper.tiktok.messages.data.Image;
|
||||
@@ -37,7 +39,7 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
@@ -45,46 +47,46 @@ class TikTokGiftEventHandlerTest {
|
||||
|
||||
public static TikTokGiftEventHandler handler;
|
||||
|
||||
|
||||
@BeforeAll
|
||||
public void before() {
|
||||
var manager = new TikTokGiftManager(Logger.getLogger("x"));
|
||||
manager.registerGift(123, "example", 123, new Picture("image.webp"));
|
||||
handler = new TikTokGiftEventHandler(manager);
|
||||
var manager = new TikTokGiftsManager(List.of());
|
||||
var info = new TikTokRoomInfo();
|
||||
info.setHost(new io.github.jwdeveloper.tiktok.data.models.users.User(123L, "test", new Picture("")));
|
||||
manager.attachGift(new Gift(123, "example", 123, "image.webp"));
|
||||
handler = new TikTokGiftEventHandler(manager, info);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleGifts() {
|
||||
var message = getGiftMessage("example-new-name", 123, "image-new.png", 0, 1,false);
|
||||
var message = getGiftMessage("example-new-name", 123, "image-new.png", 0, 1, false);
|
||||
var result = handler.handleGift(message);
|
||||
|
||||
Assertions.assertEquals(2, result.size());
|
||||
|
||||
var event = (TikTokGiftEvent) result.get(0);
|
||||
var gift = event.getGift();
|
||||
Assertions.assertEquals("image-new.png",gift.getPicture().getLink());
|
||||
Assertions.assertEquals(123,gift.getId());
|
||||
Assertions.assertEquals("image-new.png", gift.getPicture().getLink());
|
||||
Assertions.assertEquals(123, gift.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleStrakableGift() {
|
||||
var message = getGiftMessage("example-new-name", 123, "image-new.png", 0, 1,true);
|
||||
var message = getGiftMessage("example-new-name", 123, "image-new.png", 0, 1, true);
|
||||
var result = handler.handleGift(message);
|
||||
|
||||
Assertions.assertEquals(1, result.size());
|
||||
|
||||
var event = (TikTokGiftEvent) result.get(0);
|
||||
var gift = event.getGift();
|
||||
Assertions.assertEquals("image-new.png",gift.getPicture().getLink());
|
||||
Assertions.assertEquals(123,gift.getId());
|
||||
Assertions.assertEquals("image-new.png", gift.getPicture().getLink());
|
||||
Assertions.assertEquals(123, gift.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldHandleStrike()
|
||||
{
|
||||
var message1 = getGiftMessage("example-new-name", 123, "image-new.png", 1, 1,true);
|
||||
var message2 = getGiftMessage("example-new-name", 123, "image-new.png", 2, 1,true);
|
||||
var message3 = getGiftMessage("example-new-name", 123, "image-new.png", 0, 1,true);
|
||||
void shouldHandleStrike() {
|
||||
var message1 = getGiftMessage("example-new-name", 123, "image-new.png", 1, 1, true);
|
||||
var message2 = getGiftMessage("example-new-name", 123, "image-new.png", 2, 1, true);
|
||||
var message3 = getGiftMessage("example-new-name", 123, "image-new.png", 0, 1, true);
|
||||
|
||||
var result1 = handler.handleGift(message1);
|
||||
var result2 = handler.handleGift(message2);
|
||||
@@ -96,9 +98,9 @@ class TikTokGiftEventHandlerTest {
|
||||
Assertions.assertEquals(2, result3.size());
|
||||
var event3 = (TikTokGiftComboEvent) result3.get(0);
|
||||
|
||||
Assertions.assertEquals(GiftSendType.Begin,event1.getComboState());
|
||||
Assertions.assertEquals(GiftSendType.Active,event2.getComboState());
|
||||
Assertions.assertEquals(GiftSendType.Finished,event3.getComboState());
|
||||
Assertions.assertEquals(GiftComboStateType.Begin, event1.getComboState());
|
||||
Assertions.assertEquals(GiftComboStateType.Active, event2.getComboState());
|
||||
Assertions.assertEquals(GiftComboStateType.Finished, event3.getComboState());
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +118,7 @@ class TikTokGiftEventHandlerTest {
|
||||
giftBuilder.setId(giftId);
|
||||
giftBuilder.setName(giftName);
|
||||
giftBuilder.setImage(Image.newBuilder().addUrlList(giftImage).build());
|
||||
giftBuilder.setType(streakable?1:0);
|
||||
giftBuilder.setType(streakable ? 1 : 0);
|
||||
userBuilder.setId(userId);
|
||||
|
||||
builder.setGiftId(giftId);
|
||||
@@ -127,5 +129,4 @@ class TikTokGiftEventHandlerTest {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,133 +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 io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
|
||||
import io.github.jwdeveloper.tiktok.mappers.LiveRoomMetaMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class TikTokApiServiceTest
|
||||
{
|
||||
@Mock
|
||||
TikTokHttpClient tiktokHttpClient;
|
||||
|
||||
@Mock
|
||||
Logger logger;
|
||||
|
||||
@Mock
|
||||
ClientSettings clientSettings;
|
||||
|
||||
@InjectMocks
|
||||
TikTokApiService tikTokApiService;
|
||||
|
||||
@Test
|
||||
void updateSessionId_NullSessionId_DoesNotSetSessionId() {
|
||||
when(clientSettings.getSessionId()).thenReturn(null);
|
||||
|
||||
tikTokApiService.updateSessionId();
|
||||
|
||||
verify(tiktokHttpClient, times(0)).setSessionId(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateSessionId_EmptySessionId_DoesNotSetSessionId() {
|
||||
when(clientSettings.getSessionId()).thenReturn("");
|
||||
|
||||
tikTokApiService.updateSessionId();
|
||||
|
||||
verify(tiktokHttpClient, times(0)).setSessionId(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateSessionId_ValidSessionId_SetsSessionId() {
|
||||
when(clientSettings.getSessionId()).thenReturn("validSessionId");
|
||||
|
||||
tikTokApiService.updateSessionId();
|
||||
|
||||
verify(tiktokHttpClient, times(1)).setSessionId("validSessionId");
|
||||
}
|
||||
|
||||
|
||||
// @Test
|
||||
void fetchRoomId_ValidResponse_ReturnsRoomId() throws Exception {
|
||||
String expectedRoomId = "123456";
|
||||
String htmlResponse = "room_id=" + expectedRoomId ;
|
||||
when(tiktokHttpClient.getLivestreamPage(anyString())).thenReturn(htmlResponse);
|
||||
|
||||
String roomId = tikTokApiService.fetchRoomId("username");
|
||||
|
||||
assertEquals(expectedRoomId, roomId);
|
||||
verify(clientSettings.getClientParameters()).put("room_id", expectedRoomId);
|
||||
}
|
||||
|
||||
// @Test
|
||||
void fetchRoomId_ExceptionThrown_ThrowsTikTokLiveRequestException() throws Exception {
|
||||
when(tiktokHttpClient.getLivestreamPage(anyString())).thenThrow(new Exception("some exception"));
|
||||
|
||||
assertThrows(TikTokLiveRequestException.class, () -> {
|
||||
tikTokApiService.fetchRoomId("username");
|
||||
});
|
||||
}
|
||||
|
||||
//@Test
|
||||
void fetchRoomInfo_ValidResponse_ReturnsLiveRoomMeta() throws Exception {
|
||||
HashMap<String, Object> clientParameters = new HashMap<>();
|
||||
var mockResponse = new JsonObject(); // Assume JsonObject is from the Gson library
|
||||
var expectedLiveRoomMeta = new LiveRoomMeta(); // Assume LiveRoomMeta is a simple POJO
|
||||
|
||||
when(clientSettings.getClientParameters()).thenReturn(clientParameters);
|
||||
when(tiktokHttpClient.getJsonFromWebcastApi(anyString(), any())).thenReturn(mockResponse);
|
||||
when(new LiveRoomMetaMapper().map(mockResponse)).thenReturn(expectedLiveRoomMeta); // Assuming LiveRoomMetaMapper is a simple mapper class
|
||||
|
||||
LiveRoomMeta liveRoomMeta = tikTokApiService.fetchRoomInfo();
|
||||
|
||||
assertEquals(expectedLiveRoomMeta, liveRoomMeta);
|
||||
}
|
||||
|
||||
// @Test
|
||||
void fetchRoomInfo_ExceptionThrown_ThrowsTikTokLiveRequestException() throws Exception {
|
||||
when(tiktokHttpClient.getJsonFromWebcastApi(anyString(), any())).thenThrow(new Exception("some exception"));
|
||||
|
||||
assertThrows(TikTokLiveRequestException.class, () -> {
|
||||
tikTokApiService.fetchRoomInfo();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,103 +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.TikTokLive;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class TikTokLiveOnlineCheckerTest {
|
||||
|
||||
public boolean enableTests = false;
|
||||
|
||||
@Test
|
||||
public void shouldTestOnline() {
|
||||
|
||||
if(!enableTests)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var TARGET_USER = "bangbetmenygy";
|
||||
var sut = new TikTokDataChecker();
|
||||
var result = sut.isOnline(TARGET_USER);
|
||||
|
||||
Assertions.assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeOffline() {
|
||||
|
||||
var TARGET_USER = "karacomparetto";
|
||||
var sut = new TikTokDataChecker();
|
||||
var result = sut.isOnline(TARGET_USER);
|
||||
|
||||
Assertions.assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeValid() throws InterruptedException {
|
||||
|
||||
var TARGET_USER = "dostawcavideo";
|
||||
var sut = new TikTokDataChecker();
|
||||
var result = sut.isHostNameValid(TARGET_USER);
|
||||
|
||||
|
||||
TikTokLive.newClient("asdasd")
|
||||
.onWebsocketResponse((liveClient, event) ->
|
||||
{
|
||||
for(var message : event.getResponse().getMessagesList())
|
||||
{
|
||||
if(message.getMethod().equals("WebcastGiftMessage"))
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytes = message.getMethodBytes();
|
||||
var rawMessage = WebcastGiftMessage.parseFrom(bytes);
|
||||
var giftName =rawMessage.getGift().getName();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Assertions.assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotBeValid() {
|
||||
var TARGET_USER = "dqagdagda , asdaaasd";
|
||||
var sut = new TikTokDataChecker();
|
||||
var result = sut.isHostNameValid(TARGET_USER);
|
||||
|
||||
Assertions.assertFalse(result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.listener;
|
||||
|
||||
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.data.events.gift.TikTokGiftEvent;
|
||||
@@ -41,12 +42,12 @@ import static org.mockito.Mockito.verify;
|
||||
|
||||
class TikTokListenersManagerTest {
|
||||
|
||||
private io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver eventObserver;
|
||||
private TikTokLiveEventHandler eventObserver;
|
||||
private TikTokListenersManager tikTokListenersManager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
eventObserver = Mockito.mock(io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver.class);
|
||||
eventObserver = Mockito.mock(TikTokLiveEventHandler.class);
|
||||
List<TikTokEventListener> listeners = new ArrayList<>();
|
||||
tikTokListenersManager = new TikTokListenersManager(listeners, eventObserver);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
<parent>
|
||||
<artifactId>TikTokLiveJava</artifactId>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<version>1.0.9-Release</version>
|
||||
<version>1.5.2-Release</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@@ -60,6 +60,24 @@
|
||||
<version>${project.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<artifactId>extension-collector</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<artifactId>extension-recorder</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<artifactId>extension-collector</artifactId>
|
||||
<version>1.5.2-Release</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
@@ -22,21 +22,41 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.events_generator.EventGeneratorSettings;
|
||||
import io.github.jwdeveloper.tiktok.intefacee.EventsInterfaceGenerator;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.extension.collector.TikTokLiveCollector;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
public class CollectorExample {
|
||||
|
||||
public class EventsInterfaceGeneratorRun
|
||||
{
|
||||
public static void main(String[] args) throws IOException {
|
||||
var settings = new EventGeneratorSettings();
|
||||
settings.setTikTokEvent(true);
|
||||
settings.setPrefix("TikTok");
|
||||
settings.setEndFix("Event");
|
||||
settings.setInputDictionary("C:\\Users\\ja\\RiderProjects\\TikTokLiveSharp\\TikTokLiveSharp\\Events\\Messages");
|
||||
settings.setOutputDictionary("C:\\Users\\ja\\IdeaProjects\\TikTokLiveJava\\API\\src\\main\\java\\io\\github\\jwdeveloper\\tiktok\\events\\messages");
|
||||
var generator = new EventsInterfaceGenerator();
|
||||
generator.compile(settings);
|
||||
|
||||
var path = "C:\\Users\\ja\\IdeaProjects\\TikTokLiveJava\\Examples\\src\\main\\resources";
|
||||
var collector = TikTokLiveCollector.useFile(settings ->
|
||||
{
|
||||
settings.setParentFile(new File(path));
|
||||
});
|
||||
collector.connect();
|
||||
|
||||
var users = List.of("tehila_723", "dino123597", "domaxyzx", "dash4214", "obserwacje_live");
|
||||
Map<String, Object> additionalDataFields = Map.of("sessionTag", "ExampleTag");
|
||||
for (var user : users) {
|
||||
TikTokLive.newClient(user)
|
||||
.configure(liveClientSettings ->
|
||||
{
|
||||
liveClientSettings.setPrintToConsole(true);
|
||||
})
|
||||
.onError((liveClient, event) ->
|
||||
{
|
||||
event.getException().printStackTrace();
|
||||
})
|
||||
.addListener(collector.newListener(additionalDataFields))
|
||||
.buildAndConnectAsync();
|
||||
}
|
||||
|
||||
System.in.read();
|
||||
collector.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,77 +23,36 @@
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokSubNotifyEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokSubscribeEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.envelop.TikTokChestEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftEvent;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveOfflineHostException;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
import io.github.jwdeveloper.tiktok.utils.ConsoleColors;
|
||||
import io.github.jwdeveloper.tiktok.utils.JsonUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class SimpleExample {
|
||||
public static String TIKTOK_HOSTNAME = "bangbetmenygy";
|
||||
public class ConnectionExample {
|
||||
public static String TIKTOK_HOSTNAME = "kvadromama_marina1";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
showLogo();
|
||||
// set tiktok username
|
||||
|
||||
var gifts = TikTokLive.gifts();
|
||||
|
||||
|
||||
|
||||
/*
|
||||
//Optional checking if host name is correct
|
||||
if(TikTokLive.isHostNameValid(TIKTOK_HOSTNAME))
|
||||
{
|
||||
System.out.println("user name exists!");
|
||||
}
|
||||
*/
|
||||
|
||||
// Optional checking if live is online
|
||||
if (TikTokLive.isLiveOnline(TIKTOK_HOSTNAME)) {
|
||||
System.out.println("Live is online!");
|
||||
}
|
||||
|
||||
|
||||
TikTokLive.newClient("test")
|
||||
.onWebsocketResponse((liveClient, event) ->
|
||||
{
|
||||
var response = event.getResponse();
|
||||
for (var message : response.getMessagesList()) {
|
||||
var name = message.getMethod();
|
||||
var binaryData = message.getPayload();
|
||||
System.out.println("Event name: " + name);
|
||||
if (name.equals("WebcastGiftEvent")) {
|
||||
try {
|
||||
WebcastGiftMessage giftMessage = WebcastGiftMessage.parseFrom(binaryData);
|
||||
var giftName = giftMessage.getGift().getName();
|
||||
var giftId = giftMessage.getGiftId();
|
||||
var userName = giftMessage.getUser().getNickname();
|
||||
System.out.println("Gift: "+giftName+" id: "+giftId+" from user: "+userName);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Mapping error", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}).buildAndConnect();
|
||||
|
||||
|
||||
TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
|
||||
TikTokLive.newClient(ConnectionExample.TIKTOK_HOSTNAME)
|
||||
.configure(clientSettings ->
|
||||
{
|
||||
clientSettings.setHostName(SimpleExample.TIKTOK_HOSTNAME); // This method is useful in case you want change hostname later
|
||||
clientSettings.setHostName(ConnectionExample.TIKTOK_HOSTNAME); // This method is useful in case you want change hostname later
|
||||
clientSettings.setClientLanguage("en"); // Language
|
||||
clientSettings.setTimeout(Duration.ofSeconds(2)); // Connection timeout
|
||||
clientSettings.setLogLevel(Level.ALL); // Log level
|
||||
clientSettings.setPrintToConsole(true); // Printing all logs to console even if log level is Level.OFF
|
||||
clientSettings.setRetryOnConnectionFailure(true); // Reconnecting if TikTok user is offline
|
||||
clientSettings.setRetryConnectionTimeout(Duration.ofSeconds(1)); // Timeout before next reconnection
|
||||
|
||||
|
||||
clientSettings.getHttpSettings();
|
||||
|
||||
//Optional: Sometimes not every message 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
|
||||
|
||||
@@ -105,15 +64,6 @@ public class SimpleExample {
|
||||
|
||||
//clientSettings.setRoomId("XXXXXXXXXXXXXXXXX");
|
||||
})
|
||||
.onConnected((liveClient, event) ->
|
||||
{
|
||||
for (var gift : liveClient.getGiftManager().getGifts()) {
|
||||
gift.getPicture().downloadImageAsync().thenAccept(image ->
|
||||
{
|
||||
|
||||
});
|
||||
}
|
||||
})
|
||||
.onWebsocketMessage((liveClient, event) ->
|
||||
{
|
||||
|
||||
@@ -124,16 +74,21 @@ public class SimpleExample {
|
||||
}
|
||||
|
||||
})
|
||||
.onWebsocketResponse((liveClient, event) ->
|
||||
.onEvent((liveClient, event) ->
|
||||
{
|
||||
event.getResponse();
|
||||
if (event instanceof TikTokGiftEvent giftEvent) {
|
||||
System.out.println("1");
|
||||
}
|
||||
if (event instanceof TikTokChestEvent chestEvent) {
|
||||
System.out.println("2");
|
||||
}
|
||||
})
|
||||
.onGift((liveClient, event) ->
|
||||
{
|
||||
switch (event.getGift()) {
|
||||
case ROSE -> print(ConsoleColors.RED, "Rose!");
|
||||
case GG -> print(ConsoleColors.YELLOW, " GOOD GAME!");
|
||||
case TIKTOK -> print(ConsoleColors.CYAN, "Thanks for TikTok");
|
||||
switch (event.getGift().getName()) {
|
||||
case "ROSE" -> print(ConsoleColors.RED, "Rose!");
|
||||
case "GG" -> print(ConsoleColors.YELLOW, " GOOD GAME!");
|
||||
case "TIKTOK" -> print(ConsoleColors.CYAN, "Thanks for TikTok");
|
||||
default ->
|
||||
print(ConsoleColors.GREEN, "[Thanks for gift] ", ConsoleColors.YELLOW, event.getGift().getName(), "x", event.getCombo());
|
||||
}
|
||||
@@ -142,7 +97,7 @@ public class SimpleExample {
|
||||
{
|
||||
print(ConsoleColors.RED, "GIFT COMBO", event.getGift().getName(), event.getCombo());
|
||||
})
|
||||
.onConnected((client, event) ->
|
||||
.onConnected((liveClient, event) ->
|
||||
{
|
||||
print(ConsoleColors.GREEN, "[Connected]");
|
||||
})
|
||||
@@ -158,19 +113,19 @@ public class SimpleExample {
|
||||
{
|
||||
print(ConsoleColors.BLUE, "Follow:", ConsoleColors.WHITE_BRIGHT, event.getUser().getName());
|
||||
})
|
||||
.onJoin((client, event) ->
|
||||
.onJoin((liveClient, event) ->
|
||||
{
|
||||
print(ConsoleColors.WHITE, "Join:", ConsoleColors.WHITE_BRIGHT, event.getUser().getName());
|
||||
})
|
||||
.onComment((client, event) ->
|
||||
.onComment((liveClient, event) ->
|
||||
{
|
||||
print(ConsoleColors.GREEN, event.getUser().getName(), ":", ConsoleColors.WHITE_BRIGHT, event.getText());
|
||||
})
|
||||
.onEvent((client, event) ->
|
||||
.onEvent((liveClient, event) ->
|
||||
{
|
||||
//System.out.println("Event: " +event.getClass().getSimpleName());
|
||||
})
|
||||
.onError((client, event) ->
|
||||
.onError((liveClient, event) ->
|
||||
{
|
||||
event.getException().printStackTrace();
|
||||
})
|
||||
@@ -197,4 +152,4 @@ public class SimpleExample {
|
||||
""");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* 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 io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
public class CustomEventExample {
|
||||
@AllArgsConstructor
|
||||
public static class CheapGiftEvent extends TikTokEvent {
|
||||
Gift gift;
|
||||
}
|
||||
|
||||
@AllArgsConstructor
|
||||
public static class ExpensiveGiftEvent extends TikTokEvent {
|
||||
Gift gift;
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
TikTokLive.newClient(ConnectionExample.TIKTOK_HOSTNAME)
|
||||
.configure(clientSettings ->
|
||||
{
|
||||
clientSettings.setPrintToConsole(true);
|
||||
})
|
||||
.onGift((liveClient, event) ->
|
||||
{
|
||||
if (event.getGift().getDiamondCost() > 100)
|
||||
liveClient.publishEvent(new ExpensiveGiftEvent(event.getGift()));
|
||||
else
|
||||
liveClient.publishEvent(new CheapGiftEvent(event.getGift()));
|
||||
})
|
||||
.onEvent(CheapGiftEvent.class, (liveClient, event) ->
|
||||
{
|
||||
System.out.println("Thanks for cheap gift");
|
||||
})
|
||||
.onEvent(ExpensiveGiftEvent.class, (liveClient, event) ->
|
||||
{
|
||||
System.out.println("Thanks for expensive gift!");
|
||||
})
|
||||
.buildAndConnect();
|
||||
}
|
||||
}
|
||||
@@ -1,73 +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 io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
|
||||
|
||||
public class CustomGiftExample {
|
||||
/**
|
||||
* If you can't find your wanted Gift inside Gift enum register it manually
|
||||
*/
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
LiveClient client = TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
|
||||
.onConnected((liveClient, event) ->
|
||||
{
|
||||
liveClient.disconnect();
|
||||
})
|
||||
.onWebsocketResponse((liveClient, event) ->
|
||||
{
|
||||
var packets =event.getResponse().getMessagesList();
|
||||
for(var packet : packets)
|
||||
{
|
||||
var name = packet.getMethod();
|
||||
var data = packet.getPayload();
|
||||
if(name.equals("WebcastGiftMessage"))
|
||||
{
|
||||
// var message = WebcastGiftMessage.parseFrom(data);
|
||||
|
||||
}
|
||||
}
|
||||
})
|
||||
.onGift((liveClient, event) ->
|
||||
{
|
||||
liveClient.getLogger().info(event.getGift().getName());
|
||||
}).build();
|
||||
|
||||
GiftManager giftManager = client.getGiftManager();
|
||||
|
||||
//If you can't find your wanted Gift inside Gift enum register it manually
|
||||
giftManager.registerGift(123, "my custom gift", 69, new Picture("https://as2.ftcdn.net/v2/jpg/03/03/62/45/1000_F_303624505_u0bFT1Rnoj8CMUSs8wMCwoKlnWlh5Jiq.jpg"));
|
||||
|
||||
|
||||
//You can also override existing gift, for example Rose has Id 5655
|
||||
//We can make our custom gift appear in the event instead of rose
|
||||
giftManager.registerGift(5655, "custom-rose", 999, new Picture("https://as2.ftcdn.net/v2/jpg/03/03/62/45/1000_F_303624505_u0bFT1Rnoj8CMUSs8wMCwoKlnWlh5Jiq.jpg"));
|
||||
|
||||
client.connect();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user