parent
c4a4ec5287
commit
888b624ff6
@ -1,86 +0,0 @@
|
||||
package com.fox2code.mmm.utils.io;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Base64;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Arrays;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import timber.log.Timber;
|
||||
|
||||
|
||||
public class AddCookiesInterceptor implements Interceptor {
|
||||
private final Context context;
|
||||
|
||||
public AddCookiesInterceptor(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Response intercept(Interceptor.Chain chain) throws IOException {
|
||||
Request.Builder builder = chain.request().newBuilder();
|
||||
|
||||
String cookieFileName = "cookies";
|
||||
String[] cookies;
|
||||
// cookies are split by | so we can split the string into an array of cookies
|
||||
File cookieFile = new File(context.getFilesDir(), cookieFileName);
|
||||
if (cookieFile.exists()) {
|
||||
// read the file into a string
|
||||
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(cookieFile)));
|
||||
char[] buf = new char[1024];
|
||||
int read;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
while ((read = bufferedReader.read(buf)) != -1) {
|
||||
stringBuilder.append(buf, 0, read);
|
||||
}
|
||||
bufferedReader.close();
|
||||
String cookieString = stringBuilder.toString();
|
||||
// base64 decode the string
|
||||
cookieString = Arrays.toString(Base64.decode(cookieString, Base64.DEFAULT));
|
||||
// split the string into an array of cookies
|
||||
cookies = cookieString.split("\\|");
|
||||
} else {
|
||||
cookies = new String[0];
|
||||
}
|
||||
|
||||
for (String cookie : cookies) {
|
||||
// ensure the cookie applies to the current domain
|
||||
if (cookie.contains("domain=")) {
|
||||
// match from the start of the string to the first semicolon
|
||||
try {
|
||||
Pattern pattern = Pattern.compile("domain=([^;]+)");
|
||||
String domain = pattern.matcher(cookie).group(1);
|
||||
if (domain != null && !chain.request().url().host().contains(domain)) {
|
||||
//noinspection UnnecessaryContinue
|
||||
continue;
|
||||
} else {
|
||||
// yeet any newlines from the cookie
|
||||
cookie = cookie.replaceAll("[\\r\\n]", "");
|
||||
builder.addHeader("Cookie", cookie);
|
||||
}
|
||||
} catch (
|
||||
Exception ignored) {
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
builder.addHeader("Cookie", cookie);
|
||||
} catch (Exception e) {
|
||||
Timber.e(e, "Error adding cookie to request: %s", cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return chain.proceed(builder.build());
|
||||
}
|
||||
}
|
@ -1,99 +0,0 @@
|
||||
package com.fox2code.mmm.utils.io;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.util.Base64;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Response;
|
||||
import timber.log.Timber;
|
||||
|
||||
public class ReceivedCookiesInterceptor implements Interceptor {
|
||||
private final Context context;
|
||||
|
||||
public ReceivedCookiesInterceptor(Context context) {
|
||||
this.context = context;
|
||||
} // AddCookiesInterceptor()
|
||||
|
||||
@NonNull
|
||||
@SuppressLint({"MutatingSharedPrefs", "ApplySharedPref"})
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Response originalResponse = chain.proceed(chain.request());
|
||||
|
||||
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
|
||||
StringBuilder cookieBuffer = new StringBuilder();
|
||||
for (String header : originalResponse.headers("Set-Cookie")) {
|
||||
cookieBuffer.append(header).append("|");
|
||||
} // for
|
||||
|
||||
int lastPipe = cookieBuffer.lastIndexOf("|");
|
||||
if (lastPipe > 0) {
|
||||
cookieBuffer.deleteCharAt(lastPipe);
|
||||
}
|
||||
|
||||
String cookieFileName = "cookies";
|
||||
String[] cookies = new String[0];
|
||||
try {
|
||||
File cookieFile = new File(context.getFilesDir(), cookieFileName);
|
||||
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(cookieFile)));
|
||||
char[] buf = new char[1024];
|
||||
int read;
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
while ((read = bufferedReader.read(buf)) != -1) {
|
||||
stringBuilder.append(buf, 0, read);
|
||||
}
|
||||
bufferedReader.close();
|
||||
String cookieString = stringBuilder.toString();
|
||||
// base64 decode the string
|
||||
cookieString = Arrays.toString(Base64.decode(cookieString, Base64.DEFAULT));
|
||||
// split the string into an array of cookies
|
||||
cookies = cookieString.split("\\|");
|
||||
} catch (Exception e) {
|
||||
Timber.e(e, "Error reading cookies from file");
|
||||
}
|
||||
|
||||
// Logic to merge our cookies with received cookies
|
||||
// We need to check if the cookie we received is already in our file
|
||||
// If it is, we need to replace it with the new one
|
||||
// If it isn't, we need to add it to the end of the file
|
||||
HashSet<String> cookieSet = new HashSet<>(Arrays.asList(cookies));
|
||||
String[] newCookies = cookieBuffer.toString().split("\\|");
|
||||
for (String cookie : newCookies) {
|
||||
cookieSet.remove(cookie);
|
||||
cookieSet.add(cookie);
|
||||
}
|
||||
|
||||
// convert the set back into a string
|
||||
StringBuilder newCookieBuffer = new StringBuilder();
|
||||
for (String cookie : cookieSet) {
|
||||
newCookieBuffer.append(cookie).append("|");
|
||||
}
|
||||
|
||||
// remove the last pipe
|
||||
lastPipe = newCookieBuffer.lastIndexOf("|");
|
||||
if (lastPipe > 0) {
|
||||
newCookieBuffer.deleteCharAt(lastPipe);
|
||||
}
|
||||
|
||||
// write the new cookies to the file
|
||||
File cookieFile = new File(context.getFilesDir(), cookieFileName);
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(cookieFile);
|
||||
fileOutputStream.write(newCookieBuffer.toString().getBytes());
|
||||
fileOutputStream.close();
|
||||
}
|
||||
|
||||
return originalResponse;
|
||||
}
|
||||
}
|
@ -0,0 +1,127 @@
|
||||
package com.fox2code.mmm.utils.io.net;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.CookieManager;
|
||||
import java.net.CookiePolicy;
|
||||
import java.net.CookieStore;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import okhttp3.Cookie;
|
||||
import okhttp3.CookieJar;
|
||||
import okhttp3.HttpUrl;
|
||||
import timber.log.Timber;
|
||||
|
||||
public class WebkitCookieManagerProxy extends CookieManager implements CookieJar {
|
||||
private final android.webkit.CookieManager webkitCookieManager;
|
||||
|
||||
public WebkitCookieManagerProxy() {
|
||||
this(null, null);
|
||||
}
|
||||
|
||||
WebkitCookieManagerProxy(CookieStore ignoredStore, CookiePolicy cookiePolicy) {
|
||||
super(null, cookiePolicy);
|
||||
this.webkitCookieManager = android.webkit.CookieManager.getInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(URI uri, Map<String, List<String>> responseHeaders)
|
||||
throws IOException {
|
||||
// make sure our args are valid
|
||||
if ((uri == null) || (responseHeaders == null))
|
||||
return;
|
||||
|
||||
// save our url once
|
||||
String url = uri.toString();
|
||||
|
||||
// go over the headers
|
||||
for (String headerKey : responseHeaders.keySet()) {
|
||||
// ignore headers which aren't cookie related
|
||||
if ((headerKey == null)
|
||||
|| !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey
|
||||
.equalsIgnoreCase("Set-Cookie")))
|
||||
continue;
|
||||
|
||||
// process each of the headers
|
||||
for (String headerValue : Objects.requireNonNull(responseHeaders.get(headerKey))) {
|
||||
webkitCookieManager.setCookie(url, headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, List<String>> get(URI uri,
|
||||
Map<String, List<String>> requestHeaders) throws IOException {
|
||||
// make sure our args are valid
|
||||
if ((uri == null) || (requestHeaders == null))
|
||||
throw new IllegalArgumentException("Argument is null");
|
||||
|
||||
// save our url once
|
||||
String url = uri.toString();
|
||||
|
||||
// prepare our response
|
||||
Map<String, List<String>> res = new java.util.HashMap<>();
|
||||
|
||||
// get the cookie
|
||||
String cookie = webkitCookieManager.getCookie(url);
|
||||
|
||||
// return it
|
||||
if (cookie != null) {
|
||||
res.put("Cookie", List.of(cookie));
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CookieStore getCookieStore() {
|
||||
// we don't want anyone to work with this cookie store directly
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveFromResponse(@NonNull HttpUrl url, List<Cookie> cookies) {
|
||||
HashMap<String, List<String>> generatedResponseHeaders = new HashMap<>();
|
||||
ArrayList<String> cookiesList = new ArrayList<>();
|
||||
for (Cookie c : cookies) {
|
||||
// toString correctly generates a normal cookie string
|
||||
cookiesList.add(c.toString());
|
||||
}
|
||||
|
||||
generatedResponseHeaders.put("Set-Cookie", cookiesList);
|
||||
try {
|
||||
put(url.uri(), generatedResponseHeaders);
|
||||
} catch (IOException e) {
|
||||
Timber.e(e, "Error adding cookies through okhttp");
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public List<Cookie> loadForRequest(HttpUrl url) {
|
||||
ArrayList<Cookie> cookieArrayList = new ArrayList<>();
|
||||
try {
|
||||
Map<String, List<String>> cookieList = get(url.uri(), new HashMap<>());
|
||||
// Format here looks like: "Cookie":["cookie1=val1;cookie2=val2;"]
|
||||
for (List<String> ls : cookieList.values()) {
|
||||
for (String s : ls) {
|
||||
String[] cookies = s.split(";");
|
||||
for (String cookie : cookies) {
|
||||
Cookie c = Cookie.parse(url, cookie);
|
||||
cookieArrayList.add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Timber.e(e, "error making cookie!");
|
||||
}
|
||||
return cookieArrayList;
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue