Skip to content

Instantly share code, notes, and snippets.

@cTatu
Last active August 23, 2019 14:10
Show Gist options
  • Save cTatu/9c3184b01dcdeaefd6eec166c56f5ed4 to your computer and use it in GitHub Desktop.
Save cTatu/9c3184b01dcdeaefd6eec166c56f5ed4 to your computer and use it in GitHub Desktop.
void main() {
Map goodCookies = newCookiesMethod();
Map badCookies = oldCookiesMethod();
print('Are cookies parsed equal to original?');
print('NewMethod: ${deepCompare(cookiesPrepared, goodCookies)}');
print('OldMethod: ${deepCompare(cookiesPrepared, badCookies)}');
print('If there are not cookies the result must be an empty map');
Map goodCookiesEmpty = newCookiesMethod(emptyCookies: true);
print('NewMethod Empty: ${goodCookiesEmpty.isEmpty}');
}
Map newCookiesMethod({bool emptyCookies}){
final RegExp escapeQuotes = RegExp(r'(?<=").+?(?=")');
var cookiesString = evalJavascript('document.cookie', emptyCookies: emptyCookies);
final cookies = <String, String>{};
cookiesString = escapeQuotes.allMatches(cookiesString).map((m) => m.group(0)).join('"');
cookiesString
.split('; ')
.where((c) => c.isNotEmpty)
.forEach((cookie) =>
cookies[cookie.split('=').first] = cookie.split('=').skip(1).join('=')
);
return cookies;
}
Map oldCookiesMethod(){
final cookiesString = evalJavascript('document.cookie');
final cookies = <String, String>{};
if (cookiesString?.isNotEmpty == true) {
cookiesString.split(';').forEach((String cookie) {
final split = cookie.split('=');
cookies[split[0]] = split[1];
});
}
return cookies;
}
// Simulate webView 'document.cookies'
String evalJavascript(_, {bool emptyCookies}){
String cookies = '';
int i = 0;
Map cookiesMap = cookiesPrepared;
if (emptyCookies ?? false)
cookiesMap = {};
cookiesMap.forEach((k, v) {
cookies += '$k=$v';
i++;
if (i < cookiesMap.length)
cookies += '; ';
});
return '"$cookies"';
}
Map<String, String> cookiesPrepared = {
'username': 'John Doe',
'expires': 'Thu, 18 Dec 2013 12:00:00 UTC',
'path': '/usr/apache2/www/',
'timestamp': '57246556',
'cookieWithDoubleQuotes': 'fe23\"·dsd',
'cookieWithSimpleQuotes': "rrer8974\'ve76\'",
'..///\\\\**-++!\"··%&((': '/+-*()!"·?¿¿`+ç´.-',
'empty': '',
'rsa': '4IlzOY3Y9fXoh3Y5f06wBbtTg94Pt6vcfcd1KQ0FLm0S36aGJtTSb6pYKfyX7PqCUQ8wgL6xUJ5GRPEsu9gyz8ZobwfZsGCsvu40CWoT9fcFBZPfXro1Vtlh/xl/yYHm+Gzqh0Bw76xtLHSfLfpVOrmZdwKmSFKMTvNXOFd0V18='
};
bool deepCompare(Map m1, Map m2){
var k1 = m1.keys.toList();
var k2 = m2.keys.toList();
var v1 = m1.values.toList();
var v2 = m2.values.toList();
for(var i = 0; i < m1.length; i++){
if (k1[i] != k2[i])
return false;
if (v1[i] != v2[i])
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment