-
Notifications
You must be signed in to change notification settings - Fork 2
/
MysqlPostReader.cs
273 lines (243 loc) · 9.93 KB
/
MysqlPostReader.cs
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
// https://github.com/abock/goodbye-wordpress
// Copyright 2020 Aaron Bockover.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using MySqlConnector;
using Serilog;
using Serilog.Events;
using Serilog.Parsing;
namespace Goodbye.WordPress
{
public sealed class MysqlPostReader : IPostReader
{
static readonly HashSet<int> s_supportedDatabaseVersions = new()
{
// https://codex.wordpress.org/WordPress_Versions
38590, // 4.7 (Dec 6, 2016) through 4.9.15 (Jun 10, 2020)
49752, // 5.7 (Mar 9, 2021) through 5.8.2 (Present)
};
public ConnectionStringBuilder ConnectionString { get; }
public bool IgnoreUnsupportedDatabaseVersion { get; }
public MysqlPostReader(
ConnectionStringBuilder connectionString,
bool ignoreUnsupportedDatabaseVersion = false)
{
ConnectionString = new ConnectionStringBuilder(
connectionString.Parameters.Add(("ConvertZeroDateTime", "true")));
IgnoreUnsupportedDatabaseVersion = ignoreUnsupportedDatabaseVersion;
}
public async IAsyncEnumerable<Post> ReadPostsAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
string? originalPermalinkStructure = null;
using var connection = new MySqlConnection(ConnectionString);
try
{
await connection.OpenAsync(cancellationToken);
}
catch (Exception e)
{
throw new ConnectionFailedException(e);
}
var dbSupported = false;
var dbVersion = 0;
try
{
dbSupported = await new MySqlCommand(
"SELECT option_value FROM wp_options WHERE option_name = 'db_version'",
connection).ExecuteScalarAsync(cancellationToken)
is string dbVersionString &&
int.TryParse(dbVersionString, out dbVersion) &&
s_supportedDatabaseVersions.Contains(dbVersion);
}
catch
{
}
if (!dbSupported)
{
var e = new WordPressDbNotSupportedException(
s_supportedDatabaseVersions
.OrderByDescending(v => v)
.ToArray(),
dbVersion);
if (IgnoreUnsupportedDatabaseVersion)
Log.Write(e.LogEvent);
else
throw e;
}
try
{
if (await new MySqlCommand(
"SELECT option_value FROM wp_options WHERE option_name = 'permalink_structure'",
connection).ExecuteScalarAsync(cancellationToken)
is string permalinkStructure &&
permalinkStructure.Length > 0)
originalPermalinkStructure = permalinkStructure;
}
catch
{
}
var command = new MySqlCommand(@"
SELECT
p.id AS ID,
p.post_status AS Status,
p.post_date AS PublishedLocalDate,
p.post_date_gmt AS PublishedUtcDate,
p.post_modified AS UpdatedLocalDate,
p.post_modified_gmt AS UpdatedUtcDate,
p.post_name AS Name,
p.post_title AS Title,
COALESCE(
GROUP_CONCAT(DISTINCT c.name SEPARATOR ';'),
'NULL'
) AS Category,
COALESCE(
GROUP_CONCAT(DISTINCT t.name SEPARATOR ';'),
'NULL'
) AS Tags,
p.post_content AS Content
FROM wp_posts p
LEFT JOIN wp_term_relationships cr
ON (p.id = cr.object_id)
LEFT JOIN wp_term_taxonomy ct
ON (ct.term_taxonomy_id = cr.term_taxonomy_id
AND ct.taxonomy = 'category')
LEFT JOIN wp_terms c
ON (ct.term_id = c.term_id)
LEFT JOIN wp_term_relationships tr
ON (p.id = tr.object_id)
LEFT JOIN wp_term_taxonomy tt
ON (tt.term_taxonomy_id = tr.term_taxonomy_id
AND tt.taxonomy = 'post_tag')
LEFT JOIN wp_terms t
ON (tt.term_id = t.term_id)
WHERE
p.post_type = 'post'
GROUP BY p.id
", connection);
var reader = await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var postId = reader.GetInt32("ID");
var publishedDate = ParseDate(
reader.GetDateTime("PublishedLocalDate"),
reader.GetDateTime("PublishedUtcDate"));
var updatedDate = ParseDate(
reader.GetDateTime("UpdatedLocalDate"),
reader.GetDateTime("UpdatedUtcDate"));
if (publishedDate is null)
continue;
var postName = reader.GetString("Name");
var originalUrl = ExpandPermalinkStructure(
originalPermalinkStructure,
publishedDate.Value,
postId,
postName);
yield return new Post(
postId,
reader.GetString("Status"),
publishedDate,
updatedDate,
postName,
reader.GetString("Title"),
reader.GetString("Category")
.Split(";")
.Select(c => c.Trim().ToLowerInvariant())
.ToImmutableList(),
reader.GetString("Tags")
.Split(";")
.Select(t => t.Trim().ToLowerInvariant())
.ToImmutableList(),
reader.GetString("Content"),
originalUrl is null
? ImmutableList<string>.Empty
: ImmutableList.Create(originalUrl),
ImmutableList<PostResource>.Empty);
}
}
static DateTimeOffset? ParseDate(DateTime localDate, DateTime utcDate)
=> localDate > DateTime.MinValue && utcDate > DateTime.MinValue
? new DateTimeOffset(localDate, localDate - utcDate)
: null;
static string? ExpandPermalinkStructure(
string? originalPermalinkStructure,
DateTimeOffset date,
int id,
string name)
{
if (string.IsNullOrEmpty(originalPermalinkStructure))
return null;
return Regex.Replace(
originalPermalinkStructure,
"%(?<key>[^%]+)%",
match =>
{
var key = match.Groups["key"].Value;
return key.ToLowerInvariant() switch
{
"year" => $"{date:yyyy}",
"monthnum" => $"{date:MM}",
"day" => $"{date:dd}",
"hour" => $"{date:HH}",
"minute" => $"{date:mm}",
"second" => $"{date:ss}",
"post_id" => id.ToString(CultureInfo.InvariantCulture),
"postname" => name,
_ => key,
};
});
}
}
public sealed class WordPressDbNotSupportedException : Exception
{
public IReadOnlyList<int> SupportedVersions { get; }
public int EncounteredVersion { get; }
public LogEvent LogEvent { get; }
WordPressDbNotSupportedException(
IReadOnlyList<int> supportedVersions,
int encounteredVersion,
LogEvent logEvent)
: base(logEvent.RenderMessage())
{
SupportedVersions = supportedVersions;
EncounteredVersion = encounteredVersion;
LogEvent = logEvent;
}
internal WordPressDbNotSupportedException(
IReadOnlyList<int> supportedVersions,
int encounteredVersion)
: this(
supportedVersions,
encounteredVersion,
new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Warning,
null,
new MessageTemplateParser().Parse(
"Unsupported datbase version {EncounteredVersion}; supported versions: {SupportedVersions}. " +
"See https://codex.wordpress.org/WordPress_Versions for a list of all database versions. " +
"Add your version to MysqlPostReader.supportedDatabaseVersions and if things work, " +
"submit a pull request please!"),
new[]
{
new LogEventProperty(
"EncounteredVersion",
new ScalarValue(encounteredVersion)),
new LogEventProperty(
"SupportedVersions",
new SequenceValue(
supportedVersions.Select(
v => new ScalarValue(v))))
}))
{
}
}
}