1
0
mirror of https://github.com/KokaKiwi/BarInsta synced 2024-11-22 14:47:29 +00:00

Replace some usages of Date with LocalDateTime. austinhuang0131/barinsta#1309

This commit is contained in:
Ammar Githam 2021-05-23 21:58:19 +09:00
parent c784ca937d
commit b273bff738
11 changed files with 51 additions and 68 deletions

View File

@ -1,6 +1,5 @@
package awais.instagrabber.adapters; package awais.instagrabber.adapters;
import android.text.format.DateFormat;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -13,8 +12,10 @@ import androidx.recyclerview.widget.AsyncListDiffer;
import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.function.Function; import java.util.function.Function;
@ -57,7 +58,6 @@ import awais.instagrabber.repositories.responses.User;
import awais.instagrabber.repositories.responses.directmessages.DirectItem; import awais.instagrabber.repositories.responses.directmessages.DirectItem;
import awais.instagrabber.repositories.responses.directmessages.DirectItemStoryShare; import awais.instagrabber.repositories.responses.directmessages.DirectItemStoryShare;
import awais.instagrabber.repositories.responses.directmessages.DirectThread; import awais.instagrabber.repositories.responses.directmessages.DirectThread;
import awais.instagrabber.utils.DateUtils;
public final class DirectItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public final class DirectItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = DirectItemsAdapter.class.getSimpleName(); private static final String TAG = DirectItemsAdapter.class.getSimpleName();
@ -292,12 +292,15 @@ public final class DirectItemsAdapter extends RecyclerView.Adapter<RecyclerView.
private List<DirectItemOrHeader> sectionAndSort(final List<DirectItem> list) { private List<DirectItemOrHeader> sectionAndSort(final List<DirectItem> list) {
final List<DirectItemOrHeader> itemOrHeaders = new ArrayList<>(); final List<DirectItemOrHeader> itemOrHeaders = new ArrayList<>();
Date prevSectionDate = null; LocalDate prevSectionDate = null;
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
final DirectItem item = list.get(i); final DirectItem item = list.get(i);
if (item == null) continue; if (item == null || item.getDate() == null) continue;
final DirectItemOrHeader prev = itemOrHeaders.isEmpty() ? null : itemOrHeaders.get(itemOrHeaders.size() - 1); final DirectItemOrHeader prev = itemOrHeaders.isEmpty() ? null : itemOrHeaders.get(itemOrHeaders.size() - 1);
if (prev != null && prev.item != null && DateUtils.isSameDay(prev.item.getDate(), item.getDate())) { if (prev != null
&& prev.item != null
&& prev.item.getDate() != null
&& prev.item.getDate().toLocalDate().isEqual(item.getDate().toLocalDate())) {
// just add item // just add item
final DirectItemOrHeader itemOrHeader = new DirectItemOrHeader(); final DirectItemOrHeader itemOrHeader = new DirectItemOrHeader();
itemOrHeader.item = item; itemOrHeader.item = item;
@ -320,7 +323,7 @@ public final class DirectItemsAdapter extends RecyclerView.Adapter<RecyclerView.
final DirectItemOrHeader itemOrHeader = new DirectItemOrHeader(); final DirectItemOrHeader itemOrHeader = new DirectItemOrHeader();
itemOrHeader.item = item; itemOrHeader.item = item;
itemOrHeaders.add(itemOrHeader); itemOrHeaders.add(itemOrHeader);
prevSectionDate = DateUtils.dateAtZeroHours(item.getDate()); prevSectionDate = item.getDate().toLocalDate();
} }
return itemOrHeaders; return itemOrHeaders;
} }
@ -352,7 +355,7 @@ public final class DirectItemsAdapter extends RecyclerView.Adapter<RecyclerView.
} }
public static class DirectItemOrHeader { public static class DirectItemOrHeader {
Date date; LocalDate date;
public DirectItem item; public DirectItem item;
public boolean isHeader() { public boolean isHeader() {
@ -377,12 +380,13 @@ public final class DirectItemsAdapter extends RecyclerView.Adapter<RecyclerView.
this.binding = binding; this.binding = binding;
} }
public void bind(final Date date) { public void bind(final LocalDate date) {
if (date == null) { if (date == null) {
binding.header.setText(""); binding.header.setText("");
return; return;
} }
binding.header.setText(DateFormat.getDateFormat(itemView.getContext()).format(date)); final DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
binding.header.setText(dateFormatter.format(date));
} }
} }

View File

@ -5,7 +5,6 @@ import android.content.res.ColorStateList;
import android.content.res.Resources; import android.content.res.Resources;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.text.format.DateFormat;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewConfiguration; import android.view.ViewConfiguration;
@ -25,6 +24,8 @@ import androidx.transition.TransitionManager;
import com.google.android.material.transition.MaterialFade; import com.google.android.material.transition.MaterialFade;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -194,7 +195,8 @@ public abstract class DirectItemViewHolder extends RecyclerView.ViewHolder imple
binding.messageInfo.setVisibility(View.VISIBLE); binding.messageInfo.setVisibility(View.VISIBLE);
binding.deliveryStatus.setVisibility(messageDirection == MessageDirection.OUTGOING ? View.VISIBLE : View.GONE); binding.deliveryStatus.setVisibility(messageDirection == MessageDirection.OUTGOING ? View.VISIBLE : View.GONE);
if (item.getDate() != null) { if (item.getDate() != null) {
binding.messageTime.setText(DateFormat.getTimeFormat(itemView.getContext()).format(item.getDate())); final DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
binding.messageTime.setText(dateFormatter.format(item.getDate()));
} }
if (messageDirection == MessageDirection.OUTGOING) { if (messageDirection == MessageDirection.OUTGOING) {
if (item.isPending()) { if (item.isPending()) {

View File

@ -15,8 +15,10 @@ import androidx.room.TypeConverters;
import androidx.room.migration.Migration; import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase; import androidx.sqlite.db.SupportSQLiteDatabase;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import awais.instagrabber.db.dao.AccountDao; import awais.instagrabber.db.dao.AccountDao;
@ -195,14 +197,18 @@ public abstract class AppDatabase extends RoomDatabase {
if (favoriteTypeQueryPair == null) continue; if (favoriteTypeQueryPair == null) continue;
final FavoriteType type = favoriteTypeQueryPair.first; final FavoriteType type = favoriteTypeQueryPair.first;
final String query = favoriteTypeQueryPair.second; final String query = favoriteTypeQueryPair.second;
final long epochMillis = cursor.getLong(cursor.getColumnIndex("date_added"));
final LocalDateTime localDateTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(epochMillis),
ZoneId.systemDefault()
);
oldModels.add(new Favorite( oldModels.add(new Favorite(
0, 0,
query, query,
type, type,
queryDisplayExists ? cursor.getString(cursor.getColumnIndex("query_display")) queryDisplayExists ? cursor.getString(cursor.getColumnIndex("query_display")) : null,
: null,
null, null,
new Date(cursor.getLong(cursor.getColumnIndex("date_added"))) localDateTime
)); ));
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "onUpgrade", e); Log.e(TAG, "onUpgrade", e);
@ -222,7 +228,7 @@ public abstract class AppDatabase extends RoomDatabase {
values.put(Favorite.COL_TYPE, model.getType().toString()); values.put(Favorite.COL_TYPE, model.getType().toString());
values.put(Favorite.COL_DISPLAY_NAME, model.getDisplayName()); values.put(Favorite.COL_DISPLAY_NAME, model.getDisplayName());
values.put(Favorite.COL_PIC_URL, model.getPicUrl()); values.put(Favorite.COL_PIC_URL, model.getPicUrl());
values.put(Favorite.COL_DATE_ADDED, model.getDateAdded().getTime()); values.put(Favorite.COL_DATE_ADDED, model.getDateAdded().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
int rows; int rows;
if (model.getId() >= 1) { if (model.getId() >= 1) {
rows = db.update(Favorite.TABLE_NAME, rows = db.update(Favorite.TABLE_NAME,

View File

@ -6,7 +6,7 @@ import androidx.room.ColumnInfo;
import androidx.room.Entity; import androidx.room.Entity;
import androidx.room.PrimaryKey; import androidx.room.PrimaryKey;
import java.util.Date; import java.time.LocalDateTime;
import awais.instagrabber.models.enums.FavoriteType; import awais.instagrabber.models.enums.FavoriteType;
@ -37,14 +37,14 @@ public class Favorite {
private final String picUrl; private final String picUrl;
@ColumnInfo(name = COL_DATE_ADDED) @ColumnInfo(name = COL_DATE_ADDED)
private final Date dateAdded; private final LocalDateTime dateAdded;
public Favorite(final int id, public Favorite(final int id,
final String query, final String query,
final FavoriteType type, final FavoriteType type,
final String displayName, final String displayName,
final String picUrl, final String picUrl,
final Date dateAdded) { final LocalDateTime dateAdded) {
this.id = id; this.id = id;
this.query = query; this.query = query;
this.type = type; this.type = type;
@ -73,7 +73,7 @@ public class Favorite {
return picUrl; return picUrl;
} }
public Date getDateAdded() { public LocalDateTime getDateAdded() {
return dateAdded; return dateAdded;
} }

View File

@ -38,7 +38,7 @@ import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.util.Date; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -531,7 +531,7 @@ public class HashTagFragment extends Fragment implements SwipeRefreshLayout.OnRe
FavoriteType.HASHTAG, FavoriteType.HASHTAG,
hashtagModel.getName(), hashtagModel.getName(),
"res:/" + R.drawable.ic_hashtag, "res:/" + R.drawable.ic_hashtag,
new Date() LocalDateTime.now()
), new RepositoryCallback<Void>() { ), new RepositoryCallback<Void>() {
@Override @Override
public void onSuccess(final Void result) { public void onSuccess(final Void result) {

View File

@ -36,7 +36,7 @@ import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.util.Date; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -539,7 +539,7 @@ public class LocationFragment extends Fragment implements SwipeRefreshLayout.OnR
FavoriteType.LOCATION, FavoriteType.LOCATION,
locationModel.getName(), locationModel.getName(),
"res:/" + R.drawable.ic_location, "res:/" + R.drawable.ic_location,
new Date() LocalDateTime.now()
), new RepositoryCallback<Void>() { ), new RepositoryCallback<Void>() {
@Override @Override
public void onSuccess(final Void result) { public void onSuccess(final Void result) {

View File

@ -45,8 +45,8 @@ import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.time.LocalDateTime;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
@ -722,7 +722,7 @@ public class ProfileFragment extends Fragment implements SwipeRefreshLayout.OnRe
FavoriteType.USER, FavoriteType.USER,
profileModel.getFullName(), profileModel.getFullName(),
profileModel.getProfilePicUrl(), profileModel.getProfilePicUrl(),
new Date() LocalDateTime.now()
), new RepositoryCallback<Void>() { ), new RepositoryCallback<Void>() {
@Override @Override
public void onSuccess(final Void result) { public void onSuccess(final Void result) {

View File

@ -8,7 +8,6 @@ import java.io.Serializable
import java.time.Instant import java.time.Instant
import java.time.LocalDateTime import java.time.LocalDateTime
import java.time.ZoneId import java.time.ZoneId
import java.util.*
data class DirectItem( data class DirectItem(
var itemId: String? = null, var itemId: String? = null,
@ -40,9 +39,8 @@ data class DirectItem(
val hideInThread: Int? = 0, val hideInThread: Int? = 0,
val showForwardAttribution: Boolean = false val showForwardAttribution: Boolean = false
) : Cloneable, Serializable { ) : Cloneable, Serializable {
private var date: Date? = null
var isPending = false var isPending = false
var localDateTime: LocalDateTime? = null var date: LocalDateTime? = null
get() { get() {
if (field == null) { if (field == null) {
field = Instant.ofEpochMilli(timestamp / 1000).atZone(ZoneId.systemDefault()).toLocalDateTime() field = Instant.ofEpochMilli(timestamp / 1000).atZone(ZoneId.systemDefault()).toLocalDateTime()
@ -60,13 +58,6 @@ data class DirectItem(
date = null date = null
} }
fun getDate(): Date? {
if (date == null) {
date = Date(timestamp / 1000)
}
return date
}
@Throws(CloneNotSupportedException::class) @Throws(CloneNotSupportedException::class)
public override fun clone(): Any { public override fun clone(): Any {
return super.clone() return super.clone()

View File

@ -112,7 +112,7 @@ public class DMSyncService extends LifecycleService {
final DirectItem latestItem = unreadItems.get(unreadItems.size() - 1); final DirectItem latestItem = unreadItems.get(unreadItems.size() - 1);
lastNotifiedListBuilder.add(new DMLastNotified(0, lastNotifiedListBuilder.add(new DMLastNotified(0,
unreadMessagesEntry.getKey(), unreadMessagesEntry.getKey(),
latestItem.getLocalDateTime(), latestItem.getDate(),
now)); now));
} }
dmLastNotifiedRepository.insertOrUpdateDMLastNotified( dmLastNotifiedRepository.insertOrUpdateDMLastNotified(
@ -145,8 +145,8 @@ public class DMSyncService extends LifecycleService {
if (item.getUserId() == viewerId) break; // Reached a message from the viewer, it is assumed the viewer has read the next messages if (item.getUserId() == viewerId) break; // Reached a message from the viewer, it is assumed the viewer has read the next messages
final boolean read = DMUtils.isRead(item, lastSeenAt, Collections.singletonList(viewerId)); final boolean read = DMUtils.isRead(item, lastSeenAt, Collections.singletonList(viewerId));
if (read) break; if (read) break;
if (dmLastNotified != null && dmLastNotified.getLastNotifiedMsgTs() != null) { if (dmLastNotified != null && dmLastNotified.getLastNotifiedMsgTs() != null && item.getDate() != null) {
if (count == 0 && DateUtils.isBeforeOrEqual(item.getLocalDateTime(), dmLastNotified.getLastNotifiedMsgTs())) { if (count == 0 && DateUtils.isBeforeOrEqual(item.getDate(), dmLastNotified.getLastNotifiedMsgTs())) {
// The first unread item has been notified and hence all subsequent items can be ignored // The first unread item has been notified and hence all subsequent items can be ignored
// since the items are in desc timestamp order // since the items are in desc timestamp order
break; break;

View File

@ -4,39 +4,15 @@ import androidx.annotation.NonNull;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.Locale; import java.util.Locale;
public final class DateUtils { public final class DateUtils {
public static boolean isSameDay(final Date date1, final Date date2) {
if (date1 == null || date2 == null) {
return false;
}
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
&& calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)
&& calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}
public static Date dateAtZeroHours(@NonNull final Date date) {
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static int getTimezoneOffset() { public static int getTimezoneOffset() {
final Calendar calendar = Calendar.getInstance(Locale.getDefault()); final Calendar calendar = Calendar.getInstance(Locale.getDefault());
return -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000); return -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000);
} }
public static boolean isBeforeOrEqual(final LocalDateTime localDateTime, final LocalDateTime comparedTo) { public static boolean isBeforeOrEqual(@NonNull final LocalDateTime localDateTime, @NonNull final LocalDateTime comparedTo) {
return localDateTime.isBefore(comparedTo) || localDateTime.isEqual(comparedTo); return localDateTime.isBefore(comparedTo) || localDateTime.isEqual(comparedTo);
} }
} }

View File

@ -23,8 +23,10 @@ import org.json.JSONObject;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -147,13 +149,15 @@ public final class ExportImportUtils {
if (query == null || favoriteType == null) { if (query == null || favoriteType == null) {
continue; continue;
} }
final long epochMillis = favsObject.getLong("d");
final Favorite favorite = new Favorite( final Favorite favorite = new Favorite(
0, 0,
query, query,
favoriteType, favoriteType,
favsObject.optString("s"), favsObject.optString("s"),
favoriteType == FavoriteType.USER ? favsObject.optString("pic_url") : null, favoriteType == FavoriteType.USER ? favsObject.optString("pic_url") : null,
new Date(favsObject.getLong("d"))); LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), ZoneId.systemDefault())
);
// Log.d(TAG, "importJson: favoriteModel: " + favoriteModel); // Log.d(TAG, "importJson: favoriteModel: " + favoriteModel);
final FavoriteRepository favRepo = FavoriteRepository.getInstance(FavoriteDataSource.getInstance(context)); final FavoriteRepository favRepo = FavoriteRepository.getInstance(FavoriteDataSource.getInstance(context));
favRepo.getFavorite(query, favoriteType, new RepositoryCallback<Favorite>() { favRepo.getFavorite(query, favoriteType, new RepositoryCallback<Favorite>() {
@ -370,7 +374,7 @@ public final class ExportImportUtils {
jsonObject.put("type", favorite.getType().toString()); jsonObject.put("type", favorite.getType().toString());
jsonObject.put("s", favorite.getDisplayName()); jsonObject.put("s", favorite.getDisplayName());
jsonObject.put("pic_url", favorite.getPicUrl()); jsonObject.put("pic_url", favorite.getPicUrl());
jsonObject.put("d", favorite.getDateAdded().getTime()); jsonObject.put("d", favorite.getDateAdded().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
jsonArray.put(jsonObject); jsonArray.put(jsonObject);
} }
} catch (Exception e) { } catch (Exception e) {