summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework/LogParsing/LogParser.cs
blob: 4e61ac959ec4e04a2ed9048e6e8f1cbbfc1d2ab3 (plain)
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#nullable disable

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using StardewModdingAPI.Web.Framework.LogParsing.Models;

namespace StardewModdingAPI.Web.Framework.LogParsing
{
    /// <summary>Parses SMAPI log files.</summary>
    public class LogParser
    {
        /*********
        ** Fields
        *********/
        /// <summary>A regex pattern matching the start of a SMAPI message.</summary>
        private readonly Regex MessageHeaderPattern = new(@"^\[(?<time>\d\d[:\.]\d\d[:\.]\d\d) (?<level>[a-z]+)(?: +screen_(?<screen>\d+))? +(?<modName>[^\]]+)\] ", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching SMAPI's initial platform info message.</summary>
        private readonly Regex InfoLinePattern = new(@"^SMAPI (?<apiVersion>.+) with Stardew Valley (?<gameVersion>.+) on (?<os>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching SMAPI's mod folder path line.</summary>
        private readonly Regex ModPathPattern = new(@"^Mods go here: (?<path>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching SMAPI's log timestamp line.</summary>
        private readonly Regex LogStartedAtPattern = new(@"^Log started at (?<timestamp>.+) UTC", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching the start of SMAPI's mod list.</summary>
        private readonly Regex ModListStartPattern = new(@"^Loaded \d+ mods:$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching an entry in SMAPI's mod list.</summary>
        /// <remarks>The author name and description are optional.</remarks>
        private readonly Regex ModListEntryPattern = new(@"^   (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))?(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching the start of SMAPI's content pack list.</summary>
        private readonly Regex ContentPackListStartPattern = new(@"^Loaded \d+ content packs:$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching an entry in SMAPI's content pack list.</summary>
        private readonly Regex ContentPackListEntryPattern = new(@"^   (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))? \| for (?<for>[^\|]+)(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching the start of SMAPI's mod update list.</summary>
        private readonly Regex ModUpdateListStartPattern = new(@"^You can update \d+ mods?:$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching an entry in SMAPI's mod update list.</summary>
        private readonly Regex ModUpdateListEntryPattern = new(@"^   (?<name>.+) (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>A regex pattern matching SMAPI's update line.</summary>
        private readonly Regex SmapiUpdatePattern = new(@"^You can update SMAPI to (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);


        /*********
        ** Public methods
        *********/
        /// <summary>Parse SMAPI log text.</summary>
        /// <param name="logText">The SMAPI log text.</param>
        public ParsedLog Parse(string logText)
        {
            try
            {
                // skip if empty
                if (string.IsNullOrWhiteSpace(logText))
                {
                    return new ParsedLog
                    {
                        IsValid = false,
                        RawText = logText,
                        Error = "The log is empty."
                    };
                }

                // init log
                ParsedLog log = new()
                {
                    IsValid = true,
                    RawText = logText,
                    Messages = this.CollapseRepeats(this.GetMessages(logText)).ToArray()
                };

                // parse log messages
                LogModInfo smapiMod = new() { Name = "SMAPI", Author = "Pathoschild", Description = "", Loaded = true };
                LogModInfo gameMod = new() { Name = "game", Author = "", Description = "", Loaded = true };
                IDictionary<string, List<LogModInfo>> mods = new Dictionary<string, List<LogModInfo>>();
                bool inModList = false;
                bool inContentPackList = false;
                bool inModUpdateList = false;
                foreach (LogMessage message in log.Messages)
                {
                    // collect stats
                    if (message.Level == LogLevel.Error)
                    {
                        switch (message.Mod)
                        {
                            case "SMAPI":
                                smapiMod.Errors++;
                                break;

                            case "game":
                                gameMod.Errors++;
                                break;

                            default:
                                if (mods.TryGetValue(message.Mod, out var entries))
                                {
                                    foreach (var entry in entries)
                                        entry.Errors++;
                                }
                                break;
                        }
                    }

                    // collect SMAPI metadata
                    if (message.Mod == "SMAPI")
                    {
                        // update flags
                        inModList = inModList && message.Level == LogLevel.Info && this.ModListEntryPattern.IsMatch(message.Text);
                        inContentPackList = inContentPackList && message.Level == LogLevel.Info && this.ContentPackListEntryPattern.IsMatch(message.Text);
                        inModUpdateList = inModUpdateList && message.Level == LogLevel.Alert && this.ModUpdateListEntryPattern.IsMatch(message.Text);

                        // mod list
                        if (!inModList && message.Level == LogLevel.Info && this.ModListStartPattern.IsMatch(message.Text))
                        {
                            inModList = true;
                            message.IsStartOfSection = true;
                            message.Section = LogSection.ModsList;
                        }
                        else if (inModList)
                        {
                            Match match = this.ModListEntryPattern.Match(message.Text);
                            string name = match.Groups["name"].Value;
                            string version = match.Groups["version"].Value;
                            string author = match.Groups["author"].Value;
                            string description = match.Groups["description"].Value;

                            if (!mods.TryGetValue(name, out List<LogModInfo> entries))
                                mods[name] = entries = new List<LogModInfo>();
                            entries.Add(new LogModInfo { Name = name, Author = author, Version = version, Description = description, Loaded = true });

                            message.Section = LogSection.ModsList;
                        }

                        // content pack list
                        else if (!inContentPackList && message.Level == LogLevel.Info && this.ContentPackListStartPattern.IsMatch(message.Text))
                        {
                            inContentPackList = true;
                            message.IsStartOfSection = true;
                            message.Section = LogSection.ContentPackList;
                        }
                        else if (inContentPackList)
                        {
                            Match match = this.ContentPackListEntryPattern.Match(message.Text);
                            string name = match.Groups["name"].Value;
                            string version = match.Groups["version"].Value;
                            string author = match.Groups["author"].Value;
                            string description = match.Groups["description"].Value;
                            string forMod = match.Groups["for"].Value;

                            if (!mods.TryGetValue(name, out List<LogModInfo> entries))
                                mods[name] = entries = new List<LogModInfo>();
                            entries.Add(new LogModInfo { Name = name, Author = author, Version = version, Description = description, ContentPackFor = forMod, Loaded = true });

                            message.Section = LogSection.ContentPackList;
                        }

                        // mod update list
                        else if (!inModUpdateList && message.Level == LogLevel.Alert && this.ModUpdateListStartPattern.IsMatch(message.Text))
                        {
                            inModUpdateList = true;
                            message.IsStartOfSection = true;
                            message.Section = LogSection.ModUpdateList;
                        }
                        else if (inModUpdateList)
                        {
                            Match match = this.ModUpdateListEntryPattern.Match(message.Text);
                            string name = match.Groups["name"].Value;
                            string version = match.Groups["version"].Value;
                            string link = match.Groups["link"].Value;

                            if (mods.TryGetValue(name, out var entries))
                            {
                                foreach (var entry in entries)
                                {
                                    entry.UpdateLink = link;
                                    entry.UpdateVersion = version;
                                }
                            }

                            message.Section = LogSection.ModUpdateList;
                        }

                        else if (message.Level == LogLevel.Alert && this.SmapiUpdatePattern.IsMatch(message.Text))
                        {
                            Match match = this.SmapiUpdatePattern.Match(message.Text);
                            string version = match.Groups["version"].Value;
                            string link = match.Groups["link"].Value;
                            smapiMod.UpdateVersion = version;
                            smapiMod.UpdateLink = link;
                        }

                        // platform info line
                        else if (message.Level == LogLevel.Info && this.InfoLinePattern.IsMatch(message.Text))
                        {
                            Match match = this.InfoLinePattern.Match(message.Text);
                            log.ApiVersion = match.Groups["apiVersion"].Value;
                            log.GameVersion = match.Groups["gameVersion"].Value;
                            log.OperatingSystem = match.Groups["os"].Value;
                            smapiMod.Version = log.ApiVersion;
                        }

                        // mod path line
                        else if (message.Level == LogLevel.Info && this.ModPathPattern.IsMatch(message.Text))
                        {
                            Match match = this.ModPathPattern.Match(message.Text);
                            log.ModPath = match.Groups["path"].Value;
                            int lastDelimiterPos = log.ModPath.LastIndexOfAny(new[] { '/', '\\' });
                            log.GamePath = lastDelimiterPos >= 0
                                ? log.ModPath.Substring(0, lastDelimiterPos)
                                : log.ModPath;
                        }

                        // log UTC timestamp line
                        else if (message.Level == LogLevel.Trace && this.LogStartedAtPattern.IsMatch(message.Text))
                        {
                            Match match = this.LogStartedAtPattern.Match(message.Text);
                            log.Timestamp = DateTime.Parse(match.Groups["timestamp"].Value + "Z");
                        }
                    }
                }

                // finalize log
                gameMod.Version = log.GameVersion;
                log.Mods = new[] { gameMod, smapiMod }.Concat(mods.Values.SelectMany(p => p).OrderBy(p => p.Name)).ToArray();
                return log;
            }
            catch (LogParseException ex)
            {
                return new ParsedLog
                {
                    IsValid = false,
                    Error = ex.Message,
                    RawText = logText
                };
            }
            catch (Exception ex)
            {
                return new ParsedLog
                {
                    IsValid = false,
                    Error = $"Parsing the log file failed. Technical details:\n{ex}",
                    RawText = logText
                };
            }
        }


        /*********
        ** Private methods
        *********/
        /// <summary>Collapse consecutive repeats into the previous message.</summary>
        /// <param name="messages">The messages to filter.</param>
        private IEnumerable<LogMessage> CollapseRepeats(IEnumerable<LogMessage> messages)
        {
            LogMessage next = null;
            foreach (LogMessage message in messages)
            {
                // new message
                if (next == null)
                {
                    next = message;
                    continue;
                }

                // repeat
                if (next.Level == message.Level && next.Mod == message.Mod && next.Text == message.Text)
                {
                    next.Repeated++;
                    continue;
                }

                // non-repeat message
                yield return next;
                next = message;
            }
            yield return next;
        }

        /// <summary>Split a SMAPI log into individual log messages.</summary>
        /// <param name="logText">The SMAPI log text.</param>
        /// <exception cref="LogParseException">The log text can't be parsed successfully.</exception>
        private IEnumerable<LogMessage> GetMessages(string logText)
        {
            LogMessageBuilder builder = new();
            using StringReader reader = new(logText);
            while (true)
            {
                // read line
                string line = reader.ReadLine();
                if (line == null)
                    break;

                // match header
                Match header = this.MessageHeaderPattern.Match(line);
                bool isNewMessage = header.Success;

                // start/continue message
                if (isNewMessage)
                {
                    if (builder.Started)
                    {
                        yield return builder.Build();
                        builder.Clear();
                    }

                    var screenGroup = header.Groups["screen"];
                    builder.Start(
                        time: header.Groups["time"].Value,
                        level: Enum.Parse<LogLevel>(header.Groups["level"].Value, ignoreCase: true),
                        screenId: screenGroup.Success ? int.Parse(screenGroup.Value) : 0, // main player is always screen ID 0
                        mod: header.Groups["modName"].Value,
                        text: line.Substring(header.Length)
                    );
                }
                else
                {
                    if (!builder.Started)
                        throw new LogParseException("Found a log message with no SMAPI metadata. Is this a SMAPI log file?");

                    builder.AddLine(line);
                }
            }

            // end last message
            if (builder.Started)
                yield return builder.Build();
        }
    }
}