Skip to content

Commit

Permalink
Allow to delete selected cookies on exit
Browse files Browse the repository at this point in the history
  • Loading branch information
Mishiranu committed Nov 21, 2020
1 parent 7d0067a commit 94950c7
Show file tree
Hide file tree
Showing 10 changed files with 198 additions and 49 deletions.
1 change: 1 addition & 0 deletions lang/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
<string name="default_name_cant_be_hidden">Нельзя скрыть имя по умолчанию</string>
<string name="default_starting_board">Раздел по умолчанию</string>
<string name="delete">Удалить</string>
<string name="delete_on_exit">Удалять при выходе</string>
<string name="deleted_posts_will_be_deleted__sentence">Удалённые сообщение будут удалены навсегда.</string>
<string name="description">Описание</string>
<string name="detailed_file_name">Подробное имя файла</string>
Expand Down
1 change: 1 addition & 0 deletions lang/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
<string name="default_name_cant_be_hidden">Default name can\'t be hidden</string>
<string name="default_starting_board">Default starting board</string>
<string name="delete">Delete</string>
<string name="delete_on_exit">Delete on exit</string>
<string name="deleted_posts_will_be_deleted__sentence">Deleted posts will be permanently deleted.</string>
<string name="description">Description</string>
<string name="detailed_file_name">Detailed file name</string>
Expand Down
42 changes: 37 additions & 5 deletions src/com/mishiranu/dashchan/content/database/ChanDatabase.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
Expand Down Expand Up @@ -70,6 +71,7 @@ interface Columns {
interface Flags {
int DELETED = 0x00000001;
int BLOCKED = 0x00000002;
int DELETE_ON_EXIT = 0x00000004;
}
}

Expand Down Expand Up @@ -191,12 +193,14 @@ public static class CookieItem {
public String value;
public String title;
public boolean blocked;
public boolean deleteOnExit;

public CookieItem update(CookieCursor cursor) {
name = cursor.getString(cursor.nameIndex);
value = cursor.getString(cursor.valueIndex);
title = cursor.getString(cursor.titleIndex);
blocked = FlagUtils.get(cursor.getInt(cursor.flagsIndex), Schema.Cookies.Flags.BLOCKED);
deleteOnExit = FlagUtils.get(cursor.getInt(cursor.flagsIndex), Schema.Cookies.Flags.DELETE_ON_EXIT);
return this;
}

Expand All @@ -206,6 +210,7 @@ public CookieItem copy() {
cookieItem.value = value;
cookieItem.title = title;
cookieItem.blocked = blocked;
cookieItem.deleteOnExit = deleteOnExit;
return cookieItem;
}
}
Expand Down Expand Up @@ -285,7 +290,7 @@ private ChanDatabase() {
String title = jsonObject.optString("displayName");
boolean blocked = jsonObject.optBoolean("blocked");
setCookie(chanName, name, value, title);
setCookieBlocked(chanName, name, blocked);
setCookieState(chanName, name, blocked, null);
}
}
}
Expand All @@ -294,6 +299,7 @@ private ChanDatabase() {
}
}
}
deleteCookiesOnExit();
}

private static class Helper extends SQLiteOpenHelper {
Expand Down Expand Up @@ -661,20 +667,27 @@ public void setCookie(@NonNull String chanName, @NonNull String name, String val
}
}

public void setCookieBlocked(@NonNull String chanName, @NonNull String name, boolean blocked) {
public void setCookieState(@NonNull String chanName, @NonNull String name, Boolean blocked, Boolean deleteOnExit) {
Objects.requireNonNull(chanName);
Objects.requireNonNull(name);
if (blocked == null && deleteOnExit == null) {
return;
}
Expression.Filter filter = Expression.filter()
.equals(Schema.Cookies.Columns.CHAN_NAME, chanName)
.equals(Schema.Cookies.Columns.NAME, name)
.build();
database.beginTransaction();
try {
int clearFlags = (blocked != null ? Schema.Cookies.Flags.BLOCKED : 0) |
(deleteOnExit != null ? Schema.Cookies.Flags.DELETE_ON_EXIT : 0);
int setFlags = (blocked != null && blocked ? Schema.Cookies.Flags.BLOCKED : 0) |
(deleteOnExit != null && deleteOnExit ? Schema.Cookies.Flags.DELETE_ON_EXIT : 0);
database.execSQL("UPDATE " + Schema.Cookies.TABLE_NAME + " " +
"SET " + Schema.Cookies.Columns.FLAGS + " = " + Schema.Cookies.Columns.FLAGS + " " +
(blocked ? "| " : "& ~") + Schema.Cookies.Flags.BLOCKED + " " +
"SET " + Schema.Cookies.Columns.FLAGS + " = " +
Schema.Cookies.Columns.FLAGS + " & " + ~clearFlags + " | " + setFlags + " " +
"WHERE " + filter.value, filter.args);
if (!blocked) {
if (setFlags == 0) {
boolean delete;
String[] projection = {Schema.Cookies.Columns.FLAGS};
try (Cursor cursor = database.query(Schema.Cookies.TABLE_NAME, projection,
Expand All @@ -691,6 +704,25 @@ public void setCookieBlocked(@NonNull String chanName, @NonNull String name, boo
}
}

private void deleteCookiesOnExit() {
database.execSQL("UPDATE " + Schema.Cookies.TABLE_NAME + " " +
"SET " + Schema.Cookies.Columns.VALUE + " = '', " +
Schema.Cookies.Columns.FLAGS + " = " +
Schema.Cookies.Columns.FLAGS + " | " + Schema.Cookies.Flags.DELETED + " " +
"WHERE " + Schema.Cookies.Columns.FLAGS + " & " + Schema.Cookies.Flags.DELETE_ON_EXIT);
}

private final AtomicInteger requireCookiesReferenceCount = new AtomicInteger(0);

public Runnable requireCookies() {
requireCookiesReferenceCount.incrementAndGet();
return () -> {
if (requireCookiesReferenceCount.decrementAndGet() == 0) {
deleteCookiesOnExit();
}
};
}

public String getCookieChecked(@NonNull String chanName, @NonNull String name) {
Objects.requireNonNull(chanName);
Objects.requireNonNull(name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
Expand All @@ -17,6 +16,7 @@
import com.mishiranu.dashchan.content.CacheManager;
import com.mishiranu.dashchan.content.LocaleManager;
import com.mishiranu.dashchan.content.async.ReadFileTask;
import com.mishiranu.dashchan.content.database.ChanDatabase;
import com.mishiranu.dashchan.content.model.ErrorItem;
import com.mishiranu.dashchan.ui.MainActivity;
import com.mishiranu.dashchan.util.AndroidUtils;
Expand All @@ -27,7 +27,7 @@
import com.mishiranu.dashchan.widget.ThemeEngine;
import java.io.File;

public class AudioPlayerService extends Service implements MediaPlayer.OnCompletionListener,
public class AudioPlayerService extends BaseService implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener, ReadFileTask.FileCallback {
private static final String ACTION_START = "start";
private static final String ACTION_CANCEL = "cancel";
Expand Down Expand Up @@ -102,6 +102,7 @@ public void onCreate() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getPackageName() + ":AudioPlayerWakeLock");
wakeLock.setReferenceCounted(false);
addOnDestroyListener(ChanDatabase.getInstance().requireCookies());
}

private void notifyToggle() {
Expand Down
26 changes: 26 additions & 0 deletions src/com/mishiranu/dashchan/content/service/BaseService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.mishiranu.dashchan.content.service;

import android.app.Service;
import java.util.ArrayList;

public abstract class BaseService extends Service {
private ArrayList<Runnable> onDestroyListeners;

public void addOnDestroyListener(Runnable listener) {
if (onDestroyListeners == null) {
onDestroyListeners = new ArrayList<>();
}
onDestroyListeners.add(listener);
}

@Override
public void onDestroy() {
super.onDestroy();
if (onDestroyListeners != null) {
ArrayList<Runnable> onDestroyListeners = new ArrayList<>(this.onDestroyListeners);
for (Runnable listener : onDestroyListeners) {
listener.run();
}
}
}
}
38 changes: 30 additions & 8 deletions src/com/mishiranu/dashchan/content/service/DownloadService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
Expand All @@ -18,6 +17,7 @@
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.SystemClock;
import android.service.notification.StatusBarNotification;
import android.util.DisplayMetrics;
import android.util.Pair;
import androidx.core.app.NotificationCompat;
Expand All @@ -33,6 +33,7 @@
import com.mishiranu.dashchan.content.Preferences;
import com.mishiranu.dashchan.content.async.ExecutorTask;
import com.mishiranu.dashchan.content.async.ReadFileTask;
import com.mishiranu.dashchan.content.database.ChanDatabase;
import com.mishiranu.dashchan.content.model.ErrorItem;
import com.mishiranu.dashchan.content.model.FileHolder;
import com.mishiranu.dashchan.ui.MainActivity;
Expand Down Expand Up @@ -65,7 +66,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class DownloadService extends Service implements ReadFileTask.Callback {
public class DownloadService extends BaseService implements ReadFileTask.Callback {
private static final Executor SINGLE_THREAD_EXECUTOR = Executors.newSingleThreadExecutor();

private static final String ACTION_CANCEL = "cancel";
Expand Down Expand Up @@ -135,6 +136,7 @@ public void onCreate() {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getPackageName() + ":DownloadServiceWakeLock");
wakeLock.setReferenceCounted(false);
addOnDestroyListener(ChanDatabase.getInstance().requireCookies());
}

@Override
Expand Down Expand Up @@ -1023,12 +1025,32 @@ private void refreshNotificationFromThread(NotificationData notificationData) {
} else {
builder.setTicker(headsUp ? contentTitle : null);
}
builder.setOngoing(foreground);
builder.setAutoCancel(false);
if (foreground) {
startStopForeground(true, builder.build());
} else {
startStopForeground(false, null);
startStopForeground(foreground, foreground ? builder.build() : null);
if (!foreground) {
if (C.API_NOUGAT) {
// Await notification removed so it could be dismissed by user
for (int i = 0; i < 10; i++) {
StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
if (notifications == null) {
break;
}
boolean found = false;
for (StatusBarNotification notification : notifications) {
if (notification.getId() == C.NOTIFICATION_ID_DOWNLOADING) {
found = true;
break;
}
}
if (!found) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
return;
}
}
}
notificationManager.notify(C.NOTIFICATION_ID_DOWNLOADING, builder.build());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
Expand All @@ -26,6 +25,7 @@
import com.mishiranu.dashchan.content.LocaleManager;
import com.mishiranu.dashchan.content.Preferences;
import com.mishiranu.dashchan.content.async.SendPostTask;
import com.mishiranu.dashchan.content.database.ChanDatabase;
import com.mishiranu.dashchan.content.database.CommonDatabase;
import com.mishiranu.dashchan.content.model.ErrorItem;
import com.mishiranu.dashchan.content.model.PendingUserPost;
Expand All @@ -48,7 +48,7 @@
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

public class PostingService extends Service implements SendPostTask.Callback<PostingService.Key> {
public class PostingService extends BaseService implements SendPostTask.Callback<PostingService.Key> {
private static final String ACTION_CANCEL = "cancel";

private final HashMap<Key, ArrayList<Callback>> callbacks = new HashMap<>();
Expand Down Expand Up @@ -170,6 +170,7 @@ public void onCreate() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getPackageName() + ":PostingWakeLock");
wakeLock.setReferenceCounted(false);
addOnDestroyListener(ChanDatabase.getInstance().requireCookies());
notificationsWorker = new Thread(notificationsRunnable, "PostingServiceNotificationThread");
notificationsWorker.start();
}
Expand Down Expand Up @@ -219,7 +220,6 @@ public int onStartCommand(Intent intent, int flags, int startId) {
TaskState taskState = notificationData.taskState;
NotificationCompat.Builder builder = taskState.builder;
if (notificationData.type == NotificationData.Type.CREATE) {
builder.setOngoing(true);
builder.setSmallIcon(android.R.drawable.stat_sys_upload);
PendingIntent cancelIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, Receiver.class)
.setAction(ACTION_CANCEL), PendingIntent.FLAG_UPDATE_CURRENT);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.mishiranu.dashchan.content.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
Expand All @@ -18,6 +17,7 @@
import com.mishiranu.dashchan.content.WatcherNotifications;
import com.mishiranu.dashchan.content.async.ExecutorTask;
import com.mishiranu.dashchan.content.async.ReadPostsTask;
import com.mishiranu.dashchan.content.database.ChanDatabase;
import com.mishiranu.dashchan.content.database.PagesDatabase;
import com.mishiranu.dashchan.content.model.ErrorItem;
import com.mishiranu.dashchan.content.model.PendingUserPost;
Expand All @@ -34,7 +34,7 @@
import java.util.Set;
import java.util.concurrent.Executor;

public class WatcherService extends Service {
public class WatcherService extends BaseService {
public static class Counter {
public enum State {ENABLED, UNAVAILABLE, DISABLED}

Expand Down Expand Up @@ -693,6 +693,7 @@ public void onCreate() {

WatcherNotifications.configure(this);
updateNotificationColor();
addOnDestroyListener(ChanDatabase.getInstance().requireCookies());
Preferences.PREFERENCES.registerOnSharedPreferenceChangeListener(preferencesListener);
FavoritesStorage.getInstance().getObservable().register(favoritesObserver);
for (FavoritesStorage.FavoriteItem favoriteItem : FavoritesStorage.getInstance().getThreads(null)) {
Expand Down

0 comments on commit 94950c7

Please sign in to comment.