Skip to content

Commit b672d37

Browse files
committed
fix matchToClosingParenthesis for extracting more complex nsig functions
1 parent d120036 commit b672d37

File tree

2 files changed

+54
-4
lines changed

2 files changed

+54
-4
lines changed

extractor/src/main/java/org/schabi/newpipe/extractor/utils/StringUtils.java

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,13 @@ public static String matchToClosingParenthesis(@Nonnull final String string,
2323
}
2424

2525
startIndex += start.length();
26-
int endIndex = startIndex;
27-
while (string.charAt(endIndex) != '{') {
28-
++endIndex;
29-
}
26+
int endIndex = findNextParenthesis(string, startIndex, true);
3027
++endIndex;
3128

3229
int openParenthesis = 1;
3330
while (openParenthesis > 0) {
31+
endIndex = findNextParenthesis(string, endIndex, false);
32+
3433
switch (string.charAt(endIndex)) {
3534
case '{':
3635
++openParenthesis;
@@ -46,4 +45,45 @@ public static String matchToClosingParenthesis(@Nonnull final String string,
4645

4746
return string.substring(startIndex, endIndex);
4847
}
48+
49+
private static int findNextParenthesis(@Nonnull final String string, final int offset,
50+
final boolean onlyOpen) {
51+
boolean lastEscaped = false;
52+
char quote = ' ';
53+
54+
for (int i = offset; i < string.length(); i++) {
55+
boolean thisEscaped = false;
56+
final char c = string.charAt(i);
57+
58+
switch (c) {
59+
case '{':
60+
if (quote == ' ') {
61+
return i;
62+
}
63+
break;
64+
case '}':
65+
if (!onlyOpen && quote == ' ') {
66+
return i;
67+
}
68+
break;
69+
case '\\':
70+
if (!lastEscaped) {
71+
thisEscaped = true;
72+
}
73+
break;
74+
case '\'':
75+
case '"':
76+
if (!lastEscaped) {
77+
if (quote == ' ') {
78+
quote = c;
79+
} else if (quote == c) {
80+
quote = ' ';
81+
}
82+
}
83+
}
84+
85+
lastEscaped = thisEscaped;
86+
}
87+
return -1;
88+
}
4989
}

extractor/src/test/java/org/schabi/newpipe/extractor/utils/StringUtilsTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,14 @@ public void lessClosing__success() {
5858

5959
assertEquals(expected, substring);
6060
}
61+
62+
@Test
63+
public void find_closing_with_quotes() {
64+
String expected = "{return \",}\\\"/\"}";
65+
String string = "function(d){return \",}\\\"/\"}";
66+
67+
String substring = matchToClosingParenthesis(string, "function(d)");
68+
69+
assertEquals(expected, substring);
70+
}
6171
}

0 commit comments

Comments
 (0)