forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquote_rewriter.rb
75 lines (58 loc) · 2.17 KB
/
quote_rewriter.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
# frozen_string_literal: true
class QuoteRewriter
def initialize(user_id)
@user_id = user_id
end
def rewrite_raw_username(raw, old_username, new_username)
pattern =
Regexp.union(
/(?<pre>\[quote\s*=\s*["'']?.*username:)#{old_username}(?<post>\,?[^\]]*\])/i,
/(?<pre>\[quote\s*=\s*["'']?)#{old_username}(?<post>\,?[^\]]*\])/i,
)
raw.gsub(pattern, "\\k<pre>#{new_username}\\k<post>")
end
def rewrite_cooked_username(cooked, old_username, new_username, avatar_img)
pattern = /(?<=\s)#{PrettyText::Helpers.format_username(old_username)}(?=:)/i
cooked
.css("aside.quote")
.each do |aside|
next unless div = aside.at_css("div.title")
username_replaced = false
aside["data-username"] = new_username if aside["data-username"] == old_username
div.children.each do |child|
if child.text?
content = child.content
username_replaced = content.gsub!(pattern, new_username).present?
child.content = content if username_replaced
end
end
if username_replaced || quotes_correct_user?(aside)
div.at_css("img.avatar")&.replace(avatar_img)
end
end
end
def rewrite_raw_display_name(raw, old_display_name, new_display_name)
pattern = /(?<pre>\[quote\s*=\s*["'']?)#{old_display_name}(?<post>\,[^\]]*username[^\]]*\])/i
raw.gsub(pattern, "\\k<pre>#{new_display_name}\\k<post>")
end
def rewrite_cooked_display_name(cooked, old_display_name, new_display_name)
pattern = /(?<=\s)#{PrettyText::Helpers.format_username(old_display_name)}(?=:)/i
cooked
.css("aside.quote")
.each do |aside|
next unless div = aside.at_css("div.title")
div.children.each do |child|
if child.text?
content = child.content
display_name_replaced = content.gsub!(pattern, new_display_name).present?
child.content = content if display_name_replaced
end
end
end
end
private
attr_reader :user_id
def quotes_correct_user?(aside)
Post.exists?(topic_id: aside["data-topic"], post_number: aside["data-post"], user_id: user_id)
end
end