mirror of
https://github.com/jwdeveloper/TikTokLiveJava.git
synced 2026-02-27 08:49:40 -05:00
Compare commits
127 Commits
1.0.15-Rel
...
develop-1.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af52e15a45 | ||
|
|
5577df7c9c | ||
|
|
2c68fe3421 | ||
|
|
5abfd95c89 | ||
|
|
5c715bfd52 | ||
|
|
b153afb332 | ||
|
|
d2ea00bcae | ||
|
|
4297af1349 | ||
|
|
d09c90ef54 | ||
|
|
9c96c8899a | ||
|
|
301df6392d | ||
|
|
fb9fc04ee5 | ||
|
|
43a8ba4225 | ||
|
|
dffccf1f0b | ||
|
|
6dcccccb78 | ||
|
|
0d467d79c3 | ||
|
|
33c98508c0 | ||
|
|
67948b14cc | ||
|
|
22e11a7822 | ||
|
|
4545503441 | ||
|
|
498d34a90b | ||
|
|
103ed7e3ed | ||
|
|
67e70c34bc | ||
|
|
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 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,10 +1,11 @@
|
||||
backend-infrastructure/.aws-sam
|
||||
|
||||
|
||||
.db
|
||||
# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode
|
||||
*.db
|
||||
### Linux ###
|
||||
*~
|
||||
.db
|
||||
# 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.14-Release</version>
|
||||
<version>1.6.2-Release</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>API</artifactId>
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
|
||||
@Data
|
||||
public class ClientSettings {
|
||||
/**
|
||||
* Timeout for Connections
|
||||
*/
|
||||
private Duration timeout;
|
||||
|
||||
/**
|
||||
* ISO-Language for Client
|
||||
*/
|
||||
|
||||
private String clientLanguage;
|
||||
|
||||
/**
|
||||
* Whether to Retry if Connection Fails
|
||||
*/
|
||||
private boolean retryOnConnectionFailure;
|
||||
|
||||
|
||||
/**
|
||||
* Before retrying connect, wait for select amount of time
|
||||
*/
|
||||
private Duration retryConnectionTimeout;
|
||||
|
||||
/**
|
||||
* Whether to 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
|
||||
*
|
||||
*/
|
||||
private String roomId;
|
||||
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -27,12 +27,12 @@ import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.LinkMicArmy;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.messages.enums.LinkMicBattleStatus;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLinkMicArmies;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/**
|
||||
* Triggered every time a battle participant receives points. Contains the current status of the battle and the army that suported the group.
|
||||
*/
|
||||
@@ -40,8 +40,10 @@ import java.util.List;
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokLinkMicArmiesEvent extends TikTokHeaderEvent {
|
||||
private final Long battleId;
|
||||
|
||||
private final Integer battleStatus;
|
||||
/**
|
||||
true if battle is finished otherwise false
|
||||
*/
|
||||
private final boolean finished;
|
||||
|
||||
private final Picture picture;
|
||||
|
||||
@@ -52,6 +54,6 @@ public class TikTokLinkMicArmiesEvent extends TikTokHeaderEvent {
|
||||
battleId = msg.getId();
|
||||
armies = msg.getBattleItemsList().stream().map(LinkMicArmy::new).toList();
|
||||
picture = Picture.map(msg.getImage());
|
||||
battleStatus = msg.getBattleStatus();
|
||||
finished = msg.getBattleStatus() == LinkMicBattleStatus.ARMY_FINISHED;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,29 +22,62 @@
|
||||
*/
|
||||
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.annotations.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.LinkMicBattleTeam;
|
||||
import io.github.jwdeveloper.tiktok.data.models.battles.*;
|
||||
import io.github.jwdeveloper.tiktok.messages.enums.LinkMicBattleStatus;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLinkMicBattle;
|
||||
import lombok.Getter;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Triggered every time a battle starts.
|
||||
* Triggered every time a battle starts & ends
|
||||
*/
|
||||
@Getter
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
public class TikTokLinkMicBattleEvent extends TikTokHeaderEvent {
|
||||
private final Long battleId;
|
||||
private final List<LinkMicBattleTeam> team1;
|
||||
private final List<LinkMicBattleTeam> team2;
|
||||
public class TikTokLinkMicBattleEvent extends TikTokHeaderEvent
|
||||
{
|
||||
private final Long battleId;
|
||||
/**
|
||||
true if battle is finished otherwise false
|
||||
*/
|
||||
private final boolean finished;
|
||||
@Getter(AccessLevel.NONE)
|
||||
private final boolean oneVsOne;
|
||||
private final List<Team> teams;
|
||||
|
||||
public TikTokLinkMicBattleEvent(WebcastLinkMicBattle msg) {
|
||||
super(msg.getCommon());
|
||||
battleId = msg.getId();
|
||||
team1 = msg.getTeams1List().stream().map(LinkMicBattleTeam::new).toList();
|
||||
team2 = msg.getTeams2List().stream().map(LinkMicBattleTeam::new).toList();
|
||||
}
|
||||
}
|
||||
public TikTokLinkMicBattleEvent(WebcastLinkMicBattle msg) {
|
||||
super(msg.getCommon());
|
||||
battleId = msg.getId();
|
||||
finished = msg.getBattleStatus() == LinkMicBattleStatus.BATTLE_FINISHED;
|
||||
teams = new ArrayList<>();
|
||||
if (msg.getHostTeamCount() == 2) { // 1v1 battle
|
||||
teams.add(new Team1v1(msg.getHostTeam(0), msg));
|
||||
teams.add(new Team1v1(msg.getHostTeam(1), msg));
|
||||
oneVsOne = true;
|
||||
} else { // 2v2 battle
|
||||
if (isFinished()) {
|
||||
teams.add(new Team2v2(msg.getHostData2V2List().stream().filter(data -> data.getTeamNumber() == 1).findFirst().orElse(null), msg));
|
||||
teams.add(new Team2v2(msg.getHostData2V2List().stream().filter(data -> data.getTeamNumber() == 2).findFirst().orElse(null), msg));
|
||||
} else {
|
||||
teams.add(new Team2v2(msg.getHostTeam(0), msg.getHostTeam(1), msg));
|
||||
teams.add(new Team2v2(msg.getHostTeam(2), msg.getHostTeam(3), msg));
|
||||
}
|
||||
oneVsOne = false;
|
||||
}
|
||||
|
||||
// Info:
|
||||
// - msg.getDetailsList() & msg.getViewerTeamList() both only have content when battle is finished
|
||||
// - msg.getDetailsCount() & msg.getViewerTeamCount() always is 2 only when battle is finished
|
||||
// - msg.getHostTeamCount() always is 2 for 1v1 or 4 for 2v2
|
||||
}
|
||||
|
||||
public boolean is1v1() {
|
||||
return oneVsOne;
|
||||
}
|
||||
|
||||
public boolean is2v2() {
|
||||
return !oneVsOne;
|
||||
}
|
||||
}
|
||||
@@ -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,17 +20,18 @@
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
package io.github.jwdeveloper.tiktok.data.events.control;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
|
||||
import io.github.jwdeveloper.tiktok.annotations.EventType;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface UserManager
|
||||
/**
|
||||
* Triggered when client is connecting to live is successfully established.
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Control)
|
||||
public class TikTokConnectingEvent extends TikTokLiveClientEvent
|
||||
{
|
||||
TrackedUser observeUser(User user);
|
||||
|
||||
TrackedUser getTrackedUser(Long id);
|
||||
|
||||
List<TrackedUser> getTrackedUsers();
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.data.events.control;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.annotations.*;
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.*;
|
||||
import lombok.*;
|
||||
|
||||
/**
|
||||
* Triggered before the connection is established.
|
||||
*/
|
||||
@EventMeta(eventType = EventType.Control)
|
||||
public class TikTokPreConnectionEvent extends TikTokLiveClientEvent
|
||||
{
|
||||
@Getter private final LiveUserData.Response userData;
|
||||
@Getter private final LiveData.Response roomData;
|
||||
@Getter @Setter boolean cancelConnection = false;
|
||||
|
||||
public TikTokPreConnectionEvent(LiveUserData.Response userData, LiveData.Response liveData) {
|
||||
this.userData = userData;
|
||||
this.roomData = liveData;
|
||||
}
|
||||
}
|
||||
@@ -22,10 +22,9 @@
|
||||
*/
|
||||
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;
|
||||
@@ -34,7 +33,7 @@ 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>
|
||||
@@ -47,10 +46,21 @@ import lombok.Getter;
|
||||
@EventMeta(eventType = EventType.Message)
|
||||
@Getter
|
||||
public class TikTokGiftComboEvent extends TikTokGiftEvent {
|
||||
private final GiftSendType comboState;
|
||||
private final GiftComboStateType comboState;
|
||||
|
||||
public TikTokGiftComboEvent(Gift gift, User host, WebcastGiftMessage msg, GiftSendType comboState) {
|
||||
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
|
||||
@@ -60,4 +56,20 @@ public class TikTokGiftEvent extends TikTokHeaderEvent {
|
||||
}
|
||||
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, ""));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,4 +46,4 @@ public class LinkMicArmy {
|
||||
List<User> Users;
|
||||
Integer Points;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,11 +44,11 @@ public class Picture {
|
||||
}
|
||||
|
||||
public static Picture map(io.github.jwdeveloper.tiktok.messages.data.Image profilePicture) {
|
||||
var index = profilePicture.getUrlListCount() - 1;
|
||||
var index = profilePicture.getUrlCount() - 1;
|
||||
if (index < 0) {
|
||||
return new Picture("");
|
||||
}
|
||||
var url = profilePicture.getUrlList(index);
|
||||
var url = profilePicture.getUrl(index);
|
||||
return new Picture(url);
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ public class Picture {
|
||||
}
|
||||
}
|
||||
|
||||
public static Picture Empty() {
|
||||
public static Picture empty() {
|
||||
return new Picture("");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.github.jwdeveloper.tiktok.data.models.battles;
|
||||
|
||||
public abstract class Team {
|
||||
/**
|
||||
* Provides a check for verifying if this team represents a 1v1 Team.
|
||||
* @return true if this team is of type {@link Team1v1}, false otherwise.
|
||||
*/
|
||||
public boolean is1v1Team() {
|
||||
return this instanceof Team1v1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides a check for verifying if this team represents a 1v1 Team.
|
||||
* @return true if this team is of type {@link Team1v1}, false otherwise.
|
||||
*/
|
||||
public boolean is2v2Team() {
|
||||
return this instanceof Team2v2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to get this team as a {@link Team1v1}. If this team is of some
|
||||
* other type, an {@link IllegalStateException} will result. Hence it is best to use this method
|
||||
* after ensuring that this element is of the desired type by calling {@link #is1v1Team()} first.
|
||||
*
|
||||
* @return this team as a {@link Team1v1}.
|
||||
* @throws IllegalStateException if this team is of another type.
|
||||
*/
|
||||
public Team1v1 getAs1v1Team() {
|
||||
if (is1v1Team())
|
||||
return (Team1v1) this;
|
||||
throw new IllegalStateException("Not a 1v1Team: " + this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to get this team as a {@link Team2v2}. If this team is of some
|
||||
* other type, an {@link IllegalStateException} will result. Hence it is best to use this method
|
||||
* after ensuring that this element is of the desired type by calling {@link #is2v2Team()} first.
|
||||
*
|
||||
* @return this team as a {@link Team2v2}.
|
||||
* @throws IllegalStateException if this team is of another type.
|
||||
*/
|
||||
public Team2v2 getAs2v2Team() {
|
||||
if (is2v2Team())
|
||||
return (Team2v2) this;
|
||||
throw new IllegalStateException("Not a 2v2Team: " + this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.github.jwdeveloper.tiktok.data.models.battles;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLinkMicBattle;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Getter
|
||||
public class Team1v1 extends Team
|
||||
{
|
||||
/** Value >= 0 when finished otherwise -1 */
|
||||
private final int totalPoints;
|
||||
private final int winStreak;
|
||||
private final User host;
|
||||
private final List<Viewer> viewers;
|
||||
|
||||
public Team1v1(WebcastLinkMicBattle.LinkMicBattleHost hostTeam, WebcastLinkMicBattle msg) {
|
||||
long hostId = hostTeam.getId();
|
||||
this.winStreak = msg.getTeamDataList().stream().filter(data -> data.getTeamId() == hostId).map(data -> data.getData().getWinStreak()).findFirst().orElse(-1);
|
||||
this.totalPoints = msg.getDetailsList().stream().filter(dets -> dets.getId() == hostId).map(dets -> dets.getSummary().getPoints()).findFirst().orElse(-1);
|
||||
this.host = new User(hostTeam.getHostGroup(0).getHost(0));
|
||||
this.viewers = msg.getViewerTeamList().stream().filter(team -> team.getId() == hostId).findFirst().map(topViewers ->
|
||||
topViewers.getViewerGroup(0).getViewerList().stream().map(Viewer::new).toList()).orElseGet(ArrayList::new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.github.jwdeveloper.tiktok.data.models.battles;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLinkMicBattle;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Getter
|
||||
public class Team2v2 extends Team {
|
||||
/** Value >= 0 when finished otherwise -1 */
|
||||
private final int totalPoints;
|
||||
|
||||
private final List<User> hosts;
|
||||
private final List<Viewer> viewers;
|
||||
|
||||
public Team2v2(WebcastLinkMicBattle.LinkMicBattleHost hostTeam1, WebcastLinkMicBattle.LinkMicBattleHost hostTeam2, WebcastLinkMicBattle msg) {
|
||||
this.totalPoints = -1;
|
||||
this.hosts = List.of(new User(hostTeam1.getHostGroup(0).getHost(0)), new User(hostTeam2.getHostGroup(0).getHost(0)));
|
||||
this.viewers = new ArrayList<>();
|
||||
}
|
||||
|
||||
public Team2v2(WebcastLinkMicBattle.Host2v2Data hd, WebcastLinkMicBattle msg) {
|
||||
this.totalPoints = hd.getTotalPoints();
|
||||
var host = new User(msg.getHostTeamList().stream().filter(data -> data.getId() == hd.getHostdata(0).getHostId()).findFirst().orElseThrow().getHostGroup(0).getHost(0));
|
||||
var cohost = new User(msg.getHostTeamList().stream().filter(data -> data.getId() == hd.getHostdata(1).getHostId()).findFirst().orElseThrow().getHostGroup(0).getHost(0));
|
||||
this.hosts = List.of(host, cohost);
|
||||
this.viewers = msg.getViewerTeamList().stream().filter(team -> team.getId() == host.getId() || team.getId() == cohost.getId()).findFirst().map(topViewers ->
|
||||
topViewers.getViewerGroup(0).getViewerList().stream().map(Viewer::new).toList()).orElseGet(ArrayList::new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package io.github.jwdeveloper.tiktok.data.models.battles;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLinkMicBattle;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class Viewer {
|
||||
private final User user;
|
||||
private final int points;
|
||||
|
||||
public Viewer(WebcastLinkMicBattle.LinkMicBattleTopViewers.TopViewerGroup.TopViewer topViewer) {
|
||||
this.user = new User(topViewer.getId(), null, topViewer.getProfileId(), Picture.map(topViewer.getImages(0)));
|
||||
this.points = topViewer.getPoints();
|
||||
}
|
||||
}
|
||||
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
@@ -24,7 +24,7 @@ package io.github.jwdeveloper.tiktok.data.models.users;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.badges.Badge;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastEnvelopeMessage;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.*;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
|
||||
@@ -136,6 +136,14 @@ public class User {
|
||||
this.picture = picture;
|
||||
}
|
||||
|
||||
public User(long id, String name, String profileId, Picture picture) {
|
||||
this(id, name, profileId, picture, 0, 0, List.of(Badge.empty()));
|
||||
}
|
||||
|
||||
public User(WebcastLinkMicBattle.LinkMicBattleHost.HostGroup.Host host) {
|
||||
this(host.getId(), host.getName(), host.getProfileId(), Picture.map(host.getImages(0)));
|
||||
}
|
||||
|
||||
public User(io.github.jwdeveloper.tiktok.messages.data.User user) {
|
||||
this(user.getId(), user.getDisplayId(), Picture.map(user.getAvatarThumb()));
|
||||
profileName = user.getNickname();
|
||||
@@ -159,10 +167,9 @@ public class User {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static User EMPTY = new User(0L,
|
||||
"",
|
||||
Picture.Empty(),
|
||||
Picture.empty(),
|
||||
0,
|
||||
0,
|
||||
List.of(Badge.empty()));
|
||||
@@ -209,4 +216,18 @@ public class User {
|
||||
0,
|
||||
List.of(Badge.empty()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", name='" + name + "'" +
|
||||
", profileName='" + profileName + "'" +
|
||||
", picture=" + picture +
|
||||
", following=" + following +
|
||||
", followers=" + followers +
|
||||
", badges=" + badges +
|
||||
", attributes=" + attributes +
|
||||
"}";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -20,22 +20,49 @@
|
||||
* 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;
|
||||
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.users.User;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLinkMicBattle;
|
||||
import lombok.Value;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Value
|
||||
public class LinkMicBattleTeam {
|
||||
Long teamId;
|
||||
List<User> users;
|
||||
|
||||
public LinkMicBattleTeam(WebcastLinkMicBattle.LinkMicBattleTeam team) {
|
||||
this.teamId = team.getId();
|
||||
this.users = team.getUsersList().stream().map(User::new).toList();
|
||||
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,34 +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.tools.db.tables;
|
||||
package io.github.jwdeveloper.tiktok.data.requests;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import lombok.*;
|
||||
|
||||
public class ExceptionInfoModel
|
||||
{
|
||||
private String message;
|
||||
private String stackTrace;
|
||||
public class LiveUserData {
|
||||
|
||||
public ExceptionInfoModel(Throwable throwable) {
|
||||
this.message = throwable.getMessage();
|
||||
this.stackTrace = getStackTraceAsString(throwable);
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Request {
|
||||
private String userName;
|
||||
}
|
||||
|
||||
public static String getStackTraceAsString(Throwable throwable) {
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
throwable.printStackTrace(pw);
|
||||
return sw.toString();
|
||||
@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;
|
||||
}
|
||||
}
|
||||
|
||||
// Getters for message and stackTrace
|
||||
public String getMessage() {
|
||||
return message;
|
||||
public enum UserStatus {
|
||||
NotFound,
|
||||
Offline,
|
||||
LivePaused,
|
||||
Live,
|
||||
}
|
||||
|
||||
public String getStackTrace() {
|
||||
return stackTrace;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
|
||||
@Getter
|
||||
public class HttpClientSettings {
|
||||
|
||||
private final Map<String, Object> params;
|
||||
|
||||
private final Map<String, String> headers;
|
||||
|
||||
private final Map<String, String> cookies;
|
||||
|
||||
@Setter
|
||||
private ProxyClientSettings proxyClientSettings;
|
||||
|
||||
private Consumer<HttpClient.Builder> onClientCreating;
|
||||
|
||||
private Consumer<HttpRequest.Builder> onRequestCreating;
|
||||
|
||||
@Setter
|
||||
private 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,98 @@ import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class Constants {
|
||||
@Data
|
||||
public class LiveClientSettings {
|
||||
|
||||
/**
|
||||
* Web-URL for TikTok
|
||||
* Sets client to offline mode, prohibits connection to TikTok servers
|
||||
* @apiNote Useful when testing client with custom events
|
||||
*/
|
||||
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";
|
||||
private boolean offline;
|
||||
|
||||
/**
|
||||
* Default TimeOut for Connections
|
||||
* Fetch and download gifts data before TikTokLive starts
|
||||
* @apiNote If `false`, client.giftManager() does not contain initial gifts
|
||||
*/
|
||||
public static final int DEFAULT_TIMEOUT = 20;
|
||||
|
||||
private boolean fetchGifts = true;
|
||||
|
||||
/**
|
||||
* Default Settings for Client
|
||||
* ISO-Language for Client
|
||||
*/
|
||||
public static ClientSettings DefaultClientSettings() {
|
||||
var clientSettings = new ClientSettings();
|
||||
clientSettings.setTimeout(Duration.ofSeconds(DEFAULT_TIMEOUT));
|
||||
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;
|
||||
|
||||
/** Throw an exception on 18+ Age Restriction */
|
||||
private boolean throwOnAgeRestriction;
|
||||
|
||||
/**
|
||||
* 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 +160,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,31 +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.events_generator;
|
||||
package io.github.jwdeveloper.tiktok.exceptions;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CSharpClassInfo
|
||||
/*
|
||||
* Happens while bad response from http proxy request to TikTok
|
||||
*/
|
||||
public class TikTokProxyRequestException extends TikTokLiveException
|
||||
{
|
||||
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));
|
||||
public TikTokProxyRequestException() {
|
||||
}
|
||||
|
||||
public void addConstructor(List<FieldInfo> arguments)
|
||||
{
|
||||
this.constructors.add(new ConstructorInfo(arguments));
|
||||
public TikTokProxyRequestException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public record FieldInfo(String type, String name){};
|
||||
public TikTokProxyRequestException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public record ConstructorInfo(List<FieldInfo> arguemtns){};
|
||||
}
|
||||
public TikTokProxyRequestException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public TikTokProxyRequestException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -20,29 +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.http;
|
||||
package io.github.jwdeveloper.tiktok.exceptions;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TikTokCookieJar {
|
||||
private final Map<String, String> cookies;
|
||||
public TikTokCookieJar() {
|
||||
cookies = new HashMap<>();
|
||||
public class TikTokSignServerException extends TikTokLiveRequestException
|
||||
{
|
||||
public TikTokSignServerException() {
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
return cookies.get(key);
|
||||
public TikTokSignServerException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public void set(String key, String value) {
|
||||
cookies.put(key, value);
|
||||
public TikTokSignServerException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public String parseCookies() {
|
||||
return cookies.entrySet()
|
||||
.stream()
|
||||
.map(entry -> entry.getKey()+"="+entry.getValue()+";")
|
||||
.collect(Collectors.joining());
|
||||
public TikTokSignServerException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
|
||||
public TikTokSignServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* 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 {@link GiftsData.Response} list of gifts that are compiled and available on github
|
||||
*/
|
||||
GiftsData.Response fetchGiftsData();
|
||||
|
||||
/**
|
||||
* @return {@link GiftsData.Response} list of gifts that are available in your region / livestream
|
||||
*/
|
||||
GiftsData.Response fetchRoomGiftsData(String room_id);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
@@ -22,42 +22,65 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.live;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import com.google.gson.JsonObject;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public interface GiftManager {
|
||||
public interface GiftsManager {
|
||||
|
||||
/**
|
||||
* In case you can't find your gift in Gift enum. You can register gift
|
||||
* manually here to make it detected while TikTokGiftEvent
|
||||
* You can create and attach your own custom gift to manager
|
||||
*
|
||||
* @param id gift's id
|
||||
* @param name gift's name
|
||||
* @param diamondCost diamond cost
|
||||
* @return
|
||||
* @param gift
|
||||
*/
|
||||
Gift registerGift(int id, String name, int diamondCost, Picture picture);
|
||||
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);
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param giftId
|
||||
* @return
|
||||
* finds gift by filter
|
||||
* When gift not found return Gift.UNDEFINED;
|
||||
*/
|
||||
Gift findById(int giftId);
|
||||
Gift getByFilter(Predicate<Gift> filter);
|
||||
|
||||
List<Gift> getManyByFilter(Predicate<Gift> filter);
|
||||
|
||||
/**
|
||||
*
|
||||
* @param giftName
|
||||
* @return
|
||||
* @return list of all gifts
|
||||
*/
|
||||
Gift findByName(String giftName);
|
||||
List<Gift> toList();
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @return all gifts
|
||||
* @return list of all map of all gifts where Integer is gift Id
|
||||
*/
|
||||
List<Gift> getGifts();
|
||||
}
|
||||
Map<Integer, Gift> toMap();
|
||||
}
|
||||
@@ -59,12 +59,21 @@ public interface LiveClient {
|
||||
/**
|
||||
* 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.
|
||||
|
||||
@@ -47,7 +47,7 @@ public interface LiveRoomInfo
|
||||
String getRoomId();
|
||||
String getHostName();
|
||||
String getTitle();
|
||||
User getHostUser();
|
||||
User getHost();
|
||||
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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -102,7 +102,8 @@ message Text {
|
||||
|
||||
// @Image
|
||||
message Image {
|
||||
repeated string urlList = 1;
|
||||
repeated string url = 1;
|
||||
string extras = 2;
|
||||
bool isAnimated = 9;
|
||||
}
|
||||
|
||||
@@ -976,131 +977,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 +1129,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 {
|
||||
|
||||
}
|
||||
|
||||
@@ -35,6 +35,14 @@ enum LinkmicApplierSortSetting {
|
||||
LINKMIC_APPLIER_SORT_SETTING_BY_GIFT_SCORE = 1;
|
||||
}
|
||||
|
||||
enum LinkMicBattleStatus {
|
||||
BATTLE_ARMY_UNKNOWN = 0;
|
||||
ARMY_ONGOING = 1;
|
||||
ARMY_FINISHED = 2;
|
||||
BATTLE_ONGOING = 4;
|
||||
BATTLE_FINISHED = 5;
|
||||
}
|
||||
|
||||
enum HashtagNamespace {
|
||||
GLOBAL = 0;
|
||||
GAMING = 1;
|
||||
@@ -241,6 +249,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;
|
||||
|
||||
@@ -25,10 +25,6 @@ message WebcastPushFrame {
|
||||
|
||||
}
|
||||
|
||||
message WebcastWebsocketAck {
|
||||
uint64 Id = 1;
|
||||
string Type = 2;
|
||||
}
|
||||
|
||||
|
||||
//@WebcastResponse
|
||||
@@ -525,7 +521,7 @@ message WebcastLinkMicArmies {
|
||||
uint64 id2 = 4;
|
||||
uint64 timeStamp1 = 5;
|
||||
uint64 timeStamp2 = 6;
|
||||
int32 battleStatus = 7; // SHOULD BE AN ENUM
|
||||
LinkMicBattleStatus battleStatus = 7;
|
||||
uint64 data1 = 8;
|
||||
uint64 data2 = 9;
|
||||
uint32 data3 = 10;
|
||||
@@ -578,11 +574,26 @@ message WebcastLinkMicBattle {
|
||||
Common common = 1;
|
||||
uint64 id = 2;
|
||||
LinkMicBattleConfig battleConfig = 3;
|
||||
uint32 data2 = 4;
|
||||
LinkMicBattleStatus battleStatus = 4;
|
||||
repeated LinkMicBattleDetails details = 5;
|
||||
repeated LinkMicBattleTeam teams1 = 9;
|
||||
repeated LinkMicBattleTeam teams2 = 10;
|
||||
repeated LinkMicBattleTopViewers viewerTeam = 9;
|
||||
repeated LinkMicBattleHost hostTeam = 10;
|
||||
repeated LinkMicBattleTeamData teamData = 13;
|
||||
uint64 unknownData16 = 16;
|
||||
repeated Host2v2Data hostData2v2 = 17;
|
||||
|
||||
message Host2v2Data {
|
||||
uint32 teamNumber = 1;
|
||||
repeated HostData hostdata = 2;
|
||||
uint32 unknownData3 = 3;
|
||||
uint32 totalPoints = 4;
|
||||
|
||||
message HostData {
|
||||
uint64 hostId = 1;
|
||||
uint32 points = 2;
|
||||
string hostIdStr = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message LinkMicBattleConfig {
|
||||
uint64 id1 = 1;
|
||||
@@ -590,29 +601,69 @@ message WebcastLinkMicBattle {
|
||||
uint32 data1 = 3;
|
||||
uint64 id2 = 4;
|
||||
uint32 data2 = 5;
|
||||
uint32 data3 = 6;
|
||||
uint32 data4 = 8;
|
||||
}
|
||||
|
||||
message LinkMicBattleTeamData {
|
||||
uint64 teamId = 1;
|
||||
LinkMicBattleData data = 2;
|
||||
}
|
||||
|
||||
message LinkMicBattleData {
|
||||
uint64 id = 1;
|
||||
uint32 data1 = 2;
|
||||
uint32 data2 = 3;
|
||||
uint32 winStreak = 3;
|
||||
uint32 data3 = 5;
|
||||
string url = 6;
|
||||
}
|
||||
|
||||
message LinkMicBattleDetails {
|
||||
uint64 id = 1;
|
||||
LinkMicBattleData details = 2;
|
||||
LinkMicBattleDetailsSummary summary = 2;
|
||||
|
||||
message LinkMicBattleDetailsSummary {
|
||||
uint64 id = 1;
|
||||
uint32 unknownData2 = 2;
|
||||
uint32 points = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message LinkMicBattleTeam {
|
||||
message LinkMicBattleTopViewers {
|
||||
uint64 id = 1;
|
||||
repeated User users = 2;
|
||||
repeated TopViewerGroup viewerGroup = 2;
|
||||
|
||||
message TopViewerGroup {
|
||||
repeated TopViewer viewer = 1;
|
||||
uint32 points = 2;
|
||||
string hostIdOrTeamNum = 3; // 1v1 Battle = HostId | 2v2 Battle = Team # - 1 & 2
|
||||
|
||||
message TopViewer {
|
||||
uint64 id = 1;
|
||||
uint32 points = 2;
|
||||
string profileId = 3;
|
||||
repeated Image images = 4;
|
||||
string stringId = 6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
message LinkMicBattleTeamData {
|
||||
uint64 teamId = 1;
|
||||
LinkMicBattleData data = 2;
|
||||
message LinkMicBattleHost {
|
||||
uint64 id = 1;
|
||||
repeated HostGroup hostGroup = 2;
|
||||
|
||||
message HostGroup {
|
||||
repeated Host host = 1;
|
||||
uint32 points = 2;
|
||||
string hostId = 3;
|
||||
|
||||
message Host {
|
||||
uint64 id = 1;
|
||||
string profileId = 2;
|
||||
repeated Image images = 3;
|
||||
string name = 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -733,7 +784,7 @@ message WebcastSystemMessage {
|
||||
//@WebcastLinkMessage
|
||||
message WebcastLinkMessage {
|
||||
Common common = 1;
|
||||
MessageType MessageType = 2;
|
||||
LinkMessageType MessageType = 2;
|
||||
int64 LinkerId = 3;
|
||||
Scene Scene = 4;
|
||||
LinkerInviteContent InviteContent = 5;
|
||||
@@ -752,14 +803,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -796,6 +847,4 @@ message RoomVerifyMessage {
|
||||
string content = 3;
|
||||
int64 noticeType = 4;
|
||||
bool closeRoom = 5;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<artifactId>TikTokLiveJava</artifactId>
|
||||
<groupId>io.github.jwdeveloper.tiktok</groupId>
|
||||
<version>1.0.14-Release</version>
|
||||
<version>1.6.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,88 @@
|
||||
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,51 +22,52 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.dto.TikTokUserInfo;
|
||||
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 com.google.protobuf.ByteString;
|
||||
import io.github.jwdeveloper.tiktok.data.events.*;
|
||||
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.listener.ListenersManager;
|
||||
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.LiveRoomInfo;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
|
||||
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.LiveHttpClient;
|
||||
import io.github.jwdeveloper.tiktok.listener.*;
|
||||
import io.github.jwdeveloper.tiktok.live.*;
|
||||
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
|
||||
import io.github.jwdeveloper.tiktok.models.ConnectionState;
|
||||
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;
|
||||
@@ -76,17 +77,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;
|
||||
});
|
||||
@@ -117,56 +116,95 @@ 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 (clientSettings.isFetchGifts())
|
||||
giftsManager.attachGiftsList(httpClient.fetchRoomGiftsData(userData.getRoomId()).getGifts());
|
||||
|
||||
apiService.updateSessionId();
|
||||
if (userData.getUserStatus() == LiveUserData.UserStatus.Offline)
|
||||
throw new TikTokLiveOfflineHostException("User is offline: " + liveRoomInfo.getHostName());
|
||||
|
||||
TikTokUserInfo info = apiService.fetchUserInfoFromTikTokApi(liveRoomInfo.getHostName());
|
||||
liveRoomInfo.setStartTime(info.getStartTime());
|
||||
if (clientSettings.getRoomId() != null) {
|
||||
liveRoomInfo.setRoomId(clientSettings.getRoomId());
|
||||
logger.info("Using roomID from settings: " + clientSettings.getRoomId());
|
||||
} else {
|
||||
liveRoomInfo.setRoomId(info.getRoomId());
|
||||
}
|
||||
apiService.updateRoomId(liveRoomInfo.getRoomId());
|
||||
if (userData.getUserStatus() == LiveUserData.UserStatus.NotFound)
|
||||
throw new TikTokLiveOfflineHostException("User not found: " + liveRoomInfo.getHostName());
|
||||
|
||||
var liveDataRequest = new LiveData.Request(userData.getRoomId());
|
||||
var liveData = httpClient.fetchLiveData(liveDataRequest);
|
||||
|
||||
var 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.isAgeRestricted() && clientSettings.isThrowOnAgeRestriction())
|
||||
throw new TikTokLiveException("Livestream for " + liveRoomInfo.getHostName() + " is 18+ or age restricted!");
|
||||
|
||||
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.HostNotFound)
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for " + liveRoomInfo.getHostName() + " could not be found.");
|
||||
|
||||
if (liveData.getLiveStatus() == LiveData.LiveStatus.HostOffline)
|
||||
throw new TikTokLiveOfflineHostException("LiveStream for " + liveRoomInfo.getHostName() + " not found, is the Host offline?");
|
||||
|
||||
tikTokEventHandler.publish(this, new TikTokRoomDataResponseEvent(liveData));
|
||||
|
||||
liveRoomInfo.setTitle(liveData.getTitle());
|
||||
liveRoomInfo.setViewersCount(liveData.getViewers());
|
||||
liveRoomInfo.setTotalViewersCount(liveData.getTotalViewers());
|
||||
liveRoomInfo.setAgeRestricted(liveData.isAgeRestricted());
|
||||
liveRoomInfo.setHost(liveData.getHost());
|
||||
|
||||
var preconnectEvent = new TikTokPreConnectionEvent(userData, liveData);
|
||||
tikTokEventHandler.publish(this, preconnectEvent);
|
||||
if (preconnectEvent.isCancelConnection())
|
||||
throw new TikTokLiveException("TikTokPreConnectionEvent cancelled connection!");
|
||||
|
||||
var liveConnectionRequest = new LiveConnectionData.Request(userData.getRoomId());
|
||||
var liveConnectionData = httpClient.fetchLiveConnectionData(liveConnectionRequest);
|
||||
webSocketClient.start(liveConnectionData, this);
|
||||
|
||||
var clientData = apiService.fetchClientData();
|
||||
webSocketClient.start(clientData, this);
|
||||
setState(ConnectionState.CONNECTED);
|
||||
tikTokEventHandler.publish(this, new TikTokRoomInfoEvent(liveRoomInfo));
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (liveRoomInfo.hasConnectionState(ConnectionState.DISCONNECTED)) {
|
||||
return;
|
||||
}
|
||||
setState(ConnectionState.DISCONNECTED);
|
||||
webSocketClient.stop();
|
||||
}
|
||||
|
||||
private void setState(ConnectionState connectionState) {
|
||||
logger.info("TikTokLive client state: " + connectionState.name());
|
||||
liveRoomInfo.setConnectionState(connectionState);
|
||||
}
|
||||
|
||||
public void publishEvent(TikTokEvent event) {
|
||||
tikTokEventHandler.publish(this, event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishMessage(String webcastMessageName, String payloadBase64) {
|
||||
this.publishMessage(webcastMessageName, Base64.getDecoder().decode(payloadBase64));
|
||||
}
|
||||
@Override
|
||||
public void publishMessage(String webcastMessageName, byte[] payload) {
|
||||
|
||||
var builder = WebcastResponse.Message.newBuilder();
|
||||
builder.setMethod(webcastMessageName);
|
||||
builder.setPayload(ByteString.copyFrom(payload));
|
||||
var message = builder.build();
|
||||
messageHandler.handleSingleMessage(this, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GiftsManager getGiftManager() {
|
||||
return giftsManager;
|
||||
}
|
||||
|
||||
public LiveRoomInfo getRoomInfo() {
|
||||
return liveRoomInfo;
|
||||
@@ -181,20 +219,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().isEmpty()) {
|
||||
clientSettings.setClientLanguage(Constants.DefaultClientSettings().getClientLanguage());
|
||||
}
|
||||
|
||||
|
||||
if (clientSettings.getHostName() == null || clientSettings.getHostName().isEmpty()) {
|
||||
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, roomInfo);
|
||||
var giftHandler = new TikTokGiftEventHandler(giftsManager, roomInfo);
|
||||
var roomInfoHandler = new TikTokRoomInfoEventHandler(roomInfo);
|
||||
var socialHandler = new TikTokSocialMediaEventHandler(roomInfo);
|
||||
|
||||
@@ -248,14 +207,20 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
|
||||
|
||||
|
||||
//LinkMic events
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicArmies.class, TikTokLinkMicArmiesEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
|
||||
mapper.forMessage(WebcastLinkMicBattle.class, (inputBytes, messageName, mapperHelper) -> {
|
||||
var message = mapperHelper.bytesToWebcastObject(inputBytes, WebcastLinkMicBattle.class);
|
||||
return MappingResult.of(message, new TikTokLinkMicBattleEvent(message));
|
||||
});
|
||||
mapper.forMessage(WebcastLinkMicArmies.class, (inputBytes, messageName, mapperHelper) -> {
|
||||
var message = mapperHelper.bytesToWebcastObject(inputBytes, WebcastLinkMicArmies.class);
|
||||
return MappingResult.of(message, new TikTokLinkMicArmiesEvent(message));
|
||||
});
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
|
||||
|
||||
//Rank events
|
||||
// mapper.webcastObjectToConstructor(WebcastRankTextMessage.class, TikTokRankTextEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
|
||||
// mapper.webcastObjectToConstructor(WebcastHourlyRankMessage.class, TikTokRankUpdateEvent.class);
|
||||
|
||||
//Others events
|
||||
@@ -263,7 +228,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,273 +248,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,230 @@
|
||||
/*
|
||||
* 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 String TIKTOK_ROOM_GIFTS_URL = TIKTOK_URL_WEBCAST+"gift/list/";
|
||||
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 fetchRoomGiftsData(String room_id) {
|
||||
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
|
||||
if (proxyClientSettings.isEnabled()) {
|
||||
while (proxyClientSettings.hasNext()) {
|
||||
try {
|
||||
return getRoomGiftsData(room_id);
|
||||
} catch (TikTokProxyRequestException ignored) {}
|
||||
}
|
||||
}
|
||||
return getRoomGiftsData(room_id);
|
||||
}
|
||||
|
||||
public GiftsData.Response getRoomGiftsData(String room_id) {
|
||||
var result = httpFactory.client(TIKTOK_ROOM_GIFTS_URL)
|
||||
.withParam("room_id", room_id)
|
||||
.build()
|
||||
.toJsonResponse();
|
||||
|
||||
if (result.isFailure())
|
||||
throw new TikTokLiveRequestException("Unable to fetch gifts information's - "+result);
|
||||
|
||||
var json = result.getContent();
|
||||
return giftsDataMapper.mapRoom(json);
|
||||
}
|
||||
|
||||
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,50 @@
|
||||
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 GiftsData.Response fetchRoomGiftsData(String room_id) {
|
||||
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));
|
||||
@@ -61,11 +61,6 @@ public class TikTokRoomInfo implements LiveRoomInfo {
|
||||
return connectionState == state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getHostUser() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void updateRanking(List<RankingUser> rankingUsers) {
|
||||
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,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.gifts;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
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) {
|
||||
Gift gift = indexById.get(giftId);
|
||||
return gift == null ? Gift.UNDEFINED : gift;
|
||||
}
|
||||
|
||||
public Gift findByName(String giftName) {
|
||||
Gift gift = indexByName.get(giftName);
|
||||
return gift == null ? Gift.UNDEFINED : gift;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Gift> getGifts() {
|
||||
return indexById.values().stream().toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.jwdeveloper.tiktok.gifts;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftsManager;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
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, Function.identity()));
|
||||
}
|
||||
|
||||
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) {
|
||||
return giftsByIdIndex.getOrDefault(giftId, Gift.UNDEFINED);
|
||||
}
|
||||
|
||||
public Gift getByFilter(Predicate<Gift> filter) {
|
||||
return giftsByIdIndex.values()
|
||||
.stream()
|
||||
.filter(filter)
|
||||
.findFirst()
|
||||
.orElse(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);
|
||||
}
|
||||
}
|
||||
@@ -22,14 +22,23 @@
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import java.util.Map;
|
||||
import io.github.jwdeveloper.tiktok.data.settings.*;
|
||||
|
||||
public interface TikTokHttpRequest {
|
||||
TikTokHttpRequest setQueries(Map<String, Object> queries);
|
||||
public class HttpClientFactory {
|
||||
private final LiveClientSettings liveClientSettings;
|
||||
|
||||
TikTokHttpRequest setHeader(String key, String value);
|
||||
String get(String url);
|
||||
public HttpClientFactory(LiveClientSettings liveClientSettings) {
|
||||
this.liveClientSettings = liveClientSettings;
|
||||
}
|
||||
|
||||
String post(String url);
|
||||
public HttpClientBuilder client(String url) {
|
||||
return new HttpClientBuilder(url, liveClientSettings.getHttpSettings().clone());
|
||||
}
|
||||
|
||||
}
|
||||
//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);
|
||||
}
|
||||
}
|
||||
@@ -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,51 +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 java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class HttpUtils
|
||||
{
|
||||
public static String parseParameters(String url, Map<String,Object> parameters)
|
||||
{
|
||||
if (parameters.isEmpty())
|
||||
return url;
|
||||
|
||||
return url+ "?" + parameters.entrySet().stream().map(entry -> entry.getKey()+"="+entry.getValue()).collect(Collectors.joining("&"));
|
||||
}
|
||||
|
||||
public static String parseParametersEncode(String url, Map<String,Object> parameters)
|
||||
{
|
||||
if (parameters.isEmpty())
|
||||
return url;
|
||||
|
||||
return url+ "?" + parameters.entrySet().stream().map(entry -> {
|
||||
String encodedKey = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
|
||||
String encodedValue = URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8);
|
||||
return encodedKey+"="+encodedValue;
|
||||
}).collect(Collectors.joining("&"));
|
||||
}
|
||||
}
|
||||
@@ -1,138 +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.*;
|
||||
import io.github.jwdeveloper.tiktok.ClientSettings;
|
||||
import io.github.jwdeveloper.tiktok.data.dto.TikTokUserInfo;
|
||||
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;
|
||||
|
||||
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 void updateRoomId(String roomId)
|
||||
{
|
||||
clientSettings.getClientParameters().put("room_id", roomId);
|
||||
}
|
||||
|
||||
public TikTokUserInfo fetchUserInfoFromTikTokApi(String userName) {
|
||||
var params = new HashMap<>(clientSettings.getClientParameters());
|
||||
params.put("uniqueId", userName);
|
||||
params.put("sourceType", 54);
|
||||
JsonObject roomData;
|
||||
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 the developer");
|
||||
}
|
||||
if (message.equals("user_not_found")) {
|
||||
return new TikTokUserInfo(TikTokUserInfo.UserStatus.NotFound, "", -1);
|
||||
}
|
||||
//live -> status 2
|
||||
//live paused -> 3
|
||||
//not live -> status 4
|
||||
var element = roomData.get("data");
|
||||
if (element.isJsonNull()) {
|
||||
return new TikTokUserInfo(TikTokUserInfo.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 -> TikTokUserInfo.UserStatus.Live;
|
||||
case 3 -> TikTokUserInfo.UserStatus.LivePaused;
|
||||
case 4 -> TikTokUserInfo.UserStatus.Offline;
|
||||
default -> TikTokUserInfo.UserStatus.NotFound;
|
||||
};
|
||||
|
||||
return new TikTokUserInfo(statusEnum, roomId, startTime);
|
||||
}
|
||||
|
||||
|
||||
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,154 +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,167 +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;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
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<>(queries);
|
||||
query = testMap.entrySet().stream().map(x -> {
|
||||
var key = x.getKey();
|
||||
try {
|
||||
return key+"="+URLEncoder.encode(x.getValue().toString(), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return key + "=";
|
||||
}
|
||||
}).collect(Collectors.joining("&"));
|
||||
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(response), HttpData.map(request));
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.data.requests.GiftsData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class GiftsDataMapper {
|
||||
|
||||
public GiftsData.Response map(String json) {
|
||||
var parsedJson = JsonParser.parseString(json);
|
||||
var jsonObject = parsedJson.getAsJsonObject();
|
||||
var gifts = jsonObject.entrySet()
|
||||
.parallelStream()
|
||||
.map(e -> mapSingleGift(e.getValue()))
|
||||
.toList();
|
||||
|
||||
return new GiftsData.Response(json, gifts);
|
||||
}
|
||||
|
||||
private Gift mapSingleGift(JsonElement jsonElement) {
|
||||
var jsonObject = jsonElement.getAsJsonObject();
|
||||
|
||||
var id = jsonObject.get("id").getAsInt();
|
||||
var name = jsonObject.get("name").getAsString();
|
||||
var diamondCost = jsonObject.get("diamondCost").getAsInt();
|
||||
var image = jsonObject.get("image").getAsString();
|
||||
return new Gift(id, name, diamondCost, new Picture(image), jsonObject);
|
||||
}
|
||||
|
||||
public GiftsData.Response mapRoom(String json) {
|
||||
var parsedJson = JsonParser.parseString(json);
|
||||
var jsonObject = parsedJson.getAsJsonObject();
|
||||
if (jsonObject.get("data") instanceof JsonObject data && data.get("gifts") instanceof JsonArray giftArray) {
|
||||
var gifts = giftArray.asList().parallelStream()
|
||||
.map(this::mapSingleRoomGift)
|
||||
.toList();
|
||||
|
||||
return new GiftsData.Response(json, gifts);
|
||||
}
|
||||
return new GiftsData.Response("", List.of());
|
||||
}
|
||||
|
||||
private Gift mapSingleRoomGift(JsonElement jsonElement) {
|
||||
var jsonObject = jsonElement.getAsJsonObject();
|
||||
|
||||
var id = jsonObject.get("id").getAsInt();
|
||||
var name = jsonObject.get("name").getAsString();
|
||||
var diamondCost = jsonObject.get("diamond_count").getAsInt();
|
||||
Picture picture;
|
||||
if (jsonObject.get("image") instanceof JsonObject image && image.get("url_list") instanceof JsonArray urls && !urls.isEmpty()) {
|
||||
String url = urls.get(0).getAsString();
|
||||
if (url.endsWith(".webp"))
|
||||
url = url.substring(0, url.length()-4)+"png";
|
||||
picture = new Picture(url);
|
||||
} else
|
||||
picture = Picture.empty();
|
||||
return new Gift(id, name, diamondCost, picture, 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,17 +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.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 - ?
|
||||
@@ -38,38 +41,46 @@ 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") && data.get("prompts").getAsString().isEmpty() && jsonObject.has("status_code")) {
|
||||
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")) {
|
||||
@@ -81,44 +92,57 @@ 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,6 +111,7 @@ 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);
|
||||
|
||||
@@ -24,32 +24,27 @@ 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.exceptions.TikTokLiveException;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
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, TikTokRoomInfo tikTokRoomInfo) {
|
||||
this.giftManager = giftManager;
|
||||
private final GiftsManager giftsManager;
|
||||
|
||||
public TikTokGiftEventHandler(GiftsManager giftsManager, TikTokRoomInfo tikTokRoomInfo) {
|
||||
giftsMessages = new HashMap<>();
|
||||
this.tikTokRoomInfo = tikTokRoomInfo;
|
||||
this.giftsManager = giftsManager;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
@@ -61,40 +56,40 @@ public class TikTokGiftEventHandler {
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -107,42 +102,28 @@ public class TikTokGiftEventHandler {
|
||||
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, 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")) {
|
||||
updatePicture(gift, giftMessage);
|
||||
}
|
||||
if (gift.getPicture().getLink().endsWith(".webp"))
|
||||
gift.setPicture(Picture.map(giftMessage.getGift().getImage()));
|
||||
|
||||
return gift;
|
||||
}
|
||||
|
||||
|
||||
private void updatePicture(Gift gift, WebcastGiftMessage webcastGiftMessage) {
|
||||
try {
|
||||
var picture = Picture.map(webcastGiftMessage.getGift().getImage());
|
||||
var constructor = Unsafe.class.getDeclaredConstructors()[0];
|
||||
constructor.setAccessible(true);
|
||||
var field = Gift.class.getDeclaredField("picture");
|
||||
field.setAccessible(true);
|
||||
field.set(gift, picture);
|
||||
} catch (Exception e) {
|
||||
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<>(clientSettings.getHttpSettings().getHeaders());
|
||||
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,92 @@
|
||||
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 (isOpen()) {
|
||||
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 (isOpen()) {
|
||||
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 (isOpen()) {
|
||||
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 (isOpen()) {
|
||||
sendPing();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<WebcastPushFrame> getWebcastPushFrame(byte[] buffer) {
|
||||
try {
|
||||
var websocketMessage = WebcastPushFrame.parseFrom(buffer);
|
||||
if (websocketMessage.getPayload().isEmpty()) {
|
||||
@@ -139,28 +128,8 @@ public class TikTokWebSocketListener extends WebSocketClient {
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -26,8 +26,9 @@ 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;
|
||||
@@ -38,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)
|
||||
@@ -46,13 +47,12 @@ class TikTokGiftEventHandlerTest {
|
||||
|
||||
public static TikTokGiftEventHandler handler;
|
||||
|
||||
|
||||
@BeforeAll
|
||||
public void before() {
|
||||
var manager = new TikTokGiftManager(Logger.getLogger("x"));
|
||||
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.registerGift(123, "example", 123, new Picture("image.webp"));
|
||||
manager.attachGift(new Gift(123, "example", 123, "image.webp"));
|
||||
handler = new TikTokGiftEventHandler(manager, info);
|
||||
}
|
||||
|
||||
@@ -98,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());
|
||||
}
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ class TikTokGiftEventHandlerTest {
|
||||
|
||||
giftBuilder.setId(giftId);
|
||||
giftBuilder.setName(giftName);
|
||||
giftBuilder.setImage(Image.newBuilder().addUrlList(giftImage).build());
|
||||
giftBuilder.setImage(Image.newBuilder().addUrl(giftImage).build());
|
||||
giftBuilder.setType(streakable ? 1 : 0);
|
||||
userBuilder.setId(userId);
|
||||
|
||||
@@ -129,4 +129,4 @@ class TikTokGiftEventHandlerTest {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
package io.github.jwdeveloper.tiktok.http;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class HttpUtilsTest
|
||||
{
|
||||
@Test
|
||||
public void parseParameters_EmptyParameters_ShouldHaveNoParameters()
|
||||
{
|
||||
String parsed = HttpUtils.parseParameters("https://webcast.tiktok.com/webcast/im/fetch/", new HashMap<>());
|
||||
|
||||
Assertions.assertEquals("https://webcast.tiktok.com/webcast/im/fetch/", parsed);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseParameters_ValidParameters_ShouldConstructValidURL()
|
||||
{
|
||||
LinkedHashMap<String, Object> testMap = new LinkedHashMap<>();
|
||||
testMap.put("room_id", 1);
|
||||
testMap.put("uniqueId", "randomName");
|
||||
String parsed = HttpUtils.parseParameters("https://webcast.tiktok.com/webcast/im/fetch/", testMap);
|
||||
|
||||
Assertions.assertEquals("https://webcast.tiktok.com/webcast/im/fetch/?room_id=1&uniqueId=randomName", parsed);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseParametersEncode_EmptyParameters_ShouldHaveNoParameters()
|
||||
{
|
||||
String parsed = HttpUtils.parseParametersEncode("https://webcast.tiktok.com/webcast/im/fetch/", new HashMap<>());
|
||||
|
||||
Assertions.assertEquals("https://webcast.tiktok.com/webcast/im/fetch/", parsed);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseParametersEncode_ValidParameters_ShouldConstructValidURL()
|
||||
{
|
||||
LinkedHashMap<String, Object> testMap = new LinkedHashMap<>();
|
||||
testMap.put("room_id", 1);
|
||||
testMap.put("root_referer", "https://www.tiktok.com/");
|
||||
String parsed = HttpUtils.parseParametersEncode("https://webcast.tiktok.com/webcast/im/fetch/", testMap);
|
||||
|
||||
Assertions.assertEquals("https://webcast.tiktok.com/webcast/im/fetch/?room_id=1&root_referer=https%3A%2F%2Fwww.tiktok.com%2F", parsed);
|
||||
}
|
||||
}
|
||||
@@ -1,110 +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.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 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.14-Release</version>
|
||||
<version>1.6.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.6.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 {
|
||||
""");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,10 +23,7 @@
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.models.Picture;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
|
||||
import io.github.jwdeveloper.tiktok.live.GiftManager;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
import io.github.jwdeveloper.tiktok.data.models.gifts.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
public class CustomEventExample {
|
||||
@@ -40,8 +37,13 @@ public class CustomEventExample {
|
||||
Gift gift;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
|
||||
public static void main(String[] args)
|
||||
{
|
||||
TikTokLive.newClient(ConnectionExample.TIKTOK_HOSTNAME)
|
||||
.configure(clientSettings ->
|
||||
{
|
||||
clientSettings.setPrintToConsole(true);
|
||||
})
|
||||
.onGift((liveClient, event) ->
|
||||
{
|
||||
if (event.getGift().getDiamondCost() > 100)
|
||||
@@ -49,14 +51,14 @@ public class CustomEventExample {
|
||||
else
|
||||
liveClient.publishEvent(new CheapGiftEvent(event.getGift()));
|
||||
})
|
||||
.onEvent(CheapGiftEvent.class,(liveClient, event) ->
|
||||
.onEvent(CheapGiftEvent.class, (liveClient, event) ->
|
||||
{
|
||||
System.out.println("Thanks for cheap gift");
|
||||
})
|
||||
.onEvent(ExpensiveGiftEvent.class,(liveClient, event) ->
|
||||
.onEvent(ExpensiveGiftEvent.class, (liveClient, event) ->
|
||||
{
|
||||
System.out.println("Thanks for expensive gift!");
|
||||
})
|
||||
.build();
|
||||
.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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokCommentEvent;
|
||||
import io.github.jwdeveloper.tiktok.data.events.TikTokSubscribeEvent;
|
||||
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.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.models.gifts.GiftComboStateType;
|
||||
import io.github.jwdeveloper.tiktok.live.LiveClient;
|
||||
|
||||
public class Events_And_Gifts_Testing_Example
|
||||
{
|
||||
|
||||
public static void main(String[] args) {
|
||||
LiveClient client = TikTokLive.newClient(ConnectionExample.TIKTOK_HOSTNAME)
|
||||
.configure(liveClientSettings ->
|
||||
{
|
||||
liveClientSettings.setOffline(true);
|
||||
liveClientSettings.setPrintToConsole(true);
|
||||
})
|
||||
.onConnected((liveClient, event) ->
|
||||
{
|
||||
liveClient.getLogger().info("Connected");
|
||||
})
|
||||
.onDisconnected((liveClient, event) ->
|
||||
{
|
||||
liveClient.getLogger().info("Disconnected");
|
||||
})
|
||||
.onGiftCombo((liveClient, event) ->
|
||||
{
|
||||
liveClient.getLogger().info("New fake combo Gift: " + event.getGift());
|
||||
})
|
||||
.onGift((liveClient, event) ->
|
||||
{
|
||||
liveClient.getLogger().info("New fake Gift: " + event.getGift());
|
||||
})
|
||||
.onLike((liveClient, event) ->
|
||||
{
|
||||
liveClient.getLogger().info("New fake Like event: " + event.getLikes());
|
||||
})
|
||||
.build();
|
||||
|
||||
var gifts = TikTokLive.gifts();
|
||||
var roseGift = gifts.getByName("Rose");
|
||||
|
||||
var fakeGift = TikTokGiftEvent.of(roseGift);
|
||||
var fakeComboGift = TikTokGiftComboEvent.of(roseGift, 12, GiftComboStateType.Begin);
|
||||
|
||||
var fakeMessage = TikTokCommentEvent.of("Mark", "Hello world");
|
||||
|
||||
var fakeSubscriber = TikTokSubscribeEvent.of("Mark");
|
||||
var fakeFollow = TikTokFollowEvent.of("Mark");
|
||||
var fakeLike = TikTokLikeEvent.of("Mark", 12);
|
||||
var fakeJoin = TikTokJoinEvent.of("Mark");
|
||||
|
||||
client.connect();
|
||||
|
||||
client.publishEvent(fakeGift);
|
||||
client.publishEvent(fakeComboGift);
|
||||
client.publishEvent(fakeMessage);
|
||||
client.publishEvent(fakeSubscriber);
|
||||
client.publishEvent(fakeFollow);
|
||||
client.publishEvent(fakeJoin);
|
||||
|
||||
client.publishEvent(fakeLike);
|
||||
client.publishMessage("WebcastLikeMessage", webcastLikeMessageBase64);
|
||||
|
||||
client.disconnect();
|
||||
}
|
||||
|
||||
private static final String webcastLikeMessageBase64 = "SAFSBRABGKwCUgcIAhABGKwCCv8BUAFYAbABA7gBARCflqWWo8Ha72UgzoPZhd8xQrwBGg4gkAMKCSNmZmZmZmZmZiJ/qgF6CngIhYjjgPWJv7RgGhDwnZKm8J2TjvCdk47wk4WTsgIKa3lsbGVlaGFsbPICTE1TNHdMakFCQUFBQXUyX21LNEw4WGJYa3lNaUFvZzJUTnNmVjk5N09WM2tpQ3NCTkNjYWkwcWxIcUt0Q3B0UGU1N2RLYVhxb0xWSXoICwoQcG1fbXRfbXNnX3ZpZXdlchIXezA6dXNlcn0gbGlrZWQgdGhlIExJVkVIAQoSV2ViY2FzdExpa2VNZXNzYWdlGIaWvY+RhdjvZTABwAEBEA8Y+Voq7RCyAQYImwEQjwK6AQCCAgDyAkxNUzR3TGpBQkFBQUF1Ml9tSzRMOFhiWGt5TWlBb2cyVE5zZlY5OTdPVjNraUNzQk5DY2FpMHFsSHFLdENwdFBlNTdkS2FYcW9MVkl6ggTqCLoBnwUqBggBEAEYIFoNCgASCSNCMzQ3N0VGRoABDwgEEtgEEix3ZWJjYXN0LXZhL2dyYWRlX2JhZGdlX2ljb25fbGl0ZV9sdjE1X3YyLnBuZzrpAnNzbG9jYWw6Ly93ZWJjYXN0X2x5bnh2aWV3X3BvcHVwP3VzZV9zcGFyaz0xJnVybD1odHRwcyUzQSUyRiUyRmxmMTYtZ2Vja28tc291cmNlLnRpa3Rva2Nkbi5jb20lMkZvYmolMkZieXRlLWd1cmQtc291cmNlLXNnJTJGdGlrdG9rJTJGZmUlMkZsaXZlJTJGdGlrdG9rX2xpdmVfcmV2ZW51ZV91c2VyX2xldmVsX21haW4lMkZzcmMlMkZwYWdlcyUyRnByaXZpbGVnZSUyRnBhbmVsJTJGdGVtcGxhdGUuanMmaGlkZV9zdGF0dXNfYmFyPTAmaGlkZV9uYXZfYmFyPTEmY29udGFpbmVyX2JnX2NvbG9yPTAwMDAwMDAwJmhlaWdodD05MCUyNSZiZGhtX2JpZD10aWt0b2tfbGl2ZV9yZXZlbnVlX3VzZXJfbGV2ZWxfbWFpbiZ1c2VfZm9yZXN0PTEKXWh0dHBzOi8vcDE2LXdlYmNhc3QudGlrdG9rY2RuLmNvbS93ZWJjYXN0LXZhL2dyYWRlX2JhZGdlX2ljb25fbGl0ZV9sdjE1X3YyLnBuZ350cGx2LW9iai5pbWFnZQpdaHR0cHM6Ly9wMTktd2ViY2FzdC50aWt0b2tjZG4uY29tL3dlYmNhc3QtdmEvZ3JhZGVfYmFkZ2VfaWNvbl9saXRlX2x2MTVfdjIucG5nfnRwbHYtb2JqLmltYWdlIgIxNTIAOgYaAhIAIgBiDQoAEgkjQjM0NzdFRkZ4DqIBBggBEAEYIAgEEBQYCCABUukCc3Nsb2NhbDovL3dlYmNhc3RfbHlueHZpZXdfcG9wdXA/dXNlX3NwYXJrPTEmdXJsPWh0dHBzJTNBJTJGJTJGbGYxNi1nZWNrby1zb3VyY2UudGlrdG9rY2RuLmNvbSUyRm9iaiUyRmJ5dGUtZ3VyZC1zb3VyY2Utc2clMkZ0aWt0b2slMkZmZSUyRmxpdmUlMkZ0aWt0b2tfbGl2ZV9yZXZlbnVlX3VzZXJfbGV2ZWxfbWFpbiUyRnNyYyUyRnBhZ2VzJTJGcHJpdmlsZWdlJTJGcGFuZWwlMkZ0ZW1wbGF0ZS5qcyZoaWRlX3N0YXR1c19iYXI9MCZoaWRlX25hdl9iYXI9MSZjb250YWluZXJfYmdfY29sb3I9MDAwMDAwMDAmaGVpZ2h0PTkwJTI1JmJkaG1fYmlkPXRpa3Rva19saXZlX3JldmVudWVfdXNlcl9sZXZlbF9tYWluJnVzZV9mb3Jlc3Q9MVgBYk8qAjE1CgEyEhM3MTM4MzgxNzQ3MjkyNTQyNzU2GgEwIi5tb2NrX2ZpeF93aWR0aF90cmFuc3BhcmVudF83MTM4MzgxNzQ3MjkyNTQyNzU2CIWI44D1ib+0YBoQ8J2SpvCdk47wnZOO8JOFk0r1BhJBMTAweDEwMC90b3MtdXNlYXN0OC1hdnQtMDA2OC10eDIvNjY0NmM4NjZjMzI1MWEwOTY3NjhiYjY4OTUyODVjMzEK0gFodHRwczovL3AxOS1wdS1zaWduLXVzZWFzdDgudGlrdG9rY2RuLXVzLmNvbS90b3MtdXNlYXN0OC1hdnQtMDA2OC10eDIvNjY0NmM4NjZjMzI1MWEwOTY3NjhiYjY4OTUyODVjMzF+dHBsdi10aWt0b2stc2hyaW5rOjcyOjcyLndlYnA/bGszcz1hNWQ0ODA3OCZ4LWV4cGlyZXM9MTcwOTMxMjQwMCZ4LXNpZ25hdHVyZT1VMlNEbUk3Z3R5RW9rMlBlWFdmeTNsM1F6NlElM0QKyAFodHRwczovL3AxNi1wdS1zaWduLXVzZWFzdDgudGlrdG9rY2RuLXVzLmNvbS90b3MtdXNlYXN0OC1hdnQtMDA2OC10eDIvNjY0NmM4NjZjMzI1MWEwOTY3NjhiYjY4OTUyODVjMzF+YzVfMTAweDEwMC53ZWJwP2xrM3M9YTVkNDgwNzgmeC1leHBpcmVzPTE3MDkzMTI0MDAmeC1zaWduYXR1cmU9aWNWZEVZa0FnWkYlMkZ2WU5OTSUyRlVNMzE2eG9HdyUzRArGAWh0dHBzOi8vcDE5LXB1LXNpZ24tdXNlYXN0OC50aWt0b2tjZG4tdXMuY29tL3Rvcy11c2Vhc3Q4LWF2dC0wMDY4LXR4Mi82NjQ2Yzg2NmMzMjUxYTA5Njc2OGJiNjg5NTI4NWMzMX5jNV8xMDB4MTAwLndlYnA/bGszcz1hNWQ0ODA3OCZ4LWV4cGlyZXM9MTcwOTMxMjQwMCZ4LXNpZ25hdHVyZT1PQzdBQ3htQUklMkJsYlp4RkVuWktJT1RyRExGUSUzRArGAWh0dHBzOi8vcDE2LXB1LXNpZ24tdXNlYXN0OC50aWt0b2tjZG4tdXMuY29tL3Rvcy11c2Vhc3Q4LWF2dC0wMDY4LXR4Mi82NjQ2Yzg2NmMzMjUxYTA5Njc2OGJiNjg5NTI4NWMzMX5jNV8xMDB4MTAwLmpwZWc/bGszcz1hNWQ0ODA3OCZ4LWV4cGlyZXM9MTcwOTMxMjQwMCZ4LXNpZ25hdHVyZT02YUwlMkZNZWtOeHg5NXlvVTVLOTZON0xwRUlNdyUzRLICCmt5bGxlZWhhbGxCyQEIgojG1pKb0clgErwBChBwbV9tdF9tc2dfdmlld2VyEhd7MDp1c2VyfSBsaWtlZCB0aGUgTElWRRoOCgkjZmZmZmZmZmYgkAMifwgLqgF6CngIhYjjgPWJv7RgGhDwnZKm8J2TjvCdk47wk4WTsgIKa3lsbGVlaGFsbPICTE1TNHdMakFCQUFBQXUyX21LNEw4WGJYa3lNaUFvZzJUTnNmVjk5N09WM2tpQ3NCTkNjYWkwcWxIcUt0Q3B0UGU1N2RLYVhxb0xWSXo=";
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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.gifts.Gift;
|
||||
|
||||
public class GiftsExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
var giftsManager = TikTokLive.gifts();
|
||||
|
||||
|
||||
|
||||
var giftsList = giftsManager.toList();
|
||||
for (var gift : giftsList) {
|
||||
System.out.println("Gift: " + gift);
|
||||
}
|
||||
|
||||
var giftsMap = giftsManager.toMap();
|
||||
for (var entry : giftsMap.entrySet()) {
|
||||
System.out.println("GiftId: " + entry.getKey() + " Gift: " + entry.getValue());
|
||||
}
|
||||
|
||||
System.out.println("total number of gifts: " + giftsManager.toList().size());
|
||||
|
||||
var giftRose = giftsManager.getById(5655);
|
||||
var giftRoseByName = giftsManager.getByName("Rose");
|
||||
var giftByFilter = giftsManager.getByFilter(e -> e.getDiamondCost() > 50);
|
||||
|
||||
var giftsByFilter = giftsManager.getManyByFilter(e -> e.getDiamondCost() > 100);
|
||||
System.out.println("total number of gifts with cost higher then 100: " + giftsByFilter.size());
|
||||
/**
|
||||
* In case searched gift not exists getByName returns you Gift.UNDEFINED
|
||||
*/
|
||||
var undefiedGift = giftsManager.getByName("GIFT WITH WRONG NAME");
|
||||
|
||||
|
||||
var customGift = new Gift(123213213, "Custom gift", 50, "https://images.pexels.com/photos/2071882/pexels-photo-2071882.jpeg?cs=srgb&dl=pexels-wojciech-kumpicki-2071882.jpg&fm=jpg");
|
||||
giftsManager.attachGift(customGift);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ public class ListenerExample
|
||||
showLogo();
|
||||
CustomListener customListener = new CustomListener();
|
||||
|
||||
TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
|
||||
TikTokLive.newClient(ConnectionExample.TIKTOK_HOSTNAME)
|
||||
.addListener(customListener)
|
||||
.buildAndConnect();
|
||||
System.in.read();
|
||||
@@ -57,7 +57,7 @@ public class ListenerExample
|
||||
/**
|
||||
*
|
||||
* Method in TikTokEventListener should meet 4 requirements to be detected
|
||||
* - must have @TikTokEventHandler annotation
|
||||
* - must have @TikTokEventObserver annotation
|
||||
* - must have 2 parameters
|
||||
* - first parameter must be LiveClient
|
||||
* - second must be class that extending TikTokEvent
|
||||
@@ -84,12 +84,12 @@ public class ListenerExample
|
||||
|
||||
@TikTokEventObserver
|
||||
public void onGift(LiveClient liveClient, TikTokGiftEvent event) {
|
||||
var message = switch (event.getGift()) {
|
||||
case ROSE -> "Thanks :)";
|
||||
case APPETIZERS -> ":OO";
|
||||
case APRIL -> ":D";
|
||||
case TIKTOK -> ":P";
|
||||
case CAP -> ":F";
|
||||
var message = switch (event.getGift().getName()) {
|
||||
case "ROSE" -> "Thanks :)";
|
||||
case "APPETIZERS" -> ":OO";
|
||||
case "APRIL" -> ":D";
|
||||
case "TIKTOK" -> ":P";
|
||||
case "CAP" -> ":F";
|
||||
default -> ":I";
|
||||
};
|
||||
liveClient.getLogger().info(message);
|
||||
@@ -115,4 +115,4 @@ public class ListenerExample
|
||||
""");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 java.net.Proxy;
|
||||
|
||||
public class ProxyExample {
|
||||
public static void main(String[] args) throws Exception {
|
||||
TikTokLive.newClient(ConnectionExample.TIKTOK_HOSTNAME)
|
||||
.configure(clientSettings -> {
|
||||
clientSettings.setPrintToConsole(true);
|
||||
clientSettings.getHttpSettings().configureProxy(proxySettings -> {
|
||||
proxySettings.setOnProxyUpdated(proxyData -> System.err.println("Next proxy: " + proxyData.toString()));
|
||||
proxySettings.setType(Proxy.Type.SOCKS);
|
||||
proxySettings.addProxy("localhost", 8080);
|
||||
});
|
||||
})
|
||||
.onConnected((liveClient, event) ->
|
||||
liveClient.getLogger().info("Connected "+liveClient.getRoomInfo().getHostName()))
|
||||
.onComment((liveClient, event) -> liveClient.getLogger().info(event.getUser().getName()+": "+event.getText()))
|
||||
.onLike((liveClient, event) -> liveClient.getLogger().info(event.getUser().getName()+" sent "+event.getLikes()+"x likes!"))
|
||||
.onDisconnected((liveClient, event) ->
|
||||
liveClient.getLogger().info("Disconnect reason: "+event.getReason()))
|
||||
.onLiveEnded((liveClient, event) ->
|
||||
liveClient.getLogger().info("Live Ended: "+liveClient.getRoomInfo().getHostName()))
|
||||
.onError((liveClient, event) ->
|
||||
event.getException().printStackTrace())
|
||||
.buildAndConnect();
|
||||
|
||||
System.in.read();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package io.github.jwdeveloper.tiktok;
|
||||
|
||||
|
||||
import io.github.jwdeveloper.tiktok.extension.recorder.TikTokLiveRecorder;
|
||||
import io.github.jwdeveloper.tiktok.extension.recorder.impl.event.TikTokLiveRecorderStartedEvent;
|
||||
|
||||
public class RecorderExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
TikTokLive.newClient("bangbetmenygy")
|
||||
.configure(liveClientSettings ->
|
||||
{
|
||||
liveClientSettings.setPrintToConsole(true);
|
||||
})
|
||||
.onError((liveClient, event) ->
|
||||
{
|
||||
event.getException().printStackTrace();
|
||||
})
|
||||
.addListener(TikTokLiveRecorder.use(recorderSettings ->
|
||||
{
|
||||
recorderSettings.setFfmpegPath("C:\\Users\\ja\\IdeaProjects\\TikTokLiveJava\\extension-recorder\\libs\\ffmpeg.exe");
|
||||
recorderSettings.setOutputPath("C:\\Users\\ja\\IdeaProjects\\TikTokLiveJava\\extension-recorder\\out");
|
||||
recorderSettings.setOutputFileName("test.flv");
|
||||
}))
|
||||
.onEvent(TikTokLiveRecorderStartedEvent.class, (liveClient, event) ->
|
||||
{
|
||||
System.out.println(event.getDownloadData().getFullUrl());
|
||||
})
|
||||
.buildAndConnect();
|
||||
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user