оптимизации

This commit is contained in:
PC1\PTyTb
2025-08-17 00:39:58 +03:00
parent 8357a587df
commit d7bf17daa2
7 changed files with 260 additions and 229 deletions
+4 -2
View File
@@ -189,8 +189,9 @@ var
ssl: TIdSSLIOHandlerSocketOpenSSL; ssl: TIdSSLIOHandlerSocketOpenSSL;
begin begin
Result := ''; Result := '';
http := TIdHTTP.Create(nil);
try try
http := TIdHTTP.Create(nil);
ssl := TIdSSLIOHandlerSocketOpenSSL.Create(nil); ssl := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try try
http.IOHandler := ssl; http.IOHandler := ssl;
@@ -200,6 +201,7 @@ begin
Result := http.Get('https://api.betterttv.net/3/cached/' + aMethod); Result := http.Get('https://api.betterttv.net/3/cached/' + aMethod);
finally finally
ssl.Free; ssl.Free;
http.Free;
end; end;
except except
on E: Exception do on E: Exception do
@@ -208,7 +210,7 @@ begin
Result := ''; Result := '';
end; end;
end; end;
http.Free;
end; end;
procedure TBTTV.toLog(alevel: integer; amethod, amessage: string); procedure TBTTV.toLog(alevel: integer; amethod, amessage: string);
+24 -11
View File
@@ -50,9 +50,7 @@ begin
FClient := THTTPClient.Create; FClient := THTTPClient.Create;
FBaseURL := 'https://api-key.fusionbrain.ai/'; FBaseURL := 'https://api-key.fusionbrain.ai/';
FApiKey :=aKey; FApiKey :=aKey;
// FApiKey := '28C9C30489D635732FB04AA6B85F0671';
FSecretKey := aSecret; FSecretKey := aSecret;
// FSecretKey := '805CB624C052202A05E3F40C0582045A';
end; end;
destructor TFusionBrainAPI.Destroy; destructor TFusionBrainAPI.Destroy;
@@ -62,8 +60,10 @@ begin
end; end;
procedure TFusionBrainAPI.StartGeneration(const APrompt: string); procedure TFusionBrainAPI.StartGeneration(const APrompt: string);
var
Task: ITask;
begin begin
TTask.Run(procedure Task :=TTask.Run(procedure
var var
PipelineID, UUID, FileName: string; PipelineID, UUID, FileName: string;
Links: TArray<string>; Links: TArray<string>;
@@ -94,6 +94,7 @@ begin
SetLength(Result, 2); SetLength(Result, 2);
Result[0] := TNetHeader.Create('X-Key', 'Key ' + FApiKey); Result[0] := TNetHeader.Create('X-Key', 'Key ' + FApiKey);
Result[1] := TNetHeader.Create('X-Secret', 'Secret ' + FSecretKey); Result[1] := TNetHeader.Create('X-Secret', 'Secret ' + FSecretKey);
end; end;
function TFusionBrainAPI.GetPipeline: string; function TFusionBrainAPI.GetPipeline: string;
@@ -117,11 +118,11 @@ var
Response: IHTTPResponse; Response: IHTTPResponse;
Json: TJSONObject; Json: TJSONObject;
begin begin
// Óïðîùåííîå ñîçäàíèå JSON
Params := TJSONObject.Create;
Root := TJSONObject.Create; Root := TJSONObject.Create;
try try
Params := TJSONObject.Create;
Params.AddPair('query', Prompt); Params.AddPair('query', Prompt);
Root.AddPair('type', 'GENERATE'); Root.AddPair('type', 'GENERATE');
Root.AddPair('numImages', TJSONNumber.Create(1)); Root.AddPair('numImages', TJSONNumber.Create(1));
Root.AddPair('width', TJSONNumber.Create(512)); Root.AddPair('width', TJSONNumber.Create(512));
@@ -145,22 +146,31 @@ begin
end; end;
finally finally
Root.Free; Root.Free;
// Params îñâîáîæäàåòñÿ àâòîìàòè÷åñêè ÷åðåç Root
end; end;
end; end;
function TFusionBrainAPI.CheckGeneration(const RequestId: string): TArray<string>; function TFusionBrainAPI.CheckGeneration(const RequestId: string): TArray<string>;
const
MaxAttempts = 60;
var var
Response: IHTTPResponse; Response: IHTTPResponse;
Json, ResultObj: TJSONObject; Json, ResultObj: TJSONObject;
Files: TJSONArray; Files: TJSONArray;
i: Integer; i, Attempt: Integer;
Status: string;
begin begin
repeat Attempt := 0;
while Attempt < MaxAttempts do
begin
Sleep(5000); Sleep(5000);
Inc(Attempt);
Response := FClient.Get(FBaseURL + 'key/api/v1/pipeline/status/' + RequestId, nil, GetAuthHeaders); Response := FClient.Get(FBaseURL + 'key/api/v1/pipeline/status/' + RequestId, nil, GetAuthHeaders);
Json := TJSONObject.ParseJSONValue(Response.ContentAsString) as TJSONObject; Json := TJSONObject.ParseJSONValue(Response.ContentAsString) as TJSONObject;
try try
if Json.GetValue<string>('status') = 'DONE' then Status := Json.GetValue<string>('status');
if Status = 'DONE' then
begin begin
ResultObj := Json.GetValue<TJSONObject>('result'); ResultObj := Json.GetValue<TJSONObject>('result');
Files := ResultObj.GetValue<TJSONArray>('files'); Files := ResultObj.GetValue<TJSONArray>('files');
@@ -168,11 +178,14 @@ begin
for i := 0 to Files.Count - 1 do for i := 0 to Files.Count - 1 do
Result[i] := Files.Items[i].Value; Result[i] := Files.Items[i].Value;
Exit; Exit;
end; end
else if Status = 'FAILED' then
raise Exception.Create('Generation failed');
finally finally
Json.Free; Json.Free;
end; end;
until False; end;
raise Exception.Create('Timeout waiting for generation');
end; end;
procedure TFusionBrainAPI.SaveBase64Image(const Base64Str, FileName: string); procedure TFusionBrainAPI.SaveBase64Image(const Base64Str, FileName: string);
@@ -181,7 +194,7 @@ var
InputStr: TStringStream; InputStr: TStringStream;
begin begin
DecodedStream := TMemoryStream.Create; DecodedStream := TMemoryStream.Create;
InputStr := TStringStream.Create(Base64Str); InputStr := TStringStream.Create(Base64Str, TEncoding.ASCII);
try try
TNetEncoding.Base64.Decode(InputStr, DecodedStream); TNetEncoding.Base64.Decode(InputStr, DecodedStream);
DecodedStream.SaveToFile(FileName); DecodedStream.SaveToFile(FileName);
+210 -198
View File
@@ -15,10 +15,11 @@ type
TGetGiftEvent = procedure(s: TGiftEvent) of object; TGetGiftEvent = procedure(s: TGiftEvent) of object;
TGetSubEvent = procedure(s: TSubEvent) of object; TGetSubEvent = procedure(s: TSubEvent) of object;
TGetRaidEvent = procedure(s: TRaidEvent) of object; TGetRaidEvent = procedure(s: TRaidEvent) of object;
TOnLog = procedure(aModul: string; aMethod: string; aMessage: string; aLevel: integer) of object; TOnLog = procedure(aModul: string; aMethod: string; aMessage: string;
aLevel: integer) of object;
TOnStatus = procedure(Sender: TObject; const ConnectionEvent: String; TOnStatus = procedure(Sender: TObject; const ConnectionEvent: String;
StatusCode: Integer; const Description: String) of Object; StatusCode: integer; const Description: String) of Object;
type type
TTTW_ES = class(TObject) TTTW_ES = class(TObject)
@@ -43,22 +44,23 @@ type
FOnStatus: TOnStatus; FOnStatus: TOnStatus;
SW: TWelcomMessage; SW: TWelcomMessage;
procedure HandleTimer(Sender: TObject); procedure HandleTimer(Sender: TObject);
procedure ipwWSClient1DataIn(Sender: TObject; DataFormat: Integer; procedure ipwWSClient1DataIn(Sender: TObject; DataFormat: integer;
const Text: string; const TextB: TBytes; EOM, EOL: Boolean); const Text: string; const TextB: TBytes; EOM, EOL: Boolean);
procedure ipwWSPing(Sender: TObject; const Payload: String; procedure ipwWSPing(Sender: TObject; const Payload: String;
const PayloadB: TBytes; Response: Boolean); const PayloadB: TBytes; Response: Boolean);
procedure ipwWSClient1ConnectionStatus(Sender: TObject; procedure ipwWSClient1ConnectionStatus(Sender: TObject;
const ConnectionEvent: String; StatusCode: Integer; const ConnectionEvent: String; StatusCode: integer;
const Description: String); const Description: String);
procedure ipwWSClientError(Sender: TObject; ErrorCode: Integer; procedure ipwWSClientError(Sender: TObject; ErrorCode: integer;
const Description: string); const Description: string);
procedure ipwWSClientDisconnected(Sender: TObject; StatusCode: Integer; procedure ipwWSClientDisconnected(Sender: TObject; StatusCode: integer;
const Description: String); const Description: String);
procedure ipwWSClientHeader(Sender: TObject; const Field: String; procedure ipwWSClientHeader(Sender: TObject; const Field: String;
const Value: String); const Value: String);
procedure ipwWSClientLog(Sender: TObject; LogLevel: Integer; procedure ipwWSClientLog(Sender: TObject; LogLevel: integer;
const aMessage, aLog: string); const aMessage, aLog: string);
function subscribeTo(const EventType, Version: string; const Condition: string): Boolean; function subscribeTo(const EventType, Version: string;
const Condition: string): Boolean;
procedure subscribe(); procedure subscribe();
// function ParseRewardRedeemed(const AJsonString: string): TRewardRedeemed; // function ParseRewardRedeemed(const AJsonString: string): TRewardRedeemed;
procedure EventMSG(const AText: string); procedure EventMSG(const AText: string);
@@ -104,18 +106,14 @@ begin
raise Exception.CreateFmt('JSON object "%s" not found', [Name]); raise Exception.CreateFmt('JSON object "%s" not found', [Name]);
end; end;
function SafeGetStr(Parent: TJSONObject; const Name: string): string; function GetStrDef(Obj: TJSONObject; const Name: string;
var Default: string = ''): string;
V: TJSONValue;
begin begin
V := Parent.GetValue(Name); if not Obj.TryGetValue(Name, Result) then
if Assigned(V) then Result := Default;
Result := V.Value
else
Result := '';
end; end;
function SafeGetInt(Parent: TJSONObject; const Name: string): Integer; function SafeGetInt(Parent: TJSONObject; const Name: string): integer;
var var
V: TJSONValue; V: TJSONValue;
begin begin
@@ -143,16 +141,15 @@ begin
FOnLog('uTTWEvenSub', aMethod, aMessage, aLevel); FOnLog('uTTWEvenSub', aMethod, aMessage, aLevel);
end; end;
procedure TTTW_ES.Connect; procedure TTTW_ES.Connect;
begin begin
if wss.Connected then if wss.Connected then
wss.Disconnect; wss.Disconnect;
try try
wss.ConnectTo('wss://eventsub.wss.twitch.tv/ws?keepalive_timeout_seconds=60'); wss.ConnectTo
('wss://eventsub.wss.twitch.tv/ws?keepalive_timeout_seconds=60');
toLog(0, 'Connect', 'Ïîäêëþ÷åíèå ê WebSocket âûïîëíåíî'); toLog(0, 'Connect', 'Ïîäêëþ÷åíèå ê WebSocket âûïîëíåíî');
FTimer.Enabled := True; FTimer.Enabled := True;
except except
@@ -178,7 +175,7 @@ begin
wss.OnDisconnected := ipwWSClientDisconnected; wss.OnDisconnected := ipwWSClientDisconnected;
wss.OnHeader := ipwWSClientHeader; wss.OnHeader := ipwWSClientHeader;
FTimer := TTimer.Create(nil); FTimer := ttimer.Create(nil);
FTimer.Interval := 9000; FTimer.Interval := 9000;
FTimer.OnTimer := HandleTimer; FTimer.OnTimer := HandleTimer;
FTimer.Enabled := False; FTimer.Enabled := False;
@@ -188,7 +185,7 @@ end;
destructor TTTW_ES.Destroy; destructor TTTW_ES.Destroy;
begin begin
toLog(0, 'Destroy', 'Çàâåðøåíèå ðàáîòû EventSub'); toLog(0, 'Destroy', 'Çàâåðøåíèå ðàáîòû EventSub');
try try
if Assigned(FTimer) then if Assigned(FTimer) then
FreeAndNil(FTimer); FreeAndNil(FTimer);
@@ -210,6 +207,7 @@ begin
try try
if wss.Connected then if wss.Connected then
wss.Disconnect; wss.Disconnect;
FTimer.Enabled := False;
except except
on E: Exception do on E: Exception do
toLog(2, 'Disconnect', E.ClassName + ': ' + E.Message); toLog(2, 'Disconnect', E.ClassName + ': ' + E.Message);
@@ -220,50 +218,55 @@ procedure TTTW_ES.EventMSG(const AText: string);
var var
md: TMetadata; md: TMetadata;
begin begin
if Assigned(FOnRAW) then TThread.Queue(nil,
FOnRAW(AText); procedure
begin
md := ParseMetadata(AText); if Assigned(FOnRAW) then
toLog(0, 'EventMSG', 'Òèï ñîîáùåíèÿ: ' + md.message_type + ', Òèï ïîäïèñêè: ' + md.subscription_type); FOnRAW(AText);
if md.message_type = 'session_welcome' then md := ParseMetadata(AText);
begin toLog(0, 'EventMSG', 'Òèï ñîîáùåíèÿ: ' + md.message_type +
toLog(0, 'EventMSG', 'Ïîëó÷åí session_welcome'); ', Òèï ïîäïèñêè: ' + md.subscription_type);
SW := ParseWelcomMessage(AText);
if Assigned(FOnMessage) then
FOnMessage('Welcome message');
subscribe;
end
else if md.message_type = 'notification' then
begin
if md.subscription_type = 'channel.channel_points_custom_reward_redemption.add' then
if Assigned(FOnGetCustomReward) then
FOnGetCustomReward(ParseCustomRewardEvent(AText));
if md.subscription_type = 'channel.follow' then if md.message_type = 'session_welcome' then
if Assigned(FOnFollow) then begin
FOnFollow(ParseFollowEvent(AText)); toLog(0, 'EventMSG', 'Ïîëó÷åí session_welcome');
SW := ParseWelcomMessage(AText);
if Assigned(FOnMessage) then
FOnMessage('Welcome message');
subscribe;
end
else if md.message_type = 'notification' then
begin
if Assigned(FOnGetCustomReward) and
(md.subscription_type = 'channel.channel_points_custom_reward_redemption.add')
then
FOnGetCustomReward(ParseCustomRewardEvent(AText));
if md.subscription_type = 'channel.subscribe' then if Assigned(FOnFollow) and (md.subscription_type = 'channel.follow')
if Assigned(FOnSub) then then
FOnSub(ParseSubEvent(AText)); FOnFollow(ParseFollowEvent(AText));
if md.subscription_type = 'channel.subscription.gift' then if Assigned(FOnSub) and (md.subscription_type = 'channel.subscribe')
if Assigned(FOnGift) then then
FOnGift(ParseGiftEvent(AText)); FOnSub(ParseSubEvent(AText));
if md.subscription_type = 'channel.raid' then if Assigned(FOnGift) and
if Assigned(FOnRaid) then (md.subscription_type = 'channel.subscription.gift') then
FOnRaid(ParseRaidEvent(AText)); FOnGift(ParseGiftEvent(AText));
end
else if md.message_type = 'session_keepalive' then
toLog(3, 'EventMSG', 'Ïîëó÷åí keepalive');
if Assigned(FOnRaid) and (md.subscription_type = 'channel.raid') then
FOnRaid(ParseRaidEvent(AText));
end
else if md.message_type = 'session_keepalive' then
toLog(3, 'EventMSG', 'Ïîëó÷åí keepalive');
end);
end; end;
procedure TTTW_ES.HandleTimer(Sender: TObject); procedure TTTW_ES.HandleTimer(Sender: TObject);
begin begin
if wss.Connected then if wss.Connected then
begin begin
toLog(3, 'HandleTimer', 'Îòïðàâêà ping'); toLog(3, 'HandleTimer', 'Îòïðàâêà ping');
wss.Ping; wss.Ping;
@@ -271,46 +274,46 @@ if wss.Connected then
end; end;
procedure TTTW_ES.ipwWSClient1ConnectionStatus(Sender: TObject; procedure TTTW_ES.ipwWSClient1ConnectionStatus(Sender: TObject;
const ConnectionEvent: String; StatusCode: Integer; const ConnectionEvent: String; StatusCode: integer; const Description: String);
const Description: String);
begin begin
toLog(0, 'ConnectionStatus', toLog(0, 'ConnectionStatus', Format('%s | %d | %s', [ConnectionEvent,
Format('%s | %d | %s', [ConnectionEvent, StatusCode, Description])); StatusCode, Description]));
if Assigned(FOnStatus) then if Assigned(FOnStatus) then
FOnStatus(Sender, ConnectionEvent, StatusCode, Description); FOnStatus(Sender, ConnectionEvent, StatusCode, Description);
end; end;
procedure TTTW_ES.ipwWSClient1DataIn(Sender: TObject; DataFormat: Integer; procedure TTTW_ES.ipwWSClient1DataIn(Sender: TObject; DataFormat: integer;
const Text: string; const TextB: TBytes; EOM, EOL: Boolean); const Text: string; const TextB: TBytes; EOM, EOL: Boolean);
begin begin
toLog(3, 'ipwWSClient1DataIn', Text); toLog(3, 'ipwWSClient1DataIn', Text);
EventMSG(Text); EventMSG(Text);
end; end;
procedure TTTW_ES.ipwWSClientDisconnected(Sender: TObject; StatusCode: Integer; procedure TTTW_ES.ipwWSClientDisconnected(Sender: TObject; StatusCode: integer;
const Description: String); const Description: String);
begin begin
toLog(1, 'ipwWSClientDisconnected', Description); toLog(1, 'ipwWSClientDisconnected', Description);
end; end;
procedure TTTW_ES.ipwWSClientError(Sender: TObject; ErrorCode: Integer; procedure TTTW_ES.ipwWSClientError(Sender: TObject; ErrorCode: integer;
const Description: string); const Description: string);
begin begin
toLog(2, 'ipwWSClientError', Format('Êîä: %d | %s', [ErrorCode, Description])); toLog(2, 'ipwWSClientError', Format('Êîä: %d | %s',
[ErrorCode, Description]));
if Assigned(FOnError) then if Assigned(FOnError) then
FOnError(Description); FOnError(Description);
end; end;
procedure TTTW_ES.ipwWSClientHeader(Sender: TObject; procedure TTTW_ES.ipwWSClientHeader(Sender: TObject;
const Field, Value: String); const Field, Value: String);
begin begin
// toLog(3, 'ipwWSClientHeader', // toLog(3, 'ipwWSClientHeader',
// 'Field: ' + Field + ' | Value: ' + Value); // 'Field: ' + Field + ' | Value: ' + Value);
end; end;
procedure TTTW_ES.ipwWSClientLog(Sender: TObject; LogLevel: Integer; procedure TTTW_ES.ipwWSClientLog(Sender: TObject; LogLevel: integer;
const aMessage, aLog: string); const aMessage, aLog: string);
begin begin
// toLog(3, 'ipwWSClientLog', 'Level: ' + IntToStr(LogLevel) // toLog(3, 'ipwWSClientLog', 'Level: ' + IntToStr(LogLevel)
// + ' | ' + aMessage + ' | ' + aLog); // + ' | ' + aMessage + ' | ' + aLog);
@@ -320,9 +323,9 @@ begin
end; end;
procedure TTTW_ES.ipwWSPing(Sender: TObject; const Payload: String; procedure TTTW_ES.ipwWSPing(Sender: TObject; const Payload: String;
const PayloadB: TBytes; Response: Boolean); const PayloadB: TBytes; Response: Boolean);
begin begin
toLog(3, 'ipwWSPing', 'PING ' + Payload); toLog(3, 'ipwWSPing', 'PING ' + Payload);
end; end;
function TTTW_ES.ParseMetadata(const JSONString: string): TMetadata; function TTTW_ES.ParseMetadata(const JSONString: string): TMetadata;
@@ -334,10 +337,10 @@ begin
raise Exception.Create('Invalid JSON'); raise Exception.Create('Invalid JSON');
try try
Metadata := SafeGetObj(Root, 'metadata'); Metadata := SafeGetObj(Root, 'metadata');
Result.message_id := SafeGetStr(Metadata, 'message_id'); Result.message_id := GetStrDef(Metadata, 'message_id');
Result.message_type := SafeGetStr(Metadata, 'message_type'); Result.message_type := GetStrDef(Metadata, 'message_type');
Result.message_timestamp := SafeGetStr(Metadata, 'message_timestamp'); Result.message_timestamp := GetStrDef(Metadata, 'message_timestamp');
Result.subscription_type := SafeGetStr(Metadata, 'subscription_type'); Result.subscription_type := GetStrDef(Metadata, 'subscription_type');
finally finally
Root.Free; Root.Free;
end; end;
@@ -353,11 +356,12 @@ begin
try try
Payload := SafeGetObj(Root, 'payload'); Payload := SafeGetObj(Root, 'payload');
Session := SafeGetObj(Payload, 'session'); Session := SafeGetObj(Payload, 'session');
Result.Payload.session.id := SafeGetStr(Session, 'id'); Result.Payload.Session.id := GetStrDef(Session, 'id');
Result.Payload.session.status := SafeGetStr(Session, 'status'); Result.Payload.Session.status := GetStrDef(Session, 'status');
Result.Payload.session.connected_at := SafeGetStr(Session, 'connected_at'); Result.Payload.Session.connected_at := GetStrDef(Session, 'connected_at');
Result.Payload.session.keepalive_timeout_seconds := SafeGetInt(Session, 'keepalive_timeout_seconds'); Result.Payload.Session.keepalive_timeout_seconds :=
Result.Payload.session.reconnect_url := SafeGetStr(Session, 'reconnect_url'); SafeGetInt(Session, 'keepalive_timeout_seconds');
Result.Payload.Session.reconnect_url := GetStrDef(Session, 'reconnect_url');
finally finally
Root.Free; Root.Free;
end; end;
@@ -366,7 +370,8 @@ end;
function TTTW_ES.ParseCustomRewardEvent(const JSONString: string) function TTTW_ES.ParseCustomRewardEvent(const JSONString: string)
: TCustomRewardEvent; : TCustomRewardEvent;
var var
Root, Payload, Subscription, mCondition, mTransport, Event, mReward: TJSONObject; Root, Payload, Subscription, mCondition, mTransport, Event,
mReward: TJSONObject;
begin begin
toLog(3, 'ParseCustomRewardEvent', 'Íà÷àëî ïàðñèíãà íàãðàäû'); toLog(3, 'ParseCustomRewardEvent', 'Íà÷àëî ïàðñèíãà íàãðàäû');
Root := TJSONObject.ParseJSONValue(JSONString) as TJSONObject; Root := TJSONObject.ParseJSONValue(JSONString) as TJSONObject;
@@ -377,35 +382,36 @@ begin
Subscription := SafeGetObj(Payload, 'subscription'); Subscription := SafeGetObj(Payload, 'subscription');
with Result.Subscription do with Result.Subscription do
begin begin
id := SafeGetStr(Subscription, 'id'); id := GetStrDef(Subscription, 'id');
subscription_type := SafeGetStr(Subscription, 'type'); subscription_type := GetStrDef(Subscription, 'type');
version := SafeGetStr(Subscription, 'version'); Version := GetStrDef(Subscription, 'version');
status := SafeGetStr(Subscription, 'status'); status := GetStrDef(Subscription, 'status');
cost := SafeGetInt(Subscription, 'cost'); cost := SafeGetInt(Subscription, 'cost');
created_at := SafeGetStr(Subscription, 'created_at'); created_at := GetStrDef(Subscription, 'created_at');
mCondition := SafeGetObj(Subscription, 'condition'); mCondition := SafeGetObj(Subscription, 'condition');
condition.broadcaster_user_id := SafeGetStr(mCondition, 'broadcaster_user_id'); Condition.broadcaster_user_id :=
condition.reward_id := SafeGetStr(mCondition, 'reward_id'); GetStrDef(mCondition, 'broadcaster_user_id');
Condition.reward_id := GetStrDef(mCondition, 'reward_id');
mTransport := SafeGetObj(Subscription, 'transport'); mTransport := SafeGetObj(Subscription, 'transport');
transport.method := SafeGetStr(mTransport, 'method'); transport.method := GetStrDef(mTransport, 'method');
end; end;
Event := SafeGetObj(Payload, 'event'); Event := SafeGetObj(Payload, 'event');
with Result.Event do with Result.Event do
begin begin
id := SafeGetStr(Event, 'id'); id := GetStrDef(Event, 'id');
broadcaster_user_id := SafeGetStr(Event, 'broadcaster_user_id'); broadcaster_user_id := GetStrDef(Event, 'broadcaster_user_id');
broadcaster_user_login := SafeGetStr(Event, 'broadcaster_user_login'); broadcaster_user_login := GetStrDef(Event, 'broadcaster_user_login');
broadcaster_user_name := SafeGetStr(Event, 'broadcaster_user_name'); broadcaster_user_name := GetStrDef(Event, 'broadcaster_user_name');
user_id := SafeGetStr(Event, 'user_id'); user_id := GetStrDef(Event, 'user_id');
user_login := SafeGetStr(Event, 'user_login'); user_login := GetStrDef(Event, 'user_login');
user_name := SafeGetStr(Event, 'user_name'); user_name := GetStrDef(Event, 'user_name');
user_input := SafeGetStr(Event, 'user_input'); user_input := GetStrDef(Event, 'user_input');
mReward := SafeGetObj(Event, 'reward'); mReward := SafeGetObj(Event, 'reward');
revard.id := SafeGetStr(mReward, 'id'); revard.id := GetStrDef(mReward, 'id');
revard.title := SafeGetStr(mReward, 'title'); revard.title := GetStrDef(mReward, 'title');
revard.cost := SafeGetInt(mReward, 'cost'); revard.cost := SafeGetInt(mReward, 'cost');
revard.prompt := SafeGetStr(mReward, 'prompt'); revard.prompt := GetStrDef(mReward, 'prompt');
end; end;
finally finally
Root.Free; Root.Free;
@@ -425,28 +431,29 @@ begin
Subscription := SafeGetObj(Payload, 'subscription'); Subscription := SafeGetObj(Payload, 'subscription');
with Result.Subscription do with Result.Subscription do
begin begin
id := SafeGetStr(Subscription, 'id'); id := GetStrDef(Subscription, 'id');
subscription_type := SafeGetStr(Subscription, 'type'); subscription_type := GetStrDef(Subscription, 'type');
version := SafeGetStr(Subscription, 'version'); Version := GetStrDef(Subscription, 'version');
status := SafeGetStr(Subscription, 'status'); status := GetStrDef(Subscription, 'status');
cost := SafeGetInt(Subscription, 'cost'); cost := SafeGetInt(Subscription, 'cost');
created_at := SafeGetStr(Subscription, 'created_at'); created_at := GetStrDef(Subscription, 'created_at');
mCondition := SafeGetObj(Subscription, 'condition'); mCondition := SafeGetObj(Subscription, 'condition');
condition.broadcaster_user_id := SafeGetStr(mCondition, 'broadcaster_user_id'); Condition.broadcaster_user_id :=
GetStrDef(mCondition, 'broadcaster_user_id');
mTransport := SafeGetObj(Subscription, 'transport'); mTransport := SafeGetObj(Subscription, 'transport');
transport.method := SafeGetStr(mTransport, 'method'); transport.method := GetStrDef(mTransport, 'method');
end; end;
Event := SafeGetObj(Payload, 'event'); Event := SafeGetObj(Payload, 'event');
with Result.Event do with Result.Event do
begin begin
broadcaster_user_id := SafeGetStr(Event, 'broadcaster_user_id'); broadcaster_user_id := GetStrDef(Event, 'broadcaster_user_id');
broadcaster_user_login := SafeGetStr(Event, 'broadcaster_user_login'); broadcaster_user_login := GetStrDef(Event, 'broadcaster_user_login');
broadcaster_user_name := SafeGetStr(Event, 'broadcaster_user_name'); broadcaster_user_name := GetStrDef(Event, 'broadcaster_user_name');
user_id := SafeGetStr(Event, 'user_id'); user_id := GetStrDef(Event, 'user_id');
user_login := SafeGetStr(Event, 'user_login'); user_login := GetStrDef(Event, 'user_login');
user_name := SafeGetStr(Event, 'user_name'); user_name := GetStrDef(Event, 'user_name');
followed_at := SafeGetStr(Event, 'followed_at'); followed_at := GetStrDef(Event, 'followed_at');
end; end;
finally finally
Root.Free; Root.Free;
@@ -466,29 +473,30 @@ begin
Subscription := SafeGetObj(Payload, 'subscription'); Subscription := SafeGetObj(Payload, 'subscription');
with Result.Subscription do with Result.Subscription do
begin begin
id := SafeGetStr(Subscription, 'id'); id := GetStrDef(Subscription, 'id');
subscription_type := SafeGetStr(Subscription, 'type'); subscription_type := GetStrDef(Subscription, 'type');
version := SafeGetStr(Subscription, 'version'); Version := GetStrDef(Subscription, 'version');
status := SafeGetStr(Subscription, 'status'); status := GetStrDef(Subscription, 'status');
cost := SafeGetInt(Subscription, 'cost'); cost := SafeGetInt(Subscription, 'cost');
created_at := SafeGetStr(Subscription, 'created_at'); created_at := GetStrDef(Subscription, 'created_at');
mCondition := SafeGetObj(Subscription, 'condition'); mCondition := SafeGetObj(Subscription, 'condition');
condition.broadcaster_user_id := SafeGetStr(mCondition, 'broadcaster_user_id'); Condition.broadcaster_user_id :=
GetStrDef(mCondition, 'broadcaster_user_id');
mTransport := SafeGetObj(Subscription, 'transport'); mTransport := SafeGetObj(Subscription, 'transport');
transport.method := SafeGetStr(mTransport, 'method'); transport.method := GetStrDef(mTransport, 'method');
end; end;
Event := SafeGetObj(Payload, 'event'); Event := SafeGetObj(Payload, 'event');
with Result.Event do with Result.Event do
begin begin
broadcaster_user_id := SafeGetStr(Event, 'broadcaster_user_id'); broadcaster_user_id := GetStrDef(Event, 'broadcaster_user_id');
broadcaster_user_login := SafeGetStr(Event, 'broadcaster_user_login'); broadcaster_user_login := GetStrDef(Event, 'broadcaster_user_login');
broadcaster_user_name := SafeGetStr(Event, 'broadcaster_user_name'); broadcaster_user_name := GetStrDef(Event, 'broadcaster_user_name');
user_id := SafeGetStr(Event, 'user_id'); user_id := GetStrDef(Event, 'user_id');
user_login := SafeGetStr(Event, 'user_login'); user_login := GetStrDef(Event, 'user_login');
user_name := SafeGetStr(Event, 'user_name'); user_name := GetStrDef(Event, 'user_name');
total := SafeGetInt(Event, 'total'); total := SafeGetInt(Event, 'total');
tier := SafeGetStr(Event, 'tier'); tier := GetStrDef(Event, 'tier');
cumulative_total := SafeGetInt(Event, 'cumulative_total'); cumulative_total := SafeGetInt(Event, 'cumulative_total');
is_anonymous := SafeGetBool(Event, 'anonymous'); is_anonymous := SafeGetBool(Event, 'anonymous');
end; end;
@@ -497,7 +505,6 @@ begin
end; end;
end; end;
function TTTW_ES.ParseRaidEvent(const JSONString: string): TRaidEvent; function TTTW_ES.ParseRaidEvent(const JSONString: string): TRaidEvent;
var var
Root, Payload, Subscription, mCondition, mTransport, Event: TJSONObject; Root, Payload, Subscription, mCondition, mTransport, Event: TJSONObject;
@@ -511,27 +518,31 @@ begin
Subscription := SafeGetObj(Payload, 'subscription'); Subscription := SafeGetObj(Payload, 'subscription');
with Result.Subscription do with Result.Subscription do
begin begin
id := SafeGetStr(Subscription, 'id'); id := GetStrDef(Subscription, 'id');
subscription_type := SafeGetStr(Subscription, 'type'); subscription_type := GetStrDef(Subscription, 'type');
version := SafeGetStr(Subscription, 'version'); Version := GetStrDef(Subscription, 'version');
status := SafeGetStr(Subscription, 'status'); status := GetStrDef(Subscription, 'status');
cost := SafeGetInt(Subscription, 'cost'); cost := SafeGetInt(Subscription, 'cost');
created_at := SafeGetStr(Subscription, 'created_at'); created_at := GetStrDef(Subscription, 'created_at');
mCondition := SafeGetObj(Subscription, 'condition'); mCondition := SafeGetObj(Subscription, 'condition');
condition.broadcaster_user_id := SafeGetStr(mCondition, 'to_broadcaster_user_id'); Condition.broadcaster_user_id :=
GetStrDef(mCondition, 'to_broadcaster_user_id');
mTransport := SafeGetObj(Subscription, 'transport'); mTransport := SafeGetObj(Subscription, 'transport');
transport.method := SafeGetStr(mTransport, 'method'); transport.method := GetStrDef(mTransport, 'method');
end; end;
Event := SafeGetObj(Payload, 'event'); Event := SafeGetObj(Payload, 'event');
with Result.Event do with Result.Event do
begin begin
from_broadcaster_user_id := SafeGetStr(Event, 'from_broadcaster_user_id'); from_broadcaster_user_id := GetStrDef(Event, 'from_broadcaster_user_id');
from_broadcaster_user_login := SafeGetStr(Event, 'from_broadcaster_user_login'); from_broadcaster_user_login :=
from_broadcaster_user_name := SafeGetStr(Event, 'from_broadcaster_user_name'); GetStrDef(Event, 'from_broadcaster_user_login');
to_broadcaster_user_id := SafeGetStr(Event, 'to_broadcaster_user_id'); from_broadcaster_user_name :=
to_broadcaster_user_login := SafeGetStr(Event, 'to_broadcaster_user_login'); GetStrDef(Event, 'from_broadcaster_user_name');
to_broadcaster_user_name := SafeGetStr(Event, 'to_broadcaster_user_name'); to_broadcaster_user_id := GetStrDef(Event, 'to_broadcaster_user_id');
to_broadcaster_user_login :=
GetStrDef(Event, 'to_broadcaster_user_login');
to_broadcaster_user_name := GetStrDef(Event, 'to_broadcaster_user_name');
viewers := SafeGetInt(Event, 'viewers'); viewers := SafeGetInt(Event, 'viewers');
end; end;
finally finally
@@ -552,28 +563,29 @@ begin
Subscription := SafeGetObj(Payload, 'subscription'); Subscription := SafeGetObj(Payload, 'subscription');
with Result.Subscription do with Result.Subscription do
begin begin
id := SafeGetStr(Subscription, 'id'); id := GetStrDef(Subscription, 'id');
subscription_type := SafeGetStr(Subscription, 'type'); subscription_type := GetStrDef(Subscription, 'type');
version := SafeGetStr(Subscription, 'version'); Version := GetStrDef(Subscription, 'version');
status := SafeGetStr(Subscription, 'status'); status := GetStrDef(Subscription, 'status');
cost := SafeGetInt(Subscription, 'cost'); cost := SafeGetInt(Subscription, 'cost');
created_at := SafeGetStr(Subscription, 'created_at'); created_at := GetStrDef(Subscription, 'created_at');
mCondition := SafeGetObj(Subscription, 'condition'); mCondition := SafeGetObj(Subscription, 'condition');
condition.broadcaster_user_id := SafeGetStr(mCondition, 'broadcaster_user_id'); Condition.broadcaster_user_id :=
GetStrDef(mCondition, 'broadcaster_user_id');
mTransport := SafeGetObj(Subscription, 'transport'); mTransport := SafeGetObj(Subscription, 'transport');
transport.method := SafeGetStr(mTransport, 'method'); transport.method := GetStrDef(mTransport, 'method');
end; end;
Event := SafeGetObj(Payload, 'event'); Event := SafeGetObj(Payload, 'event');
with Result.Event do with Result.Event do
begin begin
broadcaster_user_id := SafeGetStr(Event, 'broadcaster_user_id'); broadcaster_user_id := GetStrDef(Event, 'broadcaster_user_id');
broadcaster_user_login := SafeGetStr(Event, 'broadcaster_user_login'); broadcaster_user_login := GetStrDef(Event, 'broadcaster_user_login');
broadcaster_user_name := SafeGetStr(Event, 'broadcaster_user_name'); broadcaster_user_name := GetStrDef(Event, 'broadcaster_user_name');
user_id := SafeGetStr(Event, 'user_id'); user_id := GetStrDef(Event, 'user_id');
user_login := SafeGetStr(Event, 'user_login'); user_login := GetStrDef(Event, 'user_login');
user_name := SafeGetStr(Event, 'user_name'); user_name := GetStrDef(Event, 'user_name');
tier := SafeGetStr(Event, 'tier'); tier := GetStrDef(Event, 'tier');
is_gift := SafeGetBool(Event, 'is_gift'); is_gift := SafeGetBool(Event, 'is_gift');
end; end;
finally finally
@@ -581,45 +593,45 @@ begin
end; end;
end; end;
function TTTW_ES.subscribeTo(const EventType, Version: string; const Condition: string): Boolean; function TTTW_ES.subscribeTo(const EventType, Version: string;
const Condition: string): Boolean;
var var
Json: TStringStream; JSON: TStringStream;
Resp: string; Resp: string;
HTTP: TNetHTTPClient; HTTP: TNetHTTPClient;
begin begin
Result := False; Result := False;
toLog(0, 'subscribeTo', 'Ïîäïèñêà íà ' + EventType); toLog(0, 'subscribeTo', 'Ïîäïèñêà íà ' + EventType);
HTTP := TNetHTTPClient.Create(nil);
try try
HTTP.ContentType := 'application/json'; HTTP := TNetHTTPClient.Create(nil);
HTTP.CustomHeaders['Authorization'] := 'Bearer ' + FAccessToken;
HTTP.CustomHeaders['Client-Id'] := FClientID;
Json := TStringStream.Create(
TJSONObject.Create
.AddPair('type', EventType)
.AddPair('version', Version)
.AddPair('condition', TJSONObject.ParseJSONValue(Condition) as TJSONObject)
.AddPair('transport',
TJSONObject.Create
.AddPair('method', 'websocket')
.AddPair('session_id', SW.Payload.session.id)
).ToJSON, TEncoding.UTF8
);
try try
Resp := HTTP.Post('https://api.twitch.tv/helix/eventsub/subscriptions', Json).ContentAsString(); HTTP.ContentType := 'application/json';
toLog(3, 'subscribeTo', 'Îòâåò Twitch: ' + Resp); HTTP.CustomHeaders['Authorization'] := 'Bearer ' + FAccessToken;
HTTP.CustomHeaders['Client-Id'] := FClientID;
JSON := TStringStream.Create(TJSONObject.Create.AddPair('type', EventType)
.AddPair('version', Version).AddPair('condition',
TJSONObject.ParseJSONValue(Condition) as TJSONObject)
.AddPair('transport', TJSONObject.Create.AddPair('method', 'websocket')
.AddPair('session_id', SW.Payload.Session.id)).ToJSON, TEncoding.UTF8);
try
Resp := HTTP.Post('https://api.twitch.tv/helix/eventsub/subscriptions',
JSON).ContentAsString();
toLog(3, 'subscribeTo', 'Îòâåò Twitch: ' + Resp);
if Pos('"status":"enabled"', Resp) > 0 then
begin
toLog(0, 'subscribeTo', 'Ïîäïèñêà óñïåøíà');
Result := True;
end
else
toLog(1, 'subscribeTo', 'Ïîäïèñêà íå ïîäòâåðæäåíà: ' + Resp);
finally
JSON.Free;
end;
if Pos('"status":"enabled"', Resp) > 0 then
begin
toLog(0, 'subscribeTo', 'Ïîäïèñêà óñïåøíà');
Result := True;
end
else
toLog(1, 'subscribeTo', 'Ïîäïèñêà íå ïîäòâåðæäåíà: ' + Resp);
finally finally
Json.Free; HTTP.Free;
end; end;
except except
on E: Exception do on E: Exception do
@@ -636,35 +648,35 @@ begin
// channel.raid (1) // channel.raid (1)
if subscribeTo('channel.channel_points_custom_reward_redemption.add', '1', if subscribeTo('channel.channel_points_custom_reward_redemption.add', '1',
'{"broadcaster_user_id":"' + BroadcasterID + '"}') then '{"broadcaster_user_id":"' + BroadcasterID + '"}') then
toLog(0, 'subscribe', toLog(0, 'subscribe',
'channel.channel_points_custom_reward_redemption.add OK') 'channel.channel_points_custom_reward_redemption.add OK')
else else
toLog(2, 'subscribe', toLog(2, 'subscribe',
'channel.channel_points_custom_reward_redemption.add'); 'channel.channel_points_custom_reward_redemption.add');
if subscribeTo('channel.raid', '1', '{"to_broadcaster_user_id":"' + if subscribeTo('channel.raid', '1', '{"to_broadcaster_user_id":"' +
BroadcasterID + '"}') then BroadcasterID + '"}') then
toLog(0, 'subscribe', 'channel.raid OK') toLog(0, 'subscribe', 'channel.raid OK')
else else
toLog(2, 'subscribe', 'channel.raid'); toLog(2, 'subscribe', 'channel.raid');
if subscribeTo('channel.follow', '2', '{"broadcaster_user_id":"' + if subscribeTo('channel.follow', '2', '{"broadcaster_user_id":"' +
BroadcasterID + '","moderator_user_id":"' + BroadcasterID + '"}') then BroadcasterID + '","moderator_user_id":"' + BroadcasterID + '"}') then
toLog(0, 'subscribe', 'channel.follow OK') toLog(0, 'subscribe', 'channel.follow OK')
else else
toLog(2, 'subscribe', 'channel.follow'); toLog(2, 'subscribe', 'channel.follow');
if subscribeTo('channel.subscribe', '1', '{"broadcaster_user_id":"' + if subscribeTo('channel.subscribe', '1', '{"broadcaster_user_id":"' +
BroadcasterID + '"}') then BroadcasterID + '"}') then
toLog(0, 'subscribe', 'channel.subscribe OK') toLog(0, 'subscribe', 'channel.subscribe OK')
else else
toLog(2, 'subscribe', 'channel.subscribe'); toLog(2, 'subscribe', 'channel.subscribe');
if subscribeTo('channel.subscription.gift', '1', '{"broadcaster_user_id":"' + if subscribeTo('channel.subscription.gift', '1', '{"broadcaster_user_id":"' +
BroadcasterID + '"}') then BroadcasterID + '"}') then
toLog(0, 'subscribe', 'channel.subscription.gift OK') toLog(0, 'subscribe', 'channel.subscription.gift OK')
else else
toLog(2, 'subscribe', 'channel.subscription.gift'); toLog(2, 'subscribe', 'channel.subscription.gift');
end; end;
end. end.
+16 -14
View File
@@ -272,7 +272,7 @@ begin
frSettings1.edtBotClientID.text, rid); frSettings1.edtBotClientID.text, rid);
// Назначение обработчиков событий // Назначение обработчиков событий
// ttw_ES.OnMessage := fRewards.ESOnMessage; ttw_ES.OnLog := toLog;
ttw_ES.OnError := ESError; ttw_ES.OnError := ESError;
ttw_ES.OnGetCustomReward := frEvents1.ESOnGetCustomReward; ttw_ES.OnGetCustomReward := frEvents1.ESOnGetCustomReward;
ttw_ES.OnStatus := ESStatus; ttw_ES.OnStatus := ESStatus;
@@ -513,23 +513,25 @@ end;
procedure TTTW_Bot.FormDestroy(Sender: TObject); procedure TTTW_Bot.FormDestroy(Sender: TObject);
begin begin
frOBS1.ChatBadges.Free; FreeAndNil(frOBS1.ChatBadges);
frOBS1.ChatEmotes.Free; FreeAndNil(frOBS1.ChatEmotes);
frOBS1.ChatWebServers.Free; FreeAndNil(frOBS1.ChatWebServers);
frOBS1.EventWebServers.Free; FreeAndNil(frOBS1.EventWebServers);
frOBS1.KandinskyWebServers.Free; FreeAndNil(frOBS1.KandinskyWebServers);
frRevards1.CustomRewards.Free; FreeAndNil(frRevards1.CustomRewards);
frOBS1.BTTV.Free;
frOBS1.m7tv.Free;
userlist.Free;
kePoints.Free; kePoints.Free;
DisconnectProcedure; DisconnectProcedure;
if Assigned(ttw_IRS) then FreeAndNil(ttw_IRS);
ttw_IRS.Free; FreeAndNil(ttw_ES);
if Assigned(ttw_ES) then FreeAndNil(ttw_API);
ttw_ES.Free;
if Assigned(Kandinsky) then if Assigned(Kandinsky) then
Kandinsky.Free; Kandinsky.Free;
if Assigned(ttw_API) then //frSettings1.Destroy;
ttw_API.Free;
frSettings1.Destroy;
FreeAndNil(db); FreeAndNil(db);
FreeAndNil(frAutoActions1.FTimerList); FreeAndNil(frAutoActions1.FTimerList);
FreeAndNil(frLog1.FLogList); FreeAndNil(frLog1.FLogList);
+1 -1
View File
@@ -60,7 +60,7 @@ begin
finally finally
FQueueCS.Leave; FQueueCS.Leave;
end; end;
FQueueCS.Free; FreeAndNil(FQueueCS);
inherited; inherited;
end; end;
+3 -1
View File
@@ -52,7 +52,7 @@ end;
destructor TTTW_Events.Destroy; destructor TTTW_Events.Destroy;
begin begin
FCriticalSection.Free; FreeAndNil(FCriticalSection);
FMessages.Free; FMessages.Free;
fFontsList.Free; fFontsList.Free;
IdHTTPServer1.Free; IdHTTPServer1.Free;
@@ -180,6 +180,8 @@ var
begin begin
JSONArray := TJSONArray.Create; JSONArray := TJSONArray.Create;
try try
CleanupOldMessages;
FCriticalSection.Enter; FCriticalSection.Enter;
try try
for I := 0 to FMessages.Count - 1 do for I := 0 to FMessages.Count - 1 do
+1 -1
View File
@@ -67,7 +67,7 @@ end;
destructor TKandinsky_Web.Destroy; destructor TKandinsky_Web.Destroy;
begin begin
IdHTTPServer1.Active := False; IdHTTPServer1.Active := False;
FCriticalSection.Free; FreeAndNil(FCriticalSection);
CleanupOldMessages; CleanupOldMessages;
end; end;