Compare commits

...

107 Commits

Author SHA1 Message Date
Jacek W
8a4248daa3 Merge pull request #49 from kohlerpop1/fixes-updates
Fixed SimpleExample name and imports!
2024-01-19 19:04:03 +01:00
Jacek W
ff5310f5bf Merge branch 'develop-1.0.18' into fixes-updates 2024-01-18 17:11:20 +01:00
JW
9ddec45740 Including Pinging Task 2024-01-18 17:03:50 +01:00
kohlerpop1
8a7b9e801b Removed not used SimpleExample imports! 2024-01-18 10:58:33 -05:00
kohlerpop1
7b4590d0a1 Fixed SimpleExample! 2024-01-18 10:51:03 -05:00
kohlerpop1
2555edd86f Moved proxy declaration to inside of try, updated websocket version to 1.5.5 from 1.5.4, and cleared up ProxyExample! 2024-01-16 22:09:56 -05:00
kohlerpop1
a805844522 Missed one print statement! 2024-01-15 20:58:40 +01:00
kohlerpop1
9da96b4417 Missed one print statement! 2024-01-15 12:32:31 -05:00
kohlerpop1
12cf9e641b Fixed stack overflow error! 2024-01-15 09:43:25 +01:00
kohlerpop1
6bfa0b7745 Fixed stack overflow error! 2024-01-14 20:46:58 -05:00
JW
cf9b882391 . 2024-01-14 23:16:35 +01:00
JW
913d473442 . 2024-01-14 22:55:05 +01:00
GitHub Action
72092bb56b Update version in pom.xml 2024-01-14 19:57:41 +00:00
kohlerpop1
b6247feb32 Final Proxy Commit! 2024-01-14 20:56:05 +01:00
kohlerpop1
0dd952a7fb Push for proxy test pt 4! 2024-01-14 20:56:05 +01:00
kohlerpop1
af4f2b4510 Push for proxy test pt 3! 2024-01-14 20:56:05 +01:00
kohlerpop1
2c12b71e99 Push for proxy test pt 2! 2024-01-14 20:56:05 +01:00
kohlerpop1
bc3386d21e Push for proxy test! 2024-01-14 20:56:05 +01:00
kohlerpop1
4801de58cb Added convenience methods back to TikTokLive and changed sing to sign where misspelled! 2024-01-14 20:56:05 +01:00
Jacek W
548a585e90 Update README.md 2024-01-06 17:55:51 +01:00
Jacek W
2667f04a1c Update README.md 2024-01-05 17:27:12 +01:00
GitHub Action
0a857594ea Update version in pom.xml 2024-01-05 16:26:35 +00:00
JW
b0593ba95c - refactor of the Http client
Changes:

Http-client settings in configure method

```
    TikTokLive.newClient("X")
                .configure(liveClientSettings ->
                {
                   var httpSetting = liveClientSettings.getHttpSettings();
                    httpSetting.setTimeout(Duration.ofSeconds(12));
                });
```

`TikTokLive.requests()` Easy and quick way of making
http request to tiktok
```
    var giftsResponse =TikTokLive.request.fetchGiftsData();
 ```

 Removed:
     TikTokLive.isLiveOnline(String hostName);
     TikTokLive.isHostNameValidAsync(String hostName);

     instead you can use
     ```
     TikTokLive.requests().fetchLiveUserData("Mike").getUserStatus()
     ```
2024-01-05 17:21:55 +01:00
JW
c23faffcde - refactor of the Http client
Changes:

Http-client settings in configure method

```
    TikTokLive.newClient("X")
                .configure(liveClientSettings ->
                {
                   var httpSetting = liveClientSettings.getHttpSettings();
                    httpSetting.setTimeout(Duration.ofSeconds(12));
                });
```

`TikTokLive.requests()` Easy and quick way of making
http request to tiktok
```
    var giftsResponse =TikTokLive.request.fetchGiftsData();
 ```

 Removed:
     TikTokLive.isLiveOnline(String hostName);
     TikTokLive.isHostNameValidAsync(String hostName);

     instead you can use
     ```
     TikTokLive.requests().fetchLiveUserData("Mike").getUserStatus()
     ```
2024-01-05 17:21:55 +01:00
JW
f7a92d5015 - refactor of the Http client
Changes:

Http-client settings in configure method

```
    TikTokLive.newClient("X")
                .configure(liveClientSettings ->
                {
                   var httpSetting = liveClientSettings.getHttpSettings();
                    httpSetting.setTimeout(Duration.ofSeconds(12));
                });
```

`TikTokLive.requests()` Easy and quick way of making
http request to tiktok
```
    var giftsResponse =TikTokLive.request.fetchGiftsData();
 ```

 Removed:
     TikTokLive.isLiveOnline(String hostName);
     TikTokLive.isHostNameValidAsync(String hostName);

     instead you can use
     ```
     TikTokLive.requests().fetchLiveUserData("Mike").getUserStatus()
     ```
2024-01-05 17:21:55 +01:00
GitHub Action
6a42da9ecb Update version in pom.xml 2024-01-05 16:21:21 +00:00
kohlerpop1
1308b86567 Made User#attributes final as its only set once and moved each constructor assignment to field declaration! 2024-01-05 17:06:50 +01:00
kohlerpop1
20ba88c0ac Removed useless lines, made Picture#toString, and optimized TikTokGiftManager#findById & TikTokGiftManager#findByName! 2024-01-05 17:06:50 +01:00
GitHub Action
77533ea4be Update version in pom.xml 2023-12-22 21:11:06 +00:00
Jacek W
3231924f8f Merge pull request #40 from kohlerpop1/kohlerpop1-fixes-updates
Optimized a few methods when calling and using the Api!
2023-12-22 18:46:56 +01:00
kohlerpop1
ea525470e2 Revert to StringBuilder and stacking stream line! 2023-12-22 12:22:50 -05:00
kohlerpop1
b0bf4ac606 Added @Getter to Badge classes and toString methods! 2023-12-22 10:32:49 -05:00
kohlerpop1
0b9f1570d0 Optimized a few methods when calling and using the Api! 2023-12-21 21:40:11 -05:00
kohlerpop1
7a4c7fecbd Merge remote-tracking branch 'origin/kohlerpop1-fixes-updates' into kohlerpop1-fixes-updates 2023-12-20 14:27:46 -05:00
GitHub Action
0ae9068858 Update version in pom.xml 2023-12-20 19:27:06 +00:00
kohlerpop1
8905958207 Merge remote-tracking branch 'origin/kohlerpop1-fixes-updates' into kohlerpop1-fixes-updates
# Conflicts:
#	Tools-EventsCollector/src/main/java/io/github/jwdeveloper/tiktok/tools/tester/mockClient/mocks/ApiServiceMock.java
2023-12-20 14:26:01 -05:00
JW
c12f3cc4dc . 2023-12-20 20:24:33 +01:00
David Kohler
7402899f52 Merge branch 'jwdeveloper:master' into kohlerpop1-fixes-updates 2023-12-20 14:19:37 -05:00
kohlerpop1
1b8b150d61 Removed not needed @Override in ApiServiceMock! 2023-12-20 14:18:55 -05:00
Jacek W
b2305b7bed Merge pull request #39 from kohlerpop1/kohlerpop1-fixes-updates
Added startTime to LiveRoomInfo to determine when the stream started!
2023-12-20 20:17:00 +01:00
kohlerpop1
7b911838a2 Added startTime to LiveRoomInfo to determine when the stream started! 2023-12-20 14:07:53 -05:00
Jacek W
e44cb71869 Update README.md 2023-12-19 21:57:24 +01:00
GitHub Action
af8c689417 Update version in pom.xml 2023-12-19 20:53:26 +00:00
Jacek W
81ac92fb33 Merge pull request #37 from jwdeveloper/develop-1-0-12
Including toUser in TikTokGiftEvent
2023-12-19 21:51:06 +01:00
JW
34a78b5435 Including toUser in TikTokGiftEvent 2023-12-19 21:49:27 +01:00
Jacek W
534cb7906d Merge pull request #36 from jwdeveloper/develop-1-0-12
Develop 1 0 12
2023-12-19 21:43:07 +01:00
JW
0bb8edfe5c Including toUser in TikTokGiftEvent 2023-12-19 21:31:58 +01:00
JW
4979c1b27a Merge remote-tracking branch 'origin/master' 2023-12-19 21:30:31 +01:00
Jacek W
f7c8ffdaa5 Update README.md 2023-12-19 17:34:07 +01:00
GitHub Action
c1fda687d3 Update version in pom.xml 2023-12-19 16:31:06 +00:00
JW
05c49c4545 . 2023-12-19 17:29:16 +01:00
Jacek W
7d36f36cee Update README.md 2023-12-19 14:01:48 +01:00
GitHub Action
f8a716429d Update version in pom.xml 2023-12-19 12:58:59 +00:00
Jacek W
fee805f0ea Merge pull request #35 from jwdeveloper/develop-1-0-10
Develop 1 0 10
2023-12-19 13:57:08 +01:00
JW
1733102aff Changes:
- TikTokHttpResponseEvent
  - Fixed User attributes in CommentEvent
  - Redesign .onMapper method
2023-12-19 13:56:25 +01:00
JW
89f54d5976 Merge branch 'master' into develop-1-0-10 2023-12-19 13:56:19 +01:00
JW
39055b5f3a Merge branch 'master' into develop-1-0-10 2023-12-19 13:54:50 +01:00
Jacek W
cd9e9ead85 Merge pull request #34 from jwdeveloper/develop-1-0-10
Develop 1 0 10
2023-12-19 13:48:47 +01:00
JW
5a2d2d23f0 Changes:
- TikTokHttpResponseEvent
  - Fixed User attributes in CommentEvent
  - Redesign .onMapper method
2023-12-19 13:46:11 +01:00
JW
3eed982d6b Changes:
- TikTokHttpResponseEvent
  - Fixed User attributes in CommentEvent
  - Redesign .onMapper method
2023-12-19 04:01:06 +01:00
GitHub Action
385560de3a Update version in pom.xml 2023-12-18 21:58:15 +00:00
Jacek W
2e37b6627b Merge pull request #33 from kohlerpop1/kohlerpop1-fixes/updates
Updates to TikTokGiftEvent & grammar fixes!
2023-12-18 22:56:33 +01:00
kohlerpop1
c4f0d63b43 Add toUser to TikTokGiftEvent to determine the correct user receiving a gift!
Made grammar fix to collaboration.md and README.md!
2023-12-18 16:52:40 -05:00
Jacek W
15550ed703 Update README.md 2023-12-12 19:49:52 +01:00
GitHub Action
c7d84218f2 Update version in pom.xml 2023-12-12 18:49:13 +00:00
Jacek W
1ecd192539 Merge pull request #30 from jwdeveloper/develop-1-0-8
updated structure of WebcastLinkLayerMessage
in proto file
2023-12-12 19:47:35 +01:00
JW
d6c0d50ac3 Changes:
updated structure of WebcastLinkLayerMessage
  in proto file
2023-12-12 19:46:37 +01:00
Jacek W
b4997da0a8 Merge pull request #29 from jwdeveloper/develop-1-0-8
updated structure of WebcastLinkLayerMessage
in proto file
2023-12-12 19:39:51 +01:00
JW
82990665b8 Changes:
updated structure of WebcastLinkLayerMessage
  in proto file
2023-12-12 19:38:55 +01:00
Jacek W
155b47977d Update README.md 2023-12-12 13:04:51 +01:00
Jacek W
3e262773a4 Update README.md 2023-12-11 23:37:30 +01:00
GitHub Action
89fbeb848b Update version in pom.xml 2023-12-11 22:28:01 +00:00
JW
aa99c5929b Changes:
onCustomEvent() <- registering custom events
  onMapping() <-  custom mappings
  check out 'CustomMappingExample'

  more gifs has been added
  exceptions are more explicit
2023-12-11 23:24:52 +01:00
JW
4dd866c6cc Changes:
onCustomEvent() <- registering custom events
  onMapping() <-  custom mappings
  check out 'CustomMappingExample'

  more gifs has been added
  exceptions are more explicit
2023-12-11 23:22:38 +01:00
Jacek W
0d384f0fdc Merge pull request #28 from jwdeveloper/develop-1-0-7
Develop 1 0 7
2023-12-11 23:20:03 +01:00
JW
3832db111e Changes:
onCustomEvent() <- registering custom events
  onMapping() <-  custom mappings
  check out 'CustomMappingExample'

  more gifs has been added
  exceptions are more explicit
2023-12-11 23:18:40 +01:00
JW
46d5f15d3f . 2023-12-11 03:56:17 +01:00
Jacek W
4f3ec1c6d9 Update collaboration.md 2023-12-05 02:56:53 +01:00
Jacek W
31075e5f09 Update collaboration.md 2023-12-05 02:55:32 +01:00
Jacek W
33a3f7afb8 Update collaboration.md 2023-12-05 02:33:33 +01:00
Jacek W
6c888c5d5b Update collaboration.md 2023-12-05 02:32:42 +01:00
Jacek W
214aa3b1ff Update collaboration.md 2023-12-05 02:30:39 +01:00
Jacek W
3f2c9083d5 Update README.md 2023-12-05 02:24:25 +01:00
Jacek W
450014759c Update collaboration.md 2023-12-05 02:17:50 +01:00
Jacek W
790f568244 Update collaboration.md 2023-12-05 02:13:43 +01:00
JW
e3e0d8a88e Merge remote-tracking branch 'origin/master' 2023-12-05 01:43:34 +01:00
JW
e0136d0f3b Collaboration Guide 2023-12-05 01:43:26 +01:00
Jacek W
dd5ccbfb7f Update README.md 2023-11-14 18:48:58 +01:00
GitHub Action
110a4fab4c Update version in pom.xml 2023-11-14 17:48:13 +00:00
Jacek W
69a2a6a338 Merge pull request #18 from jwdeveloper/develop-1-0-6
Changes:
  fixed TikTokLive.isHostNameValid()
  fixed TikTokLive.isLiveOnline()
  
  those methods was not working in some regions
2023-11-14 18:46:28 +01:00
JW
530551763c Changes:
fixed TikTokLive.isHostNameValid()
  fixed TikTokLive.isLiveOnline()

  those methods was not working in some regions
2023-11-14 18:44:09 +01:00
GitHub Action
ca1827853a Update version in pom.xml 2023-11-13 23:09:58 +00:00
Jacek W
ea8c740faa Merge pull request #17 from jwdeveloper/develop-1-0-5
New Events
- onLiveUnpaused()
- onRoomInfo() triggered when LiveRoomInfo got updated

Removed:
- clientSettings.setHandleExistingEvents - onRoom Replaced with onRoomInfo event - onRoomUserInfo Replaced with onRoomInfo event

Gifts:
- onGift event was not triggered for the more expensive gifts
- onGiftCombo with more expensive gifts was stuck in the GiftSendType.Begin state

Fixed:
- setPrintToConsole(false) was not disabling logs
2023-11-14 00:08:34 +01:00
JW
1977cbe8dc Changes:
New Events
     -  onLiveUnpaused()
     -  onRoomInfo() triggered when LiveRoomInfo got updated

  Removed:
      - clientSettings.setHandleExistingEvents
      - onRoom  Replaced with onRoomInfo event
      - onRoomUserInfo  Replaced with onRoomInfo event

  Gifts:
    - onGift event was not triggered for the more expensive gifts
    - onGiftCombo with more expensive gifts was stuck in the GiftSendType.Begin state

  Fixed:
     - setPrintToConsole(false) was not disabling logs
2023-11-14 00:07:14 +01:00
Jacek W
c3a48c4d70 Update README.md 2023-11-10 22:29:53 +01:00
GitHub Action
2c51844fd9 Update version in pom.xml 2023-11-10 21:29:22 +00:00
Jacek W
8ff4236452 Merge pull request #16 from jwdeveloper/develop-1-0-4
Changes:
   Generated new Gifts Json
   
   TikTokLive.isLiveOnline() check if live if online
   TikTokLive.isLiveOnlineAsync()
   
   TikTokLive.isHostNameValid() check if hostName is correct
   TikTokLive.isHostNameValidAsync()
2023-11-10 22:28:01 +01:00
Jacek W
7817aeb652 Merge pull request #15 from jwdeveloper/develop-1-0-4
Changes:
   Generated new Gifts Json
   
   TikTokLive.isLiveOnline() check if live if online
   TikTokLive.isLiveOnlineAsync()
   
   TikTokLive.isHostNameValid() check if hostName is correct
   TikTokLive.isHostNameValidAsync()
2023-11-10 22:24:53 +01:00
JW
4c122ab754 Changes:
Generated new Gifts Json

   TikTokLive.isLiveOnline() check if live if online
   TikTokLive.isLiveOnlineAsync()

   TikTokLive.isHostNameValid() check if hostName is correct
   TikTokLive.isHostNameValidAsync()
2023-11-10 22:24:14 +01:00
JW
519c22de8e Changes:
Generated new Gifts Json

   TikTokLive.isLiveOnline() check if live if online
   TikTokLive.isLiveOnlineAsync()

   TikTokLive.isHostNameValid() check if hostName is correct
   TikTokLive.isHostNameValidAsync()
2023-11-10 22:20:40 +01:00
JW
6d268c42f1 Changes:
Generated new Gifts Json

   TikTokLive.isLiveOnline() new method for checking if live if online
   TikTokLive.isLiveOnlineAsync()
2023-11-10 22:05:01 +01:00
Jacek W
788653484f Update README.md 2023-10-24 22:02:36 +02:00
GitHub Action
6cebbf891d Update version in pom.xml 2023-10-24 20:01:26 +00:00
Jacek W
cc32648988 Merge pull request #10 from Prokac/disconnect-fix
THX
2023-10-24 21:58:49 +02:00
Lysinka
4c797724d3 Update TikTokLiveClient.java 2023-10-24 19:07:08 +02:00
Jacek W
6941107db8 Update README.md 2023-10-13 14:00:20 +02:00
GitHub Action
ed70799cd9 Update version in pom.xml 2023-10-13 11:59:25 +00:00
227 changed files with 91078 additions and 10955 deletions

4
.gitignore vendored
View File

@@ -1,10 +1,10 @@
backend-infrastructure/.aws-sam
# 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*

3
.idea/protoeditor.xml generated
View File

@@ -64,6 +64,9 @@
<ImportPathEntry>
<option name="location" value="file://$PROJECT_DIR$/API/src/main/proto" />
</ImportPathEntry>
<ImportPathEntry>
<option name="location" value="file://$USER_HOME$/AppData/Local/JetBrains/IntelliJIdea2022.3/protoeditor" />
</ImportPathEntry>
</list>
</option>
<option name="descriptorPath" value="google/protobuf/descriptor.proto" />

View File

@@ -5,7 +5,7 @@
<parent>
<artifactId>TikTokLiveJava</artifactId>
<groupId>io.github.jwdeveloper.tiktok</groupId>
<version>1.0.1-Release</version>
<version>1.0.17-Release</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>API</artifactId>

View File

@@ -1,96 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok;
import lombok.Data;
import java.time.Duration;
import java.util.Map;
import java.util.logging.Level;
@Data
public class ClientSettings {
/**
* Timeout for Connections
*/
private Duration timeout;
/**
* ISO-Language for Client
*/
private String clientLanguage;
/**
* Whether to Retry if Connection Fails
*/
private boolean retryOnConnectionFailure;
/**
* Before retrying connect, wait for select amount of time
*/
private Duration retryConnectionTimeout;
/**
* Whether to handle Events received from Room when Connecting
*/
private boolean handleExistingEvents;
/**
* Whether to print Logs to Console
*/
private boolean printToConsole;
/**
* LoggingLevel for Logs
*/
private Level logLevel;
/**
* Optional: Use it if you need to change TikTok live hostname in builder
*/
private String hostName;
/**
* Parameters used in requests to TikTok api
*/
private Map<String, Object> clientParameters;
/*
* Optional: Sometimes not every messages from chat are send to TikTokLiveJava to fix this issue you can set sessionId
* documentation how to obtain sessionId https://github.com/isaackogan/TikTok-Live-Connector#send-chat-messages
*/
private String sessionId;
/*
* Optional: By default roomID is fetched before connect to live, but you can set it manually
*
*/
private String roomId;
}

View File

@@ -30,3 +30,6 @@ public @interface EventMeta
{
EventType eventType();
}

View File

@@ -26,7 +26,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface TikTokEventHandler
public @interface TikTokEventObserver
{
}

View File

@@ -20,23 +20,17 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.live;
package io.github.jwdeveloper.tiktok.data.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Value;
import java.time.Duration;
@Data
public class LiveRoomMeta {
private LiveRoomStatus status;
private boolean ageRestricted;
public enum LiveRoomStatus
@AllArgsConstructor
public class MessageMetaData
{
HostNotFound,
HostOnline,
HostOffline
}
private Duration handlingTime;
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.events;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import lombok.Data;
@Data
@EventMeta(eventType = EventType.Message)
public class CustomEvent extends TikTokHeaderEvent {
private final User user;
private final String title;
public CustomEvent(User user, String title) {
this.user = user;
this.title = title;
}
}

View File

@@ -47,11 +47,11 @@ public class TikTokCommentEvent extends TikTokHeaderEvent {
public TikTokCommentEvent(WebcastChatMessage msg) {
super(msg.getCommon());
user = User.map(msg.getUser());
user = User.map(msg.getUser(),msg.getUserIdentity());
text = msg.getContent();
visibleToSender = msg.getVisibleToSender();
getUserLanguage = msg.getContentLanguage();
mentionedUser = User.map(msg.getAtUser(),msg.getUserIdentity());
mentionedUser = User.map(msg.getAtUser());
pictures = msg.getEmotesListList().stream().map(e -> Picture.map(e.getEmote().getImage())).toList();
}
}

View File

@@ -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");
}
}

View File

@@ -34,18 +34,10 @@ import java.util.List;
@Getter
@EventMeta(eventType = EventType.Message)
public class TikTokLinkEvent extends TikTokHeaderEvent {
private final String token;
private User user;
private final List<User> otherUsers;
public TikTokLinkEvent(WebcastLinkMessage msg) {
super(msg.getCommon());
token = msg.getToken();
if (msg.getUser().getUser().hasUser()) {
user = new User(msg.getUser().getUser().getUser());
}
otherUsers = msg.getUser().getOtherUsersList().stream().map(e -> new User(e.getUser())).toList();
}
}

View File

@@ -20,17 +20,13 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.live;
package io.github.jwdeveloper.tiktok.data.events;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import java.util.List;
public interface TrackedUser
{
List<TikTokEvent> getInvokedEvents();
List<Gift> getGifs();
User getUserData();
@EventMeta(eventType = EventType.Message)
public class TikTokLiveUnpausedEvent extends TikTokEvent {
}

View File

@@ -26,7 +26,9 @@ import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.data.models.users.UserAttribute;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastMemberMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSubNotifyMessage;
import lombok.Getter;
/**
@@ -34,16 +36,20 @@ import lombok.Getter;
*/
@Getter
@EventMeta(eventType = EventType.Message)
public class TikTokSubscribeEvent extends TikTokHeaderEvent {
private User user;
public class TikTokSubscribeEvent extends TikTokHeaderEvent
{
private final User user;
public TikTokSubscribeEvent(WebcastMemberMessage msg) {
super(msg.getCommon());
if(msg.hasUser())
{
user = new User(msg.getUser());
user = User.map(msg.getUser());
user.addAttribute(UserAttribute.Subscriber);
}
public TikTokSubscribeEvent(WebcastSubNotifyMessage msg) {
super(msg.getCommon());
user = User.map(msg.getUser());
user.addAttribute(UserAttribute.Subscriber);
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.events.control;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokLiveClientEvent;
/**
* Triggered when client is connecting to live is successfully established.
*/
@EventMeta(eventType = EventType.Control)
public class TikTokConnectingEvent extends TikTokLiveClientEvent
{
}

View File

@@ -20,36 +20,52 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.events.room;
package io.github.jwdeveloper.tiktok.data.events.envelop;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
import io.github.jwdeveloper.tiktok.data.models.RankingUser;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastRoomUserSeqMessage;
import lombok.Getter;
import io.github.jwdeveloper.tiktok.data.models.Text;
import java.util.List;
import java.util.stream.Collectors;
import io.github.jwdeveloper.tiktok.data.models.chest.Chest;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastEnvelopeMessage;
import lombok.Value;
import java.util.Date;
@Getter
@EventMeta(eventType = EventType.Message)
public class TikTokRoomUserInfoEvent extends TikTokHeaderEvent {
private final int totalUsers;
@Value
public class TikTokChestEvent extends TikTokHeaderEvent {
/**
* Only top 5 users in ranking has detailed data
* rest has only ID
* Chest target
*/
private final List<RankingUser> usersRanking;
public TikTokRoomUserInfoEvent(WebcastRoomUserSeqMessage msg) {
Chest chest;
/**
* User that send a chest
*/
User user;
/**
* Time when chest has been open
*/
Date openedAt;
public TikTokChestEvent(Chest chest, WebcastEnvelopeMessage msg) {
super(msg.getCommon());
totalUsers = msg.getTotalUser();
usersRanking = msg.getRanksListList().stream().map(RankingUser::new)
.sorted((ru1, ru2) -> Integer.compare(ru2.getScore(), ru1.getScore()))
.collect(Collectors.toList());
}
this.chest = chest;
var text = Text.map(msg.getCommon().getDisplayText());
var userPiece = (Text.UserTextPiece) text.getTextPieces().get(0);
user = userPiece.getUser();
var envelopInfo = msg.getEnvelopeInfo();
openedAt = new Date(envelopInfo.getUnpackAt());
}
}

View File

@@ -26,6 +26,7 @@ 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.data.models.users.User;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
import lombok.Getter;
@@ -40,7 +41,7 @@ import lombok.Getter;
* <p>Combo: 4 -> comboState = GiftSendType.Active</p>
* <p>Combo: 8 -> comboState = GiftSendType.Active</p>
* <p>Combo: 12 -> comboState = GiftSendType.Finsihed</p>
*
* <p>
* Remember if comboState is Finsihed both TikTokGiftComboEvent and TikTokGiftEvent event gets triggered
*/
@EventMeta(eventType = EventType.Message)
@@ -48,8 +49,8 @@ import lombok.Getter;
public class TikTokGiftComboEvent extends TikTokGiftEvent {
private final GiftSendType comboState;
public TikTokGiftComboEvent(Gift gift, WebcastGiftMessage msg, GiftSendType comboState) {
super(gift, msg);
public TikTokGiftComboEvent(Gift gift, User host, WebcastGiftMessage msg, GiftSendType comboState) {
super(gift, host, msg);
this.comboState = comboState;
}
}

View File

@@ -26,14 +26,17 @@ 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.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.users.User;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
import lombok.Getter;
import java.util.ArrayList;
/*
/**
* Triggered when user sends gifts that has
* no combo (most of expensive gifts)
* or if combo has finished
@@ -43,11 +46,18 @@ import lombok.Getter;
public class TikTokGiftEvent extends TikTokHeaderEvent {
private final Gift gift;
private final User user;
private final User toUser;
private final int combo;
public TikTokGiftEvent(Gift gift, WebcastGiftMessage msg) {
public TikTokGiftEvent(Gift gift, User liveHost, WebcastGiftMessage msg) {
super(msg.getCommon());
this.gift = gift;
user = User.map(msg.getUser(), msg.getUserIdentity());
if (msg.getToUser().getNickname().isEmpty()) {
toUser = liveHost;
} else {
toUser = User.map(msg.getToUser());
}
combo = msg.getComboCount();
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.events.http;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.models.http.HttpData;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
@EventMeta(eventType = EventType.Debug)
public class TikTokHttpResponseEvent extends TikTokEvent
{
String url;
HttpData response;
HttpData request;
}

View File

@@ -20,17 +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.client;
package io.github.jwdeveloper.tiktok.data.events.http;
public class TikTokMessageCollectorClient
{
public static TikTokMessagessCollectorBuilder create(String outputName)
{
return new TikTokMessagessCollectorBuilder(outputName);
}
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 static TikTokMessagessCollectorBuilder create(MessageCollector messageCollector, String outputName)
@Getter
@AllArgsConstructor
@EventMeta(eventType = EventType.Debug)
public class TikTokRoomDataResponseEvent extends TikTokEvent
{
return new TikTokMessagessCollectorBuilder(outputName);
}
private final LiveData.Response liveData;
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.events.room;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokHeaderEvent;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.data.models.users.UserAttribute;
import io.github.jwdeveloper.tiktok.messages.webcast.RoomMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLiveIntroMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastRoomMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSystemMessage;
import lombok.Getter;
@Getter
@EventMeta(eventType = EventType.Message)
public class TikTokRoomEvent extends TikTokHeaderEvent
{
private User hostUser;
private String hostLanguage;
private final String welcomeMessage;
public TikTokRoomEvent(WebcastRoomMessage msg) {
super(msg.getCommon());
welcomeMessage = msg.getContent();
}
public TikTokRoomEvent(RoomMessage msg) {
super(msg.getCommon());
welcomeMessage = msg.getContent();
}
public TikTokRoomEvent(WebcastSystemMessage msg) {
super(msg.getCommon());
welcomeMessage = msg.getMessage();
}
public TikTokRoomEvent(WebcastLiveIntroMessage msg) {
super(msg.getCommon());
hostUser = User.map(msg.getHost());
hostUser.addAttribute(UserAttribute.LiveHost);
welcomeMessage = msg.getContent();
hostLanguage = msg.getLanguage();
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.events.room;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.live.LiveRoomInfo;
import lombok.AllArgsConstructor;
import lombok.Getter;
/*
Triggered when LiveRoomInfo got updated such as likes, viewers, ranking ....
*/
@Getter
@AllArgsConstructor
@EventMeta(eventType = EventType.Message)
public class TikTokRoomInfoEvent extends TikTokEvent
{
LiveRoomInfo roomInfo;
}

View File

@@ -24,7 +24,9 @@ package io.github.jwdeveloper.tiktok.data.events.websocket;
import io.github.jwdeveloper.tiktok.annotations.EventMeta;
import io.github.jwdeveloper.tiktok.annotations.EventType;
import io.github.jwdeveloper.tiktok.data.dto.MessageMetaData;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastGiftMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
import lombok.AllArgsConstructor;
import lombok.Getter;
@@ -34,22 +36,32 @@ import java.time.Duration;
/**
* Triggered every time a protobuf encoded webcast message arrives. You can deserialize the binary object depending on the use case.
* Triggered every time TikTok sends data. Data incoming as protobuf message.
* You can deserialize the binary object depending on the use case.
*/
@Getter
@AllArgsConstructor
@EventMeta(eventType = EventType.Debug)
public class TikTokWebsocketMessageEvent extends TikTokEvent
{
private TikTokEvent event;
public class TikTokWebsocketMessageEvent extends TikTokEvent {
/*
* Original message that is coming from TikTok
* message.method - Name of message type, for example "WebcastGiftMessage"
* message.payload - Bytes array that contains actual data of message.
* Example of parsing, WebcastGiftMessage giftMessage = WebcastGiftMessage.parseFrom(message.getPayload());
*/
private WebcastResponse.Message message;
private MetaData metaData;
/*
* TikTokLiveJava event that was created from TikTok message data
* Example: TikTokGiftEvent
*/
private TikTokEvent event;
/*
* Metadata information about mapping message to event, such as time and stuff
*/
private MessageMetaData metaData;
@Value
public static class MetaData
{
Duration handlingTime;
}
}

View File

@@ -39,4 +39,9 @@ public class TikTokWebsocketUnhandledMessageEvent extends TikTokUnhandledEvent<W
public TikTokWebsocketUnhandledMessageEvent(WebcastResponse.Message data) {
super(data);
}
public WebcastResponse.Message getMessage()
{
return this.getData();
}
}

View File

@@ -28,15 +28,10 @@ import lombok.Getter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Picture {
@Getter
@@ -49,7 +44,6 @@ public class Picture {
}
public static Picture map(io.github.jwdeveloper.tiktok.messages.data.Image profilePicture) {
var index = profilePicture.getUrlListCount() - 1;
if (index < 0) {
return new Picture("");
@@ -74,12 +68,11 @@ public class Picture {
return CompletableFuture.supplyAsync(this::downloadImage);
}
private BufferedImage download(String urlString)
{
if(urlString.isEmpty())
{
private BufferedImage download(String urlString) {
if (urlString.isEmpty()) {
return null;
}
var baos = new ByteArrayOutputStream();
try (var is = new URL(urlString).openStream()) {
var byteChunk = new byte[4096];
@@ -103,4 +96,9 @@ public class Picture {
public static Picture Empty() {
return new Picture("");
}
@Override
public String toString() {
return "Picture{link='" + link + "', image=" + image + "}";
}
}

View File

@@ -29,6 +29,7 @@ import lombok.Value;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
@Getter
@@ -45,6 +46,12 @@ public class Text {
this.value = computeValue();
}
public <T extends TextPiece> Optional<TextPiece> getTextPiece(Class<T> type)
{
return textPieces.stream().filter(e -> e.getClass().equals(type)).findFirst();
}
public static Text map(io.github.jwdeveloper.tiktok.messages.data.Text input) {
var pieces = input.getPiecesListList().stream().map(Text::mapTextPiece).toList();
return new Text(input.getKey(), input.getDefaultPattern(), pieces);
@@ -98,6 +105,7 @@ public class Text {
}
}
@Value
public static class UserTextPiece extends TextPiece {
User user;

View File

@@ -37,6 +37,4 @@ public class Badge {
public static Badge empty() {
return new Badge();
}
}

View File

@@ -24,19 +24,22 @@ package io.github.jwdeveloper.tiktok.data.models.badges;
import io.github.jwdeveloper.tiktok.data.models.Picture;
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
import lombok.Getter;
@Getter
public class CombineBadge extends Badge {
private final Picture picture;
private final String text;
private final String subText;
public CombineBadge(BadgeStruct.CombineBadge combineBadge) {
picture = Picture.map(combineBadge.getIcon());
text = combineBadge.getText().getDefaultPattern();
subText = combineBadge.getStr();
}
@Override
public String toString() {
return "CombineBadge{picture=" + picture +", text='" + text + "', subText='" + subText + "'}";
}
}

View File

@@ -24,12 +24,18 @@ package io.github.jwdeveloper.tiktok.data.models.badges;
import io.github.jwdeveloper.tiktok.data.models.Picture;
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
import lombok.Getter;
@Getter
public class PictureBadge extends Badge {
private final Picture picture;
public PictureBadge(BadgeStruct.ImageBadge imageBadge) {
public PictureBadge(BadgeStruct.ImageBadge imageBadge) {
picture = Picture.map(imageBadge.getImage());
}
@Override
public String toString() {
return "PictureBadge{picture=" + picture + "}";
}
}

View File

@@ -23,12 +23,18 @@
package io.github.jwdeveloper.tiktok.data.models.badges;
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
import lombok.Getter;
@Getter
public class StringBadge extends Badge {
private final String text;
public String text;
public StringBadge(BadgeStruct.StringBadge stringBadge) {
this.text = stringBadge.getStr();
}
@Override
public String toString() {
return "StringBadge{text='" + text + "'}";
}
}

View File

@@ -23,13 +23,18 @@
package io.github.jwdeveloper.tiktok.data.models.badges;
import io.github.jwdeveloper.tiktok.messages.data.BadgeStruct;
import lombok.Getter;
public class TextBadge extends Badge
{
@Getter
public class TextBadge extends Badge {
private final String text;
public TextBadge(BadgeStruct.TextBadge textBadge)
{
public TextBadge(BadgeStruct.TextBadge textBadge) {
this.text = textBadge.getDefaultPattern();
}
@Override
public String toString() {
return "TextBadge{text='" + text + "'}";
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.models.chest;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Chest {
/**
* Total diamonds inside the chest
*/
int totalDiamonds;
/**
* Total users participated in chest
*/
int totalUsers;
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.models.http;
import lombok.Data;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
@Data
public class HttpData {
String url;
String method;
Map<String, List<String>> headers = new TreeMap<>();
Map<String, String> parameters = new TreeMap<>();
int status;
String body = "";
public static HttpData map(HttpRequest request) {
var data = new HttpData();
data.setUrl(request.uri().getPath());
data.setMethod(request.method());
data.setParameters(extractQueryParams(request.uri()));
data.setStatus(200);
if (request.bodyPublisher().isPresent()) {
data.setBody(request.bodyPublisher().get().toString());
}
data.setHeaders(Collections.unmodifiableMap(request.headers().map()));
return data;
}
public static HttpData map(HttpResponse<String> response) {
var data = new HttpData();
data.setUrl(response.uri().getPath());
data.setMethod(response.request().method());
data.setParameters(extractQueryParams(response.uri()));
data.setStatus(200);
data.setBody(response.body());
data.setHeaders(Collections.unmodifiableMap(response.headers().map()));
return data;
}
private static Map<String, String> extractQueryParams(URI uri) {
Map<String, String> params = new HashMap<>();
String query = uri.getQuery();
if (query != null && !query.isEmpty()) {
for (String param : query.split("&")) {
String[] keyValue = param.split("=");
if (keyValue.length > 1) {
params.put(keyValue[0], keyValue[1]);
} else {
params.put(keyValue[0], ""); // Empty value for parameter without explicit value
}
}
}
return params;
}
}

View File

@@ -43,11 +43,12 @@ public class User {
private long followers;
private List<Badge> badges;
@Getter(AccessLevel.NONE)
private Set<UserAttribute> attributes;
private final Set<UserAttribute> attributes = new HashSet<>();
public List<UserAttribute> getAttributes() {
return attributes.stream().toList();
}
public boolean hasAttribute(UserAttribute userFlag) {
return attributes.contains(userFlag);
}
@@ -104,14 +105,28 @@ public class User {
this.following = following;
this.followers = followers;
this.badges = badges;
this.attributes = new HashSet<>();
}
public User(Long id,
String name,
String profileName,
Picture picture,
long following,
long followers,
List<Badge> badges) {
this.id = id;
this.name = name;
this.profileName = profileName;
this.picture = picture;
this.following = following;
this.followers = followers;
this.badges = badges;
}
public User(Long userId,
String nickName) {
this.id = userId;
this.name = nickName;
this.attributes = new HashSet<>();
}
public User(Long userId,

View File

@@ -0,0 +1,57 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.requests;
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import java.util.List;
public class GiftsData
{
@Getter
public final class Request
{
}
@Getter
@AllArgsConstructor
public static final class Response
{
private String json;
private List<GiftModel> gifts;
}
@Data
public static class GiftModel
{
private int id;
private String name;
private int diamondCost;
private String image;
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.requests;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import java.net.URI;
import java.time.Duration;
public class LiveConnectionData {
@Getter
@AllArgsConstructor
public static class Request {
private String roomId;
}
@Getter
@AllArgsConstructor
public static class Response {
private String websocketCookies;
private URI websocketUrl;
private WebcastResponse webcastResponse;
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.requests;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
public class LiveData {
@Getter
@AllArgsConstructor
public static class Request {
private String roomId;
}
@Data
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;
}
public enum LiveStatus {
HostNotFound,
HostOnline,
HostOffline,
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.requests;
import lombok.*;
public class LiveUserData {
@Getter
@AllArgsConstructor
public static class Request {
private String userName;
}
@Getter
@AllArgsConstructor
public static class Response {
private String json;
private UserStatus userStatus;
private String roomId;
private long startedAtTimeStamp;
public boolean isLiveOnline() {
return userStatus == LiveUserData.UserStatus.Live || userStatus == LiveUserData.UserStatus.LivePaused;
}
public boolean isHostNameValid() {
return userStatus != LiveUserData.UserStatus.NotFound;
}
}
public enum UserStatus {
NotFound,
Offline,
LivePaused,
Live,
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.requests;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class SignServerResponse
{
private String signedUrl;
private String userAgent;
}

View File

@@ -0,0 +1,112 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.data.settings;
import lombok.Getter;
import lombok.Setter;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Consumer;
public class HttpClientSettings {
@Getter
final Map<String, Object> params;
@Getter
final Map<String, String> headers;
@Getter
final Map<String, String> cookies;
@Getter
@Setter
ProxyClientSettings proxyClientSettings;
@Getter
Consumer<HttpClient.Builder> onClientCreating;
@Getter
Consumer<HttpRequest.Builder> onRequestCreating;
@Setter
@Getter
Duration timeout;
public HttpClientSettings() {
this.params = new TreeMap<>();
this.headers = new HashMap<>();
this.cookies = new HashMap<>();
this.timeout = Duration.ofSeconds(2);
this.proxyClientSettings = new ProxyClientSettings();
this.onClientCreating = (x) -> {
};
this.onRequestCreating = (x) -> {
};
}
/**
* @param consumer Use to configure proxy settings for http client
*/
public void configureProxy(Consumer<ProxyClientSettings> consumer) {
proxyClientSettings.setEnabled(true);
consumer.accept(proxyClientSettings);
}
/**
* @param onRequestCreating Every time new Http request in created this method will be triggered
* use to modify request
*/
public void onRequestCreating(Consumer<HttpRequest.Builder> onRequestCreating) {
this.onRequestCreating = onRequestCreating;
}
/**
* @param onClientCreating Every time new instance of Http client request in created this method will be triggered
* use to modify http client
*/
public void onClientCreating(Consumer<HttpClient.Builder> onClientCreating) {
this.onClientCreating = onClientCreating;
}
@Override
public HttpClientSettings clone() {
var newSettings = new HttpClientSettings();
newSettings.setTimeout(this.getTimeout());
newSettings.onRequestCreating(this.onRequestCreating);
newSettings.onClientCreating(this.onClientCreating);
newSettings.getHeaders().putAll(new TreeMap<>(this.headers));
newSettings.getCookies().putAll(new TreeMap<>(this.cookies));
newSettings.getParams().putAll(new TreeMap<>(this.params));
newSettings.proxyClientSettings = this.proxyClientSettings;
return newSettings;
}
}

View File

@@ -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,41 +30,81 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
public class Constants {
@Data
public class LiveClientSettings {
/**
* Web-URL for TikTok
* ISO-Language for Client
*/
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 String clientLanguage;
/**
* Default TimeOut for Connections
* Whether to Retry if Connection Fails
*/
public static final int DEFAULT_TIMEOUT = 20;
private boolean retryOnConnectionFailure;
/**
* Default Settings for Client
* Before retrying connect, wait for select amount of time
*/
public static ClientSettings DefaultClientSettings() {
var clientSettings = new ClientSettings();
clientSettings.setTimeout(Duration.ofSeconds(DEFAULT_TIMEOUT));
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;
/*
* 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;
public static LiveClientSettings createDefault()
{
var httpSettings = new HttpClientSettings();
httpSettings.getParams().putAll(DefaultClientParams());
httpSettings.getHeaders().putAll(DefaultRequestHeaders());
httpSettings.setTimeout(Duration.ofSeconds(3));
var clientSettings = new LiveClientSettings();
clientSettings.setClientLanguage("en-US");
clientSettings.setHandleExistingEvents(true);
clientSettings.setRetryOnConnectionFailure(false);
clientSettings.setRetryConnectionTimeout(Duration.ofSeconds(1));
clientSettings.setPrintToConsole(false);
clientSettings.setLogLevel(Level.ALL);
clientSettings.setClientParameters(Constants.DefaultClientParams());
clientSettings.setHttpSettings(httpSettings);
return clientSettings;
}
@@ -117,14 +159,14 @@ public class Constants {
var headers = new HashMap<String, String>();
headers.put("authority", "www.tiktok.com");
headers.put("Connection", "keep-alive");
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;
}
}

View File

@@ -0,0 +1,122 @@
/*
* 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, lastSuccess;
private Rotation rotation = Rotation.CONSECUTIVE;
private final List<ProxyData> proxyList = new ArrayList<>();
private int index = 0;
private boolean autoDiscard = true;
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() {
return lastSuccess ? proxyList.get(index) : rotate();
}
public ProxyData rotate() {
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 -> 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
}
}

View File

@@ -26,15 +26,20 @@ package io.github.jwdeveloper.tiktok.exceptions;
/**
* Happens when incoming data from TikTok can not be mapped to TikTokEvent's
*/
public class TikTokMessageMappingException extends TikTokLiveException
{
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, Throwable throwable)
{
public class TikTokMessageMappingException extends TikTokLiveException {
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, Throwable throwable) {
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + " to class " + outputClass.getSimpleName(), throwable);
}
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, String message)
{
public TikTokMessageMappingException(Class<?> inputClazz, Class<?> outputClass, String message) {
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + " to class " + outputClass.getSimpleName() + ": " + message);
}
public TikTokMessageMappingException(Class<?> inputClazz, String message, Throwable throwable) {
super("Unable to handle mapping from class: " + inputClazz.getSimpleName() + ": " + message, throwable);
}
public TikTokMessageMappingException(String message, Throwable throwable) {
super( message, throwable);
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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.exceptions;
/*
* Happens while bad response from http proxy request to TikTok
*/
public class TikTokProxyRequestException extends TikTokLiveException
{
public TikTokProxyRequestException() {
}
public TikTokProxyRequestException(String message) {
super(message);
}
public TikTokProxyRequestException(String message, Throwable cause) {
super(message, cause);
}
public TikTokProxyRequestException(Throwable cause) {
super(cause);
}
public TikTokProxyRequestException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -20,41 +20,26 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.utils;
package io.github.jwdeveloper.tiktok.exceptions;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
public class CancelationToken
public class TikTokSignServerException extends TikTokLiveRequestException
{
private boolean isCanceled =false;
public void cancel()
{
isCanceled =true;
public TikTokSignServerException() {
}
public boolean isCancel()
{
return isCanceled;
public TikTokSignServerException(String message) {
super(message);
}
public void throwIfCancel()
{
if(!isCanceled)
{
return;
}
throw new TikTokLiveException("Token requested cancelation");
public TikTokSignServerException(String message, Throwable cause) {
super(message, cause);
}
public boolean isNotCancel()
{
return !isCancel();
public TikTokSignServerException(Throwable cause) {
super(cause);
}
public static CancelationToken create()
{
return new CancelationToken();
public TikTokSignServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http;
import io.github.jwdeveloper.tiktok.data.requests.GiftsData;
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
public interface LiveHttpClient {
/**
* @return list of gifts that are available in your country
*/
GiftsData.Response fetchGiftsData();
/**
* Returns information about user that is having a livestream
*
* @param userName
* @return
*/
LiveUserData.Response fetchLiveUserData(String userName);
LiveUserData.Response fetchLiveUserData(LiveUserData.Request request);
/**
* @param roomId can be obtained from browsers cookies or by invoked fetchLiveUserData
* @return
*/
LiveData.Response fetchLiveData(String roomId);
LiveData.Response fetchLiveData(LiveData.Request request);
/**
* @param roomId can be obtained from browsers cookies or by invoked fetchLiveUserData
* @return
*/
LiveConnectionData.Response fetchLiveConnectionData(String roomId);
LiveConnectionData.Response fetchLiveConnectionData(LiveConnectionData.Request request);
}

View File

@@ -22,6 +22,7 @@
*/
package io.github.jwdeveloper.tiktok.live;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.listener.ListenersManager;
import io.github.jwdeveloper.tiktok.listener.TikTokEventListener;
@@ -55,6 +56,11 @@ public interface LiveClient {
void disconnect();
/**
* Use to manually invoke event
*/
void publishEvent(TikTokEvent event);
/**
* Get information about gifts
*/

View File

@@ -22,14 +22,32 @@
*/
package io.github.jwdeveloper.tiktok.live;
import io.github.jwdeveloper.tiktok.data.models.RankingUser;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.models.ConnectionState;
import java.util.List;
public interface LiveRoomInfo
{
/**
*
* @return get current count of viewers of live
*/
int getViewersCount();
/**
*
* @return get total current count of viewers since beginning of live
*/
int getTotalViewersCount();
int getLikesCount();
long getStartTime();
boolean isAgeRestricted();
String getRoomId();
String getHostName();
String getTitle();
User getHostUser();
List<RankingUser> getUsersRanking();
ConnectionState getConnectionState();
}

View File

@@ -26,8 +26,8 @@ import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.*;
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftComboEvent;
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomUserInfoEvent;
import io.github.jwdeveloper.tiktok.data.events.http.TikTokHttpResponseEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomInfoEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
@@ -39,52 +39,141 @@ import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketUnhandl
public interface EventsBuilder<T> {
T onRoom(EventConsumer<TikTokRoomEvent> event);
/**
* Invoked whenever specified event is triggered
*
* @param eventClass event class
* @param action action
*/
<E extends TikTokEvent> T onEvent(Class<E> eventClass, EventConsumer<E> action);
T onRoomUserInfo(EventConsumer<TikTokRoomUserInfoEvent> event);
T onComment(EventConsumer<TikTokCommentEvent> event);
/**
* Invoked whenever any event is triggered
*
* @param action
* @return
*/
T onEvent(EventConsumer<TikTokEvent> action);
T onWebsocketMessage(EventConsumer<TikTokWebsocketMessageEvent> event);
/**
* Invoked when information about room (live) got updated such as viewer count, etc..
*
* @param action
* @return
*/
T onRoomInfo(EventConsumer<TikTokRoomInfoEvent> action);
T onWebsocketResponse(EventConsumer<TikTokWebsocketResponseEvent> event);
/**
* Invoked when someone send message to chat
*
* @param action
* @return
*/
T onComment(EventConsumer<TikTokCommentEvent> action);
T onWebsocketUnhandledMessage(EventConsumer<TikTokWebsocketUnhandledMessageEvent> event);
T onGiftCombo(EventConsumer<TikTokGiftComboEvent> event);
T onGift(EventConsumer<TikTokGiftEvent> event);
/**
* Invoked when TikTokLiveJava makes http request and getting response
*
* @param action
* @return
*/
T onHttpResponse(EventConsumer<TikTokHttpResponseEvent> action);
T onQuestion(EventConsumer<TikTokQuestionEvent> event);
/**
* Invoked when TikTok protocolBuffer data "message" was successfully mapped to event
* events contains protocol-buffer "Message" and TikTokLiveJava "Event"
*
* @param action
* @return
*/
T onWebsocketMessage(EventConsumer<TikTokWebsocketMessageEvent> action);
T onSubscribe(EventConsumer<TikTokSubscribeEvent> event);
/**
* Invoked when there was not found event mapper for TikTok protocolBuffer data "message"
*
* @param action
* @return
*/
T onWebsocketUnhandledMessage(EventConsumer<TikTokWebsocketUnhandledMessageEvent> action);
T onFollow(EventConsumer<TikTokFollowEvent> event);
/**
* Invoked every time TikTok sends protocolBuffer data to websocket
* Response contains list of messages that are later mapped to events
* @param action
* @return
*/
T onWebsocketResponse(EventConsumer<TikTokWebsocketResponseEvent> action);
T onLike(EventConsumer<TikTokLikeEvent> event);
T onEmote(EventConsumer<TikTokEmoteEvent> event);
/**
* Invoked for gifts that has no combo, or when combo finishes
* @param action
* @return
*/
T onGift(EventConsumer<TikTokGiftEvent> action);
T onJoin(EventConsumer<TikTokJoinEvent> event);
/**
* Invoked for gifts that has combo options such as roses
* @param action
* @return
*/
T onGiftCombo(EventConsumer<TikTokGiftComboEvent> action);
T onShare(EventConsumer<TikTokShareEvent> event);
T onUnhandledSocial(EventConsumer<TikTokUnhandledSocialEvent> event);
T onLivePaused(EventConsumer<TikTokLivePausedEvent> event);
T onQuestion(EventConsumer<TikTokQuestionEvent> action);
T onLiveEnded(EventConsumer<TikTokLiveEndedEvent> event);
T onSubscribe(EventConsumer<TikTokSubscribeEvent> action);
T onConnected(EventConsumer<TikTokConnectedEvent> event);
T onFollow(EventConsumer<TikTokFollowEvent> action);
T onReconnecting(EventConsumer<TikTokReconnectingEvent> event);
T onLike(EventConsumer<TikTokLikeEvent> action);
T onDisconnected(EventConsumer<TikTokDisconnectedEvent> event);
T onEmote(EventConsumer<TikTokEmoteEvent> action);
T onError(EventConsumer<TikTokErrorEvent> event);
T onJoin(EventConsumer<TikTokJoinEvent> action);
T onEvent(EventConsumer<TikTokEvent> event);
T onShare(EventConsumer<TikTokShareEvent> action);
T onLivePaused(EventConsumer<TikTokLivePausedEvent> action);
T onLiveUnpaused(EventConsumer<TikTokLiveUnpausedEvent> action);
T onLiveEnded(EventConsumer<TikTokLiveEndedEvent> action);
/**
* Invoked when client has been successfully connected to live
* @param action
* @return
*/
T onConnected(EventConsumer<TikTokConnectedEvent> action);
/**
* Invoked when client tries to reconnect
* @param action
* @return
*/
T onReconnecting(EventConsumer<TikTokReconnectingEvent> action);
/**
* Invoked when client disconnected
* @param action
* @return
*/
T onDisconnected(EventConsumer<TikTokDisconnectedEvent> action);
/**
* Invoked when exception was throed inside client or event handler
* @param action
* @return
*/
T onError(EventConsumer<TikTokErrorEvent> action);
// TODO Figure out how those events works
// T onChest(EventConsumer<TikTokChestEvent> event);
//T onLinkMicFanTicket(TikTokEventConsumer<TikTokLinkMicFanTicketEvent> event);
//T onEnvelope(TikTokEventConsumer<TikTokEnvelopeEvent> event);

View File

@@ -22,21 +22,59 @@
*/
package io.github.jwdeveloper.tiktok.live.builder;
import io.github.jwdeveloper.tiktok.ClientSettings;
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
import io.github.jwdeveloper.tiktok.listener.TikTokEventListener;
import io.github.jwdeveloper.tiktok.live.LiveClient;
import io.github.jwdeveloper.tiktok.mappers.TikTokMapper;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public interface LiveClientBuilder extends EventsBuilder<LiveClientBuilder> {
LiveClientBuilder configure(Consumer<ClientSettings> consumer);
/**
* This method is triggered after default mappings are registered
* It could be used to OVERRIDE behaviour of mappings and implement custom behaviour
*
* Be aware if for example you override WebcastGiftEvent, onGiftEvent() will not be working
*
* @param onCustomMappings lambda method
* @return
*/
LiveClientBuilder onMapping(Consumer<TikTokMapper> onCustomMappings);
/**
* Configuration of client settings
* @see LiveClientSettings
* @param onConfigure
* @return
*/
LiveClientBuilder configure(Consumer<LiveClientSettings> onConfigure);
/**
* @see TikTokEventListener
* Adding events listener class, its fancy way to register events without using lamda method
* but actual method in class that implements TikTokEventListener
* @return
*/
LiveClientBuilder addListener(TikTokEventListener listener);
/**
*
* @return LiveClient object
*/
LiveClient build();
/**
*
* @return LiveClient object and connects to TikTok live
*/
LiveClient buildAndConnect();
/**
*
* @return LiveClient object and connects to TikTok live asynchronously
*/
CompletableFuture<LiveClient> buildAndConnectAsync();
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers;
import com.google.protobuf.GeneratedMessageV3;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.mappers.data.MappingAction;
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
import java.util.function.Function;
public interface TikTokMapper {
/**
* * if mapper is not found for messageName, TikTokLiveException is thrown
*
* @param messageName
* @return TikTokMapperModel
*/
TikTokMapperModel forMessage(String messageName);
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName);
TikTokMapperModel forMessage(String mapperName, MappingAction<MappingResult> onMapping);
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, MappingAction<MappingResult> onMapping);
TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, Function<byte[], TikTokEvent> onMapping);
TikTokMapperModel forAnyMessage();
boolean isRegistered(String mapperName);
<T extends GeneratedMessageV3> boolean isRegistered(Class<T> mapperName);
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers;
import com.google.protobuf.GeneratedMessageV3;
import io.github.jwdeveloper.tiktok.exceptions.TikTokMessageMappingException;
import io.github.jwdeveloper.tiktok.utils.ProtoBufferObject;
public interface TikTokMapperHelper {
/**
* @param bytes protocol buffer data bytes
* @param messageClass class that we want to serialize bytes to
* @param <T> @messageClass must be class that is made by protocol buffer
* @return object of type @messageClass
*/
<T extends GeneratedMessageV3> T bytesToWebcastObject(byte[] bytes, Class<T> messageClass);
/**
* @param bytes protocol buffer data bytes
* @param messageName class that we want to serialize bytes to
* @return protocol buffer objects if class for @messageName has been found
* @throws TikTokMessageMappingException if there is no suitable class for messageName
*/
Object bytesToWebcastObject(byte[] bytes, String messageName);
/**
* @param messageName checks wheaten TikTokLiveJava has class representation for certain protocol-buffer message name
* @return false if class is not found
*/
boolean isMessageHasProtoClass(String messageName);
/**
* @param bytes protocol buffer data bytes
* @return tree structure of protocol buffer object
* @see ProtoBufferObject
*/
ProtoBufferObject bytesToProtoBufferStructure(byte[] bytes);
/**
* Converts object to json
*
* @param obj any object
* @return pretty formatted json
*/
String toJson(Object obj);
}

View File

@@ -20,24 +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.collector.db;
package io.github.jwdeveloper.tiktok.mappers;
import io.github.jwdeveloper.tiktok.tools.collector.tables.TikTokErrorModel;
import io.github.jwdeveloper.tiktok.tools.collector.tables.TikTokMessageModel;
import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.mappers.data.AfterMappingAction;
import io.github.jwdeveloper.tiktok.mappers.data.MappingAction;
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
import java.util.List;
import java.util.function.Function;
@RegisterBeanMapper(TikTokMessageModel.class)
public interface TikTokMessageModelDAO
{
@SqlUpdate("INSERT INTO TikTokMessageModel (hostName, eventName,type, eventContent, createdAt) " +
"VALUES (:hostName, :eventName, :type, :eventContent, :createdAt)")
void insertTikTokMessage(@BindBean TikTokMessageModel message);
public interface TikTokMapperModel {
@SqlQuery("SELECT * FROM TikTokMessageModel")
List<TikTokMessageModel> select();
/**
* @return name of websocket message that this mapper is mapping from
*/
String getSourceMessageName();
/**
* @param action Input bytes from websocket, you can modify it and returns different bytes
*/
TikTokMapperModel onBeforeMapping(MappingAction<byte[]> action);
/**
* @param action Input bytes from websocket. As output returns list of tiktok live events
*/
TikTokMapperModel onMapping(MappingAction<MappingResult> action);
/**
* @param action You can modify output list of TikTokLive events
* @see AfterMappingAction
*/
TikTokMapperModel onAfterMapping(Function<MappingResult, List<TikTokEvent>> action);
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers.data;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import java.util.List;
@FunctionalInterface
public interface AfterMappingAction {
/**
* @param source object that was used as source to create events
* @param events list of events prepared before, could be modified or changed
* @return list of events that will be invoked
*/
List<TikTokEvent> onAfterMapping(Object source, List<TikTokEvent> events);
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers.data;
import io.github.jwdeveloper.tiktok.mappers.TikTokMapperHelper;
@FunctionalInterface
public interface MappingAction<T> {
/**
* @param inputBytes incoming bytes from TikTok server. The represents protocol buffer message that was send to client
* @param messageName name of protocol buffer message
* @param mapperHelper utils and helper methods that can be use to debbug/display/deserialize protocol buffer data
* @return
*/
T onMapping(byte[] inputBytes, String messageName, TikTokMapperHelper mapperHelper);
}

View File

@@ -20,33 +20,34 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http;
package io.github.jwdeveloper.tiktok.mappers.data;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import lombok.AllArgsConstructor;
import lombok.Getter;
public class TikTokCookieJar {
private final Map<String, String> cookies;
public TikTokCookieJar() {
cookies = new HashMap<>();
}
import java.util.List;
public String get(String key) {
return cookies.get(key);
}
public void set(String key, String value) {
cookies.put(key, value);
}
public String parseCookies()
@AllArgsConstructor
@Getter
public class MappingResult
{
var sb = new StringBuilder();
for(var entry : cookies.entrySet())
{
sb.append(entry.getKey()).append("=").append(entry.getValue()).append(";");
Object source;
List<TikTokEvent> events;
String message;
public static MappingResult of(Object source) {
return new MappingResult(source, List.of(),"");
}
return sb.toString();
public static MappingResult of(Object source, List<TikTokEvent> events) {
return new MappingResult(source, events,"");
}
public static MappingResult of(Object source,TikTokEvent events) {
return new MappingResult(source, List.of(events),"");
}
}

View File

@@ -25,8 +25,10 @@ package io.github.jwdeveloper.tiktok.utils;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.GsonBuilder;
import io.github.jwdeveloper.tiktok.data.dto.MessageMetaData;
import java.awt.*;
import java.time.Duration;
import java.util.ArrayList;
public class JsonUtil {
@@ -34,13 +36,25 @@ public class JsonUtil {
return new GsonBuilder()
.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
public boolean shouldSkipField(FieldAttributes fieldAttributes)
{
return false;
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return aClass.equals(Image.class);
public boolean shouldSkipClass(Class<?> aClass)
{
if(aClass.equals(Image.class))
{
return true;
}
if(aClass.equals(MessageMetaData.class))
{
return true;
}
return false;
}
})
.disableHtmlEscaping()

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.utils;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
public class ProtoBufferFileGenerator {
public static String generate(ProtoBufferObject protoBuffObj, String name) {
var sb = new StringBuilder();
var offset = 2;
sb.append("message ").append(name).append(" { \n");
var objects = new TreeMap<String, ProtoBufferObject>();
var objectCounter = 0;
for (var entry : protoBuffObj.getFields().entrySet()) {
var index = entry.getKey();
var field = entry.getValue();
var fieldName = field.type.toLowerCase() + "Value";
var value = field.value;
if (field.value instanceof ProtoBufferObject object) {
fieldName += objectCounter;
value = "";
objects.put(fieldName,object);
objectCounter++;
}
for (var i = 0; i < offset; i++) {
sb.append(" ");
}
sb.append(field.type).append(" ").append(fieldName)
.append(" ")
.append("=")
.append(" ")
.append(index)
.append(";")
.append(" //")
.append(value)
.append("\n");
}
sb.append(" \n");
for(var object : objects.entrySet())
{
var structure = generate(object.getValue(),object.getKey());
sb.append(structure);
}
sb.append(" \n");
sb.append("} \n");
return sb.toString();
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.utils;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
public class ProtoBufferJsonGenerator {
public static JsonObject genratejson(ProtoBufferObject protoBuffObj) {
JsonObject jsonObject = new JsonObject();
for (var entry : protoBuffObj.getFields().entrySet()) {
var fieldName = entry.getKey() + "_" + entry.getValue().type;
if (entry.getValue().value instanceof ProtoBufferObject protoObj)
{
JsonObject childJson = genratejson(protoObj);
jsonObject.add(fieldName, childJson);
continue;
}
var value = entry.getValue().value.toString();
jsonObject.addProperty(fieldName, value);
}
return jsonObject;
}
public static String generate(ProtoBufferObject protoBufferObject) {
var json = genratejson(protoBufferObject);
var gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.utils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Map;
import java.util.TreeMap;
public class ProtoBufferObject {
@Getter
private final Map<Integer, ProtoBufferField> fields;
public ProtoBufferObject() {
this.fields = new TreeMap<>();
}
public Object getField(int index)
{
return fields.get(index);
}
public void addField(int index, String type, Object value) {
fields.put(index, new ProtoBufferField(type, value));
}
public void addField(int index, ProtoBufferField value) {
fields.put(index, value);
}
public String toProtoFile()
{
return ProtoBufferFileGenerator.generate(this,"UnknownMessage");
}
public String toJson()
{
return ProtoBufferJsonGenerator.generate(this);
}
@Override
public String toString() {
return toString(0, true);
}
public String toString(int offset ,boolean nested) {
var sb = new StringBuilder();
sb.append("\n");
for (var entry : fields.entrySet()) {
var index = entry.getKey();
var field = entry.getValue();
for(var i =0;i<offset;i++)
{
sb.append(" ");
}
sb.append(index).append(" ")
.append(field.type).append(" ");
var value = field.value;
if (value instanceof ProtoBufferObject child) {
sb.append(child.toString(offset+2,nested));
} else {
sb.append(entry.getValue().value);
}
sb.append("\n");
}
return sb.toString();
}
@AllArgsConstructor
public class ProtoBufferField {
public String type;
public Object value;
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.utils;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.UnknownFieldSet;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
import java.util.Base64;
public class ProtocolUtils {
public static String toBase64(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
public static String toBase64(WebcastResponse.Message bytes) {
return Base64.getEncoder().encodeToString(bytes.toByteArray());
}
public static byte[] fromBase64(String base64) {
return Base64.getDecoder().decode(base64);
}
public static ProtoBufferObject getProtocolBufferStructure(byte[] bytes) {
try {
var files = UnknownFieldSet.parseFrom(bytes);
var protoBufferObject = new ProtoBufferObject();
createStructure(files, protoBufferObject);
return protoBufferObject;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void createStructure(UnknownFieldSet unknownFieldSet, ProtoBufferObject root) throws InvalidProtocolBufferException {
for (var entry : unknownFieldSet.asMap().entrySet()) {
var objectValue = entry.getValue();
var type = "undefind";
Object value = null;
var index = entry.getKey();
if (!objectValue.getLengthDelimitedList().isEmpty()) {
var nestedObject = new ProtoBufferObject();
for (var str : objectValue.getLengthDelimitedList()) {
try {
var nestedFieldsSet = UnknownFieldSet.parseFrom(str);
createStructure(nestedFieldsSet, nestedObject);
} catch (Exception e)
{
type = "string";
value = str.toStringUtf8();
}
}
if (value != null) {
root.addField(index, "string", value);
} else {
root.addField(index, "object", nestedObject);
}
continue;
}
if (!objectValue.getFixed32List().isEmpty()) {
type = "Fixed32List";
value = objectValue.getFixed32List();
}
if (!objectValue.getFixed64List().isEmpty()) {
type = "Fixed64List";
value = objectValue.getFixed64List();
}
if (!objectValue.getGroupList().isEmpty()) {
type = "getGroupList";
value = objectValue.getGroupList();
}
if (!objectValue.getVarintList().isEmpty()) {
type = "int";
value = objectValue.getVarintList().get(0);
}
root.addField(index, type, value);
}
}
public static WebcastResponse.Message fromBase64ToMessage(String base64) throws InvalidProtocolBufferException {
var bytes = fromBase64(base64);
return WebcastResponse.Message.parseFrom(bytes);
}
}

View File

@@ -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();
}

View File

@@ -974,3 +974,566 @@ message FanTicketRoomNoticeContent {
int64 EventTime = 4;
string FanTicketIconUrl = 5;
}
message LinkerAcceptNoticeContent {
int64 fromUserId = 1;
int64 fromRoomId = 2;
int64 toUserId = 3;
}
message LinkerCancelContent {
int64 fromUserId = 1;
int64 toUserId = 2;
int64 cancelType = 3;
int64 actionId = 4;
}
message ListUser {
User user = 1;
int64 linkmicId = 2;
string linkmicIdStr = 3;
int64 linkStatus = 4; // Enum
LinkType linkType = 5; // Enum
int32 userPosition = 6;
int32 silenceStatus = 7; // Enum
int64 modifyTime = 8;
int64 linkerId = 9;
int32 roleType = 10; // Enum
enum LinkType {
LINK_UNKNOWN = 0;
AUDIO = 1;
VIDEO = 2;
}
}
//it is just empty
message LinkerCloseContent {
}
message LinkerCreateContent {
int64 ownerId = 1;
int64 ownerRoomId = 2;
int64 linkType = 3;
}
message LinkerEnterContent {
repeated ListUser linkedUsersList = 1;
int32 anchorMultiLiveEnum = 2; // Enum
LinkmicUserSettingInfo anchorSettingInfo = 3;;
}
message LinkerInviteContent {
int64 fromUserId = 1;
int64 fromRoomId = 2;
string toRtcExtInfo = 3;
bool rtcJoinChannel = 4;
int64 vendor = 5;
string secFromUserId = 6;
string toLinkmicIdStr = 7;
User fromUser = 8;
int64 requiredMicIdx = 9;
}
message LinkerKickOutContent {
int64 fromUserId = 1;
KickoutReason kickoutReason = 2; // Enum
}
message LinkerLeaveContent {
int64 userId = 1;
string linkmicIdStr = 2;
int64 sendLeaveUid = 3;
int64 leaveReason = 4;
}
//Empty
message LinkerLinkedListChangeContent {
}
//Empty
message CohostListChangeContent {
}
message LinkerListChangeContent {
repeated ListUser linkedUsersList = 1;
repeated ListUser appliedUsersList = 2;
repeated ListUser connectingUsersList = 3;
}
message LinkerMediaChangeContent {
int64 op = 1; // Enum
int64 toUserId = 2;
int64 anchorId = 3;
int64 roomId = 4;
int64 changeScene = 5; // Enum
}
//Empty
message LinkerMicIdxUpdateContent {
}
message LinkerMuteContent {
int64 userId = 1;
int64 status = 2; // Enum
}
message LinkerRandomMatchContent {
User user = 1;
int64 roomId = 2;
int64 inviteType = 3;
string matchId = 4;
int64 innerChannelId = 5;
}
message LinkerReplyContent {
int64 fromUserId = 1;
int64 fromRoomId = 2;
LinkmicInfo fromUserLinkmicInfo = 3;
int64 toUserId = 4;
LinkmicInfo toUserLinkmicInfo = 5;
int64 linkType = 6;
int64 replyStatus = 7;
LinkerSetting linkerSetting = 8;
User fromUser = 9;
User toUser = 10;
message LinkmicInfo {
string accessKey = 1;
int64 linkMicId = 2;
bool joinable = 3;
int32 confluenceType = 4;
string rtcExtInfo = 5;
string rtcAppId = 6;
string rtcAppSign = 7;
string linkmicIdStr = 8;
int64 vendor = 9;
}
}
message LinkerSetting {
int64 MaxMemberLimit = 1;
int64 LinkType = 2;
int64 Scene = 3;
int64 OwnerUserId = 4;
int64 OwnerRoomId = 5;
int64 Vendor = 6;
}
message LinkerSysKickOutContent {
int64 userId = 1;
string linkmicIdStr = 2;
}
message LinkmicUserToastContent {
int64 userId = 1;
int64 roomId = 2;
Text displayText = 3;
}
message LinkerUpdateUserContent {
int64 fromUserId = 1;
int64 toUserId = 2;
}
//Empty
message LinkerUpdateUserSettingContent {
}
//Empty
message LinkerWaitingListChangeContent {
}
message LinkmicUserSettingInfo {
int64 userId = 1;
int64 layout = 2; // @warning Enum not found, should be Layout
int64 fixMicNum = 3; // @warning Enum not found, should be FixMicNum
int64 allowRequestFromUser = 4; // @warning Enum not found, should be AllowRequestFromUser
int64 allowRequestFromFollowerOnly = 5; // @warning Enum not found, should be AllowRequestFromFollowerOnly
LinkmicApplierSortSetting applierSortSetting = 7; // Enum
}
message Player {
int64 roomId = 1;
int64 userId = 2;
}
message AllListUser {
repeated LinkLayerListUser linkedList = 2;
repeated LinkLayerListUser appliedList = 3;
repeated LinkLayerListUser invitedList = 4;
repeated LinkLayerListUser readyList = 5;
}
message LinkLayerListUser {
User user = 1;
int64 linkmicId = 2;
Position pos = 3;
int64 linkedTimeNano = 4;
string appVersion = 5;
int64 magicNumber1 = 7;
}
message Position {
int32 type = 1;
LinkPosition link = 2;
}
message LinkPosition {
int32 position = 1;
int32 opt = 2;
}
message GroupPlayer {
int64 channelId = 1;
User user = 2;
}
message DSLConfig {
int32 sceneVersion = 1;
string layoutId = 2;
}
message GroupChannelAllUser {
int64 groupChannelId = 1;
repeated GroupChannelUser userList = 2;
}
message GroupChannelUser {
int64 channelId = 1;
GroupStatus status = 2; // Enum
TextType type = 3; // Enum
AllListUser allUser = 4;
int64 joinTime = 5;
int64 linkedTime = 6;
GroupPlayer ownerUser = 7;
}
message RTCExtraInfo {
RTCEngineConfig liveRtcEngineConfig = 1;
repeated RTCLiveVideoParam liveRtcVideoParamList = 2;
RTCBitrateMap rtcBitrateMap = 3;
int32 rtcFps = 4;
string rtcBusinessId = 8;
int32 interactClientType = 10;
message RTCEngineConfig {
string rtcAppId = 1;
string rtcUserId = 2;
string rtcToken = 3;
int64 rtcChannelId = 4;
}
message RTCLiveVideoParam {
int32 strategyId = 1;
RTCVideoParam params = 2;
}
message RTCVideoParam {
int32 width = 1;
int32 height = 2;
int32 fps = 3;
int32 bitrateKbps = 4;
}
message RTCBitrateMap {
int32 xx1 = 1;
int32 xx2 = 2;
int32 xx3 = 3;
int32 xx4 = 4;
}
}
message CreateChannelContent {
Player owner = 1;
string ownerLinkMicId = 2;
}
message ListChangeContent {
TextType type = 1; // Enum
AllListUser list = 2;
}
message MultiLiveContent {
InviteBizContent inviteBizContent = 2;
ReplyBizContent replyBizContent = 3;
PermitBizContent permitBizContent = 4;
KickOutBizContent kickOutBizContent = 6;
message InviteBizContent {
LinkmicUserSettingInfo anchorSettingInfo = 1;
int64 inviteSource = 2; // @warning Enum not found, should be InviteSource
User operatorUserInfo = 3;
int64 operatorLinkAdminType = 4; // @warning Enum not found, should be OperatorLinkAdminType
User inviteeUserInfo = 5;
}
message ReplyBizContent {
int32 linkType = 1;
int32 isTurnOffInvitation = 2;
User replyUserInfo = 3;
}
message PermitBizContent {
LinkmicUserSettingInfo anchorSettingInfo = 1;
int64 expireTimestamp = 2;
User operatorUserInfo = 3;
int64 operatorLinkAdminType = 4; // @warning Enum not found, should be OperatorLinkAdminType
}
message KickOutBizContent {
User operatorUserInfo = 1;
int64 operatorLinkAdminType = 2; // @warning Enum not found, should be OperatorLinkAdminType
User kickPlayerUserInfo = 3;
}
}
message InviteContent {
Player invitor = 1;
RTCExtraInfo inviteeRtcExtInfo = 2;
string invitorLinkMicId = 3;
string inviteeLinkMicId = 4;
bool isOwner = 5;
Position pos = 6;
DSLConfig dsl = 7;
User invitee = 8;
User operator = 9;
}
// @ApplyContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message ApplyContent {
Player applier = 1;
string applierLinkMicId = 2;
}
// @PermitApplyContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message PermitApplyContent {
Player permiter = 1;
string permiterLinkMicId = 2;
Position applierPos = 3;
ReplyStatus replyStatus = 4; // Enum
DSLConfig dsl = 5;
User applier = 6;
User operator = 7;
string applierLinkMicId = 8;
}
// @ReplyInviteContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message ReplyInviteContent {
Player invitee = 1;
ReplyStatus replyStatus = 2; // Enum
string inviteeLinkMicId = 3;
Position inviteePos = 4;
Player inviteOperatorUser = 5;
}
// @KickOutContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message KickOutContent {
Player offliner = 1;
KickoutReason kickoutReason = 2; // Enum
}
// @CancelApplyContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message CancelApplyContent {
Player applier = 1;
string applierLinkMicId = 2;
}
// @CancelInviteContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message CancelInviteContent {
Player invitor = 1;
string invitorLinkMicId = 2;
string inviteeLinkMicId = 3;
int64 inviteSeqId = 4;
Player invitee = 5;
}
// @LeaveContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message LeaveContent {
Player leaver = 1;
int64 leaveReason = 2;
}
// @FinishChannelContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message FinishChannelContent {
Player owner = 1;
int64 finishReason = 2;
}
// @JoinDirectContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message JoinDirectContent {
LinkLayerListUser joiner = 1;
AllListUser allUsers = 2;
}
// @LeaveJoinGroupContent
// proto.webcast.im
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message LeaveJoinGroupContent {
GroupPlayer operator = 1;
int64 groupChannelId = 2;
string leaveSource = 3;
}
// @PermitJoinGroupContent
// proto.webcast.im
message PermitJoinGroupContent {
GroupPlayer approver = 1;
AgreeStatus agreeStatus = 2; // Enum
TextType type = 3; // Enum
repeated RTCExtraInfo groupExtInfoList = 4;
GroupChannelAllUser groupUser = 5;
}
// @CancelJoinGroupContent
// proto.webcast.im
message CancelJoinGroupContent {
repeated GroupPlayer leaverList = 1;
GroupPlayer operator = 2;
TextType type = 3; // Enum
}
message P2PGroupChangeContent {
repeated RTCExtraInfo groupExtInfoList = 1;
GroupChannelAllUser groupUser = 2;
}
message BusinessContent {
int64 overLength = 1;
MultiLiveContent multiLiveContent = 100;
CohostContent cohostContent = 200;
message CohostContent {
JoinGroupBizContent joinGroupBizContent = 1;
}
message JoinGroupBizContent {
int32 fromRoomAgeRestricted = 1;
Tag fromTag = 2;
PerceptionDialogInfo dialog = 3;
PunishEventInfo punishInfo = 4;
JoinGroupMessageExtra joinGroupMsgExtra = 101;
}
message Tag {
int32 tagType = 1;
string tagValue = 2;
string tagText = 3;
}
message PerceptionDialogInfo {
int64 iconType = 1; // @warning Enum not found, should be IconType
Text title = 2;
Text subTitle = 3;
Text adviceActionText = 4;
Text defaultActionText = 5;
string violationDetailUrl = 6;
int32 scene = 7;
int64 targetUserId = 8;
int64 targetRoomId = 9;
int64 countDownTime = 10;
bool showFeedback = 11;
repeated PerceptionFeedbackOption feedbackOptionsList = 12;
int64 policyTip = 13;
}
message PerceptionFeedbackOption {
int64 id = 1;
string contentKey = 2;
}
message JoinGroupMessageExtra {
int64 sourceType = 1;
RivalExtra extra = 2;
repeated RivalExtra otherUsersList = 3;
// @RivalExtra
// proto.webcast.im.JoinGroupMessageExtra
// C:\Users\ja\RiderProjects\TikTokProBufferGenerator\Application\output\sources\test.js
message RivalExtra {
int64 userCount = 4;
Image avatarThumb = 5;
string displayId = 6;
AuthenticationInfo authenticationInfo = 7;
string nickname = 8;
int64 followStatus = 9;
Hashtag hashtag = 10;
TopHostInfo topHostInfo = 11;
int64 userId = 12;
bool isBestTeammate = 13;
message AuthenticationInfo {
string customVerify = 1;
string enterpriseVerifyReason = 2;
Image authenticationBadge = 3;
}
}
}
message Hashtag {
int64 id = 1;
string title = 2;
Image image = 3;
HashtagNamespace namespace = 4; // Enum
}
message TopHostInfo {
string rankType = 1;
int64 topIndex = 2;
}
}
message JoinGroupContent {
GroupChannelAllUser groupUser = 1;
GroupPlayer joinUser = 2;
TextType type = 3; // Enum
}

View File

@@ -25,6 +25,85 @@ enum EmotePrivateType {
EMOTE_PRIVATE_TYPE_SUB_WAVE = 1;
}
enum TextType {
DISPLAY_TEXT = 0;
CONTENT = 1;
}
enum LinkmicApplierSortSetting {
LINKMIC_APPLIER_SORT_SETTING_NONE = 0;
LINKMIC_APPLIER_SORT_SETTING_BY_GIFT_SCORE = 1;
}
enum HashtagNamespace {
GLOBAL = 0;
GAMING = 1;
}
enum AgreeStatus {
AGREE_UNKNOWN = 0;
AGREE = 1;
REJECT = 2;
}
enum KickoutReason {
KICKOUT_REASON_UNKNOWN = 0;
KICKOUT_REASON_FIRST_FRAME_TIMEOUT = 1;
KICKOUT_REASON_BY_HOST = 2;
KICKOUT_REASON_RTC_LOST_CONNECTION = 3;
KICKOUT_REASON_BY_PUNISH = 4;
KICKOUT_REASON_BY_ADMIN = 5;
KICKOUT_REASON_HOST_REMOVE_ALL_GUESTS = 6;
}
enum GroupStatus {
GROUP_STATUS_UNKNOWN = 0;
GROUP_STATUS_WAITING = 1;
GROUP_STATUS_LINKED = 3;
}
enum BusinessCase {
BUSINESS_NOT_SET = 0;
APPLY_BIZ_CONTENT = 1;
INVITE_BIZ_CONTENT = 2;
REPLY_BIZ_CONTENT = 3;
PERMIT_BIZ_CONTENT = 4;
JOIN_DIRECT_BIZ_CONTENT = 5;
KICK_OUT_BIZ_CONTENT = 6;
LIST_CHANGE_BIZ_CONTENT = 11;
MULTI_LIVE_CONTENT = 100;
COHOST_CONTENT = 200;
}
enum ReplyStatus {
REPLY_STATUS_UNKNOWN = 0;
REPLY_STATUS_AGREE = 1;
REPLY_STATUS_REFUSE_PERSONALLY = 2;
REPLY_STATUS_REFUSE_TYPE_NOT_SUPPORT = 3;
REPLY_STATUS_REFUSE_PROCESSING_INVITATION = 4;
REPLY_STATUS_REFUSE_BY_TIMEOUT = 5;
REPLY_STATUS_REFUSE_EXCEPTION = 6;
REPLY_STATUS_REFUSE_SYSTEM_NOT_SUPPORTED = 7;
REPLY_STATUS_REFUSE_SUBTYPE_DIFFERENCE = 8;
REPLY_STATUS_REFUSE_IN_MICROOM = 9;
REPLY_STATUS_REFUSE_NOT_LOAD_PLUGIN = 10;
REPLY_STATUS_REFUSE_IN_MULTI_GUEST = 11;
REPLY_STATUS_REFUSE_PAUSE_LIVE = 12;
REPLY_STATUS_REFUSE_OPEN_CAMERA_DIALOG_SHOWING = 13;
REPLY_STATUS_REFUSE_DRAW_GUESSING = 14;
REPLY_STATUS_REFUSE_RANDOM_MATCHING = 15;
REPLY_STATUS_REFUSE_IN_MATCH_PROCESSING = 16;
REPLY_STATUS_REFUSE_IN_MICROOM_FOR_MULTI_COHOST = 17;
REPLY_STATUS_REFUSE_COHOST_FINISHED = 18;
REPLY_STATUS_REFUSE_NOT_CONNECTED = 19;
REPLY_STATUS_REFUSE_LINKMIC_FULL = 20;
REPLY_STATUS_REFUSE_ARC_INCOMPATIBLE = 21;
REPLY_STATUS_REFUSE_PROCESSING_OTHER_INVITE = 22;
REPLY_STATUS_REFUSE_PROCESSING_OTHER_APPLY = 23;
REPLY_STATUS_REFUSE_IN_ANCHOR_COHOST = 24;
REPLY_STATUS_REFUSE_TOPIC_PAIRING = 25;
}
enum SubscribeType {
SUBSCRIBETYPE_ONCE = 0;
@@ -68,6 +147,7 @@ enum MemberMessageAction {
enum ControlAction {
ControlActionUNKNOWN = 0;
STREAM_PAUSED = 1; // Stream Paused by Host
STREAM_UNPAUSED = 2;
STREAM_ENDED = 3; // Stream Ended by Host
}
@@ -111,3 +191,104 @@ enum BarrageType
FansLevelEntrance = 11;
GamePartnership = 12;
}
enum EnvelopeBusinessType
{
BusinessTypeUnknown = 0;
BusinessTypeUserDiamond = 1;
BusinessTypePlatformDiamond = 2;
BusinessTypePlatformShell = 3;
BusinessTypePortal = 4;
BusinessTypePlatformMerch = 5;
BusinessTypeEoYDiamond = 6;
BusinessTypeFanClubGtM = 7;
}
enum EnvelopeFollowShowStatus
{
EnvelopeFollowShowUnknown = 0;
EnvelopeFollowShow = 1;
EnvelopeFollowNotShow = 2;
}
enum EnvelopeDisplay
{
EnvelopeDisplayUnknown = 0;
EnvelopeDisplayNew = 1;
EnvelopeDisplayHide = 2;
}
enum CommonContentCase {
COMMON_CONTENT_NOT_SET = 0;
CREATE_CHANNEL_CONTENT = 100;
LIST_CHANGE_CONTENT = 102;
INVITE_CONTENT = 103;
APPLY_CONTENT = 104;
PERMIT_APPLY_CONTENT = 105;
REPLY_INVITE_CONTENT = 106;
KICK_OUT_CONTENT = 107;
CANCEL_APPLY_CONTENT = 108;
CANCEL_INVITE_CONTENT = 109;
LEAVE_CONTENT = 110;
FINISH_CONTENT = 111;
JOIN_DIRECT_CONTENT = 112;
JOIN_GROUP_CONTENT = 113;
PERMIT_GROUP_CONTENT = 114;
CANCEL_GROUP_CONTENT = 115;
LEAVE_GROUP_CONTENT = 116;
P2P_GROUP_CHANGE_CONTENT = 117;
GROUP_CHANGE_CONTENT = 118;
}
enum LinkMessageType {
TPYE_LINKER_UNKNOWN = 0;
TYPE_LINKER_CREATE = 1;
TYPE_LINKER_CLOSE = 2;
TYPE_LINKER_INVITE = 3;
TYPE_LINKER_APPLY = 4;
TYPE_LINKER_REPLY = 5;
TPYE_LINKER_ENTER = 6;
TPYE_LINKER_LEAVE = 7;
TYPE_LINKER_PERMIT = 8;
TPYE_LINKER_CANCEL_INVITE = 9;
TYPE_LINKER_WAITING_LIST_CHANGE = 10;
TYPE_LINKER_LINKED_LIST_CHANGE = 11;
TYPE_LINKER_UPDATE_USER = 12;
TPYE_LINKER_KICK_OUT = 13;
TPYE_LINKER_CANCEL_APPLY = 14;
TYPE_LINKER_MUTE = 15;
TYPE_LINKER_MATCH = 16;
TYPE_LINKER_UPDATE_USER_SETTING = 17;
TYPE_LINKER_MIC_IDX_UPDATE = 18;
TYPE_LINKER_LEAVE_V2 = 19;
TYPE_LINKER_WAITING_LIST_CHANGE_V2 = 20;
TYPE_LINKER_LINKED_LIST_CHANGE_V2 = 21;
TYPE_LINKER_COHOST_LIST_CHANGE = 22;
TYPE_LINKER_MEDIA_CHANGE = 23;
TYPE_LINKER_ACCEPT_NOTICE = 24;
TPYE_LINKER_SYS_KICK_OUT = 101;
TPYE_LINKMIC_USER_TOAST = 102;
}
enum MessageType {
MESSAGETYPE_SUBSUCCESS = 0;
MESSAGETYPE_ANCHORREMINDER = 1;
MESSAGETYPE_ENTERROOMEXPIRESOON = 2;
MESSAGETYPE_SUBGOALCREATETOANCHOR = 3;
MESSAGETYPE_SUBGOALCOMPLETETOAUDIENCE = 4;
MESSAGETYPE_SUBGOALCOMPLETETOANCHOR = 5;
MESSAGETYPE_SUBGIFTTIKTOK2USERNOTICE = 6;
MESSAGETYPE_SUBGIFTTIKTOK2ANCHORNOTICE = 7;
MESSAGETYPE_SUBGIFTTRECEIVESENDNOTICE = 8;
MESSAGETYPE_SUBGIFTSENDSUCCEEDROOMMESSAGE = 9;
MESSAGETYPE_SUBGIFTSENDSUCCEEDANCHORNOTICE = 10;
MESSAGETYPE_SUBGIFTLOWVERSIONUPGRADENOTICE = 11;
MESSAGETYPE_SUBGIFTUSERBUYAUTHNOTICE = 12;
}
enum Scene {
SCENE_UNKNOWN = 0;
SCENE_CO_HOST = 2;
SCENE_MULTI_LIVE = 4;
}

View File

@@ -25,10 +25,6 @@ message WebcastPushFrame {
}
message WebcastWebsocketAck {
uint64 Id = 1;
string Type = 2;
}
//@WebcastResponse
@@ -81,6 +77,13 @@ message WebcastGiftMessage {
bool isFirstSent = 25;
string orderId = 28;
UserIdentity userIdentity = 32;
UserGiftReciever userGiftReciever = 23;
message UserGiftReciever
{
int64 userId = 1;
string deviceName = 10;
}
message GiftIMPriority {
repeated int64 queueSizesList = 1;
@@ -177,6 +180,8 @@ message WebcastCaptionMessage {
}
}
// Comment sent by User
//@WebcastChatMessage
message WebcastChatMessage {
@@ -246,13 +251,13 @@ message WebcastEmoteChatMessage {
message WebcastEnvelopeMessage {
Common common = 1;
EnvelopeInfo envelopeInfo = 2;
int64 display = 3; // @warning Enum not found, should be Display
EnvelopeDisplay display = 3; // @warning Enum not found, should be Display
// @EnvelopeInfo
// proto.webcast.im.EnvelopeMessage
message EnvelopeInfo {
string envelopeId = 1;
int64 businessType = 2; // @warning Enum not found, should be BusinessType
EnvelopeBusinessType businessType = 2;
string envelopeIdc = 3;
string sendUserName = 4;
int32 diamondCount = 5;
@@ -262,7 +267,7 @@ message WebcastEnvelopeMessage {
Image sendUserAvatar = 9;
string createAt = 10;
string roomId = 11;
int64 followShowStatus = 12; // @warning Enum not found, should be FollowShowStatus
EnvelopeFollowShowStatus followShowStatus = 12; // @warning Enum not found, should be FollowShowStatus
int32 skinId = 13;
}
}
@@ -440,7 +445,7 @@ message WebcastMemberMessage {
//@WebcastPollMessage
message WebcastPollMessage {
Common common = 1;
int32 messageType = 2;
MessageType messageType = 2;
int64 pollId = 3;
PollStartContent startContent = 4;
PollEndContent endContent = 5;
@@ -505,6 +510,9 @@ message WebcastHourlyRankMessage {
}
}
//<Battles>
//@WebcastLinkMicArmies
message WebcastLinkMicArmies {
Common common = 1;
@@ -521,6 +529,45 @@ message WebcastLinkMicArmies {
uint32 data4 = 12;
uint32 data5 = 13;
}
//@WebcastLinkMicBattlePunishFinish
message WebcastLinkMicBattlePunishFinish {
Common Header = 1;
uint64 Id1 = 2;
uint64 Timestamp = 3;
uint32 Data4 = 4;
uint64 Id2 = 5;
LinkMicBattlePunishFinishData Data6 = 6;
message LinkMicBattlePunishFinishData {
uint64 Id2 = 1; // Same as Id2 in outer object (loser?)
uint64 Timestamp = 2;
uint32 Data3 = 3;
uint64 Id1 = 4; // Same as Id1 in outer object (winner?)
uint32 Data5 = 5;
uint32 Data6 = 6;
uint32 Data8 = 8;
}
}
//@WebcastLinkmicBattleTaskMessage
message WebcastLinkmicBattleTaskMessage {
Common Header = 1;
uint32 Data2 = 2;
LinkmicBattleTaskData Data3 = 3;
LinkmicBattleTaskData2 Data5 = 5;
message LinkmicBattleTaskData {
BattleTaskData Data1 = 1;
}
message BattleTaskData {
uint32 Data1 = 1;
}
message LinkmicBattleTaskData2 {
uint32 Data1 = 1;
uint32 Data2 = 2;
}
}
//@WebcastLinkMicBattle
message WebcastLinkMicBattle {
@@ -570,11 +617,10 @@ message WebcastLinkMicFanTicketMethod {
Common common = 1;
FanTicketRoomNoticeContent FanTicketRoomNotice = 2;
}
//@WebcastLinkMicMethod
message WebcastLinkMicMethod {
Common common = 1;
int64 messageType = 2;
MessageType messageType = 2;
string accessKey = 3;
int64 anchorLinkmicId = 4;
int64 userId = 5;
@@ -588,6 +634,8 @@ message WebcastLinkMicMethod {
int64 inviteUid = 13;
}
//<Battles>
//@WebcastLiveIntroMessage
message WebcastLiveIntroMessage {
Common common = 1;
@@ -681,39 +729,63 @@ message WebcastSystemMessage {
//@WebcastLinkMessage
message WebcastLinkMessage {
Common common = 1;
uint32 data1 = 2;
uint64 data2 = 3;
uint32 data3 = 4;
LinkMessageData data = 18;
LinkMessageUserContainer user = 20;
string token = 200;
message LinkMessageData {
DataContainer data = 1; // index 1 is an Id
LinkMessageType MessageType = 2;
int64 LinkerId = 3;
Scene Scene = 4;
LinkerInviteContent InviteContent = 5;
LinkerReplyContent ReplyContent = 6;
LinkerCreateContent CreateContent = 7;
LinkerCloseContent CloseContent = 8;
LinkerEnterContent EnterContent = 9;
LinkerLeaveContent LeaveContent = 10;
LinkerCancelContent CancelContent = 11;
LinkerKickOutContent KickOutContent = 12;
LinkerLinkedListChangeContent LinkedListChangeContent = 13;
LinkerUpdateUserContent UpdateUserContent = 14;
LinkerWaitingListChangeContent WaitingListChangeContent = 15;
LinkerMuteContent MuteContent = 16;
LinkerRandomMatchContent RandomMatchContent = 17;
LinkerUpdateUserSettingContent UpdateUserSettingContent = 18;
LinkerMicIdxUpdateContent MicIdxUpdateContent = 19;
LinkerListChangeContent ListChangeContent = 20;
CohostListChangeContent CohostListChangeContent = 21;
LinkerMediaChangeContent MediaChangeContent = 22;
LinkerAcceptNoticeContent ReplyAcceptNoticeContent = 23;
LinkerSysKickOutContent SysKickOutContent = 101;
LinkmicUserToastContent UserToastContent = 102;
string extra = 200;
int64 expireTimestamp = 201;
string transferExtra = 202;
}
message LinkMessageUserContainer {
LinkMessageUser user = 1;
repeated LinkMessageUser otherUsers = 2;
message LinkMessageUser {
User user = 1;
uint64 timeStamp = 2;
uint32 data1 = 4;
string idString = 5;
uint32 data2 = 7;
}
}
}
// @WebcastLinkLayerMessage
message WebcastLinkLayerMessage {
Common common = 1;
LinkLayerMessageType messageType = 2;
MessageType messageType = 2; // Enum
int64 channelId = 3;
Scene scene = 4; // Enum
CreateChannelContent createChannelContent = 100;
ListChangeContent listChangeContent = 102;
InviteContent inviteContent = 103;
ApplyContent applyContent = 104;
PermitApplyContent permitApplyContent = 105;
ReplyInviteContent replyInviteContent = 106;
KickOutContent kickOutContent = 107;
CancelApplyContent cancelApplyContent = 108;
CancelInviteContent cancelInviteContent = 109;
LeaveContent leaveContent = 110;
FinishChannelContent finishContent = 111;
JoinDirectContent joinDirectContent = 112;
JoinGroupContent joinGroupContent = 113;
PermitJoinGroupContent permitGroupContent = 114;
CancelJoinGroupContent cancelGroupContent = 115;
LeaveJoinGroupContent leaveGroupContent = 116;
P2PGroupChangeContent p2pGroupChangeContent = 117;
BusinessContent businessContent = 200;
}
// @RoomVerifyMessage
message RoomVerifyMessage {
Common common = 1;
int32 action = 2;

View File

@@ -5,7 +5,7 @@
<parent>
<artifactId>TikTokLiveJava</artifactId>
<groupId>io.github.jwdeveloper.tiktok</groupId>
<version>1.0.1-Release</version>
<version>1.0.17-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>

View File

@@ -23,12 +23,72 @@
package io.github.jwdeveloper.tiktok;
import io.github.jwdeveloper.tiktok.http.LiveHttpClient;
import io.github.jwdeveloper.tiktok.live.builder.LiveClientBuilder;
public class TikTokLive
{
public static LiveClientBuilder newClient(String hostName)
{
import java.util.concurrent.CompletableFuture;
public class TikTokLive {
/**
* @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) {
return new TikTokLiveClientBuilder(hostName);
}
/**
*
* @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 requests().fetchLiveUserData(hostName).isLiveOnline();
}
/**
*
* @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 CompletableFuture.supplyAsync(()-> isLiveOnline(hostName));
}
/**
*
* @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 requests().fetchLiveUserData(hostName).isHostNameValid();
}
/**
*
* @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 CompletableFuture.supplyAsync(()-> isHostNameValid(hostName));
}
/**
* Use to get some data from TikTok about users are lives
*
* @return LiveHttpClient
*/
public static LiveHttpClient requests() {
return new TikTokLiveHttpClient();
}
}

View File

@@ -25,18 +25,23 @@ package io.github.jwdeveloper.tiktok;
import io.github.jwdeveloper.tiktok.data.events.TikTokDisconnectedEvent;
import io.github.jwdeveloper.tiktok.data.events.TikTokErrorEvent;
import io.github.jwdeveloper.tiktok.data.events.TikTokReconnectingEvent;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.control.TikTokConnectingEvent;
import io.github.jwdeveloper.tiktok.data.events.http.TikTokRoomDataResponseEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomInfoEvent;
import io.github.jwdeveloper.tiktok.data.requests.LiveConnectionData;
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
import io.github.jwdeveloper.tiktok.exceptions.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.models.ConnectionState;
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
import io.github.jwdeveloper.tiktok.websocket.SocketClient;
import java.util.concurrent.CompletableFuture;
@@ -46,24 +51,24 @@ import java.util.logging.Logger;
public class TikTokLiveClient implements LiveClient {
private final TikTokRoomInfo liveRoomInfo;
private final TikTokGiftManager tikTokGiftManager;
private final TikTokApiService apiService;
private final TikTokLiveHttpClient 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;
public TikTokLiveClient(TikTokRoomInfo tikTokLiveMeta,
TikTokApiService tikTokApiService,
TikTokLiveHttpClient tiktokHttpClient,
SocketClient webSocketClient,
TikTokGiftManager tikTokGiftManager,
TikTokEventObserver tikTokEventHandler,
ClientSettings clientSettings,
TikTokLiveEventHandler tikTokEventHandler,
LiveClientSettings clientSettings,
TikTokListenersManager listenersManager,
Logger logger) {
this.liveRoomInfo = tikTokLiveMeta;
this.tikTokGiftManager = tikTokGiftManager;
this.apiService = tikTokApiService;
this.httpClient = tiktokHttpClient;
this.webSocketClient = webSocketClient;
this.tikTokEventHandler = tikTokEventHandler;
this.clientSettings = clientSettings;
@@ -73,17 +78,15 @@ public class TikTokLiveClient implements LiveClient {
public void connectAsync(Consumer<LiveClient> onConnection) {
CompletableFuture.supplyAsync(() ->
{
CompletableFuture.runAsync(() -> {
connect();
onConnection.accept(this);
return this;
});
}
public CompletableFuture<LiveClient> connectAsync() {
return CompletableFuture.supplyAsync(() ->
{
return CompletableFuture.supplyAsync(() -> {
connect();
return this;
});
@@ -92,8 +95,7 @@ public class TikTokLiveClient implements LiveClient {
public void connect() {
try {
tryConnect();
} catch (TikTokLiveException e)
{
} catch (TikTokLiveException e) {
setState(ConnectionState.DISCONNECTED);
tikTokEventHandler.publish(this, new TikTokErrorEvent(e));
tikTokEventHandler.publish(this, new TikTokDisconnectedEvent());
@@ -101,53 +103,77 @@ public class TikTokLiveClient implements LiveClient {
if (e instanceof TikTokLiveOfflineHostException && clientSettings.isRetryOnConnectionFailure()) {
try {
Thread.sleep(clientSettings.getRetryConnectionTimeout().toMillis());
} catch (Exception ignored) {
}
} catch (Exception ignored) {}
logger.info("Reconnecting");
tikTokEventHandler.publish(this, new TikTokReconnectingEvent());
this.connect();
}
throw e;
} catch (Exception e) {
logger.info("Unhandled exception report this bug to github https://github.com/jwdeveloper/TikTokLiveJava/issues");
this.disconnect();
e.printStackTrace();
}
}
public void disconnect() {
if (!liveRoomInfo.hasConnectionState(ConnectionState.CONNECTED)) {
return;
}
webSocketClient.stop();
setState(ConnectionState.DISCONNECTED);
}
public void tryConnect() {
if (liveRoomInfo.hasConnectionState(ConnectionState.CONNECTED))
if (!liveRoomInfo.hasConnectionState(ConnectionState.DISCONNECTED)) {
throw new TikTokLiveException("Already connected");
if (liveRoomInfo.hasConnectionState(ConnectionState.CONNECTING))
throw new TikTokLiveException("Already connecting");
}
setState(ConnectionState.CONNECTING);
apiService.updateSessionId();
if (clientSettings.getRoomId() != null) {
liveRoomInfo.setRoomId(clientSettings.getRoomId());
logger.info("Using roomID from settings: " + clientSettings.getRoomId());
} else {
var roomId = apiService.fetchRoomId(liveRoomInfo.getHostName());
liveRoomInfo.setRoomId(roomId);
tikTokEventHandler.publish(this,new TikTokConnectingEvent());
var userDataRequest = new LiveUserData.Request(liveRoomInfo.getHostName());
var userData = httpClient.fetchLiveUserData(userDataRequest);
liveRoomInfo.setStartTime(userData.getStartedAtTimeStamp());
liveRoomInfo.setRoomId(userData.getRoomId());
if (userData.getUserStatus() == LiveUserData.UserStatus.Offline) {
throw new TikTokLiveOfflineHostException("User is offline: "+liveRoomInfo.getHostUser());
}
if (userData.getUserStatus() == LiveUserData.UserStatus.NotFound) {
throw new TikTokLiveOfflineHostException("User not found: "+liveRoomInfo.getHostUser());
}
var roomData = apiService.fetchRoomInfo();
if (roomData.getStatus() != LiveRoomMeta.LiveRoomStatus.HostOnline) {
throw new TikTokLiveOfflineHostException("LiveStream for Host name could not be found. Is the Host online?");
var liveDataRequest = new LiveData.Request(userData.getRoomId());
var liveData = httpClient.fetchLiveData(liveDataRequest);
tikTokEventHandler.publish(this, new TikTokRoomDataResponseEvent(liveData));
if (liveData.getLiveStatus() == LiveData.LiveStatus.HostNotFound) {
throw new TikTokLiveOfflineHostException("LiveStream for Host name could not be found.");
}
if (liveData.getLiveStatus() == LiveData.LiveStatus.HostOffline) {
throw new TikTokLiveOfflineHostException("LiveStream for not be found, is the Host offline?");
}
var clientData = apiService.fetchClientData();
webSocketClient.start(clientData, this);
liveRoomInfo.setTitle(liveData.getTitle());
liveRoomInfo.setViewersCount(liveData.getViewers());
liveRoomInfo.setTotalViewersCount(liveData.getTotalViewers());
liveRoomInfo.setAgeRestricted(liveData.isAgeRestricted());
liveRoomInfo.setHost(liveData.getHost());
var liveConnectionRequest =new LiveConnectionData.Request(userData.getRoomId());
var liveConnectionData = httpClient.fetchLiveConnectionData(liveConnectionRequest);
webSocketClient.start(liveConnectionData, 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);
}
public LiveRoomInfo getRoomInfo() {
return liveRoomInfo;
@@ -167,11 +193,4 @@ public class TikTokLiveClient implements LiveClient {
public GiftManager getGiftManager() {
return tikTokGiftManager;
}
private void setState(ConnectionState connectionState) {
logger.info("TikTokLive client state: " + connectionState.name());
liveRoomInfo.setConnectionState(connectionState);
}
}

View File

@@ -24,12 +24,13 @@ package io.github.jwdeveloper.tiktok;
import io.github.jwdeveloper.tiktok.data.events.*;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.envelop.TikTokChestEvent;
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftComboEvent;
import io.github.jwdeveloper.tiktok.data.events.gift.TikTokGiftEvent;
import io.github.jwdeveloper.tiktok.data.events.http.TikTokHttpResponseEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomInfoEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomPinEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomUserInfoEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
@@ -39,23 +40,27 @@ import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketRespons
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketUnhandledMessageEvent;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
import io.github.jwdeveloper.tiktok.gifts.TikTokGiftManager;
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
import io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandlerRegistration;
import io.github.jwdeveloper.tiktok.handlers.events.TikTokGiftEventHandler;
import io.github.jwdeveloper.tiktok.http.TikTokApiService;
import io.github.jwdeveloper.tiktok.http.TikTokCookieJar;
import io.github.jwdeveloper.tiktok.http.TikTokHttpClient;
import io.github.jwdeveloper.tiktok.http.TikTokHttpRequestFactory;
import io.github.jwdeveloper.tiktok.http.HttpClientFactory;
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.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.messages.webcast.*;
import io.github.jwdeveloper.tiktok.data.settings.LiveClientSettings;
import io.github.jwdeveloper.tiktok.utils.ConsoleColors;
import io.github.jwdeveloper.tiktok.websocket.TikTokWebSocketClient;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@@ -64,21 +69,31 @@ import java.util.logging.*;
public class TikTokLiveClientBuilder implements LiveClientBuilder {
protected final ClientSettings clientSettings;
protected final LiveClientSettings clientSettings;
protected final Logger logger;
protected final TikTokEventObserver tikTokEventHandler;
protected final TikTokLiveEventHandler tikTokEventHandler;
protected final List<TikTokEventListener> listeners;
protected Consumer<TikTokMapper> onCustomMappings;
public TikTokLiveClientBuilder(String userName) {
this.tikTokEventHandler = new TikTokEventObserver();
this.clientSettings = Constants.DefaultClientSettings();
public TikTokLiveClientBuilder(String userName)
{
this.clientSettings = LiveClientSettings.createDefault();
this.clientSettings.setHostName(userName);
this.tikTokEventHandler = new TikTokLiveEventHandler();
this.logger = Logger.getLogger(TikTokLive.class.getSimpleName() + " " + userName);
this.listeners = new ArrayList<>();
this.onCustomMappings = (e) -> {
};
}
public TikTokLiveClientBuilder configure(Consumer<ClientSettings> consumer) {
consumer.accept(clientSettings);
public LiveClientBuilder onMapping(Consumer<TikTokMapper> onCustomMappings) {
this.onCustomMappings = onCustomMappings;
return this;
}
public TikTokLiveClientBuilder configure(Consumer<LiveClientSettings> onConfigure) {
onConfigure.accept(clientSettings);
return this;
}
@@ -88,29 +103,23 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
}
protected void validate() {
if (clientSettings.getTimeout() == null) {
clientSettings.setTimeout(Duration.ofSeconds(Constants.DEFAULT_TIMEOUT));
}
if (clientSettings.getClientLanguage() == null || clientSettings.getClientLanguage().equals("")) {
clientSettings.setClientLanguage(Constants.DefaultClientSettings().getClientLanguage());
if (clientSettings.getClientLanguage() == null || clientSettings.getClientLanguage().isEmpty()) {
clientSettings.setClientLanguage("en");
}
if (clientSettings.getHostName() == null || clientSettings.getHostName().equals("")) {
if (clientSettings.getHostName() == null || clientSettings.getHostName().isEmpty()) {
throw new TikTokLiveException("HostName can not be null");
}
if (clientSettings.getHostName().startsWith("@"))
{
if (clientSettings.getHostName().startsWith("@")) {
clientSettings.setHostName(clientSettings.getHostName().substring(1));
}
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();
@@ -127,14 +136,10 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
});
logger.setUseParentHandlers(false);
logger.addHandler(handler);
logger.setLevel(clientSettings.getLogLevel());
if (clientSettings.isPrintToConsole() && clientSettings.getLogLevel() == Level.OFF) {
logger.setLevel(Level.ALL);
if (!clientSettings.isPrintToConsole()) {
logger.setLevel(Level.OFF);
}
}
public LiveClient build() {
@@ -144,28 +149,22 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
tiktokRoomInfo.setHostName(clientSettings.getHostName());
var listenerManager = new TikTokListenersManager(listeners, tikTokEventHandler);
var cookieJar = new TikTokCookieJar();
var requestFactory = new TikTokHttpRequestFactory(cookieJar);
var apiClient = new TikTokHttpClient(cookieJar, requestFactory);
var apiService = new TikTokApiService(apiClient, logger, clientSettings);
var giftManager = new TikTokGiftManager();
var eventMapper = new TikTokGenericEventMapper();
var giftHandler = new TikTokGiftEventHandler(giftManager);
var webResponseHandler = new TikTokMessageHandlerRegistration(tikTokEventHandler,
tiktokRoomInfo,
eventMapper,
giftHandler
);
var giftManager = new TikTokGiftManager(logger);
var eventsMapper = createMapper(giftManager, tiktokRoomInfo);
var messageHandler = new TikTokLiveMessageHandler(tikTokEventHandler, eventsMapper);
var webSocketClient = new TikTokWebSocketClient(logger,
cookieJar,
var httpClientFactory = new HttpClientFactory(clientSettings);
var tikTokLiveHttpClient = new TikTokLiveHttpClient(httpClientFactory, clientSettings);
var webSocketClient = new TikTokWebSocketClient(
clientSettings,
webResponseHandler,
messageHandler,
tikTokEventHandler);
return new TikTokLiveClient(tiktokRoomInfo,
apiService,
tikTokLiveHttpClient,
webSocketClient,
giftManager,
tikTokEventHandler,
@@ -174,6 +173,98 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
logger);
}
public TikTokLiveMapper createMapper(GiftManager giftManager, 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 roomInfoHandler = new TikTokRoomInfoEventHandler(roomInfo);
var socialHandler = new TikTokSocialMediaEventHandler(roomInfo);
mapper.forMessage(WebcastControlMessage.class, commonHandler::handleWebcastControlMessage);
//Room status events
mapper.forMessage(WebcastLiveIntroMessage.class, roomInfoHandler::handleIntro);
mapper.forMessage(WebcastRoomUserSeqMessage.class, roomInfoHandler::handleUserRanking);
mapper.forMessage(WebcastCaptionMessage.class, (inputBytes, messageName, mapperHelper) ->
{
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastCaptionMessage.class);
return MappingResult.of(messageObject, new TikTokCaptionEvent(messageObject));
});
//User Interactions events
mapper.forMessage(WebcastChatMessage.class, (inputBytes, messageName, mapperHelper) ->
{
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastChatMessage.class);
return MappingResult.of(messageObject, new TikTokCommentEvent(messageObject));
});
mapper.forMessage(WebcastSubNotifyMessage.class, (inputBytes, messageName, mapperHelper) ->
{
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastSubNotifyMessage.class);
return MappingResult.of(messageObject, new TikTokSubscribeEvent(messageObject));
});
mapper.forMessage(WebcastEmoteChatMessage.class, (inputBytes, messageName, mapperHelper) ->
{
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastEmoteChatMessage.class);
return MappingResult.of(messageObject, new TikTokEmoteEvent(messageObject));
});
mapper.forMessage(WebcastQuestionNewMessage.class, (inputBytes, messageName, mapperHelper) ->
{
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastQuestionNewMessage.class);
return MappingResult.of(messageObject, new TikTokQuestionEvent(messageObject));
});
mapper.forMessage(WebcastLikeMessage.class, roomInfoHandler::handleLike);
mapper.forMessage(WebcastGiftMessage.class, giftHandler::handleGifts);
mapper.forMessage(WebcastSocialMessage.class, socialHandler::handle);
mapper.forMessage(WebcastMemberMessage.class, roomInfoHandler::handleMemberMessage);
//Host Interaction events
mapper.forMessage(WebcastPollMessage.class, commonHandler::handlePollEvent);
mapper.forMessage(WebcastRoomPinMessage.class, commonHandler::handlePinMessage);
mapper.forMessage(WebcastChatMessage.class, (inputBytes, messageName, mapperHelper) ->
{
var messageObject = mapperHelper.bytesToWebcastObject(inputBytes, WebcastChatMessage.class);
return MappingResult.of(messageObject, new TikTokCommentEvent(messageObject));
});
//LinkMic events
// mapper.webcastObjectToConstructor(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
// mapper.webcastObjectToConstructor(WebcastLinkMicArmies.class, TikTokLinkMicArmiesEvent.class);
// mapper.webcastObjectToConstructor(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
// mapper.webcastObjectToConstructor(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
//Rank events
// mapper.webcastObjectToConstructor(WebcastRankTextMessage.class, TikTokRankTextEvent.class);
// mapper.webcastObjectToConstructor(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
// mapper.webcastObjectToConstructor(WebcastHourlyRankMessage.class, TikTokRankUpdateEvent.class);
//Others events
// mapper.webcastObjectToConstructor(WebcastInRoomBannerMessage.class, TikTokInRoomBannerEvent.class);
// mapper.webcastObjectToConstructor(WebcastMsgDetectMessage.class, TikTokDetectEvent.class);
// mapper.webcastObjectToConstructor(WebcastBarrageMessage.class, TikTokBarrageEvent.class);
// mapper.webcastObjectToConstructor(WebcastUnauthorizedMemberMessage.class, TikTokUnauthorizedMemberEvent.class);
// mapper.webcastObjectToConstructor(WebcastOecLiveShoppingMessage.class, TikTokShopEvent.class);
// mapper.webcastObjectToConstructor(WebcastImDeleteMessage.class, TikTokIMDeleteEvent.class);
// mapper.bytesToEvents(WebcastEnvelopeMessage.class, commonHandler::handleEnvelop);
onCustomMappings.accept(mapper);
return mapper;
}
public LiveClient buildAndConnect() {
var client = build();
client.connect();
@@ -184,12 +275,20 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
return build().connectAsync();
}
public TikTokLiveClientBuilder onUnhandledSocial(
EventConsumer<TikTokUnhandledSocialEvent> event) {
tikTokEventHandler.subscribe(TikTokUnhandledSocialEvent.class, event);
return this;
}
// @Override
public LiveClientBuilder onChest(EventConsumer<TikTokChestEvent> event) {
tikTokEventHandler.subscribe(TikTokChestEvent.class, event);
return this;
}
public TikTokLiveClientBuilder onLinkMicFanTicket(
EventConsumer<TikTokLinkMicFanTicketEvent> event) {
tikTokEventHandler.subscribe(TikTokLinkMicFanTicketEvent.class, event);
@@ -239,16 +338,31 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
return this;
}
public TikTokLiveClientBuilder onRoom(EventConsumer<TikTokRoomEvent> event) {
tikTokEventHandler.subscribe(TikTokRoomEvent.class, event);
@Override
public <E extends TikTokEvent> LiveClientBuilder onEvent(Class<E> eventClass, EventConsumer<E> event) {
tikTokEventHandler.subscribe(eventClass, event);
return this;
}
@Override
public TikTokLiveClientBuilder onRoomInfo(EventConsumer<TikTokRoomInfoEvent> event) {
tikTokEventHandler.subscribe(TikTokRoomInfoEvent.class, event);
return this;
}
public TikTokLiveClientBuilder onLivePaused(EventConsumer<TikTokLivePausedEvent> event) {
tikTokEventHandler.subscribe(TikTokLivePausedEvent.class, event);
return this;
}
@Override
public TikTokLiveClientBuilder onLiveUnpaused(EventConsumer<TikTokLiveUnpausedEvent> event) {
tikTokEventHandler.subscribe(TikTokLiveUnpausedEvent.class, event);
return this;
}
public TikTokLiveClientBuilder onLike(EventConsumer<TikTokLikeEvent> event) {
tikTokEventHandler.subscribe(TikTokLikeEvent.class, event);
return this;
@@ -321,15 +435,14 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
return this;
}
public TikTokLiveClientBuilder onRoomUserInfo(
EventConsumer<TikTokRoomUserInfoEvent> event) {
tikTokEventHandler.subscribe(TikTokRoomUserInfoEvent.class, event);
public TikTokLiveClientBuilder onComment(EventConsumer<TikTokCommentEvent> event) {
tikTokEventHandler.subscribe(TikTokCommentEvent.class, event);
return this;
}
public TikTokLiveClientBuilder onComment(EventConsumer<TikTokCommentEvent> event) {
tikTokEventHandler.subscribe(TikTokCommentEvent.class, event);
@Override
public LiveClientBuilder onHttpResponse(EventConsumer<TikTokHttpResponseEvent> action) {
tikTokEventHandler.subscribe(TikTokHttpResponseEvent.class, action);
return this;
}
@@ -432,10 +545,3 @@ public class TikTokLiveClientBuilder implements LiveClientBuilder {
return this;
}
}

View File

@@ -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<>();
}

View File

@@ -0,0 +1,247 @@
/*
* 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.data.requests.*;
import io.github.jwdeveloper.tiktok.data.settings.*;
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.Optional;
public class TikTokLiveHttpClient implements LiveHttpClient {
/**
* Signing API by Isaac Kogan
* https://github-wiki-see.page/m/isaackogan/TikTokLive/wiki/All-About-Signatures
*/
private static final String TIKTOK_SIGN_API = "https://tiktok.eulerstream.com/webcast/sign_url";
private static final String TIKTOK_URL_WEB = "https://www.tiktok.com/";
private static final String TIKTOK_URL_WEBCAST = "https://webcast.tiktok.com/webcast/";
private final HttpClientFactory httpFactory;
private final LiveClientSettings clientSettings;
private final LiveUserDataMapper liveUserDataMapper;
private final LiveDataMapper liveDataMapper;
private final SignServerResponseMapper signServerResponseMapper;
private final GiftsDataMapper giftsDataMapper;
public TikTokLiveHttpClient(HttpClientFactory factory, LiveClientSettings settings) {
this.httpFactory = factory;
clientSettings = settings;
liveUserDataMapper = new LiveUserDataMapper();
liveDataMapper = new LiveDataMapper();
signServerResponseMapper = new SignServerResponseMapper();
giftsDataMapper = new GiftsDataMapper();
}
public TikTokLiveHttpClient() {
this(new HttpClientFactory(LiveClientSettings.createDefault()), LiveClientSettings.createDefault());
}
public GiftsData.Response fetchGiftsData() {
var url = TIKTOK_URL_WEBCAST + "gift/list/";
var optional = httpFactory.client(url)
.build()
.toJsonResponse();
if (optional.isEmpty()) {
throw new TikTokLiveRequestException("Unable to fetch gifts information's");
}
var json = optional.get();
return giftsDataMapper.map(json);
}
@Override
public LiveUserData.Response fetchLiveUserData(String userName) {
return fetchLiveUserData(new LiveUserData.Request(userName));
}
@Override
public LiveUserData.Response fetchLiveUserData(LiveUserData.Request request) {
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
if (proxyClientSettings.isEnabled()) {
while (proxyClientSettings.hasNext()) {
try {
var url = TIKTOK_URL_WEB + "api-live/user/room";
var optional = httpFactory.client(url)
.withParam("uniqueId", request.getUserName())
.withParam("sourceType", "54")
.build()
.toJsonResponse();
if (optional.isEmpty()) {
throw new TikTokLiveRequestException("Unable to get information's about user");
}
var json = optional.get();
return liveUserDataMapper.map(json);
} catch (TikTokProxyRequestException ignored) {}
}
}
var url = TIKTOK_URL_WEB + "api-live/user/room";
var optional = httpFactory.client(url)
.withParam("uniqueId", request.getUserName())
.withParam("sourceType", "54")
.build()
.toJsonResponse();
if (optional.isEmpty()) {
throw new TikTokLiveRequestException("Unable to get information's about user");
}
var json = optional.get();
return liveUserDataMapper.map(json);
}
@Override
public LiveData.Response fetchLiveData(String roomId) {
return fetchLiveData(new LiveData.Request(roomId));
}
@Override
public LiveData.Response fetchLiveData(LiveData.Request request) {
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
if (proxyClientSettings.isEnabled()) {
while (proxyClientSettings.hasNext()) {
try {
var url = TIKTOK_URL_WEBCAST + "room/info";
var optional = httpFactory.client(url)
.withParam("room_id", request.getRoomId())
.build()
.toJsonResponse();
if (optional.isEmpty()) {
throw new TikTokLiveRequestException("Unable to get info about live room");
}
var json = optional.get();
return liveDataMapper.map(json);
} catch (TikTokProxyRequestException ignored) {}
}
}
var url = TIKTOK_URL_WEBCAST + "room/info";
var optional = httpFactory.client(url)
.withParam("room_id", request.getRoomId())
.build()
.toJsonResponse();
if (optional.isEmpty()) {
throw new TikTokLiveRequestException("Unable to get info about live room");
}
var json = optional.get();
return liveDataMapper.map(json);
}
@Override
public LiveConnectionData.Response fetchLiveConnectionData(String roomId) {
return fetchLiveConnectionData(new LiveConnectionData.Request(roomId));
}
@Override
public LiveConnectionData.Response fetchLiveConnectionData(LiveConnectionData.Request request) {
HttpResponse<byte[]> credentialsResponse = getOptionalProxyResponse(request).orElseGet(()-> {
SignServerResponse signServerResponse = getSignedUrl(request.getRoomId());
return getWebsocketCredentialsResponse(signServerResponse.getSignedUrl());
});
try {
var optionalHeader = credentialsResponse.headers().firstValue("set-cookie");
if (optionalHeader.isEmpty()) {
throw new TikTokSignServerException("Sign server did not return the set-cookie header");
}
var websocketCookie = optionalHeader.get();
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");
}
}
SignServerResponse getSignedUrl(String roomId) {
var urlToSign = httpFactory
.client(TikTokLiveHttpClient.TIKTOK_URL_WEBCAST + "im/fetch")
.withParam("room_id", roomId)
.build()
.toUrl();
var optional = httpFactory
.client(TikTokLiveHttpClient.TIKTOK_SIGN_API)
.withParam("client", "ttlive-java")
.withParam("uuc", "1")
.withParam("url", urlToSign.toString())
.build()
.toJsonResponse();
if (optional.isEmpty()) {
throw new TikTokSignServerException("Unable to sign url: " + urlToSign);
}
var json = optional.get();
return signServerResponseMapper.map(json);
}
HttpResponse<byte[]> getWebsocketCredentialsResponse(String signedUrl) {
var optionalResponse = httpFactory
.clientEmpty(signedUrl)
.build()
.toResponse();
if (optionalResponse.isEmpty()) {
throw new TikTokSignServerException("Unable to get websocket connection credentials");
}
return optionalResponse.get();
}
Optional<HttpResponse<byte[]>> getOptionalProxyResponse(LiveConnectionData.Request request) {
var proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
if (proxyClientSettings.isEnabled()) {
while (proxyClientSettings.hasNext()) {
try {
SignServerResponse signServerResponse = getSignedUrl(request.getRoomId());
HttpResponse<byte[]> credentialsResponse = getWebsocketCredentialsResponse(signServerResponse.getSignedUrl());
clientSettings.getHttpSettings().getProxyClientSettings().rotate();
return Optional.of(credentialsResponse);
} catch (TikTokProxyRequestException | TikTokSignServerException ignored) {}
}
}
return Optional.empty();
}
}

View File

@@ -20,51 +20,32 @@
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.handlers;
package io.github.jwdeveloper.tiktok;
import io.github.jwdeveloper.tiktok.data.dto.MessageMetaData;
import io.github.jwdeveloper.tiktok.data.events.TikTokErrorEvent;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketMessageEvent;
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketResponseEvent;
import io.github.jwdeveloper.tiktok.data.events.websocket.TikTokWebsocketUnhandledMessageEvent;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveMessageException;
import io.github.jwdeveloper.tiktok.live.LiveClient;
import io.github.jwdeveloper.tiktok.mappers.TikTokGenericEventMapper;
import io.github.jwdeveloper.tiktok.mappers.TikTokLiveMapper;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
import io.github.jwdeveloper.tiktok.utils.Stopwatch;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class TikTokLiveMessageHandler {
public abstract class TikTokMessageHandler {
private final TikTokLiveEventHandler tikTokEventHandler;
private final TikTokLiveMapper mapper;
private final Map<String, io.github.jwdeveloper.tiktok.handler.TikTokMessageHandler> handlers;
private final TikTokEventObserver tikTokEventHandler;
protected final TikTokGenericEventMapper mapper;
public TikTokMessageHandler(TikTokEventObserver tikTokEventHandler, TikTokGenericEventMapper mapper) {
handlers = new HashMap<>();
public TikTokLiveMessageHandler(TikTokLiveEventHandler tikTokEventHandler, TikTokLiveMapper mapper) {
this.tikTokEventHandler = tikTokEventHandler;
this.mapper = mapper;
}
public void registerMapping(Class<?> clazz, Function<byte[], TikTokEvent> func) {
handlers.put(clazz.getSimpleName(), messagePayload -> List.of(func.apply(messagePayload)));
}
public void registerMappings(Class<?> clazz, Function<byte[], List<TikTokEvent>> func) {
handlers.put(clazz.getSimpleName(), func::apply);
}
public void registerMapping(Class<?> input, Class<?> output) {
registerMapping(input, (e) -> mapper.mapToEvent(input, output, e));
}
public void handle(LiveClient client, WebcastResponse webcastResponse) {
tikTokEventHandler.publish(client, new TikTokWebsocketResponseEvent(webcastResponse));
for (var message : webcastResponse.getMessagesList()) {
@@ -77,21 +58,21 @@ public abstract class TikTokMessageHandler {
}
}
public void handleSingleMessage(LiveClient client, WebcastResponse.Message message) throws Exception {
public void handleSingleMessage(LiveClient client, WebcastResponse.Message message)
{
var messageClassName = message.getMethod();
if (!handlers.containsKey(messageClassName)) {
if (!mapper.isRegistered(messageClassName)) {
tikTokEventHandler.publish(client, new TikTokWebsocketUnhandledMessageEvent(message));
return;
}
var handler = handlers.get(messageClassName);
var stopwatch = new Stopwatch();
stopwatch.start();
var events = handler.handle(message.getPayload().toByteArray());
var events = mapper.handleMapping(messageClassName, message.getPayload().toByteArray());
var handlingTimeInMs = stopwatch.stop();
var metadata = new TikTokWebsocketMessageEvent.MetaData(Duration.ofNanos(handlingTimeInMs));
var metadata = new MessageMetaData(Duration.ofNanos(handlingTimeInMs));
for (var event : events) {
tikTokEventHandler.publish(client, new TikTokWebsocketMessageEvent(event, message, metadata));
tikTokEventHandler.publish(client, new TikTokWebsocketMessageEvent(message, event, metadata));
tikTokEventHandler.publish(client, event);
}
}

View File

@@ -22,28 +22,52 @@
*/
package io.github.jwdeveloper.tiktok;
import io.github.jwdeveloper.tiktok.models.ConnectionState;
import io.github.jwdeveloper.tiktok.data.models.RankingUser;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.live.LiveRoomInfo;
import io.github.jwdeveloper.tiktok.models.ConnectionState;
import lombok.Data;
import java.util.LinkedList;
import java.util.List;
@Data
public class TikTokRoomInfo implements LiveRoomInfo
{
public class TikTokRoomInfo implements LiveRoomInfo {
private String roomId;
private int likesCount;
private int viewersCount;
private String roomId;
private int totalViewersCount;
private long startTime;
private boolean ageRestricted;
private User host;
private List<RankingUser> usersRanking = new LinkedList<>();
private String hostName;
private String title;
private String language = "en";
private ConnectionState connectionState = ConnectionState.DISCONNECTED;
public boolean hasConnectionState(ConnectionState state)
{
public boolean hasConnectionState(ConnectionState state) {
return connectionState == state;
}
@Override
public User getHostUser() {
return host;
}
public void updateRanking(List<RankingUser> rankingUsers) {
usersRanking.clear();
usersRanking.addAll(rankingUsers);
}
}

View File

@@ -22,24 +22,26 @@
*/
package io.github.jwdeveloper.tiktok.gifts;
import io.github.jwdeveloper.tiktok.data.models.gifts.Gift;
import io.github.jwdeveloper.tiktok.data.models.Picture;
import io.github.jwdeveloper.tiktok.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.HashMap;
import java.util.List;
import java.util.Map;
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() {
public TikTokGiftManager(Logger logger)
{
indexById = new HashMap<>();
indexByName = new HashMap<>();
this.logger = logger;
init();
}
@@ -66,6 +68,7 @@ public class TikTokGiftManager implements GiftManager {
field.set(enumInstance, name);
// EnumSet
field = Gift.class.getDeclaredField("diamondCost");
field.setAccessible(true);
field.set(enumInstance, diamondCost);
@@ -84,23 +87,17 @@ public class TikTokGiftManager implements GiftManager {
}
public Gift findById(int giftId) {
if (!indexById.containsKey(giftId)) {
return Gift.UNDEFINED;
}
return indexById.get(giftId);
Gift gift = indexById.get(giftId);
return gift == null ? Gift.UNDEFINED : gift;
}
public Gift findByName(String giftName) {
if (!indexByName.containsKey(giftName)) {
return Gift.UNDEFINED;
}
return indexByName.get(giftName);
Gift gift = indexByName.get(giftName);
return gift == null ? Gift.UNDEFINED : gift;
}
@Override
public List<Gift> getGifts()
{
public List<Gift> getGifts() {
return indexById.values().stream().toList();
}
}

View File

@@ -1,191 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.handlers;
import io.github.jwdeveloper.tiktok.TikTokRoomInfo;
import io.github.jwdeveloper.tiktok.data.events.*;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEndEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollStartEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollUpdateEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomPinEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomUserInfoEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokShareEvent;
import io.github.jwdeveloper.tiktok.data.models.Text;
import io.github.jwdeveloper.tiktok.handlers.events.TikTokGiftEventHandler;
import io.github.jwdeveloper.tiktok.mappers.TikTokGenericEventMapper;
import io.github.jwdeveloper.tiktok.messages.webcast.*;
import io.github.jwdeveloper.tiktok.models.SocialTypes;
import lombok.SneakyThrows;
import java.util.regex.Pattern;
public class TikTokMessageHandlerRegistration extends TikTokMessageHandler {
private final TikTokRoomInfo roomInfo;
private final TikTokGiftEventHandler giftHandler;
private final Pattern socialMediaPattern = Pattern.compile("pm_mt_guidance_viewer_([0-9]+)_share");
public TikTokMessageHandlerRegistration(TikTokEventObserver tikTokEventHandler,
TikTokRoomInfo roomInfo,
TikTokGenericEventMapper genericTikTokEventMapper,
TikTokGiftEventHandler tikTokGiftEventHandler) {
super(tikTokEventHandler, genericTikTokEventMapper);
this.giftHandler = tikTokGiftEventHandler;
this.roomInfo = roomInfo;
init();
}
public void init() {
//ConnectionEvents events
registerMapping(WebcastControlMessage.class, this::handleWebcastControlMessage);
registerMapping(WebcastSystemMessage.class, TikTokRoomEvent.class);
//Room status events
registerMapping(WebcastLiveIntroMessage.class, TikTokRoomEvent.class);
registerMapping(WebcastRoomUserSeqMessage.class, this::handleRoomUserSeqMessage);
registerMapping(RoomMessage.class, TikTokRoomEvent.class);
registerMapping(WebcastRoomMessage.class, TikTokRoomEvent.class);
registerMapping(WebcastCaptionMessage.class, TikTokCaptionEvent.class);
//User Interactions events
registerMapping(WebcastChatMessage.class, TikTokCommentEvent.class);
registerMapping(WebcastLikeMessage.class, this::handleLike);
registerMappings(WebcastGiftMessage.class, giftHandler::handleGift);
registerMapping(WebcastSocialMessage.class, this::handleSocialMedia);
registerMapping(WebcastMemberMessage.class, this::handleMemberMessage);
//Host Interaction events
registerMapping(WebcastPollMessage.class, this::handlePollEvent);
registerMapping(WebcastRoomPinMessage.class, this::handlePinMessage);
registerMapping(WebcastGoalUpdateMessage.class, TikTokGoalUpdateEvent.class);
//LinkMic events
registerMapping(WebcastLinkMicBattle.class, TikTokLinkMicBattleEvent.class);
registerMapping(WebcastLinkMicArmies.class, TikTokLinkMicArmiesEvent.class);
registerMapping(WebcastLinkMicMethod.class, TikTokLinkMicMethodEvent.class);
registerMapping(WebcastLinkMicFanTicketMethod.class, TikTokLinkMicFanTicketEvent.class);
//Rank events
registerMapping(WebcastRankTextMessage.class, TikTokRankTextEvent.class);
registerMapping(WebcastRankUpdateMessage.class, TikTokRankUpdateEvent.class);
registerMapping(WebcastHourlyRankMessage.class, TikTokRankUpdateEvent.class);
//Others events
registerMapping(WebcastInRoomBannerMessage.class, TikTokInRoomBannerEvent.class);
registerMapping(WebcastMsgDetectMessage.class, TikTokDetectEvent.class);
registerMapping(WebcastBarrageMessage.class, TikTokBarrageEvent.class);
registerMapping(WebcastUnauthorizedMemberMessage.class, TikTokUnauthorizedMemberEvent.class);
registerMapping(WebcastOecLiveShoppingMessage.class, TikTokShopEvent.class);
registerMapping(WebcastImDeleteMessage.class, TikTokIMDeleteEvent.class);
registerMapping(WebcastQuestionNewMessage.class, TikTokQuestionEvent.class);
registerMapping(WebcastEnvelopeMessage.class, TikTokEnvelopeEvent.class);
registerMapping(WebcastSubNotifyMessage.class, TikTokSubNotifyEvent.class);
registerMapping(WebcastEmoteChatMessage.class, TikTokEmoteEvent.class);
}
@SneakyThrows
private TikTokEvent handleWebcastControlMessage(byte[] msg) {
var message = WebcastControlMessage.parseFrom(msg);
return switch (message.getAction()) {
case STREAM_PAUSED -> new TikTokLivePausedEvent();
case STREAM_ENDED -> new TikTokLiveEndedEvent();
default -> new TikTokUnhandledControlEvent(message);
};
}
@SneakyThrows
private TikTokEvent handleSocialMedia(byte[] msg) {
var message = WebcastSocialMessage.parseFrom(msg);
var socialType = Text.map(message.getCommon().getDisplayText()).getKey();
var matcher = socialMediaPattern.matcher(socialType);
if (matcher.find()) {
var value = matcher.group(1);
var number = Integer.parseInt(value);
return new TikTokShareEvent(message, number);
}
return switch (socialType) {
case SocialTypes.LikeType -> new TikTokLikeEvent(message, roomInfo.getLikesCount());
case SocialTypes.FollowType -> new TikTokFollowEvent(message);
case SocialTypes.ShareType -> new TikTokShareEvent(message);
case SocialTypes.JoinType -> new TikTokJoinEvent(message, roomInfo.getViewersCount());
default -> new TikTokUnhandledSocialEvent(message);
};
}
@SneakyThrows
private TikTokEvent handleMemberMessage(byte[] msg) {
var message = WebcastMemberMessage.parseFrom(msg);
return switch (message.getAction()) {
case JOINED -> new TikTokJoinEvent(message);
case SUBSCRIBED -> new TikTokSubscribeEvent(message);
default -> new TikTokUnhandledMemberEvent(message);
};
}
private TikTokEvent handleRoomUserSeqMessage(byte[] msg) {
var event = (TikTokRoomUserInfoEvent) mapper.mapToEvent(WebcastRoomUserSeqMessage.class, TikTokRoomUserInfoEvent.class, msg);
roomInfo.setViewersCount(event.getTotalUsers());
return event;
}
private TikTokEvent handleLike(byte[] msg) {
var event = (TikTokLikeEvent) mapper.mapToEvent(WebcastLikeMessage.class, TikTokLikeEvent.class, msg);
roomInfo.setLikesCount(event.getTotalLikes());
return event;
}
@SneakyThrows
private TikTokEvent handlePinMessage(byte[] msg) {
var pinMessage = WebcastRoomPinMessage.parseFrom(msg);
var chatMessage = WebcastChatMessage.parseFrom(pinMessage.getPinnedMessage());
var chatEvent = new TikTokCommentEvent(chatMessage);
return new TikTokRoomPinEvent(pinMessage, chatEvent);
}
//TODO Probably not working
@SneakyThrows
private TikTokEvent handlePollEvent(byte[] msg) {
var poolMessage = WebcastPollMessage.parseFrom(msg);
return switch (poolMessage.getMessageType()) {
case 0 -> new TikTokPollStartEvent(poolMessage);
case 1 -> new TikTokPollEndEvent(poolMessage);
case 2 -> new TikTokPollUpdateEvent(poolMessage);
default -> new TikTokPollEvent(poolMessage);
};
}
}

View File

@@ -0,0 +1,129 @@
/*
* 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 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 Optional<HttpResponse<byte[]>> toResponse() {
var client = prepareClient();
var request = prepareGetRequest();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() != 200) {
return Optional.empty();
}
return Optional.of(response);
} catch (Exception e) {
throw new TikTokLiveRequestException(e);
}
}
public Optional<String> toJsonResponse() {
var optional = toResponse();
if (optional.isEmpty()) {
return Optional.empty();
}
var response = optional.get();
var body = response.body();
var charset = charsetFrom(response.headers());
return Optional.of(new String(body,charset));
}
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 Optional<byte[]> toBinaryResponse() {
var optional = toResponse();
if (optional.isEmpty()) {
return Optional.empty();
}
var body = optional.get().body();
return Optional.of(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("&"));
}
}

View File

@@ -0,0 +1,85 @@
/*
* 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() {
if (httpClientSettings.getProxyClientSettings().isEnabled())
return new HttpProxyClient(httpClientSettings, url);
return new HttpClient(httpClientSettings, url);
}
}

View File

@@ -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.http;
import io.github.jwdeveloper.tiktok.data.settings.*;
public class HttpClientFactory {
private final LiveClientSettings liveClientSettings;
public HttpClientFactory(LiveClientSettings liveClientSettings) {
this.liveClientSettings = liveClientSettings;
}
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);
}
}

View File

@@ -0,0 +1,207 @@
/*
* 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.*;
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 Optional<HttpResponse<byte[]>> toResponse() {
return switch (proxySettings.getType()) {
case HTTP, DIRECT -> handleHttpProxyRequest();
default -> handleSocksProxyRequest();
};
}
public Optional<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) {
proxySettings.setLastSuccess(false);
continue;
}
proxySettings.setLastSuccess(true);
return Optional.of(response);
} catch (HttpConnectTimeoutException | ConnectException e) {
if (proxySettings.isAutoDiscard())
proxySettings.remove();
proxySettings.setLastSuccess(false);
} catch (Exception e) {
throw new TikTokLiveRequestException(e);
}
}
throw new TikTokLiveRequestException("No more proxies available!");
}
private Optional<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);
proxySettings.setLastSuccess(true);
return Optional.of(response);
} catch (IOException e) {
if (proxySettings.isAutoDiscard())
proxySettings.remove();
proxySettings.setLastSuccess(false);
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, reach us on discord!");
e.printStackTrace();
return Optional.empty();
} catch (TikTokLiveRequestException e) {
e.printStackTrace();
return Optional.empty();
}
}
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();
}
};
}
}

View File

@@ -1,79 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http;
import lombok.SneakyThrows;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils
{
public static String parseParameters(String url, Map<String,Object> parameters)
{
var parameterString = "";
if (!parameters.isEmpty()) {
var builder = new StringBuilder();
builder.append("?");
var first = false;
for (var param : parameters.entrySet()) {
if (first) {
builder.append("&");
}
builder.append(param.getKey()).append("=").append(param.getValue());
first = true;
}
parameterString = builder.toString();
}
return url+parameterString;
}
@SneakyThrows
public static String parseParametersEncode(String url, Map<String,Object> parameters)
{
var parameterString = "";
if (!parameters.isEmpty()) {
var builder = new StringBuilder();
builder.append("?");
var first = false;
for (var param : parameters.entrySet()) {
if (first) {
builder.append("&");
}
final String encodedKey = URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8);
final String encodedValue = URLEncoder.encode(param.getValue().toString(), StandardCharsets.UTF_8);
builder.append(encodedKey).append("=").append(encodedValue);
first = true;
}
parameterString = builder.toString();
}
return url+parameterString;
}
}

View File

@@ -1,147 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http;
import io.github.jwdeveloper.tiktok.ClientSettings;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveOfflineHostException;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
import io.github.jwdeveloper.tiktok.mappers.LiveRoomMetaMapper;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastResponse;
import javax.script.ScriptEngineManager;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class TikTokApiService {
private final TikTokHttpClient tiktokHttpClient;
private final Logger logger;
private final ClientSettings clientSettings;
public TikTokApiService(TikTokHttpClient apiClient, Logger logger, ClientSettings clientSettings) {
this.tiktokHttpClient = apiClient;
this.logger = logger;
this.clientSettings = clientSettings;
}
public void updateSessionId()
{
if(clientSettings.getSessionId() == null)
{
return;
}
if(clientSettings.getSessionId().isEmpty())
{
return;
}
tiktokHttpClient.setSessionId(clientSettings.getSessionId());
}
public boolean sendMessage(String message, String sessionId) {
if (sessionId.isEmpty()) {
throw new TikTokLiveException("Session ID must not be Empty");
}
var roomId = clientSettings.getClientParameters().get("room_id");
if (roomId == null) {
throw new TikTokLiveException("Room ID must not be Empty");
}
logger.info("Sending message to chat");
try {
var params = new HashMap<String, Object>(clientSettings.getClientParameters());
params.put("content", message);
params.put("channel", "tiktok_web");
params.remove("cursor");
tiktokHttpClient.setSessionId(sessionId);
tiktokHttpClient.postMessageToChat(params);
return true;
} catch (Exception e) {
throw new TikTokLiveRequestException("Failed to fetch room id from WebCast, see stacktrace for more info.", e);
}
}
public String fetchRoomId(String userName) {
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");
}
clientSettings.getClientParameters().put("room_id", id);
logger.info("RoomID -> " + id);
return id;
}
public LiveRoomMeta fetchRoomInfo() {
logger.info("Fetching RoomInfo");
try {
var response = tiktokHttpClient.getJObjectFromWebcastAPI("room/info/", clientSettings.getClientParameters());
var mapper = new LiveRoomMetaMapper();
var liveRoomMeta = mapper.map(response);
logger.info("RoomInfo status -> " + liveRoomMeta.getStatus());
return liveRoomMeta;
} catch (Exception e)
{
throw new TikTokLiveRequestException("Failed to fetch room info from WebCast, see stacktrace for more info.", e);
}
}
public WebcastResponse fetchClientData() {
logger.info("Fetching ClientData");
try {
var response = tiktokHttpClient.getSigningServerMessage("im/fetch/", clientSettings.getClientParameters());
clientSettings.getClientParameters().put("cursor", response.getCursor());
clientSettings.getClientParameters().put("internal_ext", response.getInternalExt());
return response;
} catch (Exception e) {
throw new TikTokLiveRequestException("Failed to fetch client data", e);
}
}
}

View File

@@ -1,158 +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 String postMessageToChat(Map<String,Object> parameters)
{
var get = postRequest(Constants.TIKTOK_URL_WEBCAST + "room/chat/", parameters);
return get;
}
public JsonObject getJObjectFromWebcastAPI(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 getSigningServerMessage(String path, Map<String, Object> parameters) {
var bytes = getSignRequest(Constants.TIKTOK_URL_WEBCAST + path, parameters);
try {
return WebcastResponse.parseFrom(bytes);
}
catch (Exception e)
{
throw new TikTokLiveRequestException("Unable to deserialize message: "+path,e);
}
}
private String postRequest(String url, Map<String, Object> parameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
System.out.println("RomMID: "+parameters.get("room_id"));
var request = requestFactory.setQueries(parameters);
return request.post(url);
}
private String getRequest(String url, Map<String, Object> parameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
var request = requestFactory.setQueries(parameters);
return request.get(url);
}
private byte[] getSignRequest(String url, Map<String, Object> parameters) {
url = getSignedUrl(url, parameters);
try {
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
.uri(new URI(url))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
var cookies = response.headers().allValues("Set-Cookie");
for(var cookie : cookies)
{
var split = cookie.split(";")[0].split("=");
var key = split[0];
var value = split[1];
tikTokCookieJar.set(key, value);
}
return response.body();
}
catch (Exception e)
{
throw new TikTokLiveRequestException("Unable to send signature");
}
}
private String getSignedUrl(String url, Map<String, Object> parameters) {
var fullUrl = HttpUtils.parseParameters(url,parameters);
var signParams = new TreeMap<String,Object>();
signParams.put("client", "ttlive-java");
signParams.put("uuc", 1);
signParams.put("url", fullUrl);
var request = requestFactory.setQueries(signParams);
var content = request.get(Constants.TIKTOK_SIGN_API);
try {
var json = JsonParser.parseString(content);
var jsonObject = json.getAsJsonObject();
var signedUrl = jsonObject.get("signedUrl").getAsString();
var userAgent = jsonObject.get("User-Agent").getAsString();
requestFactory.setAgent(userAgent);
return signedUrl;
} catch (Exception e) {
throw new TikTokLiveRequestException("Insufficient values have been supplied for signing. Likely due to an update. Post an issue on GitHub.", e);
}
}
}

View File

@@ -1,166 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http;
import io.github.jwdeveloper.tiktok.Constants;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
import lombok.SneakyThrows;
import java.net.CookieManager;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class TikTokHttpRequestFactory implements TikTokHttpRequest {
private final CookieManager cookieManager;
private final Map<String, String> defaultHeaders;
private final TikTokCookieJar tikTokCookieJar;
private final HttpClient client;
private String query;
public TikTokHttpRequestFactory(TikTokCookieJar tikTokCookieJar) {
this.tikTokCookieJar = tikTokCookieJar;
this.cookieManager = new CookieManager();
defaultHeaders = Constants.DefaultRequestHeaders();
client = HttpClient.newBuilder()
.cookieHandler(cookieManager)
.connectTimeout(Duration.ofSeconds(2))
.build();
}
@SneakyThrows
public String get(String url) {
var uri = URI.create(url);
var request = HttpRequest.newBuilder().GET();
for (var header : defaultHeaders.entrySet())
{
if(header.getKey().equals("Connection") || header.getKey().equals("Accept-Encoding"))
{
continue;
}
request.setHeader(header.getKey(), header.getValue());
}
if (query != null) {
var baseUri = uri.toString();
var requestUri = URI.create(baseUri + "?" + query);
request.uri(requestUri);
}
return getContent(request.build());
}
@SneakyThrows
public String post(String url) {
var uri = URI.create(url);
var request = HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(""));
for (var header : defaultHeaders.entrySet())
{
if(header.getKey().equals("Connection"))
{
continue;
}
request.setHeader(header.getKey(), header.getValue());
}
request.setHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
request.setHeader("Cookie", tikTokCookieJar.parseCookies());
if (query != null) {
var baseUri = uri.toString();
var requestUri = URI.create(baseUri + "?" + query);
request.uri(requestUri);
System.out.println(requestUri.toString());
}
return getContent(request.build());
}
public TikTokHttpRequest setHeader(String key, String value) {
defaultHeaders.put(key, value);
return this;
}
public TikTokHttpRequest setAgent(String value) {
defaultHeaders.put("User-Agent", value);
return this;
}
public TikTokHttpRequest setQueries(Map<String, Object> queries) {
if (queries == null)
return this;
var testMap = new TreeMap<String,Object>(queries);
query = String.join("&", testMap.entrySet().stream().map(x ->
{
var key = x.getKey();
var value = "";
try {
value = URLEncoder.encode(x.getValue().toString(), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return key + "=" + value;
}).toList());
return this;
}
private String getContent(HttpRequest request) throws Exception {
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 404) {
throw new TikTokLiveRequestException("Request responded with 404 NOT_FOUND");
}
if (response.statusCode() != 200) {
throw new TikTokLiveRequestException("Request was unsuccessful " + response.statusCode());
}
var cookies = response.headers().allValues("Set-Cookie");
for (var cookie : cookies) {
var split = cookie.split(";")[0].split("=");
var uri = request.uri();
var key = split[0];
var value = split[1];
tikTokCookieJar.set(key, value);
var map = new HashMap<String, List<String>>();
map.put(key, List.of(value));
cookieManager.put(uri, map);
}
return response.body();
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http.mappers;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import io.github.jwdeveloper.tiktok.data.requests.GiftsData;
import java.util.ArrayList;
public class GiftsDataMapper {
public GiftsData.Response map(String json) {
var parsedJson = JsonParser.parseString(json);
var jsonObject = parsedJson.getAsJsonObject();
if (!jsonObject.has("data")) {
return new GiftsData.Response(json, new ArrayList<>());
}
var dataElement = jsonObject.getAsJsonObject("data");
if (!dataElement.has("gifts")) {
return new GiftsData.Response(json, new ArrayList<>());
}
var gifts = dataElement.get("gifts").getAsJsonArray()
.asList()
.stream()
.map(this::mapSingleGift)
.toList();
return new GiftsData.Response(json, gifts);
}
private GiftsData.GiftModel mapSingleGift(JsonElement jsonElement) {
var id = jsonElement.getAsJsonObject().get("id").getAsInt();
var name = jsonElement.getAsJsonObject().get("name").getAsString();
var diamondCost = jsonElement.getAsJsonObject().get("diamond_count").getAsInt();
var image = jsonElement.getAsJsonObject()
.get("image").getAsJsonObject()
.get("url_list").getAsJsonArray().get(0).getAsString();
if (image.endsWith(".webp")) {
image = image.replace(".webp", ".jpg");
}
var gift = new GiftsData.GiftModel();
gift.setId(id);
gift.setName(name);
gift.setDiamondCost(diamondCost);
gift.setImage(image);
return gift;
}
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http.mappers;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.github.jwdeveloper.tiktok.data.models.Picture;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.data.models.users.UserAttribute;
import io.github.jwdeveloper.tiktok.data.requests.LiveData;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
import java.util.ArrayList;
public class LiveDataMapper {
/**
* 0 - Unknown
* 1 - ?
* 2 - Online
* 3 - ?
* 4 - Offline
*/
public LiveData.Response map(String json) {
var response = new LiveData.Response();
response.setJson(json);
var parsedJson = JsonParser.parseString(json);
var jsonObject = parsedJson.getAsJsonObject();
if (!jsonObject.has("data")) {
throw new TikTokLiveRequestException("Data section not found in LiveData.Response");
}
var data = jsonObject.getAsJsonObject("data");
if (data.has("status")) {
var status = data.get("status");
var statusId = status.getAsInt();
var statusValue = switch (statusId) {
case 2 -> LiveData.LiveStatus.HostOnline;
case 4 -> LiveData.LiveStatus.HostOffline;
default -> LiveData.LiveStatus.HostNotFound;
};
response.setLiveStatus(statusValue);
} else {
response.setLiveStatus(LiveData.LiveStatus.HostNotFound);
}
if (data.has("age_restricted")) {
var element = data.getAsJsonObject("age_restricted");
var restricted = element.get("restricted").getAsBoolean();
response.setAgeRestricted(restricted);
}
if (data.has("title")) {
var element = data.get("title");
var title = element.getAsString();
response.setTitle(title);
}
if (data.has("stats")) {
var statsElement = data.getAsJsonObject("stats");
var likeElement = statsElement.get("like_count");
var likes = likeElement.getAsInt();
var titalUsersElement = statsElement.get("total_user");
var totalUsers = titalUsersElement.getAsInt();
response.setLikes(likes);
response.setTotalViewers(totalUsers);
}
if (data.has("user_count")) {
var element = data.get("user_count");
var viewers = element.getAsInt();
response.setViewers(viewers);
}
if (data.has("owner")) {
var element = data.getAsJsonObject("owner");
var user = getUser(element);
response.setHost(user);
}
return response;
}
public User getUser(JsonObject jsonElement) {
var id = jsonElement.get("id").getAsLong();
var name = jsonElement.get("display_id").getAsString();
var profileName = jsonElement.get("nickname").getAsString();
var followElement = jsonElement.getAsJsonObject("follow_info");
var followers = followElement.get("follower_count").getAsInt();
var followingCount = followElement.get("following_count").getAsInt();
var pictureElement = jsonElement.getAsJsonObject("avatar_large");
var link = pictureElement.getAsJsonArray("url_list").get(1).getAsString();
var picture = new Picture(link);
var user = new User(id, name, profileName, picture, followers, followingCount, new ArrayList<>());
user.addAttribute(UserAttribute.LiveHost);
return user;
}
}

View File

@@ -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.http.mappers;
import com.google.gson.JsonParser;
import io.github.jwdeveloper.tiktok.data.requests.LiveUserData;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveRequestException;
public class LiveUserDataMapper
{
public LiveUserData.Response map(String json) {
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);
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.http.mappers;
import com.google.gson.JsonParser;
import io.github.jwdeveloper.tiktok.data.requests.SignServerResponse;
public class SignServerResponseMapper {
public SignServerResponse map(String json) {
var parsedJson = JsonParser.parseString(json);
var jsonObject = parsedJson.getAsJsonObject();
var signUrl = jsonObject.get("signedUrl").getAsString();
var userAgent = jsonObject.get("User-Agent").getAsString();
return new SignServerResponse(signUrl, userAgent);
}
}

View File

@@ -23,11 +23,11 @@
package io.github.jwdeveloper.tiktok.listener;
import io.github.jwdeveloper.tiktok.annotations.TikTokEventHandler;
import io.github.jwdeveloper.tiktok.TikTokLiveEventHandler;
import io.github.jwdeveloper.tiktok.annotations.TikTokEventObserver;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.exceptions.TikTokEventListenerMethodException;
import io.github.jwdeveloper.tiktok.exceptions.TikTokLiveException;
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
import io.github.jwdeveloper.tiktok.live.LiveClient;
import io.github.jwdeveloper.tiktok.live.builder.EventConsumer;
@@ -37,10 +37,10 @@ import java.util.HashMap;
import java.util.List;
public class TikTokListenersManager implements ListenersManager {
private final TikTokEventObserver eventObserver;
private final TikTokLiveEventHandler eventObserver;
private final List<ListenerBindingModel> bindingModels;
public TikTokListenersManager(List<TikTokEventListener> listeners, TikTokEventObserver tikTokEventHandler) {
public TikTokListenersManager(List<TikTokEventListener> listeners, TikTokLiveEventHandler tikTokEventHandler) {
this.eventObserver = tikTokEventHandler;
this.bindingModels = new ArrayList<>(listeners.size());
for (var listener : listeners) {
@@ -93,7 +93,7 @@ public class TikTokListenersManager implements ListenersManager {
var clazz = listener.getClass();
var methods = Arrays.stream(clazz.getDeclaredMethods()).filter(m ->
m.getParameterCount() == 2 &&
m.isAnnotationPresent(TikTokEventHandler.class)).toList();
m.isAnnotationPresent(TikTokEventObserver.class)).toList();
var eventsMap = new HashMap<Class<?>, List<EventConsumer<?>>>();
for (var method : methods) {
var eventClazz = method.getParameterTypes()[1];
@@ -111,12 +111,13 @@ public class TikTokListenersManager implements ListenersManager {
EventConsumer eventMethodRef = (liveClient, event) ->
{
try {
method.setAccessible(true);
method.invoke(listener, liveClient, event);
} catch (Exception e) {
throw new TikTokEventListenerMethodException(e);
}
};
eventsMap.computeIfAbsent(eventClazz, (a) -> new ArrayList<EventConsumer<?>>()).add(eventMethodRef);
eventsMap.computeIfAbsent(eventClazz, (a) -> new ArrayList<>()).add(eventMethodRef);
}
return new ListenerBindingModel(listener, eventsMap);
}

View File

@@ -1,68 +0,0 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers;
import com.google.gson.JsonObject;
import io.github.jwdeveloper.tiktok.live.LiveRoomMeta;
public class LiveRoomMetaMapper {
/**
* 0 - Unknown
* 1 - ?
* 2 - Online
* 3 - ?
* 4 - Offline
*/
public LiveRoomMeta map(JsonObject input) {
var liveRoomMeta = new LiveRoomMeta();
if (!input.has("data")) {
return liveRoomMeta;
}
var data = input.getAsJsonObject("data");
if (data.has("status")) {
var status = data.get("status");
var statusId = status.getAsInt();
var statusValue = switch (statusId) {
case 0 -> LiveRoomMeta.LiveRoomStatus.HostNotFound;
case 2 -> LiveRoomMeta.LiveRoomStatus.HostOnline;
case 4 -> LiveRoomMeta.LiveRoomStatus.HostOffline;
default-> LiveRoomMeta.LiveRoomStatus.HostNotFound;
};
liveRoomMeta.setStatus(statusValue);
}
else
{
liveRoomMeta.setStatus(LiveRoomMeta.LiveRoomStatus.HostNotFound);
}
if (data.has("age_restricted")) {
var element = data.getAsJsonObject("age_restricted");
var restricted = element.get("restricted").getAsBoolean();
liveRoomMeta.setAgeRestricted(restricted);
}
return liveRoomMeta;
}
}

View File

@@ -74,7 +74,7 @@ public class TikTokGenericEventMapper {
}
}
private Method getParsingMethod(Class<?> input) throws NoSuchMethodException {
public Method getParsingMethod(Class<?> input) throws NoSuchMethodException {
if (methodCache.containsKey(input)) {
return methodCache.get(input);
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers;
import com.google.protobuf.GeneratedMessageV3;
import io.github.jwdeveloper.tiktok.TikTokLive;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.mappers.data.MappingAction;
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class TikTokLiveMapper implements TikTokMapper {
private final Map<String, TikTokLiveMapperModel> mappers;
private final TikTokMapperHelper mapperUtils;
private final TikTokLiveMapperModel globalMapperModel;
public TikTokLiveMapper(TikTokMapperHelper mapperUtils) {
this.mappers = new HashMap<>();
this.mapperUtils = mapperUtils;
this.globalMapperModel = new TikTokLiveMapperModel("any message");
}
@Override
public TikTokMapperModel forMessage(String messageName) {
if (!isRegistered(messageName)) {
var model = new TikTokLiveMapperModel(messageName);
mappers.put(messageName, model);
}
return mappers.get(messageName);
}
@Override
public TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName) {
return forMessage(mapperName.getSimpleName());
}
@Override
public TikTokMapperModel forMessage(String mapperName, MappingAction<MappingResult> onMapping) {
var model = forMessage(mapperName);
model.onMapping(onMapping);
return model;
}
@Override
public TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, MappingAction<MappingResult> onMapping) {
var model = forMessage(mapperName);
model.onMapping(onMapping);
return model;
}
@Override
public TikTokMapperModel forMessage(Class<? extends GeneratedMessageV3> mapperName, Function<byte[], TikTokEvent> onMapping) {
return forMessage(mapperName, (inputBytes, messageName, mapperHelper) -> MappingResult.of(inputBytes, onMapping.apply(inputBytes)));
}
@Override
public TikTokMapperModel forAnyMessage() {
return globalMapperModel;
}
public boolean isRegistered(String mapperName) {
return mappers.containsKey(mapperName);
}
public <T extends GeneratedMessageV3> boolean isRegistered(Class<T> mapperName) {
return mappers.containsKey(mapperName.getSimpleName());
}
public List<TikTokEvent> handleMapping(String messageName, byte[] bytes) {
if (!isRegistered(messageName)) {
return List.of();
}
var mapperModel = mappers.get(messageName);
var inputBytes = mapperModel.getOnBeforeMapping().onMapping(bytes, messageName, mapperUtils);
var globalInputBytes = globalMapperModel.getOnBeforeMapping().onMapping(inputBytes, messageName, mapperUtils);
var mappingResult = mapperModel.getOnMapping().onMapping(globalInputBytes, messageName, mapperUtils);
if (mappingResult == null) {
mappingResult = globalMapperModel.getOnMapping().onMapping(globalInputBytes, messageName, mapperUtils);
}
var afterMappingResult = mapperModel.getOnAfterMapping().apply(mappingResult);
var globalAfterMappingResult = globalMapperModel.getOnAfterMapping().apply(MappingResult.of(mappingResult.getSource(), afterMappingResult));
return globalAfterMappingResult;
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers;
import com.google.protobuf.GeneratedMessageV3;
import io.github.jwdeveloper.tiktok.exceptions.TikTokMessageMappingException;
import io.github.jwdeveloper.tiktok.utils.JsonUtil;
import io.github.jwdeveloper.tiktok.utils.ProtoBufferObject;
import io.github.jwdeveloper.tiktok.utils.ProtocolUtils;
public class TikTokLiveMapperHelper implements TikTokMapperHelper {
private final TikTokGenericEventMapper genericMapper;
public TikTokLiveMapperHelper(TikTokGenericEventMapper genericMapper) {
this.genericMapper = genericMapper;
}
@Override
public <T extends GeneratedMessageV3> T bytesToWebcastObject(byte[] bytes, Class<T> messageClass) {
try {
var parsingMethod = genericMapper.getParsingMethod(messageClass);
var sourceObject = parsingMethod.invoke(null, bytes);
return (T) sourceObject;
} catch (Exception e) {
throw new TikTokMessageMappingException(messageClass, "can't find parsing method", e);
}
}
@Override
public Object bytesToWebcastObject(byte[] bytes, String messageName) {
try {
var packageName = "io.github.jwdeveloper.tiktok.messages.webcast." + messageName;
var clazz = Class.forName(packageName);
return bytesToWebcastObject(bytes, (Class<? extends GeneratedMessageV3>) clazz);
} catch (Exception e) {
throw new TikTokMessageMappingException(messageName, e);
}
}
@Override
public boolean isMessageHasProtoClass(String messageName) {
try {
var packageName = "io.github.jwdeveloper.tiktok.messages.webcast." + messageName;
Class.forName(packageName);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public ProtoBufferObject bytesToProtoBufferStructure(byte[] bytes) {
return ProtocolUtils.getProtocolBufferStructure(bytes);
}
@Override
public String toJson(Object obj) {
return JsonUtil.toJson(obj);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.mappers.data.MappingAction;
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.function.Function;
@Getter
@Setter
public class TikTokLiveMapperModel implements TikTokMapperModel {
@Getter
private String sourceMessageName;
private MappingAction<byte[]> onBeforeMapping;
private MappingAction<MappingResult> onMapping;
private Function<MappingResult, List<TikTokEvent>> onAfterMapping;
public TikTokLiveMapperModel(String sourceMessageName, MappingAction onMapping) {
this.sourceMessageName = sourceMessageName;
this.onBeforeMapping = (inputBytes, mesasgeName, mapperHelper) -> inputBytes;
this.onMapping = onMapping;
this.onAfterMapping = MappingResult::getEvents;
}
public TikTokLiveMapperModel(String sourceMessageName) {
this.sourceMessageName = sourceMessageName;
this.onBeforeMapping = (inputBytes, mesasgeName, mapperHelper) -> inputBytes;
this.onMapping = (inputBytes, mesasgeName, mapperHelper) -> MappingResult.of(inputBytes, List.of());
this.onAfterMapping = MappingResult::getEvents;
}
@Override
public TikTokMapperModel onBeforeMapping(MappingAction<byte[]> action) {
this.onBeforeMapping = action;
return this;
}
@Override
public TikTokMapperModel onMapping(MappingAction<MappingResult> action) {
this.onMapping = action;
return this;
}
@Override
public TikTokMapperModel onAfterMapping(Function<MappingResult, List<TikTokEvent>> action) {
this.onAfterMapping = action;
return this;
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers.handlers;
public class TikTokChestEventHandler {
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers.handlers;
import io.github.jwdeveloper.tiktok.data.events.*;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.envelop.TikTokChestEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEndEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollStartEvent;
import io.github.jwdeveloper.tiktok.data.events.poll.TikTokPollUpdateEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomPinEvent;
import io.github.jwdeveloper.tiktok.data.models.chest.Chest;
import io.github.jwdeveloper.tiktok.messages.enums.EnvelopeDisplay;
import io.github.jwdeveloper.tiktok.messages.webcast.*;
import lombok.SneakyThrows;
import java.util.Collections;
import java.util.List;
public class TikTokCommonEventHandler
{
@SneakyThrows
public TikTokEvent handleWebcastControlMessage(byte[] msg) {
var message = WebcastControlMessage.parseFrom(msg);
return switch (message.getAction()) {
case STREAM_PAUSED -> new TikTokLivePausedEvent();
case STREAM_ENDED -> new TikTokLiveEndedEvent();
case STREAM_UNPAUSED -> new TikTokLiveUnpausedEvent();
default -> new TikTokUnhandledControlEvent(message);
};
}
@SneakyThrows
public TikTokEvent handlePinMessage(byte[] msg) {
var pinMessage = WebcastRoomPinMessage.parseFrom(msg);
var chatMessage = WebcastChatMessage.parseFrom(pinMessage.getPinnedMessage());
var chatEvent = new TikTokCommentEvent(chatMessage);
return new TikTokRoomPinEvent(pinMessage, chatEvent);
}
//TODO Probably not working
@SneakyThrows
public TikTokEvent handlePollEvent(byte[] msg) {
var poolMessage = WebcastPollMessage.parseFrom(msg);
return switch (poolMessage.getMessageType()) {
case MESSAGETYPE_SUBSUCCESS -> new TikTokPollStartEvent(poolMessage);
case MESSAGETYPE_ANCHORREMINDER -> new TikTokPollEndEvent(poolMessage);
case MESSAGETYPE_ENTERROOMEXPIRESOON -> new TikTokPollUpdateEvent(poolMessage);
default -> new TikTokPollEvent(poolMessage);
};
}
@SneakyThrows
public List<TikTokEvent> handleEnvelop(byte[] data) {
var msg = WebcastEnvelopeMessage.parseFrom(data);
if (msg.getDisplay() != EnvelopeDisplay.EnvelopeDisplayNew) {
return Collections.emptyList();
}
var totalDiamonds = msg.getEnvelopeInfo().getDiamondCount();
var totalUsers = msg.getEnvelopeInfo().getPeopleCount();
var chest = new Chest(totalDiamonds, totalUsers);
return List.of(new TikTokChestEvent(chest, msg));
}
}

View File

@@ -20,8 +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.handlers.events;
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;
@@ -30,6 +31,8 @@ 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.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;
@@ -41,18 +44,34 @@ import java.util.Map;
public class TikTokGiftEventHandler {
private final GiftManager giftManager;
private final Map<Long, WebcastGiftMessage> giftsMessages;
private final TikTokRoomInfo tikTokRoomInfo;
public TikTokGiftEventHandler(GiftManager giftManager) {
public TikTokGiftEventHandler(GiftManager giftManager, TikTokRoomInfo tikTokRoomInfo) {
this.giftManager = giftManager;
giftsMessages = new HashMap<>();
this.tikTokRoomInfo = tikTokRoomInfo;
}
public List<TikTokEvent> handleGift(WebcastGiftMessage currentMessage)
{
@SneakyThrows
public MappingResult handleGifts(byte[] msg, String name, TikTokMapperHelper helper) {
var currentMessage = WebcastGiftMessage.parseFrom(msg);
var gifts = handleGift(currentMessage);
return MappingResult.of(currentMessage, gifts);
}
public List<TikTokEvent> handleGift(WebcastGiftMessage currentMessage) {
var userId = currentMessage.getUser().getId();
var currentType = GiftSendType.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 giftEvent = getGiftEvent(currentMessage);
return List.of(comboEvent, giftEvent);
}
if (!containsPreviousMessage) {
if (currentType == GiftSendType.Finished) {
return List.of(getGiftEvent(currentMessage));
@@ -81,32 +100,27 @@ public class TikTokGiftEventHandler {
return List.of();
}
@SneakyThrows
public List<TikTokEvent> handleGift(byte[] msg) {
var currentMessage = WebcastGiftMessage.parseFrom(msg);
return handleGift(currentMessage);
}
private TikTokGiftEvent getGiftEvent(WebcastGiftMessage message) {
var gift = getGiftObject(message);
return new TikTokGiftEvent(gift, message);
return new TikTokGiftEvent(gift, tikTokRoomInfo.getHost(), message);
}
private TikTokGiftEvent getGiftComboEvent(WebcastGiftMessage message, GiftSendType state) {
var gift = getGiftObject(message);
return new TikTokGiftComboEvent(gift, message, state);
return new TikTokGiftComboEvent(gift, tikTokRoomInfo.getHost(), message, state);
}
private Gift getGiftObject(WebcastGiftMessage giftMessage) {
var gift = giftManager.findById((int) giftMessage.getGiftId());
var giftId = (int) giftMessage.getGiftId();
var gift = giftManager.findById(giftId);
if (gift == Gift.UNDEFINED) {
gift = giftManager.findByName(giftMessage.getGift().getName());
}
if (gift == Gift.UNDEFINED) {
gift = giftManager.registerGift(
(int) giftMessage.getGift().getId(),
giftId,
giftMessage.getGift().getName(),
giftMessage.getGift().getDiamondCount(),
Picture.map(giftMessage.getGift().getImage()));

View File

@@ -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.mappers.handlers;
import io.github.jwdeveloper.tiktok.TikTokRoomInfo;
import io.github.jwdeveloper.tiktok.data.events.TikTokSubscribeEvent;
import io.github.jwdeveloper.tiktok.data.events.TikTokUnhandledMemberEvent;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.room.TikTokRoomInfoEvent;
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.RankingUser;
import io.github.jwdeveloper.tiktok.data.models.users.User;
import io.github.jwdeveloper.tiktok.mappers.TikTokMapperHelper;
import io.github.jwdeveloper.tiktok.mappers.data.MappingResult;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLikeMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastLiveIntroMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastMemberMessage;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastRoomUserSeqMessage;
import lombok.SneakyThrows;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class TikTokRoomInfoEventHandler {
private final TikTokRoomInfo roomInfo;
public TikTokRoomInfoEventHandler(TikTokRoomInfo roomInfo) {
this.roomInfo = roomInfo;
}
public TikTokEvent handleRoomInfo(Consumer<TikTokRoomInfo> consumer) {
consumer.accept(roomInfo);
return new TikTokRoomInfoEvent(roomInfo);
}
@SneakyThrows
public TikTokEvent handleUserRanking(byte[] msg) {
var message = WebcastRoomUserSeqMessage.parseFrom(msg);
var totalUsers = message.getTotalUser();
var userRanking = message.getRanksListList().stream().map(RankingUser::new)
.sorted((ru1, ru2) -> Integer.compare(ru2.getScore(), ru1.getScore()))
.collect(Collectors.toList());
return handleRoomInfo(tikTokRoomInfo ->
{
tikTokRoomInfo.setTotalViewersCount(totalUsers);
tikTokRoomInfo.updateRanking(userRanking);
});
}
@SneakyThrows
public TikTokEvent handleIntro(byte[] msg) {
var message = WebcastLiveIntroMessage.parseFrom(msg);
var hostUser = User.map(message.getHost());
var language = message.getLanguage();
return handleRoomInfo(tikTokRoomInfo ->
{
if (tikTokRoomInfo.getHost() == null) {
tikTokRoomInfo.setHost(hostUser);
}
tikTokRoomInfo.setLanguage(language);
});
}
@SneakyThrows
public MappingResult handleMemberMessage(byte[] msg, String name, TikTokMapperHelper helper) {
var message = WebcastMemberMessage.parseFrom(msg);
var event = switch (message.getAction()) {
case JOINED -> new TikTokJoinEvent(message);
case SUBSCRIBED -> new TikTokSubscribeEvent(message);
default -> new TikTokUnhandledMemberEvent(message);
};
var roomInfoEvent = this.handleRoomInfo(tikTokRoomInfo ->
{
tikTokRoomInfo.setViewersCount(message.getMemberCount());
});
return MappingResult.of(message, List.of(event, roomInfoEvent));
}
@SneakyThrows
public MappingResult handleLike(byte[] msg, String name, TikTokMapperHelper helper) {
var message = WebcastLikeMessage.parseFrom(msg);
var event = new TikTokLikeEvent(message);
var roomInfoEvent = this.handleRoomInfo(tikTokRoomInfo ->
{
tikTokRoomInfo.setLikesCount(event.getTotalLikes());
});
return MappingResult.of(message, List.of(event, roomInfoEvent));
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 2023-2023 jwdeveloper jacekwoln@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.jwdeveloper.tiktok.mappers.handlers;
import io.github.jwdeveloper.tiktok.TikTokRoomInfo;
import io.github.jwdeveloper.tiktok.data.events.TikTokUnhandledSocialEvent;
import io.github.jwdeveloper.tiktok.data.events.common.TikTokEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokFollowEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokJoinEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokLikeEvent;
import io.github.jwdeveloper.tiktok.data.events.social.TikTokShareEvent;
import io.github.jwdeveloper.tiktok.data.models.Text;
import io.github.jwdeveloper.tiktok.messages.webcast.WebcastSocialMessage;
import io.github.jwdeveloper.tiktok.models.SocialTypes;
import lombok.SneakyThrows;
import java.util.regex.Pattern;
public class TikTokSocialMediaEventHandler
{
private final TikTokRoomInfo roomInfo;
private final Pattern socialMediaPattern = Pattern.compile("pm_mt_guidance_viewer_([0-9]+)_share");
public TikTokSocialMediaEventHandler(TikTokRoomInfo roomInfo) {
this.roomInfo = roomInfo;
}
@SneakyThrows
public TikTokEvent handle(byte[] msg)
{
var message = WebcastSocialMessage.parseFrom(msg);
var socialType = Text.map(message.getCommon().getDisplayText()).getKey();
var matcher = socialMediaPattern.matcher(socialType);
if (matcher.find()) {
var value = matcher.group(1);
var number = Integer.parseInt(value);
return new TikTokShareEvent(message, number);
}
return switch (socialType) {
case SocialTypes.LikeType -> new TikTokLikeEvent(message, roomInfo.getLikesCount());
case SocialTypes.FollowType -> new TikTokFollowEvent(message);
case SocialTypes.ShareType -> new TikTokShareEvent(message);
case SocialTypes.JoinType -> new TikTokJoinEvent(message, roomInfo.getViewersCount());
default -> new TikTokUnhandledSocialEvent(message);
};
}
}

View File

@@ -22,67 +22,66 @@
*/
package io.github.jwdeveloper.tiktok.websocket;
import io.github.jwdeveloper.tiktok.ClientSettings;
import io.github.jwdeveloper.tiktok.Constants;
import io.github.jwdeveloper.tiktok.TikTokLiveClient;
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.TikTokLiveException;
import io.github.jwdeveloper.tiktok.handlers.TikTokEventObserver;
import io.github.jwdeveloper.tiktok.handlers.TikTokMessageHandlerRegistration;
import io.github.jwdeveloper.tiktok.http.HttpUtils;
import io.github.jwdeveloper.tiktok.http.TikTokCookieJar;
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 Logger logger;
private final ClientSettings clientSettings;
private final TikTokCookieJar tikTokCookieJar;
private final TikTokMessageHandlerRegistration webResponseHandler;
private final TikTokEventObserver tikTokEventHandler;
private final LiveClientSettings clientSettings;
private final TikTokLiveMessageHandler messageHandler;
private final TikTokLiveEventHandler tikTokEventHandler;
private WebSocketClient webSocketClient;
private TikTokWebSocketPingingTask pingingTask;
private boolean isConnected;
public TikTokWebSocketClient(Logger logger,
TikTokCookieJar tikTokCookieJar,
ClientSettings clientSettings,
TikTokMessageHandlerRegistration webResponseHandler,
TikTokEventObserver tikTokEventHandler) {
this.logger = logger;
this.tikTokCookieJar = tikTokCookieJar;
public TikTokWebSocketClient(
LiveClientSettings clientSettings,
TikTokLiveMessageHandler messageHandler,
TikTokLiveEventHandler tikTokEventHandler) {
this.clientSettings = clientSettings;
this.webResponseHandler = webResponseHandler;
this.messageHandler = messageHandler;
this.tikTokEventHandler = tikTokEventHandler;
isConnected = false;
pingingTask = new TikTokWebSocketPingingTask();
}
public void start(WebcastResponse webcastResponse, LiveClient tikTokLiveClient) {
@Override
public void start(LiveConnectionData.Response connectionData, LiveClient liveClient) {
if (isConnected) {
stop();
}
if (webcastResponse.getPushServer().isEmpty() || webcastResponse.getRouteParamsMapMap().isEmpty())
{
throw new TikTokLiveException("Could not find Room");
messageHandler.handle(liveClient, connectionData.getWebcastResponse());
var headers = new HashMap<String, String>();
headers.put("Cookie", connectionData.getWebsocketCookies());
webSocketClient = new TikTokWebSocketListener(connectionData.getWebsocketUrl(),
headers,
clientSettings.getHttpSettings().getTimeout().toMillisPart(),
messageHandler,
tikTokEventHandler,
liveClient);
// ProxyClientSettings proxyClientSettings = clientSettings.getHttpSettings().getProxyClientSettings();
// if (proxyClientSettings.isEnabled())
// connectProxy(proxyClientSettings);
// else
connectDefault();
}
private void connectDefault() {
try {
if (clientSettings.isHandleExistingEvents()) {
logger.info("Handling existing events");
webResponseHandler.handle(tikTokLiveClient, webcastResponse);
}
var url = getWebSocketUrl(webcastResponse);
webSocketClient = startWebSocket(url, tikTokLiveClient);
webSocketClient.connect();
pingingTask = new TikTokWebSocketPingingTask();
pingingTask.run(webSocketClient);
isConnected = true;
} catch (Exception e) {
@@ -91,36 +90,52 @@ public class TikTokWebSocketClient implements SocketClient {
}
}
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) {
while (proxySettings.hasNext()) {
ProxyData proxyData = proxySettings.next();
if (!tryProxyConnection(proxySettings, proxyData)) {
if (proxySettings.isAutoDiscard())
proxySettings.remove();
continue;
}
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,
webResponseHandler,
tikTokEventHandler,
liveClient);
public boolean tryProxyConnection(ProxyClientSettings proxySettings, ProxyData proxyData) {
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 stop()
{
if (isConnected && webSocketClient != null) {
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, null);
webSocketClient.setSocketFactory(sc.getSocketFactory());
}
webSocketClient.setProxy(new Proxy(proxySettings.getType(), proxyData.toSocketAddress()));
webSocketClient.connect();
return true;
} catch (Exception e) {
return false;
}
}
public void stop() {
if (isConnected && webSocketClient != null && webSocketClient.isOpen()) {
webSocketClient.closeConnection(0, "");
pingingTask.stop();
}
webSocketClient = null;
pingingTask = null;
isConnected = false;
}
}

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