summary refs log tree commit diff
path: root/MatrixLogFwd/Program.cs
blob: ec90a074887c4278d67fefa10dd6830ed04c6e80 (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
// See https://aka.ms/new-console-template for more information

using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using ArcaneLibs;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.RoomTypes;
using MatrixLogFwd;
using Microsoft.VisualBasic.CompilerServices;

Console.WriteLine("Hello, World!");
var cfgPath = Util.ExpandPath($"~/.config/MatrixLogFwd/config.json");
var cfg = JsonSerializer.Deserialize<Config>(System.IO.File.ReadAllText(cfgPath));

var hs = new AuthenticatedHomeserverGeneric(cfg.HomeserverBaseUrl, new(){Client = cfg.HomeserverBaseUrl}, null, cfg.AccessToken);
await hs.Initialise();
Console.WriteLine(hs);

string mode = "lines";
int chunkSize = 1000;
bool stripIpv4 = false;
string? command = null;
GenericRoom? room = null;

var argsEnum = args.AsEnumerable().GetEnumerator();
while (argsEnum.MoveNext())
{
    var arg = argsEnum.Current;
    switch (arg)
    {
        case "--help":
            Console.WriteLine("Usage: MatrixLogFwd [--help] [--mode <file|lines>] [--chunk-size <int>] [-- <command>]");
            break;
        case "--mode":
            argsEnum.MoveNext();
            mode = argsEnum.Current;
            if (mode != "file" && mode != "lines")
            {
                Console.WriteLine("Invalid mode");
                return;
            }
            break;
        case "--strip-ipv4":
            stripIpv4 = true;
            break;
        case "--chunk-size":
            argsEnum.MoveNext();
            chunkSize = Conversions.ToInteger(argsEnum.Current);
            break;
        case "--roomid":
            argsEnum.MoveNext();
            var roomId = argsEnum.Current;
            room = hs.GetRoom(roomId);
            break;
        
        case "--":
            command = "";
            while (argsEnum.MoveNext())
            {
                command += argsEnum.Current + " ";
            }
            break;
    }
}

if (room == null)
{
    Console.WriteLine("No room specified, creating new room");
    room = await hs.CreateRoom(new()
    {
        Name = $"MatrixLogFwd logs from {Environment.MachineName} at {DateTime.Now}",
    });
}

var stream = Console.OpenStandardInput();
if (!string.IsNullOrWhiteSpace(command))
{
    var proc = new System.Diagnostics.Process
    {
        StartInfo = new()
        {
            FileName = "/bin/sh",
            Arguments = $"-c \"{command}\"",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        }
    };
    proc.Start();
    stream = proc.StandardOutput.BaseStream;
}

if (mode == "lines")
{
    var buffer = new byte[1024];
    var line = new StringBuilder();
    int linesInBuffer = 0;
    while (true)
    {
        var read = await stream.ReadAsync(buffer);
        Console.WriteLine($"Read {read} bytes");
        if (read == 0)
        {
            await room.SendMessageEventAsync(new MessageBuilder().WithCodeBlock(line.ToString()).Build());
            break;
        }
        for (int i = 0; i < read; i++)
        {
            if (buffer[i] == '\n')
            {
                linesInBuffer++;
                if (linesInBuffer > chunkSize)
                {
                    if (stripIpv4)
                    {
                        var lineStr = line.ToString();
                        lineStr = Ipv4Regex().Replace(lineStr, "[REDACTED_IP]");
                        line.Clear();
                        line.Append(lineStr);
                    }
                    
                    await room.SendMessageEventAsync(new MessageBuilder().WithCodeBlock(line.ToString()).Build());
                    line.Clear();
                    linesInBuffer = 0;
                }
                else
                {
                    line.Append((char)buffer[i]);
                }
            }
            else
            {
                line.Append((char)buffer[i]);
            }
        }
    }
}
else
{
    var buffer = new byte[chunkSize];
    while (true)
    {
        var read = await stream.ReadAtLeastAsync(buffer, chunkSize, false);
        if (read == 0)
        {
            break;
        }
        Console.WriteLine($"Read {read} bytes");
        var ms = new MemoryStream(buffer, 0, read);
        var filename = $"log-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.txt";
        await room.SendFileAsync(filename, ms);
    }
}

partial class Program
{
    [GeneratedRegex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
    private static partial Regex Ipv4Regex();
}

// await room.LeaveAsync();