aboutsummaryrefslogtreecommitdiff
path: root/ShiftOS.Server/ChatBackend.cs
blob: 1c98a096e844b5fba4846519fb20a36793297651 (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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShiftOS.Objects;
using NetSockets;
using Newtonsoft.Json;
using System.IO;
using static ShiftOS.Server.Program;
using Discord;
using Discord.WebSocket;
using Discord.Net.WebSockets;

namespace ShiftOS.Server
{
    public static class ChatBackend
    {
        public static async Task StartDiscordBots()
        {
            Reinitialized?.Invoke();
            if (!File.Exists("chats.json"))
                File.WriteAllText("chats.json", "[]");
            foreach (var chat in JsonConvert.DeserializeObject<List<ShiftOS.Objects.Channel>>(File.ReadAllText("chats.json")))
            {
                string chatID = chat.ID;
                bool chatKilled = false;
                if (chat.IsDiscordProxy == true)
                {
                    DiscordSocketConfig builder = new DiscordSocketConfig();
                    builder.AudioMode = Discord.Audio.AudioMode.Disabled;
                    builder.WebSocketProvider = () => Discord.Net.Providers.WS4Net.WS4NetProvider.Instance();
                    var client = new DiscordSocketClient(builder);
                    await client.LoginAsync(TokenType.Bot, chat.DiscordBotToken);

                    await client.ConnectAsync();
                    await client.SetGameAsync("ShiftOS");
                    await client.SetStatusAsync(UserStatus.Online);
                    //Get the Discord channel for this chat.
                    var Chan = client.GetChannel(Convert.ToUInt64(chat.DiscordChannelID)) as ISocketMessageChannel;
                    //Relay the message to Discord.
                    await Chan.SendMessageAsync("**Hello! Multi-user domain is online.**");

                    client.MessageReceived += async (s) =>
                    {
                        if (chatKilled == false)
                        {
                            if (s.Channel.Id == Convert.ToUInt64(chat.DiscordChannelID))
                            {
                                if (s.Author.Id != client.CurrentUser.Id)
                                {
                                    server.DispatchAll(new NetObject("chat_msgreceived", new ServerMessage
                                    {
                                        Name = "chat_msgreceived",
                                        GUID = "server",
                                        Contents = JsonConvert.SerializeObject(new ChatMessage(s.Author.Username, "discord_" + s.Channel.Name, (s as SocketUserMessage).Resolve(0), chatID))
                                    }));
                                }
                            }
                        }
                    };
                    MessageReceived += (g, msg) =>
                    {
                        if (chatKilled == false)
                        {
                            //Determine if the message was sent to this channel.
                            if (msg.Channel == chat.ID)
                            {
                                //Get the Discord channel for this chat.
                                var dChan = client.GetChannel(Convert.ToUInt64(chat.DiscordChannelID)) as ISocketMessageChannel;
                                //Relay the message to Discord.
                                dChan.SendMessageAsync($"**[{msg.Username}@{msg.SystemName}]** `<mud/{msg.Channel}>` {msg.Message}");

                            }
                            //Relay it back to all MUD clients.
                            RelayMessage(g, msg);
                        }
                    };
                    Reinitialized += () =>
                    {
                        client.DisconnectAsync();
                        
                        chatKilled = true;
                    };
                }
                else
                {
                    MessageReceived += (g, msg) =>
                    {
                        if (chatKilled == false)
                        {
                            //Just relay it.
                            RelayMessage(g, msg);
                        }
                    };
                    Reinitialized += () => { chatKilled = true; };
                }
            }
        }

        internal static void RelayMessage(string guid, ChatMessage msg)
        {
            server.DispatchAllExcept(new Guid(guid), new NetObject("chat_msgreceived", new ServerMessage
            {
                Name = "chat_msgreceived",
                GUID = "server",
                Contents = JsonConvert.SerializeObject(msg)
            }));

        }

        public static event Action<string, ChatMessage> MessageReceived;
        public static event empty Reinitialized;


        public delegate void empty();

        [MudRequest("chat_getallchannels", null)]
        public static void GetAllChannels(string guid, object contents)
        {
            server.DispatchTo(new Guid(guid), new NetObject("chat_all", new ServerMessage
            {
                Name = "chat_all",
                GUID = "Server",
                Contents = (File.Exists("chats.json") == true) ? File.ReadAllText("chats.json") : "[]"
            }));
        }

        [MudRequest("chat_send", typeof(Dictionary<string, string>))]
        public static void ReceiveMessage(string guid, object contents)
        {
            var msg = contents as Dictionary<string, string>;
            MessageReceived?.Invoke(guid, new ChatMessage(msg["Username"], msg["SystemName"], msg["Message"], msg["Channel"]));

        }
    }

}