aboutsummaryrefslogtreecommitdiffstats
path: root/DiscordToXIV/Plugin.cs
blob: 2e40bba7b5c2cca156da51ae05fb0a1b4b06c4bc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
using System;
using Fleck;
using Dalamud.Game.Command;
using Dalamud.IoC;
using Dalamud.Plugin;
using Dalamud.Plugin.Services;
using System.Collections.Generic;
using System.Threading;
using System.Text.Json;
using Dalamud.Game.Text.SeStringHandling;
using Dalamud.Game.Text.SeStringHandling.Payloads;
using Dalamud.Interface.Windowing;
using DiscordToXIV.Windows;
using DiscordTOXIV.Windows;


namespace DiscordToXIV;


public sealed class Plugin : IDalamudPlugin
{
    private int[] nameColor =
    {
        45, 517, 704, 708, 52, 61
    };
    [PluginService] internal static IDalamudPluginInterface PluginInterface { get; private set; } = null!;
    [PluginService] internal static ICommandManager CommandManager { get; private set; } = null!;
    [PluginService] internal static IChatGui ChatGui { get; private set; } = null!;
    [PluginService] internal static IPluginLog PluginLog { get; private set; } = null!;

    private const string CommandName = "/pdiscordtoxiv";
    private const int DefaultPort = 8765;
    private bool IsWebSocketServerRunning = false;

    private WebSocketServer webSocketServer;
    private readonly CancellationTokenSource cancellationTokenSource;
    private readonly List<IWebSocketConnection> connectedClients;
    public Configuration Configuration { get; init; }
    private ConfigWindow ConfigWindow { get; init; }
    private MainWindow MainWindow { get; init; }
    public readonly WindowSystem WindowSystem = new("DiscordToXIV");
    

    public Plugin()
    {
        Configuration = PluginInterface.GetPluginConfig() as Configuration ?? new Configuration();
        ConfigWindow = new ConfigWindow(this);
        MainWindow = new MainWindow(this);
        WindowSystem.AddWindow(ConfigWindow);
        WindowSystem.AddWindow(MainWindow);
        cancellationTokenSource = new CancellationTokenSource();
        connectedClients = new List<IWebSocketConnection>();

        CommandManager.AddHandler(CommandName, new CommandInfo(OnCommand)
        {
            HelpMessage = "Start WebSocket server. Usage: /pdiscordtoxiv [port]"
        });
        PluginInterface.UiBuilder.Draw += DrawUI;
        PluginInterface.UiBuilder.OpenConfigUi += ToggleConfigUI;
        PluginInterface.UiBuilder.OpenMainUi += ToggleMainUI;
        if(!Configuration.HideWelcomeMessage)
            ChatGui.Print("[DiscordToXIV] Websocket Server Ready! Use /pdiscordtoxiv <port> to start the server (Need help? /pdiscordtoxiv help)");
    }

    public void Dispose()
    {
        StopWebSocketServer();
        CommandManager.RemoveHandler(CommandName);
    }

    private void OnCommand(string command, string args)
    {
        var port = DefaultPort;
        if (!string.IsNullOrEmpty(args))
        {
            if(args == "stop")
            {
                StopWebSocketServer();
                ChatGui.Print("[DiscordToXIV] WebSocket server stop requested");
            }
            else if (args == "start")
            {
                ChatGui.Print("[DiscordToXIV] Starting WebSocket server with default port " + DefaultPort);
                StartWebSocketServer(DefaultPort);
            }
            else if (args == "help")
                ToggleMainUI();
            else if(args == "config")
                ToggleConfigUI();
            else if (!int.TryParse(args, out port) || port <= 0 || port > 65535)
            {
                ChatGui.PrintError($"[DiscordToXIV] Invalid port number: {args}. Using default port {DefaultPort}.");
                StartWebSocketServer(DefaultPort);
            }
            else
            {
                ToggleMainUI(); 
            }
            return;
        }
        
        // No args provided
        if (!IsWebSocketServerRunning)
        {
            ChatGui.Print("[DiscordToXIV] Starting WebSocket server with default port " + DefaultPort);
            StartWebSocketServer(DefaultPort);
        }
        else
        {
            ChatGui.Print("[DiscordToXIV] Stopping WebSocket server...");
            StopWebSocketServer();
        }

    }

    private void StartWebSocketServer(int port)
    {
        StopWebSocketServer();
        IsWebSocketServerRunning = true;
        webSocketServer = new WebSocketServer($"ws://0.0.0.0:{port}");
        webSocketServer.Start(socket =>
        {
            socket.OnOpen = () =>
            {
                PluginLog.Information("[DiscordToXIV] WebSocket connection opened.");
                ChatGui.Print("[DiscordToXIV] Connected to BetterDiscord Relayer!");
                connectedClients.Add(socket);
            };

            socket.OnClose = () =>
            {
                PluginLog.Information("[DiscordToXIV] WebSocket connection closed.");
                ChatGui.Print("[DiscordToXIV] Disconnected from BetterDiscord Relayer!");
                connectedClients.Remove(socket);
            };

            socket.OnMessage = message =>
            {
                try
                {
                    var receivedMessage = JsonSerializer.Deserialize<Message>(message);

                    if (receivedMessage == null || string.IsNullOrEmpty(receivedMessage.Id))
                    {
                        PluginLog.Error("Received message without an ID.");
                        return;
                    }
                    

                    var seString = new SeString(new List<Payload>());
                    var name = receivedMessage.Author;
                    ushort nameColor = (ushort)ChatUtils.GetNameColor(name, this.nameColor);
                    if (receivedMessage.Nickname != null)
                    {
                        if (!Configuration.HideUsernameWhenNicknameExists)
                            name = $"{receivedMessage.Nickname} ({receivedMessage.AuthorName})";
                        else
                            name = receivedMessage.Nickname;
                    }
                    else if (receivedMessage.AuthorName != null)
                    {
                        name = receivedMessage.AuthorName;
                    }   
                    
                    if(Configuration.ChannelMappings.TryGetValue(receivedMessage.Channel, out var channelName))
                        receivedMessage.ChannelName = channelName;
                    else
                    {
                        if (Configuration.ShowOnlyKnownChannels) return;
                        receivedMessage.ChannelName = receivedMessage.Channel;
                    }

                    seString.Append(new UIForegroundPayload(56));
                    seString.Append($"[{receivedMessage.ChannelName}] ");
                    seString.Append(UIForegroundPayload.UIForegroundOff);
                    seString.Append(new UIForegroundPayload(nameColor));
                    seString.Append(name);
                    seString.Append(UIForegroundPayload.UIForegroundOff);
                    seString.Append(new UIForegroundPayload(1));
                    var messageContent = receivedMessage.Content;
                    if (Configuration.AdjustEmoteText)
                        messageContent = ChatUtils.FixEmoteText(messageContent);
                    if (Configuration.AdjustMentions)
                        messageContent = ChatUtils.ReplaceMentionsWithNames(messageContent, receivedMessage.Mentions);
                    seString.Append($": {messageContent}");
                    var stickerData = "";
                    if (receivedMessage.StickerId != null)
                        if (!Configuration.HideStickerUrls)
                        {
                            stickerData = $" [{receivedMessage.StickerName}](https://media.discordapp.net/stickers/{receivedMessage.StickerId}.webp?size=160&quality=lossless)";
                        }
                        else
                        {
                            stickerData = $" [{receivedMessage.StickerName}]";
                        }
                    var attachments = receivedMessage.Attachments;
                    if (attachments != null)
                    {
                        foreach (var attachment in attachments)
                        {
                            seString.Append(new UIForegroundPayload(25));
                            if (!Configuration.HideAttachmentUrls)
                            {
                                seString.Append($"\nAttachment:\n[{attachment.Filename}]({attachment.Url})");
                            }
                            else
                            {
                                seString.Append($"\nAttachment:\n{attachment.Filename}");
                            }
                            seString.Append(UIForegroundPayload.UIForegroundOff);
                        }
                    }
                    seString.Append(new UIForegroundPayload(25));
                    seString.Append(stickerData);
                    if(stickerData == "" && receivedMessage.Content == null) return;
                    seString.Append(UIForegroundPayload.UIForegroundOff);
                    ChatGui.Print(seString);
                }
                catch (Exception ex)
                {
                    PluginLog.Error($"Failed to process message: {ex.Message}");
                }
            };
        });
    }
    private void StopWebSocketServer()
    {
        if (webSocketServer != null)
        {
            IsWebSocketServerRunning = false;
            PluginLog.Information("Stopping WebSocket server...");

            foreach (var socket in connectedClients)
            {
                if (socket.IsAvailable)
                {
                    socket.Close();
                }
            }

            webSocketServer.Dispose();
            cancellationTokenSource.Cancel();
            PluginLog.Information("WebSocket server stopped.");
        }
    }
    

    public void ToggleConfigUI() => ConfigWindow.Toggle();
    public void ToggleMainUI() => MainWindow.Toggle();
    private void DrawUI() => WindowSystem.Draw();
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage