/
d_text.rb
430 lines (379 loc) · 15.6 KB
/
d_text.rb
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
require 'cgi'
require 'uri'
# The DText class handles Danbooru's markup language, DText. Parsing DText is
# handled by the DTextRagel class in the dtext_rb gem.
#
# @see https://github.com/evazion/dtext_rb
# @see https://danbooru.donmai.us/wiki_pages/help:dtext
class DText
MENTION_REGEXP = /(?<=^| )@\S+/
# Convert a string of DText to HTML.
# @param text [String] The DText input
# @param inline [Boolean] if true, allow only inline constructs. Ignore
# block-level constructs, such as paragraphs, quotes, lists, and tables.
# @param disable_mentions [Boolean] if true, don't generate @mentions.
# @param base_url [String, nil] if present, convert relative URLs to absolute URLs.
# @param data cached wiki/tag/artist data generated by {#preprocess}.
# @return [String, nil] The HTML output
def self.format_text(text, data: nil, inline: false, disable_mentions: false, base_url: nil)
return nil if text.nil?
data = preprocess([text]) if data.nil?
text = parse_embedded_tag_request(text)
html = DTextRagel.parse(text, inline: inline, disable_mentions: disable_mentions, base_url: base_url)
html = postprocess(html, *data)
html
rescue DTextRagel::Error
""
end
# Preprocess a set of DText messages and collect all tag, artist, and wiki
# page references. Called before rendering a collection of DText messages
# (e.g. comments or forum posts) to do all database lookups in one batch.
# @param [Array<String>] a list of DText strings
# @return an array of wiki pages, tags, and artists
def self.preprocess(dtext_messages)
dtext_messages = dtext_messages.map { |message| parse_embedded_tag_request(message) }
names = dtext_messages.map { |message| parse_wiki_titles(message) }.flatten.uniq
wiki_pages = WikiPage.where(title: names)
tags = Tag.where(name: names)
artists = Artist.where(name: names)
[wiki_pages, tags, artists]
end
# Rewrite the HTML produced by {#format_text} to colorize wiki links.
# @param wiki_pages [Array<WikiPage>]
# @param tags [Array<Tag>]
# @param artists [Array<Artist>]
# @return [String] the HTML output
def self.postprocess(html, wiki_pages, tags, artists)
fragment = Nokogiri::HTML5.fragment(html)
fragment.css("a.dtext-wiki-link").each do |node|
path = Addressable::URI.parse(node["href"]).path
name = path[%r!\A/wiki_pages/(.*)\z!i, 1]
name = CGI.unescape(name)
name = WikiPage.normalize_title(name)
wiki = wiki_pages.find { |wiki| wiki.title == name }
tag = tags.find { |tag| tag.name == name }
artist = artists.find { |artist| artist.name == name }
if tag.present? && tag.artist?
node["href"] = "/artists/show_or_new?name=#{CGI.escape(name)}"
if artist.blank?
node["class"] += " dtext-artist-does-not-exist"
node["title"] = "This artist page does not exist"
end
node["class"] += " tag-type-#{tag.category}"
else
if wiki.blank?
node["class"] += " dtext-wiki-does-not-exist"
node["title"] = "This wiki page does not exist"
end
if WikiPage.is_meta_wiki?(name)
# skip (meta wikis aren't expected to have a tag)
elsif tag.blank?
node["class"] += " dtext-tag-does-not-exist"
node["title"] = "This wiki page does not have a tag"
elsif tag.empty?
node["class"] += " dtext-tag-empty"
node["title"] = "This wiki page does not have a tag"
else
node["class"] += " tag-type-#{tag.category}"
end
end
end
fragment.to_s
end
# Wrap a DText message in a [quote] block.
# @param message [String] the DText to quote
# @param creator_name [String] the name of the user to quote.
# @return [String] the quoted DText
def self.quote(message, creator_name)
stripped_body = DText.strip_blocks(message, "quote")
"[quote]\n#{creator_name} said:\n\n#{stripped_body}\n[/quote]\n\n"
end
# Convert `[bur:<id>]`, `[ta:<id>]`, `[ti:<id>]` tags to DText.
# @param text [String] the DText input
# @return [String] the DText output
def self.parse_embedded_tag_request(text)
text = parse_embedded_tag_request_type(text, TagAlias, /\[ta:(?<id>\d+)\]/m)
text = parse_embedded_tag_request_type(text, TagImplication, /\[ti:(?<id>\d+)\]/m)
text = parse_embedded_tag_request_type(text, BulkUpdateRequest, /\[bur:(?<id>\d+)\]/m)
text
end
# Convert a `[bur:<id>]`, `[ta:<id>]`, or `[ti:<id>]` tag to DText.
# @param text [String] the DText input
# @param tag_request [BulkUpdateRequest, TagAlias, TagImplication]
# @param pattern [Regexp]
# @return [String] the DText output
def self.parse_embedded_tag_request_type(text, tag_request, pattern)
text.gsub(pattern) do |match|
obj = tag_request.find_by_id($~[:id])
tag_request_message(obj) || match
end
end
# Convert a `[bur:<id>]`, `[ta:<id>]`, or `[ti:<id>]` tag to DText.
# @param obj [BulkUpdateRequest, TagAlias, TagImplication] the object to convert
# @return [String] the DText output
def self.tag_request_message(obj)
if obj.is_a?(TagRelationship)
if obj.is_active?
"The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has been approved."
elsif obj.is_retired?
"The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has been retired."
elsif obj.is_deleted?
"The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has been rejected."
elsif obj.is_pending?
"The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] is pending approval."
else # should never happen
"The #{obj.relationship} ##{obj.id} [[#{obj.antecedent_name}]] -> [[#{obj.consequent_name}]] has an unknown status."
end
elsif obj.is_a?(BulkUpdateRequest)
if obj.script.size < 700
embedded_script = obj.processor.to_dtext
else
embedded_script = "[expand]#{obj.processor.to_dtext}[/expand]"
end
if obj.is_approved?
"The \"bulk update request ##{obj.id}\":#{Routes.bulk_update_request_path(obj)} has been approved by <@#{obj.approver.name}>.\n\n#{embedded_script}"
elsif obj.is_pending?
"The \"bulk update request ##{obj.id}\":#{Routes.bulk_update_request_path(obj)} is pending approval.\n\n#{embedded_script}"
elsif obj.is_rejected?
"The \"bulk update request ##{obj.id}\":#{Routes.bulk_update_request_path(obj)} has been rejected.\n\n#{embedded_script}"
end
end
end
# Return a list of user names mentioned in a string of DText. Ignore mentions in [quote] blocks.
# @param text [String] the string of DText
# @return [Array<String>] the list of user names
def self.parse_mentions(text)
text = strip_blocks(text.to_s, "quote")
names = text.scan(MENTION_REGEXP).map do |mention|
mention.gsub(/(?:^\s*@)|(?:[:;,.!?\)\]<>]$)/, "")
end
names.uniq
end
# Return a list of wiki pages mentioned in a string of DText.
# @param text [String] the string of DText
# @return [Array<String>] the list of wiki page names
def self.parse_wiki_titles(text)
html = DTextRagel.parse(text)
fragment = Nokogiri::HTML5.fragment(html)
titles = fragment.css("a.dtext-wiki-link").map do |node|
title = node["href"][%r{\A/wiki_pages/(.*)\z}i, 1]
title = CGI.unescape(title)
title = WikiPage.normalize_title(title)
title
end
titles.uniq
end
# Return a list of external links mentioned in a string of DText.
# @param text [String] the string of DText
# @return [Array<String>] the list of external URLs
def self.parse_external_links(text)
html = DTextRagel.parse(text)
fragment = Nokogiri::HTML5.fragment(html)
links = fragment.css("a.dtext-external-link").map { |node| node["href"] }
links.uniq
end
# Return whether the two strings of DText have the same set of links.
# @param a [String] a string of DText
# @param b [String] a string of DText
# @return [Boolean]
def self.dtext_links_differ?(a, b)
Set.new(parse_wiki_titles(a)) != Set.new(parse_wiki_titles(b)) ||
Set.new(parse_external_links(a)) != Set.new(parse_external_links(b))
end
# Rewrite wiki links to [[old_name]] with [[new_name]]. We attempt to match
# the capitalization of the old tag when rewriting it to the new tag, but if
# we can't determine how the new tag should be capitalized based on some
# simple heuristics, then we skip rewriting the tag.
# @param dtext [String] the DText input
# @param old_name [String] the old wiki name
# @param new_name [String] the new wiki name
# @return [String] the DText output
def self.rewrite_wiki_links(dtext, old_name, new_name)
old_name = old_name.downcase.squeeze("_").tr("_", " ").strip
new_name = new_name.downcase.squeeze("_").tr("_", " ").strip
# Match `[[name]]` or `[[name|title]]`
dtext.gsub(/\[\[(.*?)(?:\|(.*?))?\]\]/) do |match|
name = $1
title = $2
# Skip this link if it isn't the tag we're trying to replace.
normalized_name = name.downcase.tr("_", " ").squeeze(" ").strip
next match if normalized_name != old_name
# Strip qualifiers, e.g. `atago (midsummer march) (azur lane)` => `atago`
unqualified_name = name.tr("_", " ").squeeze(" ").strip.gsub(/( \(.*\))+\z/, "")
# If old tag was lowercase, e.g. [[ink tank (Splatoon)]], then keep new tag in lowercase.
if unqualified_name == unqualified_name.downcase
final_name = new_name
# If old tag was capitalized, e.g. [[Colored pencil (medium)]], then capitialize new tag.
elsif unqualified_name == unqualified_name.downcase.capitalize
final_name = new_name.capitalize
# If old tag was in titlecase, e.g. [[Hatsune Miku (cosplay)]], then titlecase new tag.
elsif unqualified_name == unqualified_name.split.map(&:capitalize).join(" ")
final_name = new_name.split.map(&:capitalize).join(" ")
# If we can't determine how to capitalize the new tag, then keep the old tag.
# e.g. [[Suzumiya Haruhi no Yuuutsu]] -> [[The Melancholy of Haruhi Suzumiya]]
else
next match
end
if title.present?
"[[#{final_name}|#{title}]]"
# If the new name has a qualifier, then hide the qualifier in the link.
elsif final_name.match?(/( \(.*\))+\z/)
"[[#{final_name}|]]"
else
"[[#{final_name}]]"
end
end
end
# Remove all [<tag>] blocks from the DText.
# @param string [String] the DText input
# @param tag [String] the type of block to remove
# @return [String] the DText output
def self.strip_blocks(string, tag)
n = 0
stripped = ""
string = string.dup
string.gsub!(/\s*\[#{tag}\](?!\])\s*/mi, "\n\n[#{tag}]\n\n")
string.gsub!(%r{\s*\[/#{tag}\]\s*}mi, "\n\n[/#{tag}]\n\n")
string.gsub!(/(?:\r?\n){3,}/, "\n\n")
string.strip!
string.split(/\n{2}/).each do |block|
case block
when "[#{tag}]"
n += 1
when "[/#{tag}]"
n -= 1
else
if n == 0
stripped << "#{block}\n\n"
end
end
end
stripped.strip
end
# Remove all DText formatting from a string of DText, converting it to plain text.
# @param dtext [String] the DText input
# @return [String] the plain text output
def self.strip_dtext(dtext)
html = DTextRagel.parse(dtext)
text = to_plaintext(html)
text
end
# Remove all formatting from a string of HTML, converting it to plain text.
# @param html [String] the HTML input
# @return [String] the plain text output
def self.to_plaintext(html)
text = from_html(html) do |node|
case node.name
when "a", "strong", "em", "u", "s", "h1", "h2", "h3", "h4", "h5", "h6"
node.name = "span"
node.content = node.text
when "blockquote"
node.name = "span"
node.content = to_plaintext(node.inner_html).gsub(/^/, "> ")
end
end
text.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "")
end
# Convert DText formatting to Markdown.
# @param dtext [String] the DText input
# @return [String] the Markdown output
def self.to_markdown(dtext)
html_to_markdown(format_text(dtext))
end
# Convert HTML to Markdown.
# @param html [String] the HTML input
# @return [String] the Markdown output
def self.html_to_markdown(html)
html = Nokogiri::HTML5.fragment(html)
html.children.map do |node|
case node.name
when "div", "blockquote", "table"
"" # strip [expand], [quote], and [table] tags
when "br"
"\n"
when "text"
node.text.gsub(/_/, '\_').gsub(/\*/, '\*')
when "p", "h1", "h2", "h3", "h4", "h5", "h6"
html_to_markdown(node.inner_html) + "\n\n"
else
html_to_markdown(node.inner_html)
end
end.join
end
# Convert HTML to DText.
# @param html [String] the HTML input
# @param inline [Boolean] if true, convert <img> tags to plaintext
# @return [String] the DText output
def self.from_html(text, inline: false, &block)
html = Nokogiri::HTML5.fragment(text)
dtext = html.children.map do |element|
block.call(element) if block.present?
case element.name
when "text"
element.content.gsub(/(?:\r|\n)+$/, "")
when "br"
"\n"
when "p", "ul", "ol"
from_html(element.inner_html, &block).strip + "\n\n"
when "blockquote"
"[quote]#{from_html(element.inner_html, &block).strip}[/quote]\n\n" if element.inner_html.present?
when "small", "sub"
"[tn]#{from_html(element.inner_html, &block)}[/tn]" if element.inner_html.present?
when "b", "strong"
"[b]#{from_html(element.inner_html, &block)}[/b]" if element.inner_html.present?
when "i", "em"
"[i]#{from_html(element.inner_html, &block)}[/i]" if element.inner_html.present?
when "u"
"[u]#{from_html(element.inner_html, &block)}[/u]" if element.inner_html.present?
when "s", "strike"
"[s]#{from_html(element.inner_html, &block)}[/s]" if element.inner_html.present?
when "li"
"* #{from_html(element.inner_html, &block)}\n" if element.inner_html.present?
when "h1", "h2", "h3", "h4", "h5", "h6"
hN = element.name
title = from_html(element.inner_html, &block)
"#{hN}. #{title}\n\n"
when "a"
title = from_html(element.inner_html, inline: true, &block).strip
url = element["href"]
if title.blank? || url.blank?
""
elsif title == url
"<#{url}>"
else
%("#{title}":[#{url}])
end
when "img"
alt_text = element.attributes["title"] || element.attributes["alt"] || ""
src = element["src"]
if inline
alt_text
elsif alt_text.present? && src.present?
%("#{alt_text}":[#{src}]\n\n)
else
""
end
when "comment"
# ignored
else
from_html(element.inner_html, &block)
end
end.join
dtext
end
# Return the first paragraph the search string `needle` occurs in.
# @param needle [String] the string to search for
# @param dtext [String] the DText input
# @return [String] the first paragraph mentioning the search string
def self.extract_mention(dtext, needle)
dtext = dtext.gsub(/\r\n|\r|\n/, "\n")
excerpt = ActionController::Base.helpers.excerpt(dtext, needle, separator: "\n\n", radius: 1, omission: "")
excerpt
end
# Generate a short plain text excerpt from a DText string.
# @param length [Integer] the max length of the output
# @return [String] a plain text string
def self.excerpt(text, length: 160)
strip_dtext(text).split(/\r\n|\r|\n/).first.to_s.truncate(length)
end
end