Cache messages

This commit is contained in:
Thomas 2023-02-04 11:23:31 +01:00
parent b64fd393e9
commit 8977990fea
4 changed files with 21 additions and 141 deletions

View file

@ -1,86 +0,0 @@
package app.fedilab.android.mastodon.client.entities.app;
/* Copyright 2023 Thomas Schneider
*
* This file is a part of Fedilab
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
import app.fedilab.android.mastodon.exception.DBException;
import app.fedilab.android.mastodon.helper.Helper;
import app.fedilab.android.sqlite.Sqlite;
public class HomeFetchLog implements Serializable {
private final SQLiteDatabase db;
@SerializedName("id")
public long id = -1;
@SerializedName("instance")
public String instance;
@SerializedName("user_id")
public String user_id;
@SerializedName("fetched_count")
public int fetched_count;
@SerializedName("inserted")
public int inserted;
@SerializedName("updated")
public int updated;
@SerializedName("failed")
public int failed;
@SerializedName("frequency")
public int frequency;
@SerializedName("created_at")
public Date created_ad;
private Context context;
public HomeFetchLog() {
db = null;
}
public HomeFetchLog(Context context) {
//Creation of the DB with tables
this.context = context;
this.db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
}
public long insert(HomeFetchLog homeFetchLog) throws DBException {
if (db == null) {
throw new DBException("db is null. Wrong initialization.");
}
ContentValues values = new ContentValues();
values.put(Sqlite.COL_INSTANCE, homeFetchLog.instance);
values.put(Sqlite.COL_USER_ID, homeFetchLog.user_id);
values.put(Sqlite.COL_FETCHED_COUNT, homeFetchLog.fetched_count);
values.put(Sqlite.COL_FAILED, homeFetchLog.failed);
values.put(Sqlite.COL_INSERTED, homeFetchLog.inserted);
values.put(Sqlite.COL_UPDATED, homeFetchLog.updated);
values.put(Sqlite.COL_FREQUENCY, homeFetchLog.frequency);
values.put(Sqlite.COL_CREATED_AT, Helper.dateToString(new Date()));
//Inserts logs
try {
return db.insertOrThrow(Sqlite.TABLE_HOME_FETCH_LOGS, null, values);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}

View file

@ -46,7 +46,6 @@ import app.fedilab.android.mastodon.client.entities.api.Pagination;
import app.fedilab.android.mastodon.client.entities.api.Status; import app.fedilab.android.mastodon.client.entities.api.Status;
import app.fedilab.android.mastodon.client.entities.app.Account; import app.fedilab.android.mastodon.client.entities.app.Account;
import app.fedilab.android.mastodon.client.entities.app.BaseAccount; import app.fedilab.android.mastodon.client.entities.app.BaseAccount;
import app.fedilab.android.mastodon.client.entities.app.HomeFetchLog;
import app.fedilab.android.mastodon.client.entities.app.StatusCache; import app.fedilab.android.mastodon.client.entities.app.StatusCache;
import app.fedilab.android.mastodon.client.entities.app.Timeline; import app.fedilab.android.mastodon.client.entities.app.Timeline;
import app.fedilab.android.mastodon.exception.DBException; import app.fedilab.android.mastodon.exception.DBException;
@ -77,12 +76,13 @@ public class FetchHomeWorker extends Worker {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
} }
public static void setRepeatHome(Context context, BaseAccount account) { public static void setRepeatHome(Context context, BaseAccount account, Data inputData) {
WorkManager.getInstance(context).cancelAllWorkByTag(Helper.WORKER_REFRESH_HOME + account.user_id + account.instance); WorkManager.getInstance(context).cancelAllWorkByTag(Helper.WORKER_REFRESH_HOME + account.user_id + account.instance);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String value = prefs.getString(context.getString(R.string.SET_FETCH_HOME_DELAY_VALUE) + account.user_id + account.instance, "60"); String value = prefs.getString(context.getString(R.string.SET_FETCH_HOME_DELAY_VALUE) + account.user_id + account.instance, "60");
PeriodicWorkRequest notificationPeriodic = new PeriodicWorkRequest.Builder(FetchHomeWorker.class, Long.parseLong(value), TimeUnit.MINUTES) PeriodicWorkRequest notificationPeriodic = new PeriodicWorkRequest.Builder(FetchHomeWorker.class, Long.parseLong(value), TimeUnit.MINUTES)
.addTag(Helper.WORKER_REFRESH_HOME) .setInputData(inputData)
.addTag(Helper.WORKER_REFRESH_HOME + account.user_id + account.instance)
.build(); .build();
WorkManager.getInstance(context).enqueueUniquePeriodicWork(Helper.WORKER_REFRESH_HOME + account.user_id + account.instance, ExistingPeriodicWorkPolicy.REPLACE, notificationPeriodic); WorkManager.getInstance(context).enqueueUniquePeriodicWork(Helper.WORKER_REFRESH_HOME + account.user_id + account.instance, ExistingPeriodicWorkPolicy.REPLACE, notificationPeriodic);
} }
@ -135,10 +135,15 @@ public class FetchHomeWorker extends Worker {
@NonNull @NonNull
@Override @Override
public Result doWork() { public Result doWork() {
setForegroundAsync(createForegroundInfo()); setForegroundAsync(createForegroundInfo());
String instance = getInputData().getString(Helper.ARG_INSTANCE);
String userId = getInputData().getString(Helper.ARG_USER_ID);
try { try {
List<BaseAccount> accounts = new Account(getApplicationContext()).getCrossAccounts(); BaseAccount account = new Account(getApplicationContext()).getUniqAccount(userId, instance);
for (BaseAccount account : accounts) { if (account != null) {
try { try {
fetchHome(getApplicationContext(), account); fetchHome(getApplicationContext(), account);
} catch (IOException e) { } catch (IOException e) {
@ -164,18 +169,13 @@ public class FetchHomeWorker extends Worker {
int call = 0; int call = 0;
String max_id = null; String max_id = null;
MastodonTimelinesService mastodonTimelinesService = init(account.instance); MastodonTimelinesService mastodonTimelinesService = init(account.instance);
int inserted = 0;
int updated = 0;
int failed = 0;
int count = 0;
while (canContinue && call < max_calls) { while (canContinue && call < max_calls) {
Call<List<Status>> homeCall = mastodonTimelinesService.getHome(account.token, account.instance, max_id, null, status_per_page, null); Call<List<Status>> homeCall = mastodonTimelinesService.getHome(account.token, max_id, null, null, status_per_page, null);
if (homeCall != null) { if (homeCall != null) {
Response<List<Status>> homeResponse = homeCall.execute(); Response<List<Status>> homeResponse = homeCall.execute();
if (homeResponse.isSuccessful()) { if (homeResponse.isSuccessful()) {
List<Status> statusList = homeResponse.body(); List<Status> statusList = homeResponse.body();
if (statusList != null && statusList.size() > 0) { if (statusList != null && statusList.size() > 0) {
count += statusList.size();
for (Status status : statusList) { for (Status status : statusList) {
StatusCache statusCacheDAO = new StatusCache(getApplicationContext()); StatusCache statusCacheDAO = new StatusCache(getApplicationContext());
StatusCache statusCache = new StatusCache(); StatusCache statusCache = new StatusCache();
@ -185,16 +185,9 @@ public class FetchHomeWorker extends Worker {
statusCache.type = Timeline.TimeLineEnum.HOME; statusCache.type = Timeline.TimeLineEnum.HOME;
statusCache.status_id = status.id; statusCache.status_id = status.id;
try { try {
int val = statusCacheDAO.insertOrUpdate(statusCache, Timeline.TimeLineEnum.HOME.getValue()); statusCacheDAO.insertOrUpdate(statusCache, Timeline.TimeLineEnum.HOME.getValue());
if (val == 1) {
inserted++;
}
if (val == 0) {
updated++;
}
} catch (DBException e) { } catch (DBException e) {
e.printStackTrace(); e.printStackTrace();
failed = -1;
} }
} }
Pagination pagination = MastodonHelper.getPagination(homeResponse.headers()); Pagination pagination = MastodonHelper.getPagination(homeResponse.headers());
@ -202,18 +195,13 @@ public class FetchHomeWorker extends Worker {
max_id = pagination.max_id; max_id = pagination.max_id;
} else { } else {
canContinue = false; canContinue = false;
failed = 4;
} }
} else { } else {
failed = 3;
canContinue = false; canContinue = false;
} }
} else { } else {
canContinue = false; canContinue = false;
failed = 2;
} }
} else {
failed = 1;
} }
//Pause between calls (1 second) //Pause between calls (1 second)
try { try {
@ -223,20 +211,6 @@ public class FetchHomeWorker extends Worker {
} }
call++; call++;
} }
HomeFetchLog homeFetchLog = new HomeFetchLog();
homeFetchLog.user_id = account.user_id;
homeFetchLog.instance = account.instance;
String frequency = prefs.getString(context.getString(R.string.SET_FETCH_HOME_DELAY_VALUE) + account.user_id + account.instance, "60");
homeFetchLog.frequency = Integer.parseInt(frequency);
homeFetchLog.fetched_count = count;
homeFetchLog.inserted = inserted;
homeFetchLog.updated = updated;
homeFetchLog.failed = failed;
try {
new HomeFetchLog(context).insert(homeFetchLog);
} catch (DBException e) {
e.printStackTrace();
}
} }
} }

View file

@ -23,8 +23,10 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager; import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import androidx.preference.SwitchPreference; import androidx.preference.SwitchPreference;
import androidx.work.Data;
import androidx.work.WorkManager; import androidx.work.WorkManager;
import app.fedilab.android.BaseMainActivity;
import app.fedilab.android.R; import app.fedilab.android.R;
import app.fedilab.android.activities.MainActivity; import app.fedilab.android.activities.MainActivity;
import app.fedilab.android.mastodon.helper.Helper; import app.fedilab.android.mastodon.helper.Helper;
@ -70,6 +72,10 @@ public class FragmentHomeCacheSettings extends PreferenceFragmentCompat implemen
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (getActivity() != null) { if (getActivity() != null) {
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity());
Data inputData = new Data.Builder()
.putString(Helper.ARG_INSTANCE, BaseMainActivity.currentInstance)
.putString(Helper.ARG_USER_ID, BaseMainActivity.currentUserID)
.build();
if (key.compareToIgnoreCase(getString(R.string.SET_FETCH_HOME)) == 0) { if (key.compareToIgnoreCase(getString(R.string.SET_FETCH_HOME)) == 0) {
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
SwitchPreference SET_FETCH_HOME = findPreference(getString(R.string.SET_FETCH_HOME)); SwitchPreference SET_FETCH_HOME = findPreference(getString(R.string.SET_FETCH_HOME));
@ -77,7 +83,7 @@ public class FragmentHomeCacheSettings extends PreferenceFragmentCompat implemen
editor.putBoolean(getString(R.string.SET_FETCH_HOME) + MainActivity.currentUserID + MainActivity.currentInstance, SET_FETCH_HOME.isChecked()); editor.putBoolean(getString(R.string.SET_FETCH_HOME) + MainActivity.currentUserID + MainActivity.currentInstance, SET_FETCH_HOME.isChecked());
editor.commit(); editor.commit();
if (SET_FETCH_HOME.isChecked()) { if (SET_FETCH_HOME.isChecked()) {
FetchHomeWorker.setRepeatHome(requireActivity(), MainActivity.currentAccount); FetchHomeWorker.setRepeatHome(requireActivity(), MainActivity.currentAccount, inputData);
} else { } else {
WorkManager.getInstance(requireActivity()).cancelAllWorkByTag(Helper.WORKER_REFRESH_HOME + MainActivity.currentUserID + MainActivity.currentInstance); WorkManager.getInstance(requireActivity()).cancelAllWorkByTag(Helper.WORKER_REFRESH_HOME + MainActivity.currentUserID + MainActivity.currentInstance);
} }
@ -89,7 +95,7 @@ public class FragmentHomeCacheSettings extends PreferenceFragmentCompat implemen
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(getString(R.string.SET_FETCH_HOME_DELAY_VALUE) + MainActivity.currentUserID + MainActivity.currentInstance, SET_FETCH_HOME_DELAY_VALUE.getValue()); editor.putString(getString(R.string.SET_FETCH_HOME_DELAY_VALUE) + MainActivity.currentUserID + MainActivity.currentInstance, SET_FETCH_HOME_DELAY_VALUE.getValue());
editor.commit(); editor.commit();
FetchHomeWorker.setRepeatHome(requireActivity(), MainActivity.currentAccount); FetchHomeWorker.setRepeatHome(requireActivity(), MainActivity.currentAccount, inputData);
} }
} }
} }

View file

@ -23,7 +23,7 @@ import android.database.sqlite.SQLiteOpenHelper;
public class Sqlite extends SQLiteOpenHelper { public class Sqlite extends SQLiteOpenHelper {
public static final int DB_VERSION = 10; public static final int DB_VERSION = 9;
public static final String DB_NAME = "fedilab_db"; public static final String DB_NAME = "fedilab_db";
//Table of owned accounts //Table of owned accounts
@ -212,17 +212,6 @@ public class Sqlite extends SQLiteOpenHelper {
+ COL_USER_INSTANCE + " TEXT NOT NULL)"; + COL_USER_INSTANCE + " TEXT NOT NULL)";
private static final String CREATE_TABLE_HOME_FETCH_LOGS = "CREATE TABLE IF NOT EXISTS " + TABLE_HOME_FETCH_LOGS + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_INSTANCE + " TEXT NOT NULL, "
+ COL_USER_ID + " TEXT NOT NULL, "
+ COL_FETCHED_COUNT + " INTEGER NOT NULL DEFAULT 0, "
+ COL_INSERTED + " INTEGER NOT NULL DEFAULT 0, "
+ COL_UPDATED + " INTEGER NOT NULL DEFAULT 0, "
+ COL_FAILED + " INTEGER NOT NULL DEFAULT 0, "
+ COL_FREQUENCY + " INTEGER NOT NULL DEFAULT 0, "
+ COL_CREATED_AT + " TEXT NOT NULL)";
public static SQLiteDatabase db; public static SQLiteDatabase db;
private static Sqlite sInstance; private static Sqlite sInstance;
@ -254,7 +243,6 @@ public class Sqlite extends SQLiteOpenHelper {
db.execSQL(CREATE_DOMAINS_TRACKING); db.execSQL(CREATE_DOMAINS_TRACKING);
db.execSQL(CREATE_TABLE_MUTED); db.execSQL(CREATE_TABLE_MUTED);
db.execSQL(CREATE_TABLE_STORED_INSTANCES); db.execSQL(CREATE_TABLE_STORED_INSTANCES);
db.execSQL(CREATE_TABLE_HOME_FETCH_LOGS);
} }
@Override @Override
@ -283,8 +271,6 @@ public class Sqlite extends SQLiteOpenHelper {
db.execSQL(CREATE_TABLE_MUTED); db.execSQL(CREATE_TABLE_MUTED);
case 8: case 8:
db.execSQL(CREATE_TABLE_STORED_INSTANCES); db.execSQL(CREATE_TABLE_STORED_INSTANCES);
case 9:
db.execSQL(CREATE_TABLE_HOME_FETCH_LOGS);
default: default:
break; break;
} }