Skip to content

Commit

Permalink
Merge pull request #3 from frankvHoof93/development
Browse files Browse the repository at this point in the history
0.9.1 - See Changelog for Updates
  • Loading branch information
frankvHoof93 authored Mar 31, 2023
2 parents 5113704 + 1f473fe commit 158470c
Show file tree
Hide file tree
Showing 285 changed files with 3,633 additions and 4,170 deletions.
22 changes: 22 additions & 0 deletions CHANGELOG.MD
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.9.1] - 2023-03-31

### Added

- Added newly found Message-Data (recently added by ByteDance)

### Fixed

- Added overly cautious Null-Checking in Model. Instead of Nullref, data will now simply default to NULL if not available
- Fixed invalid DataType in WebcastRoomPinMessage (Pos 35)

### Changed

- Updated Model based on Protobuf
- Buffer-array for messages is now re-used to minimize garbage
- Connecting-Boolean is now set to False once fully connected

### Removed

- Removed Dispatching for Debug-Logs in Unity, as it is not required and only adds overhead.


## [0.9.0] - 2023-03-11

### Added
Expand Down
2 changes: 1 addition & 1 deletion TikTokLiveSharp/Client/HTTP/TikTokHTTPClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using System.Threading.Tasks;
using TikTokLiveSharp.Client.Proxy;
using TikTokLiveSharp.Errors.Permissions;
using TikTokLiveSharp.Models.Protobuf;
using TikTokLiveSharp.Models.Protobuf.Messages.Generic;

namespace TikTokLiveSharp.Client.HTTP
{
Expand Down
3 changes: 1 addition & 2 deletions TikTokLiveSharp/Client/HTTP/TikTokHttpRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ public TikTokHttpRequest(string url)
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
Proxy = WebProxy,
UseProxy = WebProxy != null,
UseCookies = false,
CookieContainer = new CookieContainer()
UseCookies = false
};
if (client == null)
{
Expand Down
11 changes: 8 additions & 3 deletions TikTokLiveSharp/Client/Socket/TikTokWebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ public sealed class TikTokWebSocket : ITikTokWebSocket
/// Token used to Cancel this Connection
/// </summary>
private CancellationToken token;
/// <summary>
/// Buffer used to store incoming Messages
/// </summary>
private byte[] buffer;

/// <summary>
/// Creates a TikTok WebSocket instance
Expand All @@ -37,13 +41,14 @@ public TikTokWebSocket(TikTokCookieJar cookieContainer, CancellationToken? token
{
this.token = token ?? CancellationToken.None;
bufferSize = buffSize;
buffer = new byte[bufferSize];
clientWebSocket = new ClientWebSocket();
clientWebSocket.Options.AddSubProtocol("echo-protocol");
clientWebSocket.Options.KeepAliveInterval = TimeSpan.FromSeconds(15);
StringBuilder cookieHeader = new StringBuilder();
foreach (string cookie in cookieContainer)
cookieHeader.Append(cookie);
clientWebSocket.Options.SetRequestHeader("Cookie", cookieHeader.ToString());
clientWebSocket.Options.SetRequestHeader("Cookie", cookieHeader.ToString());
}

/// <summary>
Expand Down Expand Up @@ -92,7 +97,7 @@ public async Task WriteMessage(ArraySegment<byte> arr)
public async Task<TikTokWebSocketResponse> ReceiveMessage()
{
token.ThrowIfCancellationRequested();
var arr = new ArraySegment<byte>(new byte[bufferSize]);
var arr = new ArraySegment<byte>(buffer);
WebSocketReceiveResult response = await clientWebSocket.ReceiveAsync(arr, token);
if (response.MessageType == WebSocketMessageType.Binary)
return new TikTokWebSocketResponse(arr.Array, response.Count);
Expand All @@ -102,6 +107,6 @@ public async Task<TikTokWebSocketResponse> ReceiveMessage()
/// <summary>
/// Is the websocket currently connected?
/// </summary>
public bool IsConnected => clientWebSocket.State == WebSocketState.Open;
public bool IsConnected => clientWebSocket != null && clientWebSocket.State == WebSocketState.Open;
}
}
8 changes: 5 additions & 3 deletions TikTokLiveSharp/Client/TikTokBaseClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
using TikTokLiveSharp.Errors.Connections;
using TikTokLiveSharp.Errors.FetchErrors;
using TikTokLiveSharp.Errors.Messaging;
using TikTokLiveSharp.Models;
using TikTokLiveSharp.Models.Protobuf;
using TikTokLiveSharp.Models.HTTP;
using TikTokLiveSharp.Models.Protobuf.Messages;
using TikTokLiveSharp.Models.Protobuf.Messages.Generic;

namespace TikTokLiveSharp.Client
{
Expand Down Expand Up @@ -351,6 +352,7 @@ protected virtual async Task<string> Connect(Action<Exception> onConnectExceptio
Debug.Log("Creating WebSocketClient");
await CreateWebSocket(response);
token.ThrowIfCancellationRequested();
Connecting = false;
return RoomID;
}

Expand Down Expand Up @@ -437,7 +439,7 @@ protected virtual async Task Disconnect()
Connecting = false;
if (Connected)
{
if (ShouldLog(LogLevel.Verbose))
if (ShouldLog(LogLevel.Information))
Debug.Log("Disconnecting SocketClient");
await socketClient.Disconnect();
}
Expand Down
56 changes: 35 additions & 21 deletions TikTokLiveSharp/Client/TikTokLiveClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@
using TikTokLiveSharp.Events;
using TikTokLiveSharp.Events.MessageData.Messages;
using TikTokLiveSharp.Models.Protobuf;
using TikTokGift = TikTokLiveSharp.Events.MessageData.Objects.TikTokGift;
using RoomMessage = TikTokLiveSharp.Events.MessageData.Messages.RoomMessage;
using TikTokLiveSharp.Models.Protobuf.Messages;
using TikTokLiveSharp.Models.Protobuf.Messages.Generic;
using static TikTokLiveSharp.Models.Protobuf.Messages.WebcastControlMessage;
using static TikTokLiveSharp.Models.Protobuf.Messages.WebcastMemberMessage;
using BarrageMessage = TikTokLiveSharp.Events.MessageData.Messages.BarrageMessage;
using LinkMicMethod = TikTokLiveSharp.Events.MessageData.Messages.LinkMicMethod;
using RoomMessage = TikTokLiveSharp.Events.MessageData.Messages.RoomMessage;
using TikTokGift = TikTokLiveSharp.Events.MessageData.Objects.TikTokGift;

namespace TikTokLiveSharp.Client
{
Expand Down Expand Up @@ -181,7 +186,7 @@ private struct SocialTypes
/// Event fired when an unhandled event is received from the webcast.
/// It's up to you how you can interpret this message.
/// </summary>
public event TikTokEventHandler<Message> UnhandledEvent;
public event TikTokEventHandler<Models.Protobuf.Messages.Generic.Message> UnhandledEvent;
#endregion

#region Constructors
Expand Down Expand Up @@ -268,7 +273,7 @@ protected override async Task<string> Connect(Action<Exception> onConnectExcepti
/// Closes & Stops Connection
/// </summary>
/// <returns>Task to await</returns>
protected override async Task Disconnect()
protected override async System.Threading.Tasks.Task Disconnect()
{
await base.Disconnect();
if (ShouldLog(LogLevel.Information))
Expand Down Expand Up @@ -332,12 +337,12 @@ private void HandleMessage(Message message)
CheckForUnparsedData(controlMessage);
switch (controlMessage.Action)
{
case ControlAction.StreamPaused:
case ControlAction.Stream_Paused:
if (ShouldLog(LogLevel.Verbose))
Debug.Log("Handling Stream Paused!");
RunEvent(OnLivePaused);
return;
case ControlAction.StreamEnded:
case ControlAction.Stream_Ended:
if (ShouldLog(LogLevel.Verbose))
Debug.Log("Handling Stream Ended!");
RunEvent(OnLiveEnded);
Expand Down Expand Up @@ -389,8 +394,8 @@ private void HandleMessage(Message message)
RunEvent(OnViewerData, new RoomViewerData(userSeqMessage));
}
return;
case nameof(Models.Protobuf.RoomMessage):
Models.Protobuf.RoomMessage roomMessage = Serializer.Deserialize<Models.Protobuf.RoomMessage>(stream);
case nameof(Models.Protobuf.Messages.RoomMessage):
Models.Protobuf.Messages.RoomMessage roomMessage = Serializer.Deserialize<Models.Protobuf.Messages.RoomMessage>(stream);
if (roomMessage != null)
{
if (settings.CheckForUnparsedData)
Expand Down Expand Up @@ -538,8 +543,8 @@ private void HandleMessage(Message message)
RunEvent(OnLinkMicArmies, new LinkMicArmies(linkMicArmiesMessage));
}
return;
case nameof(Models.Protobuf.LinkMicMethod):
Models.Protobuf.LinkMicMethod linkMicMethodMessage = Serializer.Deserialize<Models.Protobuf.LinkMicMethod>(stream);
case nameof(Models.Protobuf.Messages.LinkMicMethod):
Models.Protobuf.Messages.LinkMicMethod linkMicMethodMessage = Serializer.Deserialize<Models.Protobuf.Messages.LinkMicMethod>(stream);
if (linkMicMethodMessage != null)
{
if (settings.CheckForUnparsedData)
Expand All @@ -549,8 +554,8 @@ private void HandleMessage(Message message)
RunEvent(OnLinkMicMethod, new LinkMicMethod(linkMicMethodMessage));
}
return;
case nameof(Models.Protobuf.WebcastLinkMicMethod):
Models.Protobuf.WebcastLinkMicMethod webcastLinkMicMethodMessage = Serializer.Deserialize<Models.Protobuf.WebcastLinkMicMethod>(stream);
case nameof(Models.Protobuf.Messages.WebcastLinkMicMethod):
Models.Protobuf.Messages.WebcastLinkMicMethod webcastLinkMicMethodMessage = Serializer.Deserialize<Models.Protobuf.Messages.WebcastLinkMicMethod>(stream);
if (webcastLinkMicMethodMessage != null)
{
if (settings.CheckForUnparsedData)
Expand Down Expand Up @@ -731,8 +736,8 @@ private void HandleMessage(Message message)
RunEvent(OnEnvelope, new Envelope(envelopeMessage));
}
return;
case nameof(WebcastSubNotifyMessage):
WebcastSubNotifyMessage subNotifyMessage = Serializer.Deserialize<WebcastSubNotifyMessage>(stream);
case nameof(WebcastSubnotifyMessage):
WebcastSubnotifyMessage subNotifyMessage = Serializer.Deserialize<WebcastSubnotifyMessage>(stream);
if (subNotifyMessage != null)
{
if (settings.CheckForUnparsedData)
Expand Down Expand Up @@ -775,7 +780,7 @@ private void HandleGiftMessage(WebcastGiftMessage message)
GiftId giftId = new GiftId
{
Gift = message.GiftId,
UserName = message.User.UniqueId
UserName = message.Sender.UniqueId
};
if (activeGifts.ContainsKey(giftId))
{
Expand Down Expand Up @@ -812,7 +817,7 @@ private void HandleGiftMessage(WebcastGiftMessage message)
/// <param name="messageEvent">Message to Handle</param>
private void HandleSocialMessage(WebcastSocialMessage messageEvent)
{
Match match = Regex.Match(messageEvent.Header.Details.DataType, "pm_mt_guidance_viewer_([0-9]+)_share");
Match match = Regex.Match(messageEvent.Header.SocialData.Type, "pm_mt_guidance_viewer_([0-9]+)_share");
if (match.Success)
{
if (ShouldLog(LogLevel.Verbose))
Expand All @@ -821,7 +826,7 @@ private void HandleSocialMessage(WebcastSocialMessage messageEvent)
RunEvent(OnShare, new Share(messageEvent, result));
return;
}
switch (messageEvent.Header.Details.DataType)
switch (messageEvent.Header.SocialData.Type)
{
case SocialTypes.LikeType:
if (ShouldLog(LogLevel.Verbose))
Expand Down Expand Up @@ -857,14 +862,14 @@ private void HandleSocialMessage(WebcastSocialMessage messageEvent)
/// <param name="msg">Message to Handle</param>
private void HandleMemberMessage(WebcastMemberMessage msg)
{
switch (msg.ActionId)
switch (msg.Action)
{
case MemberMessageActionType.Joined:
case (int)MemberMessageAction.Joined:
if (ShouldLog(LogLevel.Verbose))
Debug.Log("Handling Join");
RunEvent(OnJoin, new Join(msg));
return;
case MemberMessageActionType.Subscribed:
case (int)MemberMessageAction.Subscribed:
if (ShouldLog(LogLevel.Verbose))
Debug.Log("Handling Subscribe");
RunEvent(OnSubscribe, new Subscribe(msg));
Expand All @@ -873,7 +878,7 @@ private void HandleMemberMessage(WebcastMemberMessage msg)
// case 27: // ?? (Done by host? (User null, User2 == host))
// case 50: // Share?
default:
case MemberMessageActionType.Unknown:
case (int)MemberMessageAction.Unknown:
if (ShouldLog(LogLevel.Warning))
Debug.LogWarning("Handling UnhandledMemberMessage!");
RunEvent(UnhandledMemberEvent, msg);
Expand Down Expand Up @@ -944,6 +949,15 @@ private T Deserialize<T>(MemoryStream stream) where T : IExtensible
T msg = Serializer.Deserialize<T>(stream);
return msg;
}
catch (OverflowException e)
{
WebcastMessageException exc = new WebcastMessageException("Error Deserializing Message", e);
if (ShouldLog(LogLevel.Error))
Debug.LogException(exc);
CallOnException(exc); // Inform user of Error
// This is a recoverable error. Client remains connected. Do not Throw
return default; // Return null to quietly quit out of this message
}
catch (Exception ex)
{
WebcastMessageException exc = new WebcastMessageException("Error Deserializing Message", ex);
Expand Down
22 changes: 13 additions & 9 deletions TikTokLiveSharp/Events/Messages/BarrageMessage.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using TikTokLiveSharp.Models.Protobuf;
using TikTokLiveSharp.Models.Protobuf.Messages;

namespace TikTokLiveSharp.Events.MessageData.Messages
{
Expand All @@ -14,14 +13,19 @@ public sealed class BarrageMessage : AMessageData

public readonly Objects.BarrageData BarrageData;

internal BarrageMessage(WebcastBarrageMessage msg) :
base(msg.Header.RoomId, msg.Header.MessageId, msg.Header.ServerTime)
internal BarrageMessage(WebcastBarrageMessage msg) :
base(msg?.Header?.RoomId ?? 0, msg?.Header?.MessageId ?? 0, msg?.Header?.ServerTime ?? 0)
{
Picture = new Objects.Picture(msg.Picture);
Picture2 = new Objects.Picture(msg.Picture2);
Picture3 = new Objects.Picture(msg.Picture3);
User = new Objects.User(msg.UserData.User);
BarrageData = new Objects.BarrageData(msg.Data2.EventType, msg.Data2.Label, msg.Data2.Data1.Select(d => (new Objects.User(d.User.User), d.Data2)).ToList());
Picture = new Objects.Picture(msg?.Picture);
Picture2 = new Objects.Picture(msg?.Picture2);
Picture3 = new Objects.Picture(msg?.Picture3);
User = new Objects.User(msg?.UserData?.User);
BarrageData = new Objects.BarrageData(msg?.Message?.EventType, msg?.Message?.Label, msg?.Message?.Data1?.Select(d =>
{
if (d?.User?.User != null)
return (new Objects.User(d?.User?.User), d?.Data2);
return (null, d?.Data2);
})?.ToList());
}
}
}
10 changes: 5 additions & 5 deletions TikTokLiveSharp/Events/Messages/Caption.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using TikTokLiveSharp.Models.Protobuf;
using TikTokLiveSharp.Models.Protobuf.Messages;

namespace TikTokLiveSharp.Events.MessageData.Messages
{
Expand All @@ -11,11 +11,11 @@ public sealed class Caption : AMessageData
public readonly string Text;

internal Caption(WebcastCaptionMessage msg)
: base(msg.Header.RoomId, msg.Header.MessageId, msg.Header.ServerTime)
: base(msg?.Header?.RoomId ?? 0, msg?.Header?.MessageId ?? 0, msg?.Header?.ServerTime ?? 0)
{
CaptionTimeStamp = msg.Timestamp;
ISOLanguage = msg.CaptionData.ISOLanguage;
Text = msg.CaptionData.Text;
CaptionTimeStamp = msg?.Timestamp ?? 0;
ISOLanguage = msg?.CaptionData?.ISOLanguage;
Text = msg?.CaptionData?.Text;
}
}
}
28 changes: 15 additions & 13 deletions TikTokLiveSharp/Events/Messages/Comment.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using TikTokLiveSharp.Models.Protobuf;
using TikTokLiveSharp.Models.Protobuf.Messages;

namespace TikTokLiveSharp.Events.MessageData.Messages
{
Expand All @@ -16,23 +16,25 @@ public sealed class Comment : AMessageData

public readonly IReadOnlyList<Objects.Picture> Pictures;

internal Comment(PinMessageData1 data)
: base(data.Details.RoomId, data.Details.Data, data.Details.TimeStamp1)
internal Comment(RoomPinMessageData data)
: base(data?.Details?.RoomId ?? 0, data?.Details?.MessageId ?? 0, data?.Details?.ServerTime ?? 0)
{
User = new Objects.User(data.User);
Text = data.Message;
Language = data.Language;
if (data?.Sender != null)
User = new Objects.User(data.Sender);
Text = data?.Comment;
Language = data?.Language;
}

internal Comment(WebcastChatMessage msg) :
base(msg.Header.RoomId, msg.Header.MessageId, msg.Header.ServerTime)
base(msg?.Header?.RoomId ?? 0, msg?.Header?.MessageId ?? 0, msg?.Header?.ServerTime ?? 0)
{
User = new Objects.User(msg.User);
Text = msg.Comment;
Language = msg.Language;
if (msg.MentionedUsers != null && msg.MentionedUsers.Count > 0)
MentionedUsers = new List<Objects.User>(msg.MentionedUsers.Select(u => new Objects.User(u)));
if (msg.Images != null && msg.Images.Count > 0)
if (msg?.Sender != null)
User = new Objects.User(msg?.Sender);
Text = msg?.Comment;
Language = msg?.Language;
if (msg?.MentionedUsers != null && msg.MentionedUsers.Count > 0)
MentionedUsers = new List<Objects.User>(msg.MentionedUsers.Select(u => u == null ? null : new Objects.User(u)));
if (msg?.Images != null && msg.Images.Count > 0)
Pictures = new List<Objects.Picture>(msg.Images.Select(p => new Objects.Picture(p.Picture)));
}
}
Expand Down
Loading

0 comments on commit 158470c

Please sign in to comment.