Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.github.jwdeveloper.tiktok.data.dto;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class TikTokUserInfo
{
UserStatus userStatus;

String roomId;

public enum UserStatus
{
NotFound,
Offline,
LivePaused,
Live
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ public CompletableFuture<LiveClient> connectAsync() {
public void connect() {
try {
tryConnect();
} catch (TikTokLiveException e)
{
} catch (TikTokLiveException e) {
setState(ConnectionState.DISCONNECTED);
tikTokEventHandler.publish(this, new TikTokErrorEvent(e));
tikTokEventHandler.publish(this, new TikTokDisconnectedEvent());
Expand All @@ -109,6 +108,10 @@ public void connect() {
this.connect();
}
throw e;
} catch (Exception e) {
logger.info("Unhandled exception report this bug to github https://github.com/jwdeveloper/TikTokLiveJava/issues");
this.disconnect();
e.printStackTrace();
}
}

Expand Down Expand Up @@ -140,10 +143,10 @@ public void tryConnect() {


var liveRoomMeta = apiService.fetchRoomInfo();
if (liveRoomMeta.getStatus() == LiveRoomMeta.LiveRoomStatus.HostNotFound) {
if (liveRoomMeta.getStatus() == LiveRoomMeta.LiveRoomStatus.HostNotFound) {
throw new TikTokLiveOfflineHostException("LiveStream for Host name could not be found.");
}
if (liveRoomMeta.getStatus() == LiveRoomMeta.LiveRoomStatus.HostOffline) {
if (liveRoomMeta.getStatus() == LiveRoomMeta.LiveRoomStatus.HostOffline) {
throw new TikTokLiveOfflineHostException("LiveStream for not be found, is the Host offline?");
}

Expand All @@ -156,7 +159,7 @@ public void tryConnect() {
var clientData = apiService.fetchClientData();
webSocketClient.start(clientData, this);
setState(ConnectionState.CONNECTED);
tikTokEventHandler.publish(this,new TikTokRoomInfoEvent(liveRoomInfo));
tikTokEventHandler.publish(this, new TikTokRoomInfoEvent(liveRoomInfo));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
package io.github.jwdeveloper.tiktok.http;

import io.github.jwdeveloper.tiktok.ClientSettings;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
import io.github.jwdeveloper.tiktok.data.dto.TikTokUserInfo;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveOfflineHostException;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
Expand Down Expand Up @@ -57,62 +57,43 @@ public void updateSessionId() {
}

public String fetchRoomId(String userName) {
var roomId = fetchRoomIdFromTiktokApi(userName);
clientSettings.getClientParameters().put("room_id", roomId);
logger.info("RoomID -> " + roomId);
return roomId;
var userInfo = fetchUserInfoFromTikTokApi(userName);
clientSettings.getClientParameters().put("room_id", userInfo.getRoomId());
logger.info("RoomID -> " + userInfo.getRoomId());
return userInfo.getRoomId();
}

private String fetchRoomIdFromTikTokPage(String userName)
{
/* var roomId = RequestChain.<String>create()
.then(() -> fetchRoomIdFromTikTokPage(userName))
.then(() -> fetchRoomIdFromTiktokApi(userName))
.run();*/
logger.info("Fetching room ID");
String html;
try {
html = tiktokHttpClient.getLivestreamPage(userName);
} catch (Exception e) {
throw new TikTokLiveRequestException("Failed to fetch room id from WebCast, see stacktrace for more info.", e);
}

var firstPattern = Pattern.compile("room_id=([0-9]*)");
var firstMatcher = firstPattern.matcher(html);
var id = "";

if (firstMatcher.find()) {
id = firstMatcher.group(1);
} else {
var secondPattern = Pattern.compile("\"roomId\":\"([0-9]*)\"");
var secondMatcher = secondPattern.matcher(html);

if (secondMatcher.find()) {
id = secondMatcher.group(1);
}
}

if (id.isEmpty()) {
throw new TikTokLiveOfflineHostException("Unable to fetch room ID, live host could be offline or name is misspelled");
}


return id;
}

private String fetchRoomIdFromTiktokApi(String userName) {
public TikTokUserInfo fetchUserInfoFromTikTokApi(String userName) {

var params = new HashMap<>(clientSettings.getClientParameters());
params.put("uniqueId", userName);
params.put("sourceType", 54);
var roomData = tiktokHttpClient.getJsonFromTikTokApi("api-live/user/room/", params);

var message = roomData.get("message").getAsString();

if (message.equals("params_error")) {
throw new TikTokLiveRequestException("fetchRoomIdFromTiktokApi -> Unable to fetch roomID, contact with developer");
}
if (message.equals("user_not_found")) {
return new TikTokUserInfo(TikTokUserInfo.UserStatus.NotFound, "");
}
//live -> status 2
//live paused -> 3
//not live -> status 4
var data = roomData.getAsJsonObject("data");
var user =data.getAsJsonObject("user");
var user = data.getAsJsonObject("user");
var roomId = user.get("roomId").getAsString();
var status = user.get("status").getAsInt();

var statusEnum = switch (status) {
case 2 -> TikTokUserInfo.UserStatus.Live;
case 3 -> TikTokUserInfo.UserStatus.LivePaused;
case 4 -> TikTokUserInfo.UserStatus.Offline;
default -> TikTokUserInfo.UserStatus.NotFound;
};

return roomId;
return new TikTokUserInfo(statusEnum, roomId);
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
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 java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;
import java.util.regex.Pattern;

public class TikTokDataChecker
{
public class TikTokDataChecker {

public CompletableFuture<Boolean> isOnlineAsync(String hostName) {
return CompletableFuture.supplyAsync(() -> isOnline(hostName));
Expand All @@ -17,63 +20,24 @@ public CompletableFuture<Boolean> isHostNameValidAsync(String hostName) {
}

public boolean isOnline(String hostName) {
var factory = new TikTokHttpRequestFactory(new TikTokCookieJar());
var url = getLiveUrl(hostName);
try {
var response = factory.get(url);
var titleContent = extractTitleContent(response);
return isTitleLiveOnline(titleContent);
} catch (Exception e)
{
throw new TikTokLiveRequestException("Unable to make check live online request",e);
}
var data = getApiService().fetchUserInfoFromTikTokApi(hostName);
return data.getUserStatus() == TikTokUserInfo.UserStatus.Live ||
data.getUserStatus() == TikTokUserInfo.UserStatus.LivePaused;
}

public boolean isHostNameValid(String hostName) {
var factory = new TikTokHttpRequestFactory(new TikTokCookieJar());
var url = getProfileUrl(hostName);
try {
var response = factory.get(url);
var titleContent = extractTitleContent(response);
return isTitleHostNameValid(titleContent, hostName);
} catch (Exception e)
{
throw new TikTokLiveRequestException("Unable to make check host name valid request",e);
}
var data = getApiService().fetchUserInfoFromTikTokApi(hostName);
return data.getUserStatus() != TikTokUserInfo.UserStatus.NotFound;
}

private boolean isTitleLiveOnline(String title) {
return title.contains("is LIVE");
public TikTokApiService getApiService() {
var jar = new TikTokCookieJar();
var factory = new TikTokHttpRequestFactory(jar);
var client = new TikTokHttpClient(jar, factory);
var settings = new ClientSettings();
settings.setClientParameters(Constants.DefaultClientParams());
var apiService = new TikTokApiService(client, Logger.getGlobal(), settings);
return apiService;
}

private boolean isTitleHostNameValid(String title, String hostName)
{
return title.contains(hostName);
}

private String extractTitleContent(String html) {
var regex = "<title\\b[^>]*>(.*?)<\\/title>";
var pattern = Pattern.compile(regex);
var matcher = pattern.matcher(html);
if (matcher.find()) {
return matcher.group(1);
} else {
return "";
}
}

private String getLiveUrl(String hostName) {
var sb = new StringBuilder();
sb.append("https://www.tiktok.com/@");
sb.append(hostName);
sb.append("/live");
return sb.toString();
}

private String getProfileUrl(String hostName) {
var sb = new StringBuilder();
sb.append("https://www.tiktok.com/@");
sb.append(hostName);
return sb.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,50 @@

public class TikTokLiveOnlineCheckerTest {

private final String TARGET_USER = "bangbetmenygy";
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 = "dostawcavideo";
var sut = new TikTokDataChecker();
var result = sut.isOnline(TARGET_USER);

Assertions.assertFalse(result);
}

@Test
public void shouldBeValid() {

var TARGET_USER = "dostawcavideo";
var sut = new TikTokDataChecker();
var result = sut.isHostNameValid(TARGET_USER);

Assertions.assertTrue(result);
}

@Test
public void shouldNotBeValid() {
var TARGET_USER = "adadsdadadadadadadadddasdadsafafsafsafas";
var sut = new TikTokDataChecker();
var result = sut.isHostNameValid(TARGET_USER);

Assertions.assertFalse(result);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,25 @@

public class SimpleExample
{
public static String TIKTOK_HOSTNAME = "bangbetmenygy";
public static String TIKTOK_HOSTNAME = "adasdsadadadasdasdsadasdasad";
public static void main(String[] args) throws IOException {

showLogo();
// set tiktok username

/*
Optional checking if host name is correct

//Optional checking if host name is correct
if(TikTokLive.isHostNameValid(TIKTOK_HOSTNAME))
{
System.out.println("Live is online!");
System.out.println("user name exists!");
}

Optional checking if live is online
//Optional checking if live is online
if(TikTokLive.isLiveOnline(TIKTOK_HOSTNAME))
{
System.out.println("Live is online!");
}
*/


TikTokLive.newClient(SimpleExample.TIKTOK_HOSTNAME)
.configure(clientSettings ->
Expand Down
Binary file not shown.