Filters: Make behavior of "whole word" filters consistent with the web UI when filters are non-alphanumeric (#1623)

* Fix tests build

* Make behavior of non-alphanumeric whole-word filters consistent with the web UI.
Fixes #1543

* Fix typo in filter tests
This commit is contained in:
Levi Bard 2020-01-06 16:16:54 +01:00 committed by Konrad Pozniak
parent 352ff3a2d1
commit 9d65b2ace1
3 changed files with 24 additions and 3 deletions

View file

@ -208,6 +208,7 @@ class TimelineDAOTest {
favouritesCount = 2 * statusId.toInt(),
reblogged = even,
favourited = !even,
bookmarked = false,
sensitive = even,
spoilerText = "spoier$statusId",
visibility = Status.Visibility.PRIVATE,
@ -236,6 +237,7 @@ class TimelineDAOTest {
favouritesCount = 0,
reblogged = false,
favourited = false,
bookmarked = false,
sensitive = false,
spoilerText = null,
visibility = null,

View file

@ -95,6 +95,7 @@ public abstract class SFragment extends BaseFragment implements Injectable {
private static List<Filter> filters;
private boolean filterRemoveRegex;
private Matcher filterRemoveRegexMatcher;
private static Matcher alphanumeric = Pattern.compile("^\\w+$").matcher("");
@Inject
public MastodonApi mastodonApi;
@ -520,8 +521,11 @@ public abstract class SFragment extends BaseFragment implements Injectable {
}
private static String filterToRegexToken(Filter filter) {
String phrase = Pattern.quote(filter.getPhrase());
return filter.getWholeWord() ? String.format("(^|\\W)%s($|\\W)", phrase) : phrase;
String phrase = filter.getPhrase();
String quotedPhrase = Pattern.quote(phrase);
return (filter.getWholeWord() && alphanumeric.reset(phrase).matches()) ? // "whole word" should only apply to alphanumeric filters, #1543
String.format("(^|\\W)%s($|\\W)", quotedPhrase) :
quotedPhrase;
}
public static void flushFilters() {

View file

@ -86,6 +86,14 @@ class FilterTest {
expiresAt = null,
irreversible = false,
wholeWord = true
),
Filter(
id = "123",
phrase = "@twitter.com",
context = listOf(Filter.HOME),
expiresAt = null,
irreversible = false,
wholeWord = true
)
)
)
@ -145,7 +153,7 @@ class FilterTest {
}
@Test
fun shouldNotFilter_whenContentDoesNotMAtchWholeWord() {
fun shouldNotFilter_whenContentDoesNotMatchWholeWord() {
assertFalse(fragment.shouldFilterStatus(
mockStatus(content = "one two badWholeWordTest three")
))
@ -172,6 +180,13 @@ class FilterTest {
))
}
@Test
fun shouldFilterPartialWord_whenWholeWordFilterContainsNonAlphanumericCharacters() {
assertTrue(fragment.shouldFilterStatus(
mockStatus(content = "one two someone@twitter.com three")
))
}
private fun mockStatus(
content: String = "",
spoilerText: String = "",