FairEmail/app/src/main/java/eu/faircode/email/ServiceSynchronize.java

3469 lines
182 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
2018-08-14 05:53:24 +00:00
This file is part of FairEmail.
2018-08-02 13:33:06 +00:00
2018-08-14 05:53:24 +00:00
FairEmail is free software: you can redistribute it and/or modify
2018-08-02 13:33:06 +00:00
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.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-08-02 13:33:06 +00:00
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
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-08-02 13:33:06 +00:00
2023-01-01 07:52:55 +00:00
Copyright 2018-2023 by Marcel Bokhorst (M66B)
2018-08-02 13:33:06 +00:00
*/
2021-07-30 12:54:44 +00:00
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
import static eu.faircode.email.ServiceAuthenticator.AUTH_TYPE_PASSWORD;
2018-10-09 19:39:25 +00:00
import android.app.AlarmManager;
import android.app.Notification;
2018-08-02 13:33:06 +00:00
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
2018-09-14 13:31:00 +00:00
import android.content.SharedPreferences;
2018-08-02 13:33:06 +00:00
import android.net.ConnectivityManager;
import android.net.LinkProperties;
2018-08-02 13:33:06 +00:00
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
2022-04-01 07:58:07 +00:00
import android.os.BatteryManager;
2018-08-02 13:33:06 +00:00
import android.os.Build;
2019-12-09 21:26:29 +00:00
import android.os.Bundle;
2020-09-21 20:33:06 +00:00
import android.os.OperationCanceledException;
2018-10-08 06:18:44 +00:00
import android.os.PowerManager;
import android.text.TextUtils;
2018-08-02 13:33:06 +00:00
import androidx.annotation.NonNull;
2020-06-12 12:02:14 +00:00
import androidx.annotation.RequiresApi;
import androidx.car.app.connection.CarConnection;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
2022-06-17 20:46:00 +00:00
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
2019-12-06 15:00:11 +00:00
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
2022-06-17 20:46:00 +00:00
import androidx.lifecycle.OnLifecycleEvent;
import androidx.preference.PreferenceManager;
2020-12-02 13:39:48 +00:00
import com.sun.mail.iap.Argument;
import com.sun.mail.iap.ProtocolException;
import com.sun.mail.iap.Response;
2018-08-02 13:33:06 +00:00
import com.sun.mail.imap.IMAPFolder;
2020-01-07 16:43:27 +00:00
import com.sun.mail.imap.IMAPStore;
2020-12-02 13:39:48 +00:00
import com.sun.mail.imap.protocol.IMAPProtocol;
import com.sun.mail.imap.protocol.IMAPResponse;
2019-02-27 15:05:15 +00:00
2022-07-20 18:43:15 +00:00
import net.openid.appauth.AuthState;
2022-04-23 10:44:25 +00:00
import org.json.JSONObject;
2021-03-30 07:12:36 +00:00
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
2018-08-02 13:33:06 +00:00
import java.util.ArrayList;
import java.util.Arrays;
2018-08-02 13:33:06 +00:00
import java.util.Calendar;
2019-05-21 13:21:03 +00:00
import java.util.Collections;
import java.util.Comparator;
2018-08-02 13:33:06 +00:00
import java.util.Date;
2018-08-04 22:35:47 +00:00
import java.util.HashMap;
import java.util.Hashtable;
2020-11-17 17:29:02 +00:00
import java.util.LinkedHashMap;
2018-08-02 13:33:06 +00:00
import java.util.List;
2018-08-04 22:35:47 +00:00
import java.util.Map;
import java.util.Objects;
2022-04-18 10:37:28 +00:00
import java.util.concurrent.CountDownLatch;
2018-08-02 13:33:06 +00:00
import java.util.concurrent.ExecutorService;
2020-09-23 06:19:28 +00:00
import java.util.concurrent.ThreadPoolExecutor;
2022-04-18 10:37:28 +00:00
import java.util.concurrent.TimeUnit;
2018-08-02 13:33:06 +00:00
2019-06-23 18:56:07 +00:00
import javax.mail.AuthenticationFailedException;
2018-08-02 13:33:06 +00:00
import javax.mail.Folder;
2018-08-02 15:25:01 +00:00
import javax.mail.FolderClosedException;
2019-05-25 14:45:46 +00:00
import javax.mail.FolderNotFoundException;
2018-08-02 13:33:06 +00:00
import javax.mail.Message;
2021-10-25 11:38:12 +00:00
import javax.mail.MessageRemovedException;
2018-08-02 13:33:06 +00:00
import javax.mail.MessagingException;
2018-08-15 19:34:22 +00:00
import javax.mail.NoSuchProviderException;
2020-01-07 16:43:27 +00:00
import javax.mail.Quota;
2019-04-29 19:54:49 +00:00
import javax.mail.ReadOnlyFolderException;
2020-12-02 11:00:35 +00:00
import javax.mail.Store;
2018-09-03 16:34:38 +00:00
import javax.mail.StoreClosedException;
2018-08-02 13:33:06 +00:00
import javax.mail.event.FolderAdapter;
import javax.mail.event.FolderEvent;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
2019-02-27 15:05:15 +00:00
import me.leolin.shortcutbadger.ShortcutBadger;
public class ServiceSynchronize extends ServiceBase implements SharedPreferences.OnSharedPreferenceChangeListener {
2020-09-24 09:14:27 +00:00
private Network lastActive = null;
2019-12-07 21:06:40 +00:00
private Boolean lastSuitable = null;
2019-12-12 08:19:30 +00:00
private long lastLost = 0;
2019-12-07 21:06:40 +00:00
private int lastAccounts = 0;
private int lastOperations = 0;
2020-10-28 10:44:15 +00:00
private ConnectionHelper.NetworkState lastNetworkState = null;
private boolean isInCall = false;
private boolean isInCar = false;
2022-10-22 11:26:24 +00:00
private boolean isOptimizing = false;
2019-02-28 07:55:08 +00:00
private boolean foreground = false;
2021-01-17 15:12:43 +00:00
private final Map<Long, Core.State> coreStates = new Hashtable<>();
private final MutableLiveData<ConnectionHelper.NetworkState> liveNetworkState = new MutableLiveData<>();
private final MutableLiveData<List<TupleAccountState>> liveAccountState = new MutableLiveData<>();
private final MediatorState liveAccountNetworkState = new MediatorState();
2019-12-12 07:51:48 +00:00
2023-01-01 10:50:54 +00:00
private static final ExecutorService executor =
Helper.getBackgroundExecutor(1, 1, 0, "sync");
2021-01-02 20:11:31 +00:00
private static final long BACKUP_DELAY = 30 * 1000L; // milliseconds
2020-12-30 19:06:34 +00:00
private static final long PURGE_DELAY = 30 * 1000L; // milliseconds
2021-10-23 12:58:48 +00:00
private static final int QUIT_DELAY = 10; // seconds
private static final long STILL_THERE_THRESHOLD = 3 * 60 * 1000L; // milliseconds
2021-12-12 07:42:41 +00:00
private static final int TUNE_KEEP_ALIVE_INTERVAL_MIN = 9; // minutes
private static final int TUNE_KEEP_ALIVE_INTERVAL_STEP = 2; // minutes
2020-07-06 05:47:20 +00:00
private static final int OPTIMIZE_POLL_INTERVAL = 15; // minutes
private static final int CONNECT_BACKOFF_START = 8; // seconds
private static final int CONNECT_BACKOFF_MAX = 8; // seconds (totally 8+2x20=48 seconds)
private static final int CONNECT_BACKOFF_INTERMEDIATE = 5; // minutes
2020-09-29 19:47:45 +00:00
private static final int CONNECT_BACKOFF_ALARM_START = 15; // minutes
private static final int CONNECT_BACKOFF_ALARM_MAX = 60; // minutes
2020-10-31 09:00:32 +00:00
private static final long CONNECT_BACKOFF_GRACE = 2 * 60 * 1000L; // milliseconds
2020-10-31 09:33:10 +00:00
private static final long LOST_RECENTLY = 150 * 1000L; // milliseconds
2021-01-20 21:20:49 +00:00
private static final int ACCOUNT_ERROR_AFTER = 90; // minutes
2020-10-01 13:46:20 +00:00
private static final int ACCOUNT_ERROR_AFTER_POLL = 4; // times
2020-11-01 08:09:51 +00:00
private static final int FAST_FAIL_THRESHOLD = 75; // percent
2021-08-06 06:21:06 +00:00
private static final int FAST_FAIL_COUNT = 3;
2020-11-10 19:06:02 +00:00
private static final int FETCH_YIELD_DURATION = 50; // milliseconds
2021-06-16 10:53:04 +00:00
private static final long WATCHDOG_INTERVAL = 60 * 60 * 1000L; // milliseconds
2020-06-05 06:36:17 +00:00
private static final String ACTION_NEW_MESSAGE_COUNT = BuildConfig.APPLICATION_ID + ".NEW_MESSAGE_COUNT";
private static final List<String> PREF_EVAL = Collections.unmodifiableList(Arrays.asList(
2019-12-10 10:09:36 +00:00
"enabled", "poll_interval" // restart account(s)
));
private static final List<String> PREF_RELOAD = Collections.unmodifiableList(Arrays.asList(
2020-10-25 17:21:20 +00:00
"sync_nodate",
"sync_unseen",
"sync_flagged",
"delete_unseen",
"sync_kept",
"sync_folders",
"sync_shared_folders",
"download_headers", "download_eml",
2022-07-11 10:21:47 +00:00
"prefer_ip4", "bind_socket", "standalone_vpn", "tcp_keep_alive", "ssl_harden", "ssl_harden_strict", "cert_strict", // force reconnect
2020-12-02 13:39:48 +00:00
"experiments", "debug", "protocol", // force reconnect
2022-02-03 17:24:56 +00:00
"auth_plain", "auth_login", "auth_ntlm", "auth_sasl", "auth_apop", // force reconnect
"keep_alive_poll", "empty_pool", "idle_done", // force reconnect
2021-04-27 05:53:09 +00:00
"exact_alarms" // force schedule
));
2019-02-27 15:05:15 +00:00
2019-02-28 07:55:08 +00:00
static final int PI_ALARM = 1;
static final int PI_BACKOFF = 2;
static final int PI_KEEPALIVE = 3;
2021-03-29 06:37:45 +00:00
static final int PI_ENABLE = 4;
2021-03-29 13:22:49 +00:00
static final int PI_POLL = 5;
2021-03-29 19:11:13 +00:00
static final int PI_WATCHDOG = 6;
2021-03-30 07:12:36 +00:00
static final int PI_UNSNOOZE = 7;
2021-05-10 12:52:39 +00:00
static final int PI_EXISTS = 8;
2018-08-02 13:33:06 +00:00
@Override
public void onCreate() {
2021-01-22 16:34:50 +00:00
EntityLog.log(this, "Service create" +
2021-09-28 20:16:03 +00:00
" version=" + BuildConfig.VERSION_NAME + BuildConfig.REVISION +
2021-01-22 16:34:50 +00:00
" process=" + android.os.Process.myPid());
2018-08-02 13:33:06 +00:00
super.onCreate();
2020-10-16 11:02:32 +00:00
if (isBackgroundService(this))
stopForeground(true);
else
2021-07-15 16:36:39 +00:00
startForeground(NotificationHelper.NOTIFICATION_SYNCHRONIZE,
getNotificationService(null, null));
2018-08-02 13:33:06 +00:00
2022-10-22 11:26:24 +00:00
isOptimizing = Boolean.FALSE.equals(Helper.isIgnoringOptimizations(this));
2018-08-02 13:33:06 +00:00
// Listen for network changes
2022-04-13 20:27:33 +00:00
ConnectivityManager cm = Helper.getSystemService(this, ConnectivityManager.class);
2018-08-02 13:33:06 +00:00
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
// Removed because of Android VPN service
// builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
2019-10-04 15:17:42 +00:00
cm.registerNetworkCallback(builder.build(), networkCallback);
2019-07-11 06:42:20 +00:00
2019-10-04 15:17:42 +00:00
IntentFilter iif = new IntentFilter();
iif.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
iif.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(connectionChangedReceiver, iif);
2018-08-02 13:33:06 +00:00
2020-06-12 12:02:14 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
registerReceiver(idleModeChangedReceiver, new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
2021-01-17 16:23:26 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
registerReceiver(dataSaverChanged, new IntentFilter(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED));
2022-04-01 07:51:40 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
IntentFilter suspend = new IntentFilter();
suspend.addAction(Intent.ACTION_MY_PACKAGE_SUSPENDED);
suspend.addAction(Intent.ACTION_MY_PACKAGE_UNSUSPENDED);
registerReceiver(suspendChanged, suspend);
}
2022-04-01 07:58:07 +00:00
registerReceiver(batteryChanged, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
2020-10-16 11:02:32 +00:00
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
DB db = DB.getInstance(this);
db.account().liveAccountState().observe(this, new Observer<List<TupleAccountState>>() {
@Override
public void onChanged(List<TupleAccountState> accountStates) {
liveAccountState.postValue(accountStates);
}
});
2019-12-06 15:00:11 +00:00
liveAccountNetworkState.addSource(liveNetworkState, new Observer<ConnectionHelper.NetworkState>() {
@Override
public void onChanged(ConnectionHelper.NetworkState networkState) {
liveAccountNetworkState.post(networkState);
}
});
liveAccountNetworkState.addSource(liveAccountState, new Observer<List<TupleAccountState>>() {
@Override
public void onChanged(List<TupleAccountState> accountStates) {
liveAccountNetworkState.post(accountStates);
}
});
2019-12-07 19:32:58 +00:00
liveAccountNetworkState.observeForever(new Observer<List<TupleAccountNetworkState>>() {
2020-01-15 11:07:45 +00:00
private boolean fts = false;
2022-05-08 16:23:28 +00:00
private boolean lastConnected = false;
private int lastEventId = 0;
private int lastQuitId = -1;
2020-12-31 13:12:21 +00:00
private List<Long> initialized = new ArrayList<>();
private List<TupleAccountNetworkState> accountStates = new ArrayList<>();
2022-04-13 20:27:33 +00:00
private PowerManager pm = Helper.getSystemService(ServiceSynchronize.this, PowerManager.class);
2022-01-31 07:29:37 +00:00
private PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":service");
2019-12-06 15:00:11 +00:00
@Override
public void onChanged(List<TupleAccountNetworkState> accountNetworkStates) {
2019-12-07 19:32:58 +00:00
if (accountNetworkStates == null) {
2019-12-09 21:26:29 +00:00
// Destroy
2019-12-12 07:51:48 +00:00
for (TupleAccountNetworkState prev : accountStates)
2019-12-07 19:32:58 +00:00
stop(prev);
2020-01-12 18:28:19 +00:00
quit(null);
2019-12-07 19:32:58 +00:00
accountStates.clear();
2019-12-12 07:51:48 +00:00
coreStates.clear();
2019-12-07 19:32:58 +00:00
liveAccountNetworkState.removeObserver(this);
} else {
2022-05-08 16:23:28 +00:00
int enabled = 0;
int connected = 0;
int accounts = 0;
2019-12-07 21:06:40 +00:00
int operations = 0;
boolean event = false;
2022-06-22 15:27:15 +00:00
boolean runFts = true;
2019-12-07 19:32:58 +00:00
boolean runService = false;
for (TupleAccountNetworkState current : accountNetworkStates) {
2019-12-18 16:43:28 +00:00
Log.d("### evaluating " + current);
2020-12-31 13:12:21 +00:00
if (!initialized.contains(current.accountState.id)) {
initialized.add(current.accountState.id);
init(current);
}
2019-12-07 19:32:58 +00:00
if (current.accountState.shouldRun(current.enabled))
runService = true;
2022-05-08 16:23:28 +00:00
if (!current.accountState.isTransient(ServiceSynchronize.this)) {
if (current.accountState.isEnabled(current.enabled))
enabled++;
if ("connected".equals(current.accountState.state))
connected++;
2022-05-08 16:23:28 +00:00
if ("connected".equals(current.accountState.state) || current.accountState.backoff_until != null)
accounts++;
}
2019-12-09 07:33:25 +00:00
if (current.accountState.synchronize)
operations += current.accountState.operations;
2022-10-11 05:32:39 +00:00
if (current.accountState.operations > 0 && current.canRun(ServiceSynchronize.this))
2022-06-22 15:27:15 +00:00
runFts = false;
2019-12-07 19:32:58 +00:00
2019-12-10 10:09:36 +00:00
long account = current.command.getLong("account", -1);
if (account > 0 && !current.accountState.id.equals(account))
continue;
2021-02-25 09:19:15 +00:00
boolean sync = current.command.getBoolean("sync", false);
boolean force = current.command.getBoolean("force", false);
2021-07-17 09:53:14 +00:00
if (force) {
2021-03-16 07:54:59 +00:00
sync = true;
2021-07-17 09:53:14 +00:00
current.accountState.operations++;
}
2021-02-25 09:19:15 +00:00
2019-12-07 19:32:58 +00:00
int index = accountStates.indexOf(current);
if (index < 0) {
if (current.canRun(ServiceSynchronize.this)) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### new " + current +
" force=" + force +
" start=" + current.canRun(ServiceSynchronize.this) +
2021-08-15 18:32:34 +00:00
" sync=" + current.accountState.isEnabled(current.enabled) +
" enabled=" + current.accountState.synchronize +
" ondemand=" + current.accountState.ondemand +
" folders=" + current.accountState.folders +
" ops=" + current.accountState.operations +
" tbd=" + current.accountState.tbd +
" state=" + current.accountState.state +
" active=" + current.networkState.getActive());
event = true;
2021-02-25 09:19:15 +00:00
start(current, current.accountState.isEnabled(current.enabled) || sync, force);
2019-12-07 19:32:58 +00:00
}
} else {
2019-12-09 21:26:29 +00:00
boolean reload = false;
2019-12-10 10:09:36 +00:00
switch (current.command.getString("name")) {
case "reload":
reload = true;
break;
}
2019-12-09 21:26:29 +00:00
2021-01-16 10:28:08 +00:00
TupleAccountNetworkState prev = accountStates.get(index);
Core.State state = coreStates.get(current.accountState.id);
if (state != null)
state.setNetworkState(current.networkState);
2019-12-10 09:36:59 +00:00
accountStates.remove(index);
// Some networks disallow email server connections:
// - reload on network type change when disconnected
if (reload ||
prev.canRun(ServiceSynchronize.this) != current.canRun(ServiceSynchronize.this) ||
2020-10-27 19:49:20 +00:00
!prev.accountState.equals(current.accountState)) {
if (prev.canRun(ServiceSynchronize.this) || current.canRun(ServiceSynchronize.this))
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### changed " + current +
" reload=" + reload +
" force=" + force +
" stop=" + prev.canRun(ServiceSynchronize.this) +
" start=" + current.canRun(ServiceSynchronize.this) +
2021-08-15 18:32:34 +00:00
" sync=" + sync +
" enabled=" + current.accountState.isEnabled(current.enabled) +
" should=" + current.accountState.shouldRun(current.enabled) +
" changed=" + !prev.accountState.equals(current.accountState) +
" synchronize=" + current.accountState.synchronize +
" ondemand=" + current.accountState.ondemand +
" folders=" + current.accountState.folders +
" ops=" + current.accountState.operations +
" tbd=" + current.accountState.tbd +
" state=" + current.accountState.state +
" active=" + prev.networkState.getActive() + "/" + current.networkState.getActive());
if (prev.canRun(ServiceSynchronize.this)) {
event = true;
stop(prev);
}
if (current.canRun(ServiceSynchronize.this)) {
event = true;
2022-12-30 08:17:02 +00:00
boolean dosync = (sync ||
current.accountState.isEnabled(current.enabled) ||
!prev.accountState.equals(current.accountState)); // Token refreshed
start(current, dosync, force);
}
2022-09-29 04:43:04 +00:00
} else if (current.canRun(ServiceSynchronize.this) &&
state != null && !state.isAlive()) {
2022-03-30 06:14:06 +00:00
Log.e(current + " died");
EntityLog.log(ServiceSynchronize.this, "### died " + current);
event = true;
start(current, current.accountState.isEnabled(current.enabled) || sync, force);
2020-10-27 19:49:20 +00:00
} else {
if (state != null) {
Network p = prev.networkState.getActive();
if (p != null && !p.equals(current.networkState.getActive())) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### changed " + current +
" active=" + prev.networkState.getActive() + "/" + current.networkState.getActive());
2020-10-27 19:49:20 +00:00
state.error(new OperationCanceledException("Active network changed"));
}
}
2019-12-07 19:32:58 +00:00
}
}
2019-12-07 19:32:58 +00:00
if (current.accountState.tbd == null)
accountStates.add(current);
else {
event = true;
2019-12-18 16:43:28 +00:00
delete(current);
}
}
boolean ok = (enabled > 0 && connected == enabled);
if (lastConnected != ok) {
lastConnected = ok;
prefs.edit().putBoolean("connected", ok).apply();
2022-05-08 16:23:28 +00:00
WidgetSync.update(ServiceSynchronize.this);
}
if (event) {
lastEventId++;
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### eventId=" + lastEventId);
2019-12-07 19:32:58 +00:00
}
2020-01-17 07:54:16 +00:00
if (lastAccounts != accounts || lastOperations != operations) {
lastAccounts = accounts;
lastOperations = operations;
2022-06-22 15:27:15 +00:00
if (runFts) {
2020-01-17 07:54:16 +00:00
fts = true;
WorkerFts.init(ServiceSynchronize.this, false);
} else if (fts) {
fts = false;
WorkerFts.cancel(ServiceSynchronize.this);
2019-12-07 19:32:58 +00:00
}
2020-02-22 21:09:46 +00:00
2021-01-02 20:11:31 +00:00
getMainHandler().removeCallbacks(backup);
getMainHandler().postDelayed(backup, BACKUP_DELAY);
2020-10-28 10:44:15 +00:00
if (!isBackgroundService(ServiceSynchronize.this))
try {
2022-06-09 10:38:17 +00:00
NotificationManager nm =
Helper.getSystemService(ServiceSynchronize.this, NotificationManager.class);
if (NotificationHelper.areNotificationsEnabled(nm))
nm.notify(NotificationHelper.NOTIFICATION_SYNCHRONIZE,
getNotificationService(lastAccounts, lastOperations));
} catch (Throwable ex) {
2020-02-22 21:09:46 +00:00
/*
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.lang.Iterable.iterator()' on a null object reference
at android.app.ApplicationPackageManager.getUserIfProfile(ApplicationPackageManager.java:2167)
at android.app.ApplicationPackageManager.getUserBadgeForDensity(ApplicationPackageManager.java:1002)
at android.app.Notification$Builder.getProfileBadgeDrawable(Notification.java:2890)
at android.app.Notification$Builder.hasThreeLines(Notification.java:3105)
at android.app.Notification$Builder.build(Notification.java:3659)
at androidx.core.app.NotificationCompatBuilder.buildInternal(SourceFile:355)
at androidx.core.app.NotificationCompatBuilder.build(SourceFile:247)
at androidx.core.app.NotificationCompat$Builder.build(SourceFile:1677)
*/
Log.w(ex);
}
2020-01-17 07:54:16 +00:00
}
if (!runService && lastQuitId != lastEventId) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### quitting" +
" run=" + runService +
" startId=" + lastQuitId + "/" + lastEventId);
lastQuitId = lastEventId;
quit(lastEventId);
}
}
}
2020-12-31 13:12:21 +00:00
private void init(final TupleAccountNetworkState accountNetworkState) {
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("state#init") {
2020-12-31 13:12:21 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2020-12-31 13:12:21 +00:00
try {
2022-10-22 06:19:29 +00:00
wl.acquire(Helper.WAKELOCK_MAX);
2020-12-31 13:12:21 +00:00
2022-01-31 07:29:37 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
"### init " + accountNetworkState);
2020-12-31 13:12:21 +00:00
2022-01-31 07:29:37 +00:00
DB db = DB.getInstance(ServiceSynchronize.this);
try {
db.beginTransaction();
2020-12-31 13:12:21 +00:00
2022-01-31 07:29:37 +00:00
db.account().setAccountState(accountNetworkState.accountState.id, null);
db.account().setAccountBackoff(accountNetworkState.accountState.id, null);
2020-12-31 13:12:21 +00:00
2022-01-31 07:29:37 +00:00
for (EntityFolder folder : db.folder().getFolders(accountNetworkState.accountState.id, false, false)) {
db.folder().setFolderState(folder.id, null);
if (db.operation().getOperationCount(folder.id, EntityOperation.SYNC) == 0)
db.folder().setFolderSyncState(folder.id, null);
db.folder().setFolderPollCount(folder.id, 0);
}
db.operation().resetOperationStates(accountNetworkState.accountState.id);
db.setTransactionSuccessful();
} catch (Throwable ex) {
Log.e(ex);
} finally {
db.endTransaction();
}
2020-12-31 13:12:21 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wl.isHeld())
wl.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("state#init released elapse=" + (new Date().getTime() - start));
2020-12-31 13:12:21 +00:00
}
}
});
}
private void start(final TupleAccountNetworkState accountNetworkState, boolean sync, boolean force) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
"Service start=" + accountNetworkState + " sync=" + sync + " force=" + force);
2019-12-07 21:06:40 +00:00
final Core.State astate = new Core.State(accountNetworkState.networkState);
2022-04-17 19:34:33 +00:00
astate.runnable(new RunnableEx("state#monitor") {
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
try {
monitorAccount(accountNetworkState.accountState, astate, sync, force);
} catch (Throwable ex) {
Log.e(accountNetworkState.accountState.name, ex);
}
}
}, "sync.account." + accountNetworkState.accountState.id);
2019-12-12 07:51:48 +00:00
coreStates.put(accountNetworkState.accountState.id, astate);
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("state#start") {
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2020-10-30 07:02:00 +00:00
try {
2022-10-22 06:19:29 +00:00
wl.acquire(Helper.WAKELOCK_MAX);
2022-01-31 07:29:37 +00:00
2020-10-30 07:02:00 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("account", accountNetworkState.accountState.id.toString());
crumb.put("connected", Boolean.toString(accountNetworkState.networkState.isConnected()));
crumb.put("suitable", Boolean.toString(accountNetworkState.networkState.isSuitable()));
crumb.put("unmetered", Boolean.toString(accountNetworkState.networkState.isUnmetered()));
crumb.put("roaming", Boolean.toString(accountNetworkState.networkState.isRoaming()));
crumb.put("lastLost", new Date(lastLost).toString());
Log.breadcrumb("start", crumb);
Log.i("### start=" + accountNetworkState + " sync=" + sync);
astate.start();
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### started=" + accountNetworkState);
2020-10-30 07:02:00 +00:00
} catch (Throwable ex) {
Log.e(ex);
2022-01-31 07:29:37 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wl.isHeld())
wl.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("state#start released elapse=" + (new Date().getTime() - start));
2020-10-30 07:02:00 +00:00
}
}
});
}
private void stop(final TupleAccountNetworkState accountNetworkState) {
2019-12-12 07:51:48 +00:00
final Core.State state = coreStates.get(accountNetworkState.accountState.id);
2020-10-30 07:02:00 +00:00
if (state == null)
return;
2019-12-12 07:51:48 +00:00
coreStates.remove(accountNetworkState.accountState.id);
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"Service stop=" + accountNetworkState);
2020-10-30 07:02:00 +00:00
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("state#stop") {
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2020-10-30 07:02:00 +00:00
try {
2022-10-22 06:19:29 +00:00
wl.acquire(Helper.WAKELOCK_MAX);
2022-01-31 07:29:37 +00:00
2020-10-30 07:02:00 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("account", accountNetworkState.accountState.id.toString());
crumb.put("connected", Boolean.toString(accountNetworkState.networkState.isConnected()));
crumb.put("suitable", Boolean.toString(accountNetworkState.networkState.isSuitable()));
crumb.put("unmetered", Boolean.toString(accountNetworkState.networkState.isUnmetered()));
crumb.put("roaming", Boolean.toString(accountNetworkState.networkState.isRoaming()));
crumb.put("lastLost", new Date(lastLost).toString());
Log.breadcrumb("stop", crumb);
Log.i("### stop=" + accountNetworkState);
2021-04-05 06:23:00 +00:00
db.account().setAccountThread(accountNetworkState.accountState.id, null);
2020-10-30 07:02:00 +00:00
state.stop();
2021-11-28 10:09:21 +00:00
state.join();
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### stopped=" + accountNetworkState);
2020-10-30 07:02:00 +00:00
} catch (Throwable ex) {
Log.e(ex);
2022-01-31 07:29:37 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wl.isHeld())
wl.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("state#stop released elapse=" + (new Date().getTime() - start));
2020-10-30 07:02:00 +00:00
}
}
});
2019-12-06 15:00:11 +00:00
}
private void delete(final TupleAccountNetworkState accountNetworkState) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"Service delete=" + accountNetworkState);
2019-06-01 06:44:46 +00:00
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("state#delete") {
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2020-10-30 07:02:00 +00:00
try {
2022-10-22 06:19:29 +00:00
wl.acquire(Helper.WAKELOCK_MAX);
2022-01-31 07:29:37 +00:00
2020-10-30 07:02:00 +00:00
DB db = DB.getInstance(ServiceSynchronize.this);
db.account().deleteAccount(accountNetworkState.accountState.id);
2020-10-30 07:02:00 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
2022-04-13 20:27:33 +00:00
NotificationManager nm = Helper.getSystemService(ServiceSynchronize.this, NotificationManager.class);
2020-10-30 07:02:00 +00:00
nm.deleteNotificationChannel(EntityAccount.getNotificationChannelId(accountNetworkState.accountState.id));
}
} catch (Throwable ex) {
Log.e(ex);
2022-01-31 07:29:37 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wl.isHeld())
wl.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("state#delete released elapse=" + (new Date().getTime() - start));
}
2019-06-01 13:58:09 +00:00
}
});
}
2019-06-01 06:44:46 +00:00
private void quit(final Integer eventId) {
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("state#quit") {
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2020-10-30 07:02:00 +00:00
try {
2022-10-22 06:19:29 +00:00
wl.acquire(Helper.WAKELOCK_MAX);
2022-01-31 07:29:37 +00:00
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### quit eventId=" + eventId);
2020-10-30 07:02:00 +00:00
if (eventId == null) {
// Service destroy
DB db = DB.getInstance(ServiceSynchronize.this);
List<EntityOperation> ops = db.operation().getOperations(EntityOperation.SYNC);
for (EntityOperation op : ops)
db.folder().setFolderSyncState(op.folder, null);
2021-01-02 19:59:18 +00:00
2021-01-02 22:02:04 +00:00
getMainHandler().removeCallbacks(backup);
2021-01-02 19:59:18 +00:00
MessageClassifier.save(ServiceSynchronize.this);
2020-10-30 07:02:00 +00:00
} else {
// Yield update notifications/widgets
2021-03-29 13:24:22 +00:00
for (int i = 0; i < QUIT_DELAY; i++) {
try {
Thread.sleep(1000L);
} catch (InterruptedException ex) {
Log.w(ex);
}
2021-03-29 13:24:22 +00:00
if (!eventId.equals(lastEventId)) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### quit cancelled eventId=" + eventId + "/" + lastEventId);
2021-03-29 13:24:22 +00:00
return;
}
2020-10-30 07:02:00 +00:00
}
2020-10-30 07:02:00 +00:00
// Stop service
2022-01-31 07:29:37 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
"### stopping self eventId=" + eventId);
2020-10-30 07:02:00 +00:00
stopSelf();
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2022-01-31 07:29:37 +00:00
"### stopped self eventId=" + eventId);
2020-10-17 13:57:01 +00:00
2022-06-06 13:20:29 +00:00
WorkerCleanup.cleanupConditionally(getApplicationContext());
2020-10-30 07:02:00 +00:00
}
} catch (Throwable ex) {
Log.e(ex);
2022-01-31 07:29:37 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wl.isHeld())
wl.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("state#quit released elapse=" + (new Date().getTime() - start));
2020-01-12 18:28:19 +00:00
}
}
});
}
2021-01-02 20:11:31 +00:00
2022-04-17 19:34:33 +00:00
private final Runnable backup = new RunnableEx("state#backup") {
2021-01-02 20:11:31 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("state#backup#exec") {
2021-01-02 20:11:31 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2021-01-02 20:11:31 +00:00
try {
2022-10-22 06:19:29 +00:00
wl.acquire(Helper.WAKELOCK_MAX);
2022-01-31 07:29:37 +00:00
2021-01-02 20:11:31 +00:00
MessageClassifier.save(ServiceSynchronize.this);
} catch (Throwable ex) {
Log.e(ex);
2022-01-31 07:29:37 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wl.isHeld())
wl.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("state#backup released elapse=" + (new Date().getTime() - start));
2021-01-02 20:11:31 +00:00
}
}
});
}
};
});
final TwoStateOwner cowner = new TwoStateOwner(this, "liveSynchronizing");
2022-06-17 20:46:00 +00:00
2021-09-02 21:06:59 +00:00
db.folder().liveSynchronizing().observe(this, new Observer<List<TupleFolderSync>>() {
2021-09-03 05:55:29 +00:00
private List<Long> lastAccounts = new ArrayList<>();
private List<Long> lastFolders = new ArrayList<>();
@Override
2021-09-02 21:06:59 +00:00
public void onChanged(List<TupleFolderSync> syncs) {
int syncing = 0;
2021-09-03 05:55:29 +00:00
boolean changed = false;
2021-09-02 21:06:59 +00:00
List<Long> accounts = new ArrayList<>();
List<Long> folders = new ArrayList<>();
if (syncs != null)
for (TupleFolderSync sync : syncs) {
if ("syncing".equals(sync.sync_state))
syncing++;
2021-09-03 05:55:29 +00:00
if (sync.unified && !accounts.contains(sync.account)) {
2021-09-02 21:06:59 +00:00
accounts.add(sync.account);
2021-09-03 05:55:29 +00:00
if (lastAccounts.contains(sync.account))
lastAccounts.remove(sync.account); // same
else
changed = true; // new
}
2021-09-02 21:06:59 +00:00
folders.add(sync.folder);
2021-09-03 05:55:29 +00:00
if (lastFolders.contains(sync.folder))
lastFolders.remove(sync.folder); // same
else
changed = true; // new
2021-09-02 21:06:59 +00:00
}
2021-09-03 05:55:29 +00:00
changed = (changed || lastAccounts.size() > 0 || lastFolders.size() > 0); // deleted
lastAccounts = accounts;
lastFolders = folders;
Log.i("Changed=" + changed +
" syncing=" + syncing +
2021-09-02 21:06:59 +00:00
" folders=" + folders.size() +
" accounts=" + accounts.size());
if (syncing == 0)
cowner.start();
else
cowner.stop();
2021-09-02 21:06:59 +00:00
2021-09-03 05:55:29 +00:00
if (!changed)
return;
2021-09-02 21:06:59 +00:00
for (String _key : prefs.getAll().keySet())
if (_key.startsWith("widget.") && _key.endsWith(".refresh") &&
prefs.getBoolean(_key, false)) {
int appWidgetId = Integer.parseInt(_key.split("\\.")[1]);
long account = prefs.getLong("widget." + appWidgetId + ".account", -1L);
long folder = prefs.getLong("widget." + appWidgetId + ".folder", -1L);
2021-09-03 13:48:48 +00:00
boolean state;
if (folder > 0)
state = folders.contains(folder);
else if (account > 0)
state = accounts.contains(account);
else
state = (accounts.size() > 0);
String key = "widget." + appWidgetId + ".syncing";
if (state != prefs.getBoolean(key, false)) {
prefs.edit().putBoolean(key, state).apply();
WidgetUnified.init(ServiceSynchronize.this, appWidgetId);
2021-09-02 21:06:59 +00:00
}
}
}
});
// New message notifications batching
Core.NotificationData notificationData = new Core.NotificationData(this);
MutableLiveData<List<TupleMessageEx>> mutableUnseenNotify = new MutableLiveData<>();
2019-03-20 14:52:51 +00:00
db.message().liveUnseenNotify().observe(cowner, new Observer<List<TupleMessageEx>>() {
@Override
public void onChanged(List<TupleMessageEx> messages) {
mutableUnseenNotify.setValue(messages);
}
});
final TwoStateOwner mowner = new TwoStateOwner(this, "mutableUnseenNotify");
mowner.getLifecycle().addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onStateChanged() {
Lifecycle.State state = mowner.getLifecycle().getCurrentState();
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Debug, "Owner state=" + state);
if (state.equals(Lifecycle.State.DESTROYED))
mowner.getLifecycle().removeObserver(this);
}
});
MediaPlayerHelper.liveInCall(this, this, new MediaPlayerHelper.IInCall() {
@Override
public void onChanged(boolean inCall) {
boolean suppress = prefs.getBoolean("notify_suppress_in_call", false);
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Debug,
"In call=" + inCall + " suppress=" + suppress);
isInCall = (inCall && suppress);
if (isInCall || isInCar)
mowner.stop();
else
mowner.start();
}
});
new CarConnection(this).getType().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer connectionState) {
boolean projection = (connectionState != null &&
connectionState == CarConnection.CONNECTION_TYPE_PROJECTION);
boolean suppress = prefs.getBoolean("notify_suppress_in_car", false);
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Debug,
"Projection=" + projection + " state=" + connectionState + " suppress=" + suppress);
isInCar = (projection && suppress);
if (isInCall || isInCar)
mowner.stop();
else
mowner.start();
}
});
mutableUnseenNotify.observe(mowner, new Observer<List<TupleMessageEx>>() {
@Override
2019-08-01 07:19:22 +00:00
public void onChanged(final List<TupleMessageEx> messages) {
2023-01-01 10:50:54 +00:00
executor.submit(new RunnableEx("mutableUnseenNotify") {
2019-08-01 07:19:22 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2019-08-01 07:19:22 +00:00
try {
Core.notifyMessages(ServiceSynchronize.this, messages, notificationData, foreground);
2019-08-01 07:19:22 +00:00
} catch (SecurityException ex) {
Log.w(ex);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
prefs.edit().remove("sound").apply();
} catch (Throwable ex) {
Log.e(ex);
}
}
});
2018-08-02 13:33:06 +00:00
}
2020-03-28 09:02:00 +00:00
});
// Message count widgets
2020-03-28 09:02:00 +00:00
db.message().liveWidgetUnseen(null).observe(cowner, new Observer<List<TupleMessageStats>>() {
2020-04-25 06:51:50 +00:00
private Integer lastCount = null;
2020-03-28 09:02:00 +00:00
private List<TupleMessageStats> last = null;
@Override
public void onChanged(List<TupleMessageStats> stats) {
if (stats == null)
stats = new ArrayList<>();
boolean changed = false;
if (last == null || last.size() != stats.size())
changed = true;
else
for (int i = 0; i < stats.size(); i++)
if (!last.get(i).equals(stats.get(i))) {
changed = true;
break;
}
if (!changed)
return;
2020-04-20 08:38:45 +00:00
last = stats;
2021-05-16 08:17:52 +00:00
EntityLog.log(ServiceSynchronize.this, "Widget update");
2020-06-16 09:33:28 +00:00
Widget.update(ServiceSynchronize.this);
2020-03-28 09:02:00 +00:00
boolean badge = prefs.getBoolean("badge", true);
boolean unseen_ignored = prefs.getBoolean("unseen_ignored", false);
int count = 0;
for (TupleMessageStats stat : stats) {
Integer unseen = (unseen_ignored ? stat.notifying : stat.unseen);
if (unseen != null)
count += unseen;
}
2020-04-25 06:51:50 +00:00
if (lastCount == null || !lastCount.equals(count)) {
lastCount = count;
2021-09-01 13:08:59 +00:00
2021-09-05 05:42:08 +00:00
EntityLog.log(ServiceSynchronize.this, "Badge count=" + count +
" enabled=" + badge + " Unseen/ignored=" + unseen_ignored);
2021-09-01 13:08:59 +00:00
2020-06-05 06:36:17 +00:00
// Broadcast new message count
try {
Intent intent = new Intent(ACTION_NEW_MESSAGE_COUNT);
intent.putExtra("count", count);
sendBroadcast(intent);
} catch (Throwable ex) {
Log.e(ex);
}
// Update badge
2020-04-25 06:51:50 +00:00
try {
if (count == 0 || !badge)
ShortcutBadger.removeCount(ServiceSynchronize.this);
else
ShortcutBadger.applyCount(ServiceSynchronize.this, count);
} catch (Throwable ex) {
Log.e(ex);
}
2020-03-28 09:02:00 +00:00
}
}
2018-08-02 13:33:06 +00:00
});
// Message list widgets
2019-12-01 10:42:54 +00:00
db.message().liveWidgetUnified().observe(cowner, new Observer<List<TupleMessageWidgetCount>>() {
private List<TupleMessageWidgetCount> last = null;
2019-07-25 15:22:00 +00:00
@Override
public void onChanged(List<TupleMessageWidgetCount> current) {
if (current == null)
current = new ArrayList<>();
boolean changed = false;
if (last == null || last.size() != current.size())
changed = true;
else
for (int i = 0; i < current.size(); i++)
if (!current.get(i).equals(last.get(i))) {
changed = true;
break;
}
2020-06-16 09:33:28 +00:00
if (changed)
WidgetUnified.updateData(ServiceSynchronize.this);
2019-11-18 09:14:37 +00:00
last = current;
2019-07-25 15:22:00 +00:00
}
});
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
2020-10-28 10:44:15 +00:00
if (PREF_EVAL.contains(key)) {
2019-12-09 21:26:29 +00:00
Bundle command = new Bundle();
2020-04-07 09:20:27 +00:00
command.putString("pref", key);
2019-12-09 21:26:29 +00:00
command.putString("name", "eval");
2019-12-12 10:57:35 +00:00
liveAccountNetworkState.post(command);
2020-10-28 10:44:15 +00:00
} else if (PREF_RELOAD.contains(key) || ConnectionHelper.PREF_NETWORK.contains(key)) {
2020-10-29 12:57:42 +00:00
if (ConnectionHelper.PREF_NETWORK.contains(key))
2021-01-16 18:21:31 +00:00
updateNetworkState(null, "preference");
2019-12-09 21:26:29 +00:00
Bundle command = new Bundle();
2020-04-07 09:20:27 +00:00
command.putString("pref", key);
2019-12-09 21:26:29 +00:00
command.putString("name", "reload");
liveAccountNetworkState.post(command);
}
2018-10-16 10:26:35 +00:00
}
@Override
public void onDestroy() {
2019-03-25 14:05:52 +00:00
EntityLog.log(this, "Service destroy");
2018-10-16 10:26:35 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(this);
2022-04-01 07:58:07 +00:00
unregisterReceiver(batteryChanged);
2022-04-01 07:51:40 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
unregisterReceiver(suspendChanged);
2021-01-17 16:23:26 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
unregisterReceiver(dataSaverChanged);
2020-06-12 12:02:14 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
unregisterReceiver(idleModeChangedReceiver);
2019-10-04 15:17:42 +00:00
unregisterReceiver(connectionChangedReceiver);
2019-07-11 06:42:20 +00:00
2022-04-13 20:27:33 +00:00
ConnectivityManager cm = Helper.getSystemService(this, ConnectivityManager.class);
2019-10-04 15:17:42 +00:00
cm.unregisterNetworkCallback(networkCallback);
2018-10-16 10:26:35 +00:00
2019-12-07 19:32:58 +00:00
liveAccountNetworkState.postDestroy();
2018-10-21 18:29:28 +00:00
2020-07-03 19:00:15 +00:00
TTSHelper.shutdown();
2019-08-12 06:18:28 +00:00
try {
stopForeground(true);
} catch (Throwable ex) {
Log.e(ex);
/*
OnePlus A6013 - Android 9
java.lang.RuntimeException: Unable to stop service eu.faircode.email.ServiceSynchronize@3995fc9: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at android.app.ActivityThread.handleStopService(ActivityThread.java:3908)
at android.app.ActivityThread.access$1900(ActivityThread.java:209)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1826)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6954)
at java.lang.reflect.Method.invoke(Method.java:-2)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at android.os.Parcel.createException(Parcel.java:1956)
at android.os.Parcel.readException(Parcel.java:1918)
at android.os.Parcel.readException(Parcel.java:1868)
at android.app.IActivityManager$Stub$Proxy.setServiceForeground(IActivityManager.java:5111)
at android.app.Service.stopForeground(Service.java:724)
at android.app.Service.stopForeground(Service.java:710)
*/
}
2018-10-16 10:26:35 +00:00
2022-04-13 20:27:33 +00:00
NotificationManager nm = Helper.getSystemService(this, NotificationManager.class);
2021-07-15 16:36:39 +00:00
nm.cancel(NotificationHelper.NOTIFICATION_SYNCHRONIZE);
2018-10-16 10:26:35 +00:00
super.onDestroy();
2022-05-02 08:15:29 +00:00
CoalMine.watch(this, this.getClass().getName() + "#onDestroy");
2018-10-16 10:26:35 +00:00
}
2020-01-13 16:16:02 +00:00
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i("Task removed=" + rootIntent);
}
2018-10-16 10:26:35 +00:00
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
2021-10-12 05:27:07 +00:00
try {
String action = (intent == null ? null : intent.getAction());
String reason = (intent == null ? null : intent.getStringExtra("reason"));
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
"### Service command " + intent +
" action=" + action + " reason=" + reason);
Log.logExtras(intent);
super.onStartCommand(intent, flags, startId);
if (isBackgroundService(this))
stopForeground(true);
else
startForeground(NotificationHelper.NOTIFICATION_SYNCHRONIZE,
getNotificationService(null, null));
2021-10-12 05:27:07 +00:00
if (action != null) {
2019-12-12 07:51:48 +00:00
switch (action.split(":")[0]) {
2021-03-29 06:37:45 +00:00
case "enable":
onEnable(intent);
break;
case "eval":
2019-12-12 07:51:48 +00:00
onEval(intent);
2019-02-14 12:28:03 +00:00
break;
2019-12-09 21:26:29 +00:00
case "reload":
2019-12-12 07:51:48 +00:00
onReload(intent);
2019-12-09 21:26:29 +00:00
break;
2019-12-12 10:10:57 +00:00
case "backoff":
case "keepalive":
2019-12-12 07:51:48 +00:00
onWakeup(intent);
2018-12-28 17:21:31 +00:00
break;
2021-03-30 07:12:36 +00:00
case "unsnooze":
onUnsnooze(intent);
break;
2021-05-10 12:52:39 +00:00
case "exists":
onExists(intent);
break;
case "state":
onState(intent);
break;
2021-03-29 13:22:49 +00:00
case "poll":
onPoll(intent);
break;
2019-12-09 21:26:29 +00:00
case "alarm":
2019-12-12 07:51:48 +00:00
onAlarm(intent);
2019-05-12 18:15:16 +00:00
break;
2020-03-25 09:44:50 +00:00
case "watchdog":
onWatchdog(intent);
break;
2018-12-28 17:21:31 +00:00
default:
Log.w("Unknown action: " + action);
}
2018-08-22 12:30:27 +00:00
}
2021-10-12 05:27:07 +00:00
} catch (Throwable ex) {
Log.e(ex);
/*
at android.app.ApplicationPackageManager.getUserIfProfile(ApplicationPackageManager.java:2190)
at android.app.ApplicationPackageManager.getUserBadgeForDensity(ApplicationPackageManager.java:1006)
at android.app.Notification$Builder.getProfileBadgeDrawable(Notification.java:2890)
at android.app.Notification$Builder.hasThreeLines(Notification.java:3105)
at android.app.Notification$Builder.build(Notification.java:3659)
at androidx.core.app.NotificationCompatBuilder.buildInternal(NotificationCompatBuilder:426)
at androidx.core.app.NotificationCompatBuilder.build(NotificationCompatBuilder:318)
at androidx.core.app.NotificationCompat$Builder.build(NotificationCompat:2346)
at eu.faircode.email.ServiceSynchronize.onStartCommand(ServiceSynchronize:890)
*/
}
2018-08-02 13:33:06 +00:00
return START_STICKY;
}
2021-03-29 06:37:45 +00:00
private void onEnable(Intent intent) {
boolean enabled = intent.getBooleanExtra("enabled", true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("enabled", enabled).apply();
onEval(intent);
}
2019-12-12 07:51:48 +00:00
private void onEval(Intent intent) {
Bundle command = new Bundle();
command.putString("name", "eval");
command.putLong("account", intent.getLongExtra("account", -1));
liveAccountNetworkState.post(command);
}
private void onReload(Intent intent) {
boolean force = intent.getBooleanExtra("force", false);
2021-01-16 17:15:45 +00:00
if (force) {
2020-03-30 11:07:37 +00:00
lastLost = 0;
2021-01-16 18:21:31 +00:00
updateNetworkState(null, "force");
2021-01-16 17:15:45 +00:00
}
2019-12-12 07:51:48 +00:00
Bundle command = new Bundle();
command.putString("name", "reload");
command.putLong("account", intent.getLongExtra("account", -1));
command.putBoolean("force", force);
2019-12-12 07:51:48 +00:00
liveAccountNetworkState.post(command);
}
private void onWakeup(Intent intent) {
String action = intent.getAction();
long account = Long.parseLong(action.split(":")[1]);
Core.State state = coreStates.get(account);
2020-08-10 14:45:36 +00:00
2019-12-12 07:51:48 +00:00
if (state == null)
2021-08-16 07:36:23 +00:00
EntityLog.log(this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### wakeup missing account=" + account);
2019-12-12 07:51:48 +00:00
else {
2021-08-16 07:36:23 +00:00
EntityLog.log(this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### waking up account=" + account);
2020-08-11 05:47:08 +00:00
if (!state.release())
2021-08-16 07:36:23 +00:00
EntityLog.log(this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### waking up failed account=" + account);
2019-12-12 07:51:48 +00:00
}
}
2021-03-30 07:12:36 +00:00
private void onUnsnooze(Intent intent) {
String action = intent.getAction();
long id = Long.parseLong(action.split(":")[1]);
2022-12-13 09:52:39 +00:00
Helper.getSerialExecutor().submit(new RunnableEx("unsnooze") {
2021-03-30 07:12:36 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2021-03-30 07:12:36 +00:00
try {
EntityFolder folder;
DB db = DB.getInstance(ServiceSynchronize.this);
try {
db.beginTransaction();
EntityMessage message = db.message().getMessage(id);
if (message == null)
return;
folder = db.folder().getFolder(message.folder);
if (folder == null)
return;
2021-07-19 14:27:26 +00:00
EntityAccount account = db.account().getAccount(message.account);
if (account == null)
return;
2021-03-30 07:12:36 +00:00
if (EntityFolder.OUTBOX.equals(folder.type)) {
Log.i("Delayed send id=" + message.id);
if (message.ui_snoozed != null) {
db.message().setMessageSnoozed(message.id, null);
EntityOperation.queue(ServiceSynchronize.this, message, EntityOperation.SEND);
}
} else {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
folder.name + " Unsnooze" +
" id=" + message.id +
" ui_seen=" + message.ui_seen + "" +
" ui_ignored=" + message.ui_ignored +
" ui_hide=" + message.ui_hide +
" notifying=" + message.notifying +
" silent=" + message.ui_silent +
" local=" + message.ui_local_only +
2021-08-15 18:32:34 +00:00
" received=" + new Date(message.received) +
" sent=" + (message.sent == null ? null : new Date(message.sent)) +
" created=" + (account.created == null ? null : new Date(account.created)) +
" notify=" + folder.notify +
" sync=" + account.synchronize);
2021-07-19 14:27:26 +00:00
2021-03-30 07:12:36 +00:00
if (folder.notify) {
List<EntityAttachment> attachments = db.attachment().getAttachments(id);
// A new message ID is needed for a new (wearable) notification
db.message().deleteMessage(id);
message.id = null;
message.fts = false;
2021-07-19 14:27:26 +00:00
message.ui_silent = false;
message.ui_local_only = false;
2021-07-19 14:27:26 +00:00
message.notifying = 0;
2021-05-01 15:01:08 +00:00
message.stored = new Date().getTime();
2021-03-30 07:12:36 +00:00
message.id = db.message().insertMessage(message);
if (message.content) {
File source = EntityMessage.getFile(ServiceSynchronize.this, id);
File target = message.getFile(ServiceSynchronize.this);
try {
Helper.copy(source, target);
} catch (IOException ex) {
Log.e(ex);
db.message().resetMessageContent(message.id);
}
}
for (EntityAttachment attachment : attachments) {
File source = attachment.getFile(ServiceSynchronize.this);
attachment.id = null;
attachment.message = message.id;
attachment.progress = null;
attachment.id = db.attachment().insertAttachment(attachment);
if (attachment.available) {
File target = attachment.getFile(ServiceSynchronize.this);
try {
Helper.copy(source, target);
} catch (IOException ex) {
Log.e(ex);
db.attachment().setError(attachment.id, Log.formatThrowable(ex, false));
}
}
}
}
2021-06-23 07:04:24 +00:00
// Show thread
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
boolean threading = prefs.getBoolean("threading", true);
List<EntityMessage> messages = db.message().getMessagesByThread(
message.account, message.thread, threading ? null : message.id, null);
for (EntityMessage threaded : messages)
db.message().setMessageSnoozed(threaded.id, null);
db.message().setMessageUnsnoozed(message.id, true);
EntityOperation.queue(ServiceSynchronize.this, message, EntityOperation.SEEN, false, false);
2021-03-30 07:12:36 +00:00
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (EntityFolder.OUTBOX.equals(folder.type))
ServiceSend.start(ServiceSynchronize.this);
else
ServiceSynchronize.eval(ServiceSynchronize.this, "unsnooze");
} catch (Throwable ex) {
Log.e(ex);
}
}
});
}
2021-05-10 12:52:39 +00:00
private void onExists(Intent intent) {
String action = intent.getAction();
long id = Long.parseLong(action.split(":")[1]);
2022-12-13 09:52:39 +00:00
Helper.getSerialExecutor().submit(new RunnableEx("exists") {
2021-05-10 12:52:39 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2021-05-10 12:52:39 +00:00
try {
DB db = DB.getInstance(ServiceSynchronize.this);
try {
db.beginTransaction();
// Message could have been deleted in the meantime
EntityMessage message = db.message().getMessage(id);
if (message == null)
return;
EntityOperation.queue(ServiceSynchronize.this, message, EntityOperation.EXISTS, true);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
eval(ServiceSynchronize.this, "exists/delayed");
} catch (Throwable ex) {
Log.e(ex);
}
}
});
}
private void onState(Intent intent) {
foreground = intent.getBooleanExtra("foreground", false);
2022-02-03 09:35:31 +00:00
for (Core.State state : coreStates.values())
state.setForeground(foreground);
}
2021-03-29 13:22:49 +00:00
private void onPoll(Intent intent) {
2022-12-13 09:52:39 +00:00
Helper.getSerialExecutor().submit(new RunnableEx("poll") {
2021-03-29 13:22:49 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2021-03-29 13:22:49 +00:00
try {
2022-04-23 10:44:25 +00:00
long now = new Date().getTime();
2022-04-23 11:03:51 +00:00
long[] schedule = getSchedule(ServiceSynchronize.this);
2022-04-23 10:44:25 +00:00
boolean scheduled = (schedule == null || (now >= schedule[0] && now < schedule[1]));
boolean work = false;
2021-03-29 13:22:49 +00:00
DB db = DB.getInstance(ServiceSynchronize.this);
try {
db.beginTransaction();
List<EntityAccount> accounts = db.account().getPollAccounts(null);
for (EntityAccount account : accounts) {
2022-04-23 10:44:25 +00:00
JSONObject jcondition = new JSONObject();
try {
2022-04-24 07:55:04 +00:00
if (!TextUtils.isEmpty(account.conditions))
jcondition = new JSONObject(account.conditions);
2022-04-23 10:44:25 +00:00
} catch (Throwable ex) {
Log.e(ex);
}
if (scheduled || jcondition.optBoolean("ignore_schedule")) {
work = true;
2022-09-02 07:15:33 +00:00
2022-04-23 10:44:25 +00:00
List<EntityFolder> folders = db.folder().getSynchronizingFolders(account.id);
if (folders.size() > 0)
Collections.sort(folders, folders.get(0).getComparator(ServiceSynchronize.this));
for (EntityFolder folder : folders)
2022-09-02 07:15:33 +00:00
if (folder.poll ||
!account.poll_exempted ||
account.protocol == EntityAccount.TYPE_POP ||
!BuildConfig.DEBUG)
EntityOperation.poll(ServiceSynchronize.this, folder.id);
2022-04-23 10:44:25 +00:00
}
2021-03-29 13:22:49 +00:00
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2022-04-23 10:44:25 +00:00
schedule(ServiceSynchronize.this, work, true, null);
2021-03-29 13:22:49 +00:00
// Prevent service stop
eval(ServiceSynchronize.this, "poll");
} catch (Throwable ex) {
Log.e(ex);
}
}
});
}
2019-12-12 07:51:48 +00:00
private void onAlarm(Intent intent) {
2020-08-29 09:26:47 +00:00
schedule(this, true);
2021-01-17 13:55:21 +00:00
Bundle command = new Bundle();
2021-02-25 10:45:17 +00:00
command.putString("name", "reload"); // eval will not work if manual sync running
2019-12-18 08:29:38 +00:00
command.putBoolean("sync", true);
2019-12-12 07:51:48 +00:00
liveAccountNetworkState.post(command);
}
2020-03-25 09:44:50 +00:00
private void onWatchdog(Intent intent) {
2021-08-16 07:36:23 +00:00
EntityLog.log(this, EntityLog.Type.Scheduling, "Watchdog");
2021-06-16 09:48:16 +00:00
schedule(this, false);
2021-02-24 07:53:55 +00:00
if (lastNetworkState == null || !lastNetworkState.isSuitable())
updateNetworkState(null, "watchdog");
2021-03-29 19:11:13 +00:00
2022-03-30 06:14:06 +00:00
onEval(intent);
2021-03-29 19:11:13 +00:00
ServiceSend.boot(this);
scheduleWatchdog(this);
2020-03-25 09:44:50 +00:00
}
private Notification getNotificationService(Integer accounts, Integer operations) {
2019-12-07 21:06:40 +00:00
if (accounts != null)
this.lastAccounts = accounts;
if (operations != null)
this.lastOperations = operations;
2018-10-17 06:11:20 +00:00
2018-08-02 13:33:06 +00:00
// Build pending intent
2019-03-14 14:57:24 +00:00
Intent why = new Intent(this, ActivityView.class);
why.setAction("why");
2022-06-25 12:27:46 +00:00
why.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2021-03-27 17:54:55 +00:00
PendingIntent piWhy = PendingIntentCompat.getActivity(
2021-05-22 14:54:17 +00:00
this, ActivityView.PI_WHY, why, PendingIntent.FLAG_UPDATE_CURRENT);
2018-08-02 13:33:06 +00:00
// Build notification
2019-06-23 08:23:49 +00:00
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this, "service")
.setSmallIcon(R.drawable.baseline_compare_arrows_white_24)
2022-04-22 08:42:16 +00:00
.setContentIntent(piWhy)
2019-06-23 08:23:49 +00:00
.setAutoCancel(false)
.setShowWhen(false)
.setDefaults(0) // disable sound on pre Android 8
.setPriority(NotificationCompat.PRIORITY_MIN)
2019-07-23 09:38:36 +00:00
.setCategory(NotificationCompat.CATEGORY_SERVICE)
2019-10-16 13:18:59 +00:00
.setVisibility(NotificationCompat.VISIBILITY_SECRET)
.setLocalOnly(true)
.setOngoing(true);
2018-08-02 13:33:06 +00:00
2021-01-26 18:59:40 +00:00
if (lastAccounts > 0)
builder.setContentTitle(getResources().getQuantityString(
R.plurals.title_notification_synchronizing, lastAccounts, lastAccounts));
2021-01-27 08:30:56 +00:00
else
2022-02-15 07:36:09 +00:00
builder.setContentTitle(getString(R.string.title_check_operations));
2021-01-26 18:59:40 +00:00
2019-12-07 21:06:40 +00:00
if (lastOperations > 0)
2019-03-03 09:17:42 +00:00
builder.setContentText(getResources().getQuantityString(
2019-12-07 21:06:40 +00:00
R.plurals.title_notification_operations, lastOperations, lastOperations));
2019-12-07 21:06:40 +00:00
if (lastSuitable == null || !lastSuitable)
builder.setSubText(getString(R.string.title_notification_waiting));
Notification notification = builder.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
return notification;
2018-08-02 13:33:06 +00:00
}
2021-07-31 18:13:58 +00:00
private NotificationCompat.Builder getNotificationAlert(EntityAccount account, String message) {
String title = getString(R.string.title_notification_alert, account.name);
2019-12-10 10:51:03 +00:00
// Build pending intent
2021-07-31 18:13:58 +00:00
Intent intent = new Intent(this, ActivityError.class);
intent.setAction("alert:" + account.id);
intent.putExtra("type", "alert");
intent.putExtra("title", title);
intent.putExtra("message", message);
2021-10-01 17:15:11 +00:00
intent.putExtra("provider", account.provider);
2021-08-13 12:33:37 +00:00
intent.putExtra("account", account.id);
2021-10-01 17:15:11 +00:00
intent.putExtra("protocol", account.protocol);
intent.putExtra("auth_type", account.auth_type);
2021-07-31 18:13:58 +00:00
intent.putExtra("faq", 23);
2022-06-25 12:27:46 +00:00
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2021-03-27 17:54:55 +00:00
PendingIntent piAlert = PendingIntentCompat.getActivity(
2021-07-31 18:13:58 +00:00
this, ActivityError.PI_ALERT, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2019-12-10 10:51:03 +00:00
// Build notification
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this, "alerts")
.setSmallIcon(R.drawable.baseline_warning_white_24)
2021-07-31 18:13:58 +00:00
.setContentTitle(title)
2019-12-10 10:51:03 +00:00
.setContentText(message)
.setContentIntent(piAlert)
.setAutoCancel(false)
.setShowWhen(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setVisibility(NotificationCompat.VISIBILITY_SECRET)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message));
return builder;
}
private void monitorAccount(
final EntityAccount account, final Core.State state,
final boolean sync, final boolean force) throws NoSuchProviderException {
2022-04-13 20:27:33 +00:00
final PowerManager pm = Helper.getSystemService(this, PowerManager.class);
2018-12-02 13:19:54 +00:00
final PowerManager.WakeLock wlAccount = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":account." + account.id);
2019-05-18 06:02:45 +00:00
final PowerManager.WakeLock wlFolder = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":account." + account.id + ".folder");
final PowerManager.WakeLock wlMessage = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":account." + account.id + ".message");
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2018-10-10 07:26:04 +00:00
try {
2022-10-22 06:19:29 +00:00
wlAccount.acquire(Helper.WAKELOCK_MAX);
2018-10-10 07:26:04 +00:00
2020-12-02 15:58:32 +00:00
boolean forced = false;
2020-03-08 10:08:28 +00:00
final DB db = DB.getInstance(this);
2021-04-05 06:23:00 +00:00
Long currentThread = Thread.currentThread().getId();
Long accountThread = currentThread;
db.account().setAccountThread(account.id, accountThread);
2020-03-08 10:08:28 +00:00
2019-12-09 11:43:43 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (account.notify)
2020-10-31 10:11:35 +00:00
account.createNotificationChannel(this);
2019-12-09 11:43:43 +00:00
else
2020-10-31 10:11:35 +00:00
account.deleteNotificationChannel(this);
2019-12-09 11:43:43 +00:00
}
2020-10-29 09:45:24 +00:00
int fast_fails = 0;
long first_fail = 0;
2020-10-30 07:34:13 +00:00
Throwable last_fail = null;
state.setBackoff(CONNECT_BACKOFF_START);
2020-11-14 06:55:26 +00:00
if (account.backoff_until != null)
db.account().setAccountBackoff(account.id, null);
while (state.isRunning() && currentThread.equals(accountThread)) {
2020-09-21 19:46:39 +00:00
state.reset();
2020-03-08 10:08:28 +00:00
Log.i(account.name + " run thread=" + currentThread);
2018-10-10 07:26:04 +00:00
2020-10-04 14:57:19 +00:00
final ObjectHolder<TwoStateOwner> cowner = new ObjectHolder<>();
2022-12-13 09:52:39 +00:00
final ExecutorService executor = Helper.getOperationExecutor();
2018-10-10 07:26:04 +00:00
// Debug
2019-03-06 10:18:57 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
2020-12-20 07:10:36 +00:00
boolean subscriptions = prefs.getBoolean("subscriptions", false);
boolean keep_alive_poll = prefs.getBoolean("keep_alive_poll", false);
boolean empty_pool = prefs.getBoolean("empty_pool", true);
2019-04-06 07:56:37 +00:00
boolean debug = (prefs.getBoolean("debug", false) || BuildConfig.DEBUG);
2018-10-10 07:26:04 +00:00
2020-01-29 20:06:45 +00:00
final EmailService iservice = new EmailService(
2022-08-12 20:09:50 +00:00
this, account.getProtocol(), account.realm, account.encryption, account.insecure, account.unicode, debug);
2019-07-29 09:17:12 +00:00
iservice.setPartialFetch(account.partial_fetch);
iservice.setIgnoreBodyStructureSize(account.ignore_size);
2019-11-23 12:48:59 +00:00
if (account.protocol != EntityAccount.TYPE_IMAP)
2020-01-21 14:15:48 +00:00
iservice.setLeaveOnServer(account.leave_on_server);
2020-02-22 14:44:58 +00:00
if (account.keep_alive_noop) {
2022-09-02 10:28:38 +00:00
int timeout = prefs.getInt("timeout", EmailService.DEFAULT_CONNECT_TIMEOUT);
iservice.setRestartIdleInterval(timeout * 2 * 6); // 20 x 2 x 6 = 4 min
}
2021-07-31 11:25:14 +00:00
final Date lastStillHere = new Date(0);
2020-02-22 14:44:58 +00:00
2019-12-09 15:32:37 +00:00
iservice.setListener(new StoreListener() {
@Override
public void notification(StoreEvent e) {
String message = e.getMessage();
if (TextUtils.isEmpty(message))
message = "?";
if (e.getMessageType() == StoreEvent.NOTICE) {
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " notice: " + message);
2020-12-26 15:41:34 +00:00
if ("Still here".equals(message) &&
!account.isTransient(ServiceSynchronize.this)) {
2021-07-31 11:25:14 +00:00
long now = new Date().getTime();
long last = lastStillHere.getTime();
if (last > 0) {
long elapsed = now - last;
if (elapsed < STILL_THERE_THRESHOLD)
optimizeAccount(account, "'" + message + "'" +
" elapsed=" + elapsed + " ms");
}
lastStillHere.setTime(now);
}
2022-10-22 06:19:29 +00:00
} else {
long start = new Date().getTime();
2019-12-09 15:32:37 +00:00
try {
2022-10-22 06:19:29 +00:00
wlFolder.acquire(Helper.WAKELOCK_MAX);
2019-12-09 15:32:37 +00:00
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " alert: " + message);
2019-12-09 15:32:37 +00:00
2020-03-24 10:29:01 +00:00
if (!ConnectionHelper.isMaxConnections(message))
2020-02-22 21:09:46 +00:00
try {
2022-06-09 10:38:17 +00:00
NotificationManager nm =
Helper.getSystemService(ServiceSynchronize.this, NotificationManager.class);
if (NotificationHelper.areNotificationsEnabled(nm))
nm.notify("alert:" + account.id,
NotificationHelper.NOTIFICATION_TAGGED,
getNotificationAlert(account, message).build());
2020-02-22 21:09:46 +00:00
} catch (Throwable ex) {
Log.w(ex);
}
2019-12-09 15:32:37 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wlFolder.isHeld())
wlFolder.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("folder notice released elapse=" + (new Date().getTime() - start));
2019-12-09 15:32:37 +00:00
}
2022-10-22 06:19:29 +00:00
}
2019-12-09 15:32:37 +00:00
}
});
2022-04-18 07:36:59 +00:00
final Runnable purge = new RunnableEx("purge") {
@Override
public void delegate() {
executor.submit(new RunnableEx("purge#exec") {
@Override
public void delegate() {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2022-04-18 07:36:59 +00:00
try {
2022-10-22 06:19:29 +00:00
wlAccount.acquire(Helper.WAKELOCK_MAX);
2022-04-18 07:36:59 +00:00
// Close cached connections
Log.i(account.name + " Empty connection pool");
((IMAPStore) iservice.getStore()).emptyConnectionPool(false);
} catch (Throwable ex) {
Log.e(ex);
} finally {
2022-10-22 06:19:29 +00:00
if (wlAccount.isHeld())
wlAccount.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("purge released elapse=" + (new Date().getTime() - start));
2022-04-18 07:36:59 +00:00
}
}
});
}
};
2022-12-13 09:52:39 +00:00
final long group = Thread.currentThread().getId();
2020-11-17 17:29:02 +00:00
final Map<EntityFolder, IMAPFolder> mapFolders = new LinkedHashMap<>();
2018-10-10 07:26:04 +00:00
List<Thread> idlers = new ArrayList<>();
try {
2019-07-28 19:45:29 +00:00
// Initiate connection
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " connecting");
2019-07-28 19:45:29 +00:00
db.folder().setFolderStates(account.id, null);
db.account().setAccountState(account.id, "connecting");
try {
iservice.connect(account);
2021-07-31 11:25:14 +00:00
lastStillHere.setTime(0);
2019-07-28 19:45:29 +00:00
} catch (Throwable ex) {
2019-12-09 11:24:42 +00:00
// Immediately report auth errors
if (ex instanceof AuthenticationFailedException) {
2020-07-05 16:43:54 +00:00
if (ConnectionHelper.isIoError(ex)) {
if (!BuildConfig.PLAY_STORE_RELEASE)
Log.e(ex);
} else {
2020-02-24 09:35:34 +00:00
Log.e(ex);
// Allow Android account manager to refresh the access token
if (account.auth_type != AUTH_TYPE_PASSWORD &&
2022-02-03 09:39:24 +00:00
state.getBackoff() <= CONNECT_BACKOFF_ALARM_START * 60)
throw ex;
2020-02-22 21:09:46 +00:00
try {
state.setBackoff(2 * CONNECT_BACKOFF_ALARM_MAX * 60);
2022-06-09 10:38:17 +00:00
NotificationManager nm =
Helper.getSystemService(this, NotificationManager.class);
if (NotificationHelper.areNotificationsEnabled(nm))
nm.notify("receive:" + account.id,
NotificationHelper.NOTIFICATION_TAGGED,
Core.getNotificationError(this, "error", account, 0, ex)
.build());
2020-02-22 21:09:46 +00:00
} catch (Throwable ex1) {
Log.w(ex1);
}
2020-01-13 12:18:49 +00:00
throw ex;
}
2019-07-28 19:45:29 +00:00
}
throw ex;
}
2020-08-29 10:38:06 +00:00
// https://tools.ietf.org/html/rfc2177
2022-11-25 09:08:06 +00:00
final boolean capIdle =
iservice.hasCapability("IDLE") &&
!"poczta.o2.pl".equals(account.host);
2021-06-04 13:54:29 +00:00
final boolean capUtf8 =
iservice.hasCapability("UTF8=ACCEPT") ||
iservice.hasCapability("UTF8=ONLY");
2021-01-03 11:41:16 +00:00
final boolean capNotify = iservice.hasCapability("NOTIFY");
2021-08-09 05:28:07 +00:00
2021-08-08 12:13:31 +00:00
String capabilities = TextUtils.join(" ", iservice.getCapabilities());
if (capabilities.length() > 500)
capabilities = capabilities.substring(0, 500) + "...";
2020-12-02 13:39:48 +00:00
2021-08-09 05:28:07 +00:00
Log.i(account.name + " idle=" + capIdle);
if (!capIdle || account.poll_interval < TUNE_KEEP_ALIVE_INTERVAL_MIN)
2021-08-09 05:28:07 +00:00
optimizeAccount(account, "IDLE");
2019-07-28 19:45:29 +00:00
db.account().setAccountState(account.id, "connected");
2021-08-08 12:13:31 +00:00
db.account().setAccountCapabilities(account.id, capabilities, capIdle, capUtf8);
2019-07-28 19:45:29 +00:00
db.account().setAccountError(account.id, null);
db.account().setAccountWarning(account.id, null);
2020-12-02 11:00:35 +00:00
Store istore = iservice.getStore();
if (istore instanceof IMAPStore) {
Map<String, String> caps = ((IMAPStore) istore).getCapabilities();
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " connected" +
" caps=" + (caps == null ? null : TextUtils.join(" ", caps.keySet())));
2020-12-02 11:00:35 +00:00
} else
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " connected");
2019-07-28 19:45:29 +00:00
2020-07-03 07:57:43 +00:00
db.account().setAccountMaxSize(account.id, iservice.getMaxSize());
2020-12-29 17:46:17 +00:00
if (istore instanceof IMAPStore)
2021-06-28 09:31:19 +00:00
updateQuota(this, ((IMAPStore) iservice.getStore()), account);
2020-07-03 07:57:43 +00:00
2018-10-10 07:26:04 +00:00
// Listen for folder events
2019-07-28 19:45:29 +00:00
iservice.getStore().addFolderListener(new FolderAdapter() {
2018-10-10 07:26:04 +00:00
@Override
public void folderCreated(FolderEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2018-10-10 07:26:04 +00:00
try {
2022-10-22 06:19:29 +00:00
wlFolder.acquire(Helper.WAKELOCK_MAX);
2019-05-25 14:32:08 +00:00
String name = e.getFolder().getFullName();
Log.i("Folder created=" + name);
if (db.folder().getFolderByName(account.id, name) == null)
2020-03-30 11:07:37 +00:00
reload(ServiceSynchronize.this, account.id, false, "folder created");
2018-10-10 07:26:04 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wlFolder.isHeld())
wlFolder.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("folder created released elapse=" + (new Date().getTime() - start));
2018-10-10 07:26:04 +00:00
}
}
2018-08-02 13:33:06 +00:00
2018-10-10 07:26:04 +00:00
@Override
public void folderRenamed(FolderEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2018-10-10 07:26:04 +00:00
try {
2022-10-22 06:19:29 +00:00
wlFolder.acquire(Helper.WAKELOCK_MAX);
2018-09-14 06:28:23 +00:00
2018-10-10 07:26:04 +00:00
String old = e.getFolder().getFullName();
String name = e.getNewFolder().getFullName();
2019-05-25 14:32:08 +00:00
Log.i("Folder renamed from=" + old + " to=" + name);
2018-10-10 07:26:04 +00:00
int count = db.folder().renameFolder(account.id, old, name);
2018-12-24 12:27:45 +00:00
Log.i("Renamed to " + name + " count=" + count);
2021-07-17 14:10:26 +00:00
if (count != 0)
2020-03-30 11:07:37 +00:00
reload(ServiceSynchronize.this, account.id, false, "folder renamed");
2018-10-10 07:26:04 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wlFolder.isHeld())
wlFolder.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("folder renamed released elapse=" + (new Date().getTime() - start));
2018-10-10 07:26:04 +00:00
}
}
2018-08-02 13:33:06 +00:00
2018-10-10 07:26:04 +00:00
@Override
public void folderDeleted(FolderEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2018-10-10 07:26:04 +00:00
try {
2022-10-22 06:19:29 +00:00
wlFolder.acquire(Helper.WAKELOCK_MAX);
2019-05-25 14:32:08 +00:00
String name = e.getFolder().getFullName();
Log.i("Folder deleted=" + name);
if (db.folder().getFolderByName(account.id, name) != null)
2020-03-30 11:07:37 +00:00
reload(ServiceSynchronize.this, account.id, false, "folder deleted");
2018-10-10 07:26:04 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wlFolder.isHeld())
wlFolder.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("folder deleted released elapse=" + (new Date().getTime() - start));
2018-10-10 07:26:04 +00:00
}
}
2020-12-02 13:39:48 +00:00
@Override
public void folderChanged(FolderEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
2020-12-02 13:39:48 +00:00
try {
2022-10-22 06:19:29 +00:00
wlFolder.acquire(Helper.WAKELOCK_MAX);
2020-12-02 13:39:48 +00:00
String name = e.getFolder().getFullName();
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, account,
"Folder changed=" + name);
2020-12-02 13:39:48 +00:00
EntityFolder folder = db.folder().getFolderByName(account.id, name);
2021-01-24 08:19:00 +00:00
if (folder != null && folder.selectable)
2020-12-02 13:39:48 +00:00
EntityOperation.sync(ServiceSynchronize.this, folder.id, false);
} finally {
2022-10-22 06:19:29 +00:00
if (wlFolder.isHeld())
wlFolder.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("folder changed released elapse=" + (new Date().getTime() - start));
2020-12-02 13:39:48 +00:00
}
}
2018-10-10 07:26:04 +00:00
});
2018-08-02 13:33:06 +00:00
2018-10-10 07:26:04 +00:00
// Update folder list
2021-12-07 07:30:51 +00:00
Core.onSynchronizeFolders(this,
account, iservice.getStore(), state,
false, force && !forced);
2018-08-04 22:35:47 +00:00
// Open synchronizing folders
2019-07-07 07:25:52 +00:00
List<EntityFolder> folders = db.folder().getFolders(account.id, false, true);
2020-02-01 07:19:41 +00:00
if (folders.size() > 0)
2020-10-31 10:11:35 +00:00
Collections.sort(folders, folders.get(0).getComparator(this));
2019-06-24 06:34:17 +00:00
2019-05-21 13:21:03 +00:00
for (final EntityFolder folder : folders) {
2020-12-26 15:32:45 +00:00
if (folder.selectable && folder.synchronize && !folder.poll && capIdle && sync) {
2018-12-24 12:27:45 +00:00
Log.i(account.name + " sync folder " + folder.name);
2018-08-22 05:31:00 +00:00
db.folder().setFolderState(folder.id, "connecting");
2018-08-22 05:31:00 +00:00
2019-07-28 19:45:29 +00:00
final IMAPFolder ifolder = (IMAPFolder) iservice.getStore().getFolder(folder.name);
2019-12-11 10:48:57 +00:00
mapFolders.put(folder, ifolder);
try {
2019-07-07 07:25:52 +00:00
if (BuildConfig.DEBUG && "Postausgang".equals(folder.name))
throw new ReadOnlyFolderException(ifolder);
ifolder.open(Folder.READ_WRITE);
folder.read_only = ifolder.getUIDNotSticky();
db.folder().setFolderReadOnly(folder.id, folder.read_only);
2019-04-29 19:54:49 +00:00
} catch (ReadOnlyFolderException ex) {
2019-04-30 07:06:32 +00:00
Log.w(folder.name + " read only");
2019-04-29 19:54:49 +00:00
try {
ifolder.open(Folder.READ_ONLY);
folder.read_only = true;
db.folder().setFolderReadOnly(folder.id, folder.read_only);
2019-12-08 08:31:09 +00:00
} catch (Throwable ex1) {
2019-12-06 07:50:46 +00:00
db.folder().setFolderError(folder.id, Log.formatThrowable(ex1));
2019-12-08 08:31:09 +00:00
throw ex1;
2019-04-29 19:54:49 +00:00
}
2019-05-25 14:45:46 +00:00
} catch (FolderNotFoundException ex) {
2019-09-17 19:25:41 +00:00
Log.w(folder.name, ex);
2020-10-20 14:18:43 +00:00
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
db.folder().setFolderSynchronize(folder.id, false);
2019-05-25 14:45:46 +00:00
continue;
} catch (Throwable ex) {
2019-12-06 07:50:46 +00:00
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
if (EntityFolder.INBOX.equals(folder.type))
throw ex;
else
continue;
/*
javax.mail.MessagingException: D2 NO Mailbox does not exist, or must be subscribed to.;
nested exception is:
com.sun.mail.iap.CommandFailedException: D2 NO Mailbox does not exist, or must be subscribed to.
javax.mail.MessagingException: D2 NO Mailbox does not exist, or must be subscribed to.;
nested exception is:
com.sun.mail.iap.CommandFailedException: D2 NO Mailbox does not exist, or must be subscribed to.
at com.sun.mail.imap.IMAPFolder.open(SourceFile:61)
at com.sun.mail.imap.IMAPFolder.open(SourceFile:1)
at eu.faircode.email.ServiceSynchronize.monitorAccount(SourceFile:63)
at eu.faircode.email.ServiceSynchronize.access$900(SourceFile:1)
at eu.faircode.email.ServiceSynchronize$4$1.run(SourceFile:1)
at java.lang.Thread.run(Thread.java:919)
Caused by: com.sun.mail.iap.CommandFailedException: D2 NO Mailbox does not exist, or must be subscribed to.
at com.sun.mail.iap.Protocol.handleResult(SourceFile:8)
at com.sun.mail.imap.protocol.IMAPProtocol.select(SourceFile:19)
at com.sun.mail.imap.IMAPFolder.open(SourceFile:16)
*/
2022-04-11 07:50:57 +00:00
/*
Search javax.mail.MessagingException: DAE2 NO [CANNOT] Invalid mailbox name: Name must not have '/' characters (0.000 + 0.000 secs).;
nested exception is:
com.sun.mail.iap.CommandFailedException: DAE2 NO [CANNOT] Invalid mailbox name: Name must not have '/' characters (0.000 + 0.000 secs).
javax.mail.MessagingException: DAE2 NO [CANNOT] Invalid mailbox name: Name must not have '/' characters (0.000 + 0.000 secs).;
nested exception is:
com.sun.mail.iap.CommandFailedException: DAE2 NO [CANNOT] Invalid mailbox name: Name must not have '/' characters (0.000 + 0.000 secs).
at com.sun.mail.imap.IMAPFolder.open(SourceFile:61)
at com.sun.mail.imap.IMAPFolder.open(SourceFile:1)
at eu.faircode.email.BoundaryCallbackMessages.load_server(SourceFile:17)
at eu.faircode.email.BoundaryCallbackMessages.access$500(SourceFile:1)
at eu.faircode.email.BoundaryCallbackMessages$3.run(SourceFile:20)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at eu.faircode.email.Helper$PriorityFuture.run(SourceFile:1)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:920)
Caused by: com.sun.mail.iap.CommandFailedException: DAE2 NO [CANNOT] Invalid mailbox name: Name must not have '/' characters (0.000 + 0.000 secs).
at com.sun.mail.iap.Protocol.handleResult(SourceFile:8)
at com.sun.mail.imap.protocol.IMAPProtocol.select(SourceFile:19)
at com.sun.mail.imap.IMAPFolder.open(SourceFile:16)
... 10 more
*/
}
2018-08-22 05:31:00 +00:00
db.folder().setFolderState(folder.id, "connected");
db.folder().setFolderError(folder.id, null);
2018-11-29 13:00:46 +00:00
2020-08-28 10:02:08 +00:00
if (capIdle != MessageHelper.hasCapability(ifolder, "IDLE"))
Log.e("Conflicting IDLE=" + capIdle + " host=" + account.host);
2020-08-08 09:51:41 +00:00
int count = MessageHelper.getMessageCount(ifolder);
2019-03-09 08:20:46 +00:00
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
2018-12-24 12:27:45 +00:00
Log.i(account.name + " folder " + folder.name + " flags=" + ifolder.getPermanentFlags());
2018-11-25 12:34:08 +00:00
// Listen for new and deleted messages
ifolder.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
try {
2022-10-22 06:19:29 +00:00
wlMessage.acquire(Helper.WAKELOCK_MAX);
2022-01-23 07:29:11 +00:00
fetch(folder, ifolder, e.getMessages(), false, false, "added");
2020-11-10 19:06:02 +00:00
Thread.sleep(FETCH_YIELD_DURATION);
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.e(folder.name, ex);
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name + " added " + Log.formatThrowable(ex, false));
EntityOperation.sync(ServiceSynchronize.this, folder.id, false);
} finally {
2022-10-22 06:19:29 +00:00
if (wlMessage.isHeld())
wlMessage.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("message added released elapse=" + (new Date().getTime() - start));
}
}
@Override
public void messagesRemoved(MessageCountEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
try {
2022-10-22 06:19:29 +00:00
wlMessage.acquire(Helper.WAKELOCK_MAX);
2022-01-23 07:29:11 +00:00
fetch(folder, ifolder, e.getMessages(), false, true, "removed");
2020-11-10 19:06:02 +00:00
Thread.sleep(FETCH_YIELD_DURATION);
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.e(folder.name, ex);
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name + " removed " + Log.formatThrowable(ex, false));
EntityOperation.sync(ServiceSynchronize.this, folder.id, false);
} finally {
2022-10-22 06:19:29 +00:00
if (wlMessage.isHeld())
wlMessage.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("message removed released elapse=" + (new Date().getTime() - start));
}
}
});
// Flags (like "seen") at the remote could be changed while synchronizing
// Listen for changed messages
ifolder.addMessageChangedListener(new MessageChangedListener() {
@Override
public void messageChanged(MessageChangedEvent e) {
2022-10-22 06:19:29 +00:00
long start = new Date().getTime();
try {
2022-10-22 06:19:29 +00:00
wlMessage.acquire(Helper.WAKELOCK_MAX);
2022-01-19 17:59:12 +00:00
Message imessage = e.getMessage();
2022-01-23 07:29:11 +00:00
fetch(folder, ifolder, new Message[]{imessage}, true, false, "changed");
2020-11-10 19:06:02 +00:00
Thread.sleep(FETCH_YIELD_DURATION);
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.e(folder.name, ex);
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name + " changed " + Log.formatThrowable(ex, false));
EntityOperation.sync(ServiceSynchronize.this, folder.id, false);
} finally {
2022-10-22 06:19:29 +00:00
if (wlMessage.isHeld())
wlMessage.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("message changed released elapse=" + (new Date().getTime() - start));
2018-12-02 13:19:54 +00:00
}
2018-08-15 19:34:22 +00:00
}
});
2018-10-10 07:26:04 +00:00
// Idle folder
2022-04-17 19:34:33 +00:00
Thread idler = new Thread(new RunnableEx("idle") {
2021-02-24 07:14:58 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2021-02-24 07:14:58 +00:00
try {
Log.i(folder.name + " start idle");
while (ifolder.isOpen() && state.isRunning() && state.isRecoverable()) {
2021-02-24 07:14:58 +00:00
Log.i(folder.name + " do idle");
ifolder.idle(false);
state.activity();
2018-10-10 07:26:04 +00:00
}
2021-02-24 07:14:58 +00:00
} catch (Throwable ex) {
2022-12-13 21:23:09 +00:00
/*
javax.mail.FolderClosedException: * BYE Jakarta Mail Exception: java.net.SocketTimeoutException: Read timed out
at com.sun.mail.imap.IMAPFolder.handleIdle(SourceFile:252)
at com.sun.mail.imap.IMAPFolder.idle(SourceFile:7)
at eu.faircode.email.ServiceSynchronize$21.delegate(SourceFile:78)
at eu.faircode.email.RunnableEx.run(SourceFile:1)
at java.lang.Thread.run(Thread.java:1012)
... javax.mail.StoreClosedException: NOOP INBOX
javax.mail.StoreClosedException: NOOP INBOX
at eu.faircode.email.ServiceSynchronize.monitorAccount(SourceFile:151)
at eu.faircode.email.ServiceSynchronize.access$1200(Unknown Source:0)
at eu.faircode.email.ServiceSynchronize$4$2.delegate(SourceFile:15)
at eu.faircode.email.RunnableEx.run(SourceFile:1)
at java.lang.Thread.run(Thread.java:1012)
*/
2021-02-24 07:14:58 +00:00
Log.e(folder.name, ex);
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name + " idle " + Log.formatThrowable(ex, false));
2021-02-24 07:14:58 +00:00
state.error(new FolderClosedException(ifolder, "IDLE", new Exception(ex)));
} finally {
Log.i(folder.name + " end idle");
}
2021-02-24 07:14:58 +00:00
}
}, "idler." + folder.id);
idler.setPriority(THREAD_PRIORITY_BACKGROUND);
idler.start();
idlers.add(idler);
2018-12-02 13:19:54 +00:00
2020-12-26 15:32:45 +00:00
EntityOperation.sync(this, folder.id, false, force && !forced);
2020-12-02 13:39:48 +00:00
2020-12-20 07:10:36 +00:00
if (capNotify && subscriptions && EntityFolder.INBOX.equals(folder.type))
2020-12-02 13:39:48 +00:00
ifolder.doCommand(new IMAPFolder.ProtocolCommand() {
@Override
public Object doCommand(IMAPProtocol protocol) throws ProtocolException {
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, account,
account.name + " NOTIFY enable");
2020-12-02 13:39:48 +00:00
// https://tools.ietf.org/html/rfc5465
Argument arg = new Argument();
2020-12-03 11:38:22 +00:00
arg.writeAtom("SET STATUS" +
" (selected (MessageNew (uid) MessageExpunge FlagChange))" +
" (subscribed (MessageNew MessageExpunge FlagChange))");
2020-12-02 13:39:48 +00:00
Response[] responses = protocol.command("NOTIFY", arg);
if (responses.length == 0)
throw new ProtocolException("No response");
if (!responses[responses.length - 1].isOK())
2020-12-02 13:39:48 +00:00
throw new ProtocolException(responses[responses.length - 1]);
for (int i = 0; i < responses.length - 1; i++) {
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, account,
account.name + " " + responses[i]);
2020-12-02 13:39:48 +00:00
if (responses[i] instanceof IMAPResponse) {
IMAPResponse ir = (IMAPResponse) responses[i];
if (ir.keyEquals("STATUS")) {
String mailbox = ir.readAtomString();
EntityFolder f = db.folder().getFolderByName(account.id, mailbox);
if (f != null)
EntityOperation.sync(ServiceSynchronize.this, f.id, false);
}
}
}
return null;
}
});
2020-10-26 10:47:42 +00:00
} else {
2019-05-21 13:21:03 +00:00
mapFolders.put(folder, null);
2020-10-26 10:47:42 +00:00
db.folder().setFolderState(folder.id, null);
2020-10-26 12:21:43 +00:00
if (!capIdle && !folder.poll) {
folder.poll = true;
db.folder().setFolderPoll(folder.id, folder.poll);
}
2020-10-26 10:47:42 +00:00
}
2020-10-04 14:57:19 +00:00
}
2018-08-04 22:35:47 +00:00
2020-12-02 15:58:32 +00:00
forced = true;
2021-11-30 13:11:20 +00:00
final long serial = state.getSerial();
2020-10-04 14:57:19 +00:00
Log.i(account.name + " observing operations");
2022-04-17 19:34:33 +00:00
getMainHandler().post(new RunnableEx("observe#start") {
2020-10-04 14:57:19 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2020-10-04 14:57:19 +00:00
cowner.value = new TwoStateOwner(ServiceSynchronize.this, account.name);
cowner.value.start();
2019-05-22 07:33:25 +00:00
2020-10-04 14:57:19 +00:00
db.operation().liveOperations(account.id).observe(cowner.value, new Observer<List<TupleOperationEx>>() {
2022-02-01 18:47:26 +00:00
private DutyCycle dc = new DutyCycle(account.name + " operations");
2020-10-04 14:57:19 +00:00
private List<Long> handling = new ArrayList<>();
private final Map<TupleOperationEx.PartitionKey, List<TupleOperationEx>> partitions = new HashMap<>();
2020-01-27 09:24:47 +00:00
2020-10-04 14:57:19 +00:00
private final PowerManager.WakeLock wlOperations = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":operations." + account.id);
2020-01-27 09:24:47 +00:00
2020-10-04 14:57:19 +00:00
@Override
public void onChanged(final List<TupleOperationEx> _operations) {
// Get new operations
2020-11-06 08:25:00 +00:00
List<Long> all = new ArrayList<>();
2020-11-17 17:29:02 +00:00
Map<Long, List<TupleOperationEx>> added = new LinkedHashMap<>();
2020-10-04 14:57:19 +00:00
for (TupleOperationEx op : _operations) {
2020-11-06 08:25:00 +00:00
all.add(op.id);
2020-10-04 14:57:19 +00:00
if (!handling.contains(op.id)) {
2020-11-06 08:25:00 +00:00
if (!added.containsKey(op.folder))
added.put(op.folder, new ArrayList<>());
added.get(op.folder).add(op);
2020-10-04 14:57:19 +00:00
}
}
2020-11-06 08:25:00 +00:00
handling = all;
if (empty_pool && istore instanceof IMAPStore) {
2020-12-26 12:09:47 +00:00
getMainHandler().removeCallbacks(purge);
if (handling.size() == 0)
getMainHandler().postDelayed(purge, PURGE_DELAY);
}
2020-11-06 08:25:00 +00:00
for (Long fid : added.keySet()) {
EntityFolder found = null;
for (EntityFolder f : mapFolders.keySet())
if (Objects.equals(fid, f.id)) {
found = f;
break;
}
if (found == null) {
Log.w(account.name + " folder not found operation=" + fid);
continue;
}
2020-10-04 14:57:19 +00:00
2020-11-06 08:25:00 +00:00
final EntityFolder folder = found;
2021-10-31 11:21:26 +00:00
Log.i(account.name + "/" + folder.name + " queuing operations=" + added.size() +
2020-10-04 14:57:19 +00:00
" init=" + folder.initialize + " poll=" + folder.poll);
// Partition operations by priority
boolean offline = (mapFolders.get(folder) == null);
List<TupleOperationEx.PartitionKey> keys = new ArrayList<>();
synchronized (partitions) {
2020-11-06 08:25:00 +00:00
for (TupleOperationEx op : added.get(folder.id)) {
2020-10-04 14:57:19 +00:00
TupleOperationEx.PartitionKey key = op.getPartitionKey(offline);
if (!partitions.containsKey(key)) {
partitions.put(key, new ArrayList<>());
keys.add(key);
2020-01-27 12:12:57 +00:00
}
2020-10-04 14:57:19 +00:00
partitions.get(key).add(op);
}
}
2020-01-25 11:58:21 +00:00
2020-10-04 14:57:19 +00:00
Collections.sort(keys, new Comparator<TupleOperationEx.PartitionKey>() {
@Override
public int compare(TupleOperationEx.PartitionKey k1, TupleOperationEx.PartitionKey k2) {
Integer p1 = k1.getPriority();
Integer p2 = k2.getPriority();
int priority = p1.compareTo(p2);
if (priority == 0) {
Long o1 = k1.getOrder();
Long o2 = k2.getOrder();
return o1.compareTo(o2);
} else
return priority;
}
});
2020-10-04 14:57:19 +00:00
for (TupleOperationEx.PartitionKey key : keys) {
2021-09-19 20:27:26 +00:00
int ops;
2020-10-04 14:57:19 +00:00
synchronized (partitions) {
2021-09-19 20:27:26 +00:00
ops = partitions.get(key).size();
2021-10-31 11:21:26 +00:00
Log.i(account.name + "/" + folder.name +
2020-10-04 14:57:19 +00:00
" queuing partition=" + key +
2021-11-30 13:14:49 +00:00
" serial=" + serial +
2021-09-19 20:27:26 +00:00
" operations=" + ops);
2020-10-04 14:57:19 +00:00
}
2020-01-27 09:24:47 +00:00
2021-09-16 06:13:34 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("account", folder.account == null ? null : Long.toString(folder.account));
crumb.put("folder", folder.name + "/" + folder.type + ":" + folder.id);
crumb.put("partition", key.toString());
2021-09-19 20:27:26 +00:00
crumb.put("operations", Integer.toString(ops));
2021-09-16 08:43:14 +00:00
crumb.put("serial", Long.toString(serial));
2021-09-16 06:13:34 +00:00
Log.breadcrumb("Queuing", crumb);
2022-12-13 09:52:39 +00:00
executor.submit(new Helper.PriorityRunnable(group, key.getPriority(), key.getOrder()) {
2020-10-04 14:57:19 +00:00
@Override
public void run() {
super.run();
2022-10-23 14:11:36 +00:00
long timeout = Helper.WAKELOCK_MAX;
long start = new Date().getTime();
2020-10-04 14:57:19 +00:00
try {
List<TupleOperationEx> partition;
synchronized (partitions) {
partition = partitions.get(key);
partitions.remove(key);
}
2022-10-23 14:11:36 +00:00
for (TupleOperationEx op : partition)
2022-12-09 18:25:53 +00:00
if (EntityOperation.SYNC.equals(op.name) ||
EntityOperation.PURGE.equals(op.name)) {
2022-10-23 14:11:36 +00:00
timeout = 24 * 3600 * 1000L;
break;
}
wlOperations.acquire(timeout);
2022-10-22 06:37:39 +00:00
Log.i(account.name + "/" + folder.name +
" executing partition=" + key +
" serial=" + serial +
" operations=" + partition.size());
2021-09-16 06:13:34 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("account", folder.account == null ? null : Long.toString(folder.account));
crumb.put("folder", folder.name + "/" + folder.type + ":" + folder.id);
crumb.put("partition", key.toString());
crumb.put("operations", Integer.toString(partition.size()));
2021-09-16 08:43:14 +00:00
crumb.put("serial", Long.toString(serial));
2021-09-16 06:13:34 +00:00
Log.breadcrumb("Executing", crumb);
2020-10-04 14:57:19 +00:00
// Get folder
Folder ifolder = mapFolders.get(folder); // null when polling
2020-12-17 14:05:44 +00:00
boolean canOpen = (EntityFolder.INBOX.equals(folder.type) ||
(account.protocol == EntityAccount.TYPE_IMAP && !folder.local));
2020-10-04 14:57:19 +00:00
final boolean shouldClose = (ifolder == null && canOpen);
2019-02-10 19:22:35 +00:00
2020-10-04 14:57:19 +00:00
try {
2021-10-31 11:21:26 +00:00
Log.i(account.name + "/" + folder.name + " run " + (shouldClose ? "offline" : "online"));
2018-10-10 07:26:04 +00:00
2020-10-04 14:57:19 +00:00
if (shouldClose) {
// Prevent unnecessary folder connections
if (db.operation().getOperationCount(folder.id, null) == 0)
return;
2018-12-05 10:50:07 +00:00
2020-10-04 14:57:19 +00:00
db.folder().setFolderState(folder.id, "connecting");
2020-10-04 14:57:19 +00:00
try {
ifolder = iservice.getStore().getFolder(folder.name);
} catch (IllegalStateException ex) {
2021-09-15 04:46:16 +00:00
if ("Not connected".equals(ex.getMessage())) {
2022-05-11 12:20:26 +00:00
Log.i(ex);
2020-10-04 14:57:19 +00:00
return; // Store closed
2021-09-15 04:46:16 +00:00
} else
2020-10-04 14:57:19 +00:00
throw ex;
}
2018-12-05 10:50:07 +00:00
2020-10-04 14:57:19 +00:00
try {
try {
ifolder.open(Folder.READ_WRITE);
if (ifolder instanceof IMAPFolder) {
folder.read_only = ((IMAPFolder) ifolder).getUIDNotSticky();
db.folder().setFolderReadOnly(folder.id, folder.read_only);
}
} catch (ReadOnlyFolderException ex) {
Log.w(folder.name + " read only");
ifolder.open(Folder.READ_ONLY);
folder.read_only = true;
db.folder().setFolderReadOnly(folder.id, folder.read_only);
}
} catch (MessagingException ex) {
/*
javax.mail.MessagingException: GS38 NO Mailbox doesn't exist: 0 XXX (0.020 + 0.000 + 0.019 secs).;
nested exception is:
com.sun.mail.iap.CommandFailedException: GS38 NO Mailbox doesn't exist: 0 XXX (0.020 + 0.000 + 0.019 secs).
at com.sun.mail.imap.IMAPFolder.open(SourceFile:61)
at com.sun.mail.imap.IMAPFolder.open(SourceFile:1)
at eu.faircode.email.ServiceSynchronize$19$1$2.run(SourceFile:30)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:459)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at eu.faircode.email.Helper$PriorityFuture.run(SourceFile:1)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: com.sun.mail.iap.CommandFailedException: GS38 NO Mailbox doesn't exist: 0 XXX (0.020 + 0.000 + 0.019 secs).
at com.sun.mail.iap.Protocol.handleResult(SourceFile:8)
at com.sun.mail.imap.protocol.IMAPProtocol.select(SourceFile:19)
at com.sun.mail.imap.IMAPFolder.open(SourceFile:16)
*/
if (ex.getCause() instanceof ProtocolException &&
!ConnectionHelper.isIoError(ex))
throw new FolderNotFoundException(ifolder, ex.getMessage(), ex);
else
throw ex;
2020-10-04 14:57:19 +00:00
}
2020-10-04 14:57:19 +00:00
db.folder().setFolderState(folder.id, "connected");
db.folder().setFolderError(folder.id, null);
2020-10-04 14:57:19 +00:00
int count = MessageHelper.getMessageCount(ifolder);
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
2020-01-31 07:45:23 +00:00
2020-10-04 14:57:19 +00:00
Log.i(account.name + " folder " + folder.name + " flags=" + ifolder.getPermanentFlags());
}
2022-02-01 11:58:42 +00:00
try {
2022-02-01 18:47:26 +00:00
dc.start();
2022-02-01 11:58:42 +00:00
Core.processOperations(ServiceSynchronize.this,
account, folder,
partition,
iservice, ifolder,
state, serial);
} finally {
2022-02-05 20:21:33 +00:00
dc.stop(state.getForeground(), executor);
2022-02-01 11:58:42 +00:00
}
2020-10-04 14:57:19 +00:00
} catch (Throwable ex) {
2022-06-06 06:49:03 +00:00
if (ex instanceof OperationCanceledException ||
(ex instanceof IllegalStateException &&
"Folder not open".equals(ex.getMessage())))
Log.i(folder.name, ex); // Illegal state: getMessageCount
2022-02-23 19:39:11 +00:00
else
Log.e(folder.name, ex);
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name + " process " + Log.formatThrowable(ex, false));
2020-10-04 14:57:19 +00:00
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
2022-02-18 14:32:30 +00:00
if (!(ex instanceof FolderNotFoundException))
2021-12-01 16:59:25 +00:00
state.error(new Core.OperationCanceledExceptionEx("Process", ex));
2020-10-04 14:57:19 +00:00
} finally {
if (shouldClose) {
if (ifolder != null && ifolder.isOpen()) {
db.folder().setFolderState(folder.id, "closing");
try {
ifolder.close(false);
} catch (Throwable ex) {
Log.w(folder.name, ex);
2019-03-06 16:36:20 +00:00
}
2018-12-02 13:19:54 +00:00
}
2020-10-26 12:21:43 +00:00
db.folder().setFolderState(folder.id, null);
2018-12-02 13:19:54 +00:00
}
}
2021-09-16 06:13:34 +00:00
} catch (Throwable ex) {
2022-05-11 12:20:26 +00:00
if ("Not connected".equals(ex.getMessage()))
Log.i(ex);
else
Log.e(ex);
2020-10-04 14:57:19 +00:00
} finally {
2022-10-22 06:19:29 +00:00
if (wlOperations.isHeld())
wlOperations.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-23 14:11:36 +00:00
Log.e(key + " released elapse=" + (new Date().getTime() - start) + " timeout=" + timeout);
2020-02-11 15:11:03 +00:00
}
2020-10-04 14:57:19 +00:00
}
});
2019-03-06 16:36:20 +00:00
}
2018-12-05 10:50:07 +00:00
}
2020-10-04 14:57:19 +00:00
}
});
}
});
2018-10-10 07:26:04 +00:00
// Keep alive
boolean first = true;
2019-12-09 21:26:29 +00:00
while (state.isRunning()) {
2020-03-31 09:33:13 +00:00
long idleTime = state.getIdleTime();
2020-06-12 06:36:27 +00:00
boolean tune_keep_alive = prefs.getBoolean("tune_keep_alive", true);
boolean tune = (tune_keep_alive && !first &&
2021-12-12 07:42:41 +00:00
!account.keep_alive_ok &&
account.poll_interval - TUNE_KEEP_ALIVE_INTERVAL_STEP >= TUNE_KEEP_ALIVE_INTERVAL_MIN &&
2020-03-31 10:33:33 +00:00
Math.abs(idleTime - account.poll_interval * 60 * 1000L) < 60 * 1000L);
2020-06-12 06:36:27 +00:00
if (tune_keep_alive && !first && !account.keep_alive_ok)
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name +
" Tune interval=" + account.poll_interval +
" idle=" + idleTime + "/" + tune);
try {
2021-07-30 13:38:16 +00:00
if (!state.isRecoverable()) {
Throwable unrecoverable = state.getUnrecoverable();
Exception cause =
(unrecoverable instanceof Exception
? (Exception) unrecoverable
: new Exception(unrecoverable));
throw new StoreClosedException(iservice.getStore(), "Unrecoverable", cause);
}
2022-07-21 12:45:47 +00:00
// Check token expiration
if (!account.isTransient(this)) {
Long expirationTime = iservice.getAccessTokenExpirationTime();
if (expirationTime != null && expirationTime < new Date().getTime()) {
2022-08-24 18:18:31 +00:00
EntityLog.log(this, "### " + account.name + " token expired" +
2022-07-21 12:45:47 +00:00
" expired=" + new Date(expirationTime) +
" user=" + account.provider + ":" + account.user);
throw new IllegalStateException(Log.TOKEN_REFRESH_REQUIRED);
}
}
// Sends store NOOP
2020-12-25 14:51:04 +00:00
if (EmailService.SEPARATE_STORE_CONNECTION) {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " checking store" +
" memory=" + Log.getFreeMemMb() +
" battery=" + Helper.getBatteryLevel(this));
2020-12-25 14:51:04 +00:00
if (!iservice.getStore().isConnected())
throw new StoreClosedException(iservice.getStore(), "NOOP");
}
2020-10-31 10:11:35 +00:00
if (!getMainLooper().getThread().isAlive()) {
2020-01-19 08:09:50 +00:00
Log.e("App died");
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
account.name + " app died");
2020-01-19 08:09:50 +00:00
state.stop();
throw new StoreClosedException(iservice.getStore(), "App died");
}
2020-08-14 07:44:56 +00:00
if (sync) {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " checking folders");
for (EntityFolder folder : mapFolders.keySet())
2020-12-29 14:11:13 +00:00
if (folder.selectable && folder.synchronize)
if (!folder.poll && capIdle) {
// Sends folder NOOP
if (!mapFolders.get(folder).isOpen())
2020-11-04 12:30:21 +00:00
throw new StoreClosedException(iservice.getStore(), "NOOP " + folder.name);
if (keep_alive_poll)
EntityOperation.poll(this, folder.id);
2020-02-25 20:06:17 +00:00
} else {
2021-03-05 16:43:05 +00:00
if (folder.poll_count == 0) {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name + " queue sync poll");
2021-07-30 19:24:48 +00:00
EntityOperation.poll(this, folder.id);
2021-03-05 16:43:05 +00:00
}
2020-02-25 20:06:17 +00:00
folder.poll_count = (folder.poll_count + 1) % folder.poll_factor;
db.folder().setFolderPollCount(folder.id, folder.poll_count);
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, folder,
account.name + "/" + folder.name +
" poll count=" + folder.poll_count +
" factor=" + folder.poll_factor);
2020-02-25 20:06:17 +00:00
}
2021-12-29 19:56:02 +00:00
if (!first)
Core.onSynchronizeFolders(this,
account, iservice.getStore(), state,
true, false);
2020-08-14 07:44:56 +00:00
}
} catch (Throwable ex) {
2020-06-12 06:36:27 +00:00
if (tune) {
account.keep_alive_failed++;
2020-04-01 06:57:27 +00:00
account.keep_alive_succeeded = 0;
2019-12-29 16:00:38 +00:00
if (account.keep_alive_failed >= 3) {
account.keep_alive_failed = 0;
2021-12-12 07:42:41 +00:00
account.poll_interval = account.poll_interval - TUNE_KEEP_ALIVE_INTERVAL_STEP;
db.account().setAccountKeepAliveInterval(account.id, account.poll_interval);
}
2020-04-01 06:57:27 +00:00
db.account().setAccountKeepAliveValues(account.id,
account.keep_alive_failed, account.keep_alive_succeeded);
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
account.name + " keep alive" +
" failed=" + account.keep_alive_failed +
" succeeded=" + account.keep_alive_succeeded +
" interval=" + account.poll_interval +
" idle=" + idleTime);
}
2020-10-28 19:09:38 +00:00
throw ex;
}
2020-06-12 06:36:27 +00:00
if (tune) {
2020-03-31 09:33:13 +00:00
account.keep_alive_failed = 0;
2020-04-01 06:57:27 +00:00
account.keep_alive_succeeded++;
db.account().setAccountKeepAliveValues(account.id,
account.keep_alive_failed, account.keep_alive_succeeded);
if (account.keep_alive_succeeded >= 3) {
account.keep_alive_ok = true;
db.account().setAccountKeepAliveOk(account.id, true);
if (!BuildConfig.PLAY_STORE_RELEASE)
2020-07-06 10:29:20 +00:00
Log.w(account.host + " set keep-alive=" + account.poll_interval);
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
account.name + " keep alive ok");
2020-04-01 06:57:27 +00:00
} else
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
account.name + " keep alive" +
" failed=" + account.keep_alive_failed +
" succeeded=" + account.keep_alive_succeeded +
" interval=" + account.poll_interval +
" idle=" + idleTime);
}
2019-12-09 21:26:29 +00:00
// Successfully connected: reset back off time
state.setBackoff(CONNECT_BACKOFF_START);
2019-12-09 21:26:29 +00:00
// Record successful connection
account.last_connected = new Date().getTime();
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " set last_connected=" + new Date(account.last_connected));
2019-12-09 21:26:29 +00:00
db.account().setAccountConnected(account.id, account.last_connected);
db.account().setAccountWarning(account.id, capIdle ? null : getString(R.string.title_no_idle));
2022-04-13 20:27:33 +00:00
NotificationManager nm = Helper.getSystemService(this, NotificationManager.class);
2021-07-15 16:36:39 +00:00
nm.cancel("receive:" + account.id, NotificationHelper.NOTIFICATION_TAGGED);
nm.cancel("alert:" + account.id, NotificationHelper.NOTIFICATION_TAGGED);
2019-12-09 21:26:29 +00:00
// Schedule keep alive alarm
2020-10-31 10:11:35 +00:00
Intent intent = new Intent(this, ServiceSynchronize.class);
2019-12-12 10:10:57 +00:00
intent.setAction("keepalive:" + account.id);
PendingIntent pi = PendingIntentCompat.getForegroundService(
this, PI_KEEPALIVE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2022-04-13 20:27:33 +00:00
AlarmManager am = Helper.getSystemService(this, AlarmManager.class);
2019-12-09 21:26:29 +00:00
try {
long duration = account.poll_interval * 60 * 1000L;
long trigger = System.currentTimeMillis() + duration;
2022-08-24 18:18:31 +00:00
Long expirationTime = null;
if (!account.isTransient(this)) {
2022-08-24 18:18:31 +00:00
expirationTime = iservice.getAccessTokenExpirationTime();
2022-07-20 18:43:15 +00:00
if (expirationTime != null &&
expirationTime < trigger &&
expirationTime > new Date().getTime()) {
expirationTime += AuthState.EXPIRY_TIME_TOLERANCE_MS;
2022-08-24 18:18:31 +00:00
EntityLog.log(this, "### " + account.name + " expedite keep alive" +
" from " + new Date(trigger) + " to " + new Date(expirationTime));
trigger = expirationTime;
}
}
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
"### " + account.name + " keep alive" +
2022-08-24 18:18:31 +00:00
" wait=" + account.poll_interval +
" until=" + new Date(trigger) +
" expiration=" + (expirationTime == null ? null : new Date(expirationTime)));
2021-04-27 05:53:09 +00:00
AlarmManagerCompatEx.setAndAllowWhileIdle(ServiceSynchronize.this, am, AlarmManager.RTC_WAKEUP, trigger, pi);
2018-10-08 06:18:44 +00:00
2018-10-10 07:26:04 +00:00
try {
2022-10-22 06:19:29 +00:00
if (wlAccount.isHeld())
wlAccount.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("keeping alive released elapse=" + (new Date().getTime() - start));
2020-09-23 18:31:37 +00:00
state.acquire(2 * duration, false);
Log.i("### " + account.name + " keeping alive");
2018-10-10 07:26:04 +00:00
} catch (InterruptedException ex) {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
account.name + " waited state=" + state);
2018-10-10 07:26:04 +00:00
} finally {
2022-10-22 06:19:29 +00:00
start = new Date().getTime();
wlAccount.acquire(Helper.WAKELOCK_MAX);
2018-10-10 07:26:04 +00:00
}
2019-12-09 21:26:29 +00:00
} finally {
2019-12-12 10:10:57 +00:00
am.cancel(pi);
2019-06-21 15:58:41 +00:00
}
first = false;
2018-08-02 13:33:06 +00:00
}
2018-10-08 06:18:44 +00:00
2018-12-24 12:27:45 +00:00
Log.i(account.name + " done state=" + state);
2018-10-10 07:26:04 +00:00
} catch (Throwable ex) {
2020-10-30 07:34:13 +00:00
last_fail = ex;
2022-03-29 19:17:53 +00:00
iservice.dump(account.name);
2022-05-11 12:28:09 +00:00
if (ex.getMessage() != null && ex.getMessage().startsWith("OAuth refresh"))
Log.i(account.name, ex);
else
Log.e(account.name, ex);
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2022-03-29 20:33:32 +00:00
account.name + " connect " + ex + "\n" + android.util.Log.getStackTraceString(ex));
2019-12-06 07:50:46 +00:00
db.account().setAccountError(account.id, Log.formatThrowable(ex));
2020-07-05 16:46:15 +00:00
// Report account connection error
if (account.last_connected != null && !ConnectionHelper.airplaneMode(this)) {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " last connected: " + new Date(account.last_connected));
2020-07-05 16:46:15 +00:00
2021-05-01 17:02:39 +00:00
int pollInterval = getPollInterval(this);
2020-10-28 19:09:38 +00:00
long now = new Date().getTime();
2020-07-05 16:46:15 +00:00
long delayed = now - account.last_connected - account.poll_interval * 60 * 1000L;
long maxDelayed = (pollInterval > 0 && !account.isExempted(this)
2020-07-05 16:46:15 +00:00
? pollInterval * ACCOUNT_ERROR_AFTER_POLL : ACCOUNT_ERROR_AFTER) * 60 * 1000L;
2021-01-12 20:38:22 +00:00
if (delayed > maxDelayed &&
state.getBackoff() >= CONNECT_BACKOFF_ALARM_START * 60) {
2020-07-05 16:46:15 +00:00
Log.i("Reporting sync error after=" + delayed);
Throwable warning = new Throwable(
getString(R.string.title_no_sync,
Helper.getDateTimeInstance(this, DateFormat.SHORT, DateFormat.SHORT)
.format(account.last_connected)), ex);
try {
2022-06-09 10:38:17 +00:00
NotificationManager nm =
Helper.getSystemService(this, NotificationManager.class);
if (NotificationHelper.areNotificationsEnabled(nm))
nm.notify("receive:" + account.id,
NotificationHelper.NOTIFICATION_TAGGED,
Core.getNotificationError(this, "warning", account, 0, warning)
.build());
2020-07-05 16:46:15 +00:00
} catch (Throwable ex1) {
Log.w(ex1);
}
}
}
2018-08-15 19:34:22 +00:00
} finally {
2019-12-09 07:39:51 +00:00
// Update state
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " closing");
2019-12-09 07:39:51 +00:00
2022-04-18 08:56:35 +00:00
// Cancel purge
2022-04-18 07:36:59 +00:00
getMainHandler().removeCallbacks(purge);
2020-09-22 11:10:46 +00:00
// Stop watching operations
Log.i(account.name + " stop watching operations");
2022-04-18 11:19:48 +00:00
final CountDownLatch latch = new CountDownLatch(1);
2022-04-18 10:37:28 +00:00
2022-04-18 11:19:48 +00:00
getMainHandler().post(new RunnableEx("observe#stop") {
@Override
public void delegate() {
try {
2022-04-21 06:46:56 +00:00
if (cowner.value != null)
cowner.value.destroy();
2022-04-18 11:19:48 +00:00
} catch (Throwable ex) {
Log.e(ex);
} finally {
latch.countDown();
}
2022-04-18 10:37:28 +00:00
}
2022-04-18 11:19:48 +00:00
});
try {
latch.await(5000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
2022-04-23 11:03:51 +00:00
Log.i(ex);
2022-04-18 08:56:35 +00:00
}
2020-09-22 11:10:46 +00:00
// Stop executing operations
Log.i(account.name + " stop executing operations");
2021-09-16 08:43:14 +00:00
state.nextSerial();
2022-12-13 09:52:39 +00:00
for (Runnable task : ((ThreadPoolExecutor) executor).getQueue().toArray(new Runnable[0]))
if (task instanceof Helper.PriorityRunnable &&
((Helper.PriorityRunnable) task).getGroup() == group)
((ThreadPoolExecutor) executor).remove(task);
// Close store
2018-10-10 07:26:04 +00:00
try {
2020-09-24 06:20:19 +00:00
db.account().setAccountState(account.id, "closing");
2021-07-31 07:25:58 +00:00
for (EntityFolder folder : mapFolders.keySet())
if (folder.selectable && folder.synchronize && !folder.poll && mapFolders.get(folder) != null)
db.folder().setFolderState(folder.id, "closing");
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " store closing");
2019-07-28 19:45:29 +00:00
iservice.close();
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " store closed");
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.w(account.name, ex);
2018-10-10 07:26:04 +00:00
} finally {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " closed");
2018-10-10 07:26:04 +00:00
db.account().setAccountState(account.id, null);
2021-07-31 07:25:58 +00:00
for (EntityFolder folder : mapFolders.keySet())
db.folder().setFolderState(folder.id, null);
2018-09-08 08:43:13 +00:00
}
2018-10-10 08:07:37 +00:00
// Stop idlers
2018-11-28 18:47:16 +00:00
for (Thread idler : idlers)
2021-11-28 10:09:21 +00:00
state.join(idler);
2018-12-02 13:19:54 +00:00
idlers.clear();
2018-08-15 19:34:22 +00:00
}
2018-08-02 13:33:06 +00:00
2019-12-09 07:51:05 +00:00
if (state.isRunning()) {
long now = new Date().getTime();
2022-03-09 12:50:35 +00:00
boolean logarithmic_backoff = prefs.getBoolean("logarithmic_backoff", true);
2020-10-29 09:45:24 +00:00
2022-03-09 12:50:35 +00:00
if (logarithmic_backoff) {
// Check for fast successive server, connectivity, etc failures
long poll_interval = Math.min(account.poll_interval, CONNECT_BACKOFF_ALARM_START);
long fail_threshold = poll_interval * 60 * 1000L * FAST_FAIL_THRESHOLD / 100;
long was_connected = (account.last_connected == null ? 0 : now - account.last_connected);
if (was_connected < fail_threshold) {
if (state.getBackoff() == CONNECT_BACKOFF_START) {
fast_fails++;
if (fast_fails == 1)
first_fail = now;
else if (fast_fails >= FAST_FAIL_COUNT) {
long avg_fail = (now - first_fail) / fast_fails;
if (avg_fail < fail_threshold) {
long missing = (fail_threshold - avg_fail) * fast_fails;
int compensate = (int) (missing / (CONNECT_BACKOFF_ALARM_START * 60 * 1000L));
if (compensate > 0) {
if (was_connected != 0 && was_connected < CONNECT_BACKOFF_GRACE)
compensate = 1;
int backoff = compensate * CONNECT_BACKOFF_ALARM_START;
if (backoff > CONNECT_BACKOFF_ALARM_MAX)
backoff = CONNECT_BACKOFF_ALARM_MAX;
String msg = "Fast" +
" fails=" + fast_fails +
" was=" + (was_connected / 1000L) +
" first=" + ((now - first_fail) / 1000L) +
" poll=" + poll_interval +
" avg=" + (avg_fail / 1000L) + "/" + (fail_threshold / 1000L) +
" missing=" + (missing / 1000L) +
" compensate=" + compensate +
" backoff=" + backoff +
" host=" + account.host +
" ex=" + Log.formatThrowable(last_fail, false);
if (compensate > 2)
Log.e(msg);
EntityLog.log(this, EntityLog.Type.Account, account, msg);
state.setBackoff(backoff * 60);
}
2020-10-29 09:45:24 +00:00
}
}
}
2022-03-09 12:50:35 +00:00
} else {
fast_fails = 0;
first_fail = 0;
2020-10-29 09:45:24 +00:00
}
}
int backoff = state.getBackoff();
2020-10-31 09:33:10 +00:00
int recently = (lastLost + LOST_RECENTLY < now ? 1 : 2);
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
account.name + " backoff=" + backoff +
" recently=" + recently + "x" +
" logarithmic=" + logarithmic_backoff);
2022-03-09 12:50:35 +00:00
if (logarithmic_backoff) {
if (backoff < CONNECT_BACKOFF_MAX)
state.setBackoff(backoff * 2);
else if (backoff == CONNECT_BACKOFF_MAX)
if (AlarmManagerCompatEx.hasExactAlarms(this))
state.setBackoff(CONNECT_BACKOFF_INTERMEDIATE * 60);
else
state.setBackoff(CONNECT_BACKOFF_ALARM_START * 60);
else if (backoff == CONNECT_BACKOFF_INTERMEDIATE * 60)
state.setBackoff(CONNECT_BACKOFF_ALARM_START * 60);
2022-03-09 12:50:35 +00:00
else if (backoff < CONNECT_BACKOFF_ALARM_MAX * 60) {
int b = backoff * 2;
if (b > CONNECT_BACKOFF_ALARM_MAX * 60)
b = CONNECT_BACKOFF_ALARM_MAX * 60;
state.setBackoff(b);
}
} else {
// Linear back-off
2022-03-12 22:20:21 +00:00
int b = backoff + (backoff < CONNECT_BACKOFF_INTERMEDIATE * 60 ? 60 : 5 * 60);
2021-08-06 05:39:11 +00:00
if (b > CONNECT_BACKOFF_ALARM_MAX * 60)
b = CONNECT_BACKOFF_ALARM_MAX * 60;
state.setBackoff(b);
}
2020-11-20 09:06:35 +00:00
2022-08-16 06:06:07 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("account", account.name);
crumb.put("backoff", Integer.toString(backoff));
crumb.put("recently", Integer.toString(recently));
crumb.put("logarithmic", Boolean.toString(logarithmic_backoff));
Log.breadcrumb("Backing off", crumb);
2020-10-31 09:33:10 +00:00
if (backoff <= CONNECT_BACKOFF_MAX) {
// Short back-off period, keep device awake
2019-12-09 07:51:05 +00:00
try {
2020-11-20 09:06:35 +00:00
long interval = backoff * 1000L * recently;
db.account().setAccountBackoff(account.id, System.currentTimeMillis() + interval);
state.acquire(interval, true);
2019-12-09 07:51:05 +00:00
} catch (InterruptedException ex) {
Log.w(account.name + " backoff " + ex.toString());
2020-10-29 19:03:09 +00:00
} finally {
db.account().setAccountBackoff(account.id, null);
2019-12-09 07:51:05 +00:00
}
} else {
// Cancel transient sync operations
2020-12-26 15:41:34 +00:00
if (account.isTransient(this)) {
List<EntityOperation> syncs = db.operation().getOperations(account.id, EntityOperation.SYNC);
if (syncs != null) {
for (EntityOperation op : syncs) {
db.folder().setFolderSyncState(op.folder, null);
db.operation().deleteOperation(op.id);
}
Log.i(account.name + " cancelled syncs=" + syncs.size());
}
}
// Long back-off period, let device sleep
2020-10-31 10:11:35 +00:00
Intent intent = new Intent(this, ServiceSynchronize.class);
intent.setAction("backoff:" + account.id);
PendingIntent pi = PendingIntentCompat.getForegroundService(
this, PI_BACKOFF, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2019-12-12 10:10:57 +00:00
2022-04-13 20:27:33 +00:00
AlarmManager am = Helper.getSystemService(this, AlarmManager.class);
try {
long trigger = System.currentTimeMillis() + backoff * 1000L;
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
"### " + account.name + " backoff until=" + new Date(trigger));
2021-04-27 05:53:09 +00:00
AlarmManagerCompatEx.setAndAllowWhileIdle(ServiceSynchronize.this, am, AlarmManager.RTC_WAKEUP, trigger, pi);
2018-11-09 08:54:24 +00:00
2019-12-09 07:51:05 +00:00
try {
2020-10-29 19:03:09 +00:00
db.account().setAccountBackoff(account.id, trigger);
2022-10-22 06:19:29 +00:00
if (wlAccount.isHeld())
wlAccount.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("backoff released elapse=" + (new Date().getTime() - start));
state.acquire(2 * backoff * 1000L, true);
Log.i("### " + account.name + " backoff done");
} catch (InterruptedException ex) {
Log.w(account.name + " backoff " + ex.toString());
2018-11-08 17:16:32 +00:00
} finally {
2022-10-22 06:19:29 +00:00
start = new Date().getTime();
wlAccount.acquire(Helper.WAKELOCK_MAX);
2020-10-29 19:03:09 +00:00
db.account().setAccountBackoff(account.id, null);
2019-12-09 07:51:05 +00:00
}
} finally {
am.cancel(pi);
2018-11-08 17:16:32 +00:00
}
2020-04-24 07:49:17 +00:00
}
2019-12-09 07:51:05 +00:00
}
2020-03-08 10:08:28 +00:00
2021-04-05 06:23:00 +00:00
accountThread = db.account().getAccountThread(account.id);
2018-08-02 13:33:06 +00:00
}
2020-03-08 10:08:28 +00:00
if (!currentThread.equals(accountThread) && accountThread != null)
2022-04-19 06:16:46 +00:00
Log.i(account.name + " orphan thread id=" + currentThread + "/" + accountThread);
2018-10-10 07:26:04 +00:00
} finally {
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2022-03-29 17:12:43 +00:00
account.name + " stopped running=" + state.isRunning());
2022-10-22 06:19:29 +00:00
if (wlAccount.isHeld())
wlAccount.release();
2022-10-23 14:11:03 +00:00
else if (!isOptimizing && !BuildConfig.PLAY_STORE_RELEASE)
2022-10-22 06:19:29 +00:00
Log.e("account released elapse=" + (new Date().getTime() - start));
2018-08-02 13:33:06 +00:00
}
}
2022-01-23 07:29:11 +00:00
private void fetch(EntityFolder folder, IMAPFolder ifolder, Message[] messages, boolean invalidate, boolean deleted, String reason) throws MessagingException {
2021-10-25 11:38:12 +00:00
Log.i(folder.name + " " + messages.length + " messages " + reason);
List<Long> uids = new ArrayList<>();
for (Message imessage : messages)
try {
long uid = ifolder.getUID(imessage);
uids.add(uid);
} catch (MessageRemovedException ex) {
Log.w(ex);
}
Log.i(folder.name + " messages " + reason + " uids=" + TextUtils.join(",", uids));
DB db = DB.getInstance(this);
try {
db.beginTransaction();
for (long uid : uids)
2022-01-23 07:29:11 +00:00
EntityOperation.queue(this, folder, EntityOperation.FETCH, uid, invalidate, deleted);
2021-10-25 11:38:12 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
2021-06-28 09:31:19 +00:00
private void updateQuota(Context context, IMAPStore istore, EntityAccount account) {
2020-12-29 17:46:17 +00:00
DB db = DB.getInstance(this);
try {
if (istore.hasCapability("QUOTA")) {
2021-06-28 09:31:19 +00:00
// https://datatracker.ietf.org/doc/html/rfc2087
2020-12-29 17:46:17 +00:00
Quota[] quotas = istore.getQuota("INBOX");
if (quotas != null) {
2021-06-28 09:31:19 +00:00
Long usage = null;
Long limit = null;
2020-12-29 17:46:17 +00:00
for (Quota quota : quotas)
if (quota.resources != null)
for (Quota.Resource resource : quota.resources) {
2022-01-29 07:50:30 +00:00
EntityLog.log(context, EntityLog.Type.Account, account,
account.name + " Quota " + resource.name + " " + resource.usage + "/" + resource.limit);
2021-06-29 06:13:10 +00:00
// (STORAGE nnnnn 9999999999999999)
2020-12-29 17:46:17 +00:00
if ("STORAGE".equalsIgnoreCase(resource.name)) {
2021-06-29 06:13:10 +00:00
if (resource.usage * 1024 >= 0)
2021-06-28 09:31:19 +00:00
usage = (usage == null ? 0L : usage) + resource.usage * 1024;
2021-06-29 06:13:10 +00:00
if (resource.limit * 1024 > 0)
2021-06-28 09:31:19 +00:00
limit = Math.max(limit == null ? 0L : limit, resource.limit * 1024);
2020-12-29 17:46:17 +00:00
}
}
db.account().setAccountQuota(account.id, usage, limit);
}
} else
db.account().setAccountQuota(account.id, null, null);
} catch (MessagingException ex) {
Log.w(ex);
db.account().setAccountQuota(account.id, null, null);
}
}
2020-10-26 17:56:34 +00:00
private void optimizeAccount(EntityAccount account, String reason) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
2020-07-09 06:53:16 +00:00
boolean auto_optimize = prefs.getBoolean("auto_optimize", false);
2020-03-10 07:44:47 +00:00
if (!auto_optimize)
return;
2020-10-26 17:56:34 +00:00
DB db = DB.getInstance(this);
2020-03-10 07:44:47 +00:00
2021-05-01 17:02:39 +00:00
int pollInterval = getPollInterval(this);
2022-01-29 07:50:30 +00:00
EntityLog.log(this, EntityLog.Type.Account, account,
2021-08-15 18:32:34 +00:00
account.name + " auto optimize" +
" reason=" + reason +
" poll interval=" + pollInterval);
2020-03-10 07:44:47 +00:00
if (pollInterval == 0) {
try {
db.beginTransaction();
for (EntityAccount a : db.account().getAccounts())
db.account().setAccountPollExempted(a.id, !a.id.equals(account.id));
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2020-10-25 17:21:20 +00:00
prefs.edit().putInt("poll_interval", OPTIMIZE_POLL_INTERVAL).apply();
} else if (pollInterval <= 60 && account.isExempted(this)) {
2020-03-10 07:44:47 +00:00
db.account().setAccountPollExempted(account.id, false);
2021-05-11 06:24:18 +00:00
eval(this, "Optimize=" + reason);
2020-03-10 07:44:47 +00:00
}
}
2021-01-17 16:25:38 +00:00
private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
2021-03-17 11:15:25 +00:00
// Android O+: this will always immediately be followed by a call to onCapabilitiesChanged/onLinkPropertiesChanged
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
updateNetworkState(network, "available");
}
2018-08-02 13:33:06 +00:00
@Override
2020-07-15 18:41:58 +00:00
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities caps) {
2020-10-28 10:44:15 +00:00
updateNetworkState(network, "capabilities");
}
2018-08-02 13:33:06 +00:00
@Override
2020-07-15 18:41:58 +00:00
public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties props) {
2020-10-28 10:44:15 +00:00
updateNetworkState(network, "properties");
}
2021-03-17 11:16:00 +00:00
@Override
public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {
2022-01-29 07:50:30 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Network,
2021-08-15 18:32:34 +00:00
"Network " + network + " blocked=" + blocked);
2021-03-17 11:16:00 +00:00
}
@Override
public void onLost(@NonNull Network network) {
2020-10-28 10:44:15 +00:00
updateNetworkState(network, "lost");
}
2019-03-06 10:18:57 +00:00
};
2021-01-17 16:25:38 +00:00
private final BroadcastReceiver connectionChangedReceiver = new BroadcastReceiver() {
2019-09-30 18:44:22 +00:00
@Override
public void onReceive(Context context, Intent intent) {
2020-01-15 09:59:48 +00:00
Log.i("Received intent=" + intent +
" " + TextUtils.join(" ", Log.getExtras(intent.getExtras())));
2019-10-04 15:17:42 +00:00
if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
boolean on = intent.getBooleanExtra("state", false);
2021-08-16 07:36:23 +00:00
EntityLog.log(context, EntityLog.Type.Network,
2021-08-15 18:32:34 +00:00
"Airplane mode on=" + on);
2019-10-04 15:17:42 +00:00
if (!on)
2019-12-12 08:19:30 +00:00
lastLost = 0;
2019-10-04 15:17:42 +00:00
}
2021-01-16 18:21:31 +00:00
updateNetworkState(null, "connectivity");
2019-09-30 18:44:22 +00:00
}
};
2021-01-17 16:26:21 +00:00
private final BroadcastReceiver idleModeChangedReceiver = new BroadcastReceiver() {
@Override
@RequiresApi(api = Build.VERSION_CODES.M)
public void onReceive(Context context, Intent intent) {
2022-04-13 20:27:33 +00:00
PowerManager pm = Helper.getSystemService(context, PowerManager.class);
2021-01-17 16:26:21 +00:00
EntityLog.log(context, "Doze mode=" + pm.isDeviceIdleMode() +
" ignoring=" + pm.isIgnoringBatteryOptimizations(context.getPackageName()));
}
};
private final BroadcastReceiver dataSaverChanged = new BroadcastReceiver() {
@Override
@RequiresApi(api = Build.VERSION_CODES.N)
public void onReceive(Context context, Intent intent) {
Log.i("Received intent=" + intent +
" " + TextUtils.join(" ", Log.getExtras(intent.getExtras())));
2022-04-13 20:27:33 +00:00
ConnectivityManager cm = Helper.getSystemService(context, ConnectivityManager.class);
2021-01-17 16:26:21 +00:00
Integer status = (cm == null ? null : cm.getRestrictBackgroundStatus());
EntityLog.log(context, "Data saver=" + status);
updateNetworkState(null, "datasaver");
}
};
2022-04-01 07:51:40 +00:00
private final BroadcastReceiver suspendChanged = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
EntityLog.log(context, intent.getAction() + " " +
TextUtils.join(", ", Log.getExtras(intent.getExtras())));
}
};
2022-04-01 07:58:07 +00:00
private final BroadcastReceiver batteryChanged = new BroadcastReceiver() {
private Integer lastLevel = null;
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
if (!Objects.equals(level, lastLevel)) {
lastLevel = level;
EntityLog.log(context, intent.getAction() + " " +
TextUtils.join(", ", Log.getExtras(intent.getExtras())));
}
}
};
2021-01-16 18:21:31 +00:00
private void updateNetworkState(final Network network, final String reason) {
2022-04-17 19:34:33 +00:00
getMainHandler().post(new RunnableEx("network") {
2021-01-16 18:21:31 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2021-01-16 18:21:31 +00:00
try {
Network active = ConnectionHelper.getActiveNetwork(ServiceSynchronize.this);
2020-10-27 19:49:20 +00:00
2021-01-16 18:21:31 +00:00
if (active != null && !active.equals(lastActive)) {
if (ConnectionHelper.isConnected(ServiceSynchronize.this, active)) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Network,
2021-01-16 18:21:31 +00:00
reason + ": new active network=" + active + "/" + lastActive);
lastActive = active;
}
} else if (lastActive != null) {
if (!ConnectionHelper.isConnected(ServiceSynchronize.this, lastActive)) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Network,
2021-01-16 18:21:31 +00:00
reason + ": lost active network=" + lastActive);
lastActive = null;
lastLost = new Date().getTime();
}
}
2020-09-24 09:14:27 +00:00
2021-01-16 18:21:31 +00:00
if (network == null || Objects.equals(network, active)) {
ConnectionHelper.NetworkState ns = ConnectionHelper.getNetworkState(ServiceSynchronize.this);
if (!Objects.equals(lastNetworkState, ns)) {
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Network,
2021-01-16 18:21:31 +00:00
reason + ": updating state network=" + active +
" info=" + ConnectionHelper.getNetworkInfo(ServiceSynchronize.this, active) + " " + ns);
lastNetworkState = ns;
liveNetworkState.postValue(ns);
}
}
2020-10-28 10:44:15 +00:00
2021-01-16 18:21:31 +00:00
boolean isSuitable = (lastNetworkState != null && lastNetworkState.isSuitable());
if (lastSuitable == null || lastSuitable != isSuitable) {
lastSuitable = isSuitable;
2021-08-16 07:36:23 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Network,
2021-08-15 18:32:34 +00:00
reason + ": updated suitable=" + lastSuitable);
2021-01-16 18:21:31 +00:00
if (!isBackgroundService(ServiceSynchronize.this))
try {
2022-06-09 10:38:17 +00:00
NotificationManager nm =
Helper.getSystemService(ServiceSynchronize.this, NotificationManager.class);
if (NotificationHelper.areNotificationsEnabled(nm))
nm.notify(NotificationHelper.NOTIFICATION_SYNCHRONIZE,
getNotificationService(lastAccounts, lastOperations));
2021-01-16 18:21:31 +00:00
} catch (Throwable ex) {
Log.w(ex);
}
}
2020-10-27 20:41:22 +00:00
} catch (Throwable ex) {
2021-01-16 18:21:31 +00:00
Log.e(ex);
2020-10-27 20:41:22 +00:00
}
2021-01-16 18:21:31 +00:00
}
});
2020-07-17 06:06:25 +00:00
}
2019-12-12 07:56:57 +00:00
private class MediatorState extends MediatorLiveData<List<TupleAccountNetworkState>> {
2020-12-31 13:12:21 +00:00
private boolean running = true;
2021-03-16 07:42:32 +00:00
private Bundle lastCommand = null;
2019-12-12 07:56:57 +00:00
private ConnectionHelper.NetworkState lastNetworkState = null;
private List<TupleAccountState> lastAccountStates = null;
private void post(Bundle command) {
2021-08-16 08:22:26 +00:00
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"### command " + TextUtils.join(" ", Log.getExtras(command)));
2021-01-21 14:41:27 +00:00
2021-03-16 07:54:59 +00:00
if (command.getBoolean("sync") || command.getBoolean("force"))
2021-01-21 14:41:27 +00:00
lastNetworkState = ConnectionHelper.getNetworkState(ServiceSynchronize.this);
2019-12-12 07:56:57 +00:00
post(command, lastNetworkState, lastAccountStates);
}
private void post(ConnectionHelper.NetworkState networkState) {
lastNetworkState = networkState;
2021-03-16 07:42:32 +00:00
post(lastCommand, lastNetworkState, lastAccountStates);
2019-12-12 07:56:57 +00:00
}
private void post(List<TupleAccountState> accountStates) {
lastAccountStates = accountStates;
2021-03-16 07:42:32 +00:00
post(lastCommand, lastNetworkState, lastAccountStates);
2019-12-12 07:56:57 +00:00
}
private void postDestroy() {
if (running) {
running = false;
postValue(null);
}
}
private void post(Bundle command, ConnectionHelper.NetworkState networkState, List<TupleAccountState> accountStates) {
2021-09-30 05:30:12 +00:00
try {
if (!running) {
Log.i("### not running");
return;
}
2019-12-12 07:56:57 +00:00
2021-09-30 05:30:12 +00:00
if (networkState == null)
networkState = ConnectionHelper.getNetworkState(ServiceSynchronize.this);
2020-06-16 08:51:47 +00:00
2021-09-30 05:30:12 +00:00
if (accountStates == null) {
EntityLog.log(ServiceSynchronize.this, EntityLog.Type.Scheduling, "### no accounts");
lastCommand = command;
return;
}
2019-12-12 07:56:57 +00:00
2021-09-30 05:30:12 +00:00
lastCommand = null;
2021-03-16 07:42:32 +00:00
2021-09-30 05:30:12 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
boolean enabled = prefs.getBoolean("enabled", true);
int pollInterval = getPollInterval(ServiceSynchronize.this);
2019-12-12 07:56:57 +00:00
2021-09-30 05:30:12 +00:00
long[] schedule = getSchedule(ServiceSynchronize.this);
long now = new Date().getTime();
boolean scheduled = (schedule == null || (now >= schedule[0] && now < schedule[1]));
2019-12-12 07:56:57 +00:00
2021-09-30 05:30:12 +00:00
if (command == null) {
command = new Bundle();
command.putString("name", "eval");
}
2019-12-12 07:56:57 +00:00
2021-09-30 05:30:12 +00:00
List<TupleAccountNetworkState> result = new ArrayList<>();
for (TupleAccountState accountState : accountStates)
result.add(new TupleAccountNetworkState(
2022-04-23 10:44:25 +00:00
enabled && (pollInterval == 0 || accountState.isExempted(ServiceSynchronize.this)),
scheduled,
2021-09-30 05:30:12 +00:00
command,
networkState,
accountState));
2019-12-12 07:56:57 +00:00
2021-09-30 05:30:12 +00:00
postValue(result);
} catch (Throwable ex) {
Log.e(ex);
/*
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at androidx.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager:124)
at androidx.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager:119)
at eu.faircode.email.ServiceSynchronize$MediatorState.post(ServiceSynchronize:2596)
at eu.faircode.email.ServiceSynchronize$MediatorState.post(ServiceSynchronize:2569)
at eu.faircode.email.ServiceSynchronize$MediatorState.access$400(ServiceSynchronize:2546)
at eu.faircode.email.ServiceSynchronize$3.onChanged(ServiceSynchronize:219)
at eu.faircode.email.ServiceSynchronize$3.onChanged(ServiceSynchronize:216)
at androidx.lifecycle.MediatorLiveData$Source.onChanged(MediatorLiveData:152)
at androidx.lifecycle.LiveData.considerNotify(LiveData:133)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData:151)
at androidx.lifecycle.LiveData.setValue(LiveData:309)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData:50)
at androidx.lifecycle.LiveData$1.run(LiveData:93)
at android.os.Handler.handleCallback(Handler.java:761)
*/
}
2019-12-12 07:56:57 +00:00
}
}
2019-03-06 10:18:57 +00:00
static void boot(final Context context) {
2022-12-13 09:52:39 +00:00
Helper.getSerialExecutor().submit(new RunnableEx("boot") {
2019-08-01 07:08:28 +00:00
@Override
2022-04-17 19:34:33 +00:00
public void delegate() {
2019-08-01 07:08:28 +00:00
try {
2020-12-31 11:29:58 +00:00
EntityLog.log(context, "Boot sync service");
2019-08-01 07:08:28 +00:00
DB db = DB.getInstance(context);
try {
db.beginTransaction();
// Restore notifications
db.message().clearNotifyingMessages();
// Restore snooze timers
for (EntityMessage message : db.message().getSnoozed(null))
EntityMessage.snooze(context, message.id, message.ui_snoozed);
db.setTransactionSuccessful();
} catch (IllegalArgumentException ex) {
Log.w(ex);
} finally {
db.endTransaction();
}
// Restore schedule
2020-08-30 07:34:51 +00:00
schedule(context, false);
// Init service
2020-12-31 13:12:21 +00:00
eval(context, "boot");
2019-08-01 07:08:28 +00:00
} catch (Throwable ex) {
Log.e(ex);
2018-11-29 07:35:34 +00:00
}
2019-08-01 07:08:28 +00:00
}
2020-12-31 11:29:58 +00:00
});
2019-08-01 07:08:28 +00:00
}
2021-06-16 09:48:16 +00:00
private static void schedule(Context context, boolean polled) {
Intent intent = new Intent(context, ServiceSynchronize.class);
intent.setAction("alarm");
PendingIntent pi = PendingIntentCompat.getForegroundService(
context, PI_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2019-02-28 07:55:08 +00:00
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
2019-02-28 07:55:08 +00:00
2022-04-23 10:44:25 +00:00
long now = new Date().getTime();
2022-04-23 11:03:51 +00:00
long[] schedule = getSchedule(context);
2022-04-23 10:44:25 +00:00
boolean scheduled = (schedule == null || (now >= schedule[0] && now < schedule[1]));
if (schedule != null) {
2020-01-10 11:12:14 +00:00
long next = (now < schedule[0] ? schedule[0] : schedule[1]);
2020-01-10 11:12:14 +00:00
Log.i("Schedule now=" + new Date(now));
Log.i("Schedule start=" + new Date(schedule[0]));
Log.i("Schedule end=" + new Date(schedule[1]));
Log.i("Schedule next=" + new Date(next));
2021-06-16 09:48:16 +00:00
Log.i("Schedule scheduled=" + scheduled);
2021-04-27 05:53:09 +00:00
AlarmManagerCompatEx.setAndAllowWhileIdle(context, am, AlarmManager.RTC_WAKEUP, next, pi);
2020-01-10 11:12:14 +00:00
}
2022-12-13 09:52:39 +00:00
Helper.getSerialExecutor().submit(new RunnableEx("schedule") {
2022-04-23 10:44:25 +00:00
@Override
protected void delegate() {
boolean work = false;
DB db = DB.getInstance(context);
List<EntityAccount> accounts = db.account().getPollAccounts(null);
for (EntityAccount account : accounts) {
JSONObject jcondition = new JSONObject();
try {
2022-04-24 07:55:04 +00:00
if (!TextUtils.isEmpty(account.conditions))
jcondition = new JSONObject(account.conditions);
2022-04-23 10:44:25 +00:00
} catch (Throwable ex) {
Log.e(ex);
}
if (scheduled || jcondition.optBoolean("ignore_schedule")) {
work = true;
break;
}
}
Long at = null;
if (scheduled && polled) {
at = now + 30 * 1000L;
Log.i("Sync at schedule start=" + new Date(at));
}
schedule(context, work, polled, at);
}
});
2021-03-29 13:22:49 +00:00
}
2021-06-16 09:48:16 +00:00
private static void schedule(Context context, boolean scheduled, boolean polled, Long at) {
2021-03-29 13:22:49 +00:00
Intent intent = new Intent(context, ServiceSynchronize.class);
intent.setAction("poll");
PendingIntent piSync = PendingIntentCompat.getForegroundService(
context, PI_POLL, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(piSync);
if (at == null) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean enabled = prefs.getBoolean("enabled", true);
2021-05-01 17:02:39 +00:00
int pollInterval = getPollInterval(context);
2021-06-16 09:48:16 +00:00
if (scheduled && enabled && pollInterval > 0) {
2021-03-29 13:22:49 +00:00
long now = new Date().getTime();
long interval = pollInterval * 60 * 1000L;
2021-06-16 10:53:04 +00:00
long next = now - now % interval + 30 * 1000L;
if (polled || next < now)
next += interval;
2021-06-16 09:48:16 +00:00
if (polled && next < now + interval / 5)
2021-03-29 13:22:49 +00:00
next += interval;
2021-08-16 07:36:23 +00:00
EntityLog.log(context, EntityLog.Type.Scheduling,
2021-08-15 18:32:34 +00:00
"Poll next=" + new Date(next) + " polled=" + polled);
2021-03-29 13:22:49 +00:00
2021-04-27 05:53:09 +00:00
AlarmManagerCompatEx.setAndAllowWhileIdle(context, am, AlarmManager.RTC_WAKEUP, next, piSync);
2021-03-29 13:22:49 +00:00
}
} else
2021-04-27 05:53:09 +00:00
AlarmManagerCompatEx.setAndAllowWhileIdle(context, am, AlarmManager.RTC_WAKEUP, at, piSync);
}
2021-05-01 17:02:39 +00:00
static int getPollInterval(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getInt("poll_interval", 0); // minutes
2021-05-01 17:02:39 +00:00
}
2020-01-14 08:02:37 +00:00
static long[] getSchedule(Context context) {
2019-02-28 07:55:08 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2020-03-19 20:36:56 +00:00
boolean enabled = prefs.getBoolean("enabled", true);
boolean schedule = prefs.getBoolean("schedule", false);
if (!enabled || !schedule)
2019-12-23 13:08:04 +00:00
return null;
if (!ActivityBilling.isPro(context))
return null;
2019-02-28 07:55:08 +00:00
int minuteStart = prefs.getInt("schedule_start", 0);
int minuteEnd = prefs.getInt("schedule_end", 0);
Calendar calStart = Calendar.getInstance();
calStart.set(Calendar.HOUR_OF_DAY, minuteStart / 60);
calStart.set(Calendar.MINUTE, minuteStart % 60);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
2019-12-23 13:08:04 +00:00
calStart.add(Calendar.DATE, -1);
2019-02-28 07:55:08 +00:00
Calendar calEnd = Calendar.getInstance();
calEnd.set(Calendar.HOUR_OF_DAY, minuteEnd / 60);
calEnd.set(Calendar.MINUTE, minuteEnd % 60);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
2019-12-23 13:08:04 +00:00
if (minuteEnd > minuteStart)
calEnd.add(Calendar.DATE, -1);
2019-02-28 07:55:08 +00:00
long now = new Date().getTime();
2019-12-23 13:08:04 +00:00
boolean found = false;
for (int i = 0; i < 8; i++) {
int sdow = calStart.get(Calendar.DAY_OF_WEEK) - 1;
int edow = calEnd.get(Calendar.DAY_OF_WEEK) - 1;
boolean son = prefs.getBoolean("schedule_day" + sdow, true);
boolean eon = prefs.getBoolean("schedule_day" + edow, true);
if (BuildConfig.DEBUG)
Log.i("@@@ eval dow=" + sdow + "/" + edow +
" on=" + son + "/" + eon +
" start=" + new Date(calStart.getTimeInMillis()) +
" end=" + new Date(calEnd.getTimeInMillis()));
if ((son || eon) &&
now < calEnd.getTimeInMillis() &&
(i > 0 || (now >= calStart.getTimeInMillis() && eon))) {
found = true;
if (!son) {
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.add(Calendar.DATE, 1);
}
if (!eon) {
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
}
break;
}
calStart.add(Calendar.DATE, 1);
calEnd.add(Calendar.DATE, 1);
}
if (!found) {
if (BuildConfig.DEBUG)
Log.i("@@@ not found");
return null;
2019-02-28 07:55:08 +00:00
}
long start = calStart.getTimeInMillis();
long end = calEnd.getTimeInMillis();
2019-12-23 13:08:04 +00:00
if (BuildConfig.DEBUG) {
Log.i("@@@ start=" + new Date(start));
Log.i("@@@ end=" + new Date(end));
}
if (now > end)
Log.e("Schedule invalid now=" + new Date(now) + " end=" + new Date(end));
if (start > end)
Log.e("Schedule invalid start=" + new Date(start) + " end=" + new Date(end));
2019-04-27 16:07:06 +00:00
return new long[]{start, end};
2019-02-28 07:55:08 +00:00
}
2021-03-29 19:11:13 +00:00
static void scheduleWatchdog(Context context) {
try {
Intent intent = new Intent(context, ServiceSynchronize.class)
.setAction("watchdog");
PendingIntent pi;
if (isBackgroundService(context))
pi = PendingIntentCompat.getService(context, PI_WATCHDOG, intent, PendingIntent.FLAG_UPDATE_CURRENT);
else {
// Workaround for Xiaomi Android 11
pi = PendingIntentCompat.getForegroundService(context, PI_WATCHDOG, intent, PendingIntent.FLAG_NO_CREATE);
if (pi == null)
pi = PendingIntentCompat.getForegroundService(context, PI_WATCHDOG, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
2021-03-29 19:11:13 +00:00
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
2022-03-04 19:10:25 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean watchdog = prefs.getBoolean("watchdog", true);
boolean enabled = prefs.getBoolean("enabled", true);
if (watchdog && enabled) {
long now = new Date().getTime();
long next = now - now % WATCHDOG_INTERVAL + WATCHDOG_INTERVAL + WATCHDOG_INTERVAL / 4;
if (next < now + WATCHDOG_INTERVAL / 5)
next += WATCHDOG_INTERVAL;
EntityLog.log(context, "Watchdog next=" + new Date(next));
AlarmManagerCompatEx.setAndAllowWhileIdle(context, am, AlarmManager.RTC_WAKEUP, next, pi);
}
} catch (Throwable ex) {
Log.e(ex);
/*
Redmi Note 8 Pro Android 11 (SDK 30)
java.lang.RuntimeException:
at android.app.ActivityThread.handleBindApplication (ActivityThread.java:7019)
at android.app.ActivityThread.access$1600 (ActivityThread.java:263)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2034)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:236)
at android.app.ActivityThread.main (ActivityThread.java:8057)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1011)
Caused by: java.lang.SecurityException:
at android.os.Parcel.createExceptionOrNull (Parcel.java:2376)
at android.os.Parcel.createException (Parcel.java:2360)
at android.os.Parcel.readException (Parcel.java:2343)
at android.os.Parcel.readException (Parcel.java:2285)
at android.app.IActivityManager$Stub$Proxy.getIntentSenderWithFeature (IActivityManager.java:6884)
at android.app.PendingIntent.buildServicePendingIntent (PendingIntent.java:657)
at android.app.PendingIntent.getForegroundService (PendingIntent.java:645)
at eu.faircode.email.PendingIntentCompat.getForegroundService (PendingIntentCompat.java:51)
at eu.faircode.email.ServiceSynchronize.scheduleWatchdog (ServiceSynchronize.java:2972)
at eu.faircode.email.ApplicationEx.onCreate (ApplicationEx.java:229)
*/
2022-03-04 19:10:25 +00:00
}
2021-03-29 19:11:13 +00:00
}
2019-12-09 18:44:27 +00:00
static void eval(Context context, String reason) {
start(context,
2019-02-14 12:28:03 +00:00
new Intent(context, ServiceSynchronize.class)
.setAction("eval")
2019-12-09 18:44:27 +00:00
.putExtra("reason", reason));
}
2020-03-30 11:07:37 +00:00
static void reload(Context context, Long account, boolean force, String reason) {
start(context,
2019-12-09 18:44:27 +00:00
new Intent(context, ServiceSynchronize.class)
2019-12-09 21:26:29 +00:00
.setAction("reload")
.putExtra("account", account == null ? -1 : account)
2020-03-30 11:07:37 +00:00
.putExtra("force", force)
.putExtra("reason", reason));
2019-04-17 08:53:15 +00:00
}
static void reschedule(Context context) {
start(context,
new Intent(context, ServiceSynchronize.class)
.setAction("alarm"));
2018-08-02 13:33:06 +00:00
}
2020-03-25 09:44:50 +00:00
static void state(Context context, boolean foreground) {
start(context,
new Intent(context, ServiceSynchronize.class)
.setAction("state")
.putExtra("foreground", foreground));
}
2020-03-25 09:44:50 +00:00
static void watchdog(Context context) {
2021-03-29 18:08:35 +00:00
start(context,
new Intent(context, ServiceSynchronize.class)
.setAction("watchdog"));
2020-03-25 09:44:50 +00:00
}
static void stop(Context context) {
2021-02-24 14:58:53 +00:00
context.stopService(new Intent(context, ServiceSynchronize.class));
}
static void restart(Context context) {
stop(context);
2021-02-24 14:58:53 +00:00
eval(context, "restart");
}
private static void start(Context context, Intent intent) {
2022-11-24 09:06:53 +00:00
try {
if (isBackgroundService(context))
context.startService(intent);
else
2021-03-24 17:55:18 +00:00
ContextCompat.startForegroundService(context, intent);
2022-11-24 09:06:53 +00:00
} catch (Throwable ex) {
Log.e(ex);
}
}
2020-10-16 11:02:32 +00:00
private static boolean isBackgroundService(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
return false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean("background_service", false);
}
2018-08-02 13:33:06 +00:00
}