Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use okhttp client for caching (instead of glide) #1281

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions News-Android-App/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ dependencies {

implementation "com.github.bumptech.glide:glide:${GLIDE_VERSION}"
ksp "com.github.bumptech.glide:ksp:${GLIDE_VERSION}"
implementation "com.github.bumptech.glide:okhttp3-integration:4.16.0"
debugImplementation "com.github.technoir42:glide-debug-indicator:0.9.1"
implementation 'com.caverock:androidsvg-aar:1.4'

Expand Down
2 changes: 2 additions & 0 deletions News-Android-App/proguard-rules.pro
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@
-keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Observable
-keep,allowobfuscation,allowshrinking class io.reactivex.rxjava3.core.Single

# glide
-keep class com.bumptech.glide.integration.okhttp.OkHttpGlideModule



Expand Down
11 changes: 8 additions & 3 deletions News-Android-App/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,15 @@
android:usesCleartextTraffic="true"
tools:replace="android:icon, android:label, android:theme, android:name">

<meta-data android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc"/>
<meta-data android:name="com.google.android.gms.car.notification.SmallIcon"
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" />
<meta-data
android:name="com.google.android.gms.car.notification.SmallIcon"
android:resource="@drawable/ic_notification" />
<meta-data
android:name="com.bumptech.glide.integration.okhttp.OkHttpGlideModule"
android:value="GlideModule" />

<activity
android:name=".NewsReaderListActivity"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.snackbar.Snackbar;
import com.nextcloud.android.sso.AccountImporter;
import com.nextcloud.android.sso.api.NextcloudAPI;
Expand Down Expand Up @@ -592,7 +591,6 @@ public void onUserInfoUpdated(OcsUser userInfo) {

Glide.with(this)
.load(avatarUrl)
.diskCacheStrategy(DiskCacheStrategy.DATA)
.placeholder(placeHolder)
.error(placeHolder)
.circleCrop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
Expand All @@ -66,11 +67,14 @@
import de.luhmer.owncloudnewsreader.helper.ImageHandler;
import de.luhmer.owncloudnewsreader.helper.NewsFileUtils;
import de.luhmer.owncloudnewsreader.helper.PostDelayHandler;
import okhttp3.OkHttpClient;

public class SettingsFragment extends PreferenceFragmentCompat {

protected @Inject SharedPreferences mPrefs;
protected @Inject @Named("sharedPreferencesFileName") String sharedPreferencesFileName;
protected @Inject OkHttpClient mOkHttpClient;
protected @Inject
@Named("sharedPreferencesFileName") String sharedPreferencesFileName;
private static String version = "<loading>";

@Override
Expand Down Expand Up @@ -126,10 +130,9 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
private static final Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = (preference, value) -> {
String stringValue = value.toString();

if (preference instanceof ListPreference) {
if (preference instanceof ListPreference listPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);

// Set the summary to reflect the new value.
Expand Down Expand Up @@ -158,8 +161,7 @@ else if(PREF_SYNC_SETTINGS.equals(preference.getKey())) {
};

private static final Preference.OnPreferenceChangeListener sBindPreferenceBooleanToValueListener = (preference, newValue) -> {
if(preference instanceof CheckBoxPreference) { //For legacy Android support
CheckBoxPreference cbPreference = ((CheckBoxPreference) preference);
if(preference instanceof CheckBoxPreference cbPreference) { //For legacy Android support
cbPreference.setChecked((Boolean) newValue);
} else {
TwoStatePreference twoStatePreference = ((TwoStatePreference) preference);
Expand Down Expand Up @@ -262,12 +264,10 @@ private void migrateSyncIntervalValue() {
// the list will show the default sync interval value of 15min
// whereas the user may have configured some other value
// once the user selects a value, this new value is actually used; and no more impact is expected

}

private void bindDataSyncPreferences(final PreferenceFragmentCompat prefFrag)
{

// handle the sync interval list:
bindPreferenceSummaryToValue(prefFrag.findPreference(PREF_SYNC_SETTINGS));

Expand Down Expand Up @@ -317,13 +317,10 @@ private void bindPodcastPreferences(PreferenceFragmentCompat prefFrag)

public void checkForUnsycedChangesInDatabaseAndResetDatabase(final Context context) {
DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(context);
boolean resetDatabase = true;
if(dbConn.areThereAnyUnsavedChangesInDatabase()) {
resetDatabase = false;
}
boolean resetDatabase = !dbConn.areThereAnyUnsavedChangesInDatabase();

if(resetDatabase) {
new ResetDatabaseAsyncTask(context).execute();
new ResetDatabaseAsyncTask(context, mOkHttpClient).execute();
} else {
new AlertDialog.Builder(context)
.setTitle(context.getString(R.string.warning))
Expand All @@ -335,7 +332,7 @@ public void onClick(DialogInterface dialog, int which) {
PostDelayHandler pDelayHandler = new PostDelayHandler(context);
pDelayHandler.stopRunningPostDelayHandler();

new ResetDatabaseAsyncTask(context).execute();
new ResetDatabaseAsyncTask(context, mOkHttpClient).execute();
}
})
.setNegativeButton(context.getString(android.R.string.no), null)
Expand Down Expand Up @@ -379,11 +376,7 @@ private void openBugReport() {
}
}

try {
body = URLEncoder.encode(debugInfo,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
body = URLEncoder.encode(debugInfo, StandardCharsets.UTF_8);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to stay as is see #1315

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/nextcloud/news-android/issues/new?title=" + title + "&body=" + body));
startActivity(browserIntent);
}
Expand Down Expand Up @@ -418,8 +411,11 @@ public static class ResetDatabaseAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog pd;
private final Context context;

public ResetDatabaseAsyncTask(Context context) {
private final OkHttpClient okHttpClient;

public ResetDatabaseAsyncTask(Context context, OkHttpClient okHttpClient) {
this.context = context;
this.okHttpClient = okHttpClient;
}

@Override
Expand All @@ -440,7 +436,8 @@ protected Void doInBackground(Void... params) {

DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(context);
dbConn.resetDatabase();
ImageHandler.clearCache(context);
ImageHandler.clearGlideCache(context);
ImageHandler.clearOkHttpCache(okHttpClient);
NewsFileUtils.clearWebArchiveCache(context);
NewsFileUtils.clearPodcastCache(context);
return null;
Expand All @@ -453,8 +450,7 @@ protected void onPostExecute(Void result) {
pd.dismiss();
Toast.makeText(context, context.getString(R.string.cache_is_cleared), Toast.LENGTH_SHORT).show();

if(context instanceof SettingsActivity) {
SettingsActivity sa = (SettingsActivity) context;
if(context instanceof SettingsActivity sa) {
sa.resultIntent.putExtra(SettingsActivity.RI_CACHE_CLEARED, true);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

Expand Down Expand Up @@ -94,7 +93,7 @@ public void bind(@NonNull RssItem rssItem) {

mGlide
.load(mediaThumbnail)
.diskCacheStrategy(DiskCacheStrategy.DATA)
// .diskCacheStrategy(DiskCacheStrategy.DATA) // use okhttp caching
.placeholder(feedIcon)
.error(feedIcon)
.transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(60)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

Expand Down Expand Up @@ -93,7 +92,7 @@ public void bind(@NonNull RssItem rssItem) {

mGlide
.load(mediaThumbnail)
.diskCacheStrategy(DiskCacheStrategy.DATA)
// .diskCacheStrategy(DiskCacheStrategy.DATA) // use okhttp caching
.placeholder(feedIcon)
.error(feedIcon)
.transform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(60)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import android.util.Log;

import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.net.URL;
import java.util.concurrent.ExecutionException;
Expand All @@ -51,7 +50,7 @@ public void preloadSync(RequestManager glide) {
Bitmap bm = glide
.asBitmap()
.load(mImageUrl.toString())
.diskCacheStrategy(DiskCacheStrategy.DATA)
// .diskCacheStrategy(DiskCacheStrategy.DATA) // use okhttp cache
.submit()
.get();
NotifyDownloadFinished(bm);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,10 @@ private static String getDescriptionWithCachedImages(RequestManager glide, Strin
try {
File file = null;
try {
// TODO!!!! THIS CODE BELOW DOESN'T WORK WITH OKHTTP!!
file = glide
.asFile()
.diskCacheStrategy(DiskCacheStrategy.DATA)
// .diskCacheStrategy(DiskCacheStrategy.DATA) // TODO!! NOT WORKING
.onlyRetrieveFromCache(true)
// .listener(rl)
.load(link)
Expand All @@ -313,7 +314,7 @@ private static String getDescriptionWithCachedImages(RequestManager glide, Strin
return text;
}

private static RequestListener<File> rl = new RequestListener<>() {
private static final RequestListener<File> rl = new RequestListener<>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
// Log the GlideException here (locally or with a remote logging framework):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package de.luhmer.owncloudnewsreader.di;

import static de.luhmer.owncloudnewsreader.helper.NextcloudGlideModuleKt.CACHE_SIZE;
import static de.luhmer.owncloudnewsreader.helper.NextcloudGlideModuleKt.MB;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
Expand All @@ -13,6 +16,7 @@

import dagger.Module;
import dagger.Provides;
import de.luhmer.owncloudnewsreader.SettingsActivity;
import de.luhmer.owncloudnewsreader.helper.PostDelayHandler;
import de.luhmer.owncloudnewsreader.helper.ThemeChooser;
import de.luhmer.owncloudnewsreader.ssl.MemorizingTrustManager;
Expand Down Expand Up @@ -85,18 +89,36 @@ Gson provideGson() {

@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
// setCache(cache);
return new OkHttpClient();
PostDelayHandler providePostDelayHandler() {
return new PostDelayHandler(mApplication);
}


@Provides
@Singleton
PostDelayHandler providePostDelayHandler() {
return new PostDelayHandler(mApplication);
OkHttpClient provideOkHttpClient(SharedPreferences prefs) {
String cacheSize = prefs.getString(SettingsActivity.SP_MAX_CACHE_SIZE, String.valueOf(CACHE_SIZE));
Long diskCacheSizeBytes = Long.valueOf(cacheSize) * MB;

OkHttpClient.Builder client = new OkHttpClient.Builder()
.cache(new Cache(mApplication.getApplicationContext().getCacheDir(), diskCacheSizeBytes));
/*
.addInterceptor(Interceptor { chain: Interceptor.Chain ->
val response = chain.proceed(chain.request())
if (response.cacheResponse != null) {
Log.d("NextcloudGlideModule", "cached response: " + response.request.url)
} else if (response.networkResponse != null) {
Log.d("NextcloudGlideModule", "network response: " + response.request.url)
for (h in response.request.headers) {
Log.d("NextcloudGlideModule", "request headers: $h")
}
}
response
})
*/
return client.build();
}


/*
@Provides
@Singleton
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,16 @@

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.OkHttpClient;

public class ImageHandler {
private static final String TAG = "[ImageHandler]";
private static final Pattern patternImg = Pattern.compile("<img[^>]*>");
Expand Down Expand Up @@ -192,18 +195,27 @@ private static String sliceLastPathOfUrl(String url) {
private static String getFileName(String url) {
int idx = url.lastIndexOf("/");
int countOfSlashes = url.split("/").length - 1;
if(idx > 0) {
if (idx > 0) {
return url.substring(idx);
} else {
return url;
}
}

public static void clearCache(Context context)
{
public static void clearGlideCache(Context context) {
Glide.get(context).clearMemory(); // needs to run on main thread
new Thread(() -> {
Glide.get(context).clearMemory();
Glide.get(context).clearDiskCache();
}).start();
}

public static void clearOkHttpCache(OkHttpClient okHttpClient) {
new Thread(() -> {
try {
okHttpClient.cache().evictAll();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
Loading