Skip to content

profile: Display user's local time #1318

New issue

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

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

Already on GitHub? Sign in to your account

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
9 changes: 8 additions & 1 deletion assets/l10n/app_ar.arb
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,12 @@
"wildcardMentionChannelDescription": "إخطار القناة",
"wildcardMentionStreamDescription": "إخطار الدفق",
"wildcardMentionAllDmDescription": "إخطار المستلمين",
"wildcardMentionTopicDescription": "إخطار الموضوع"
"wildcardMentionTopicDescription": "إخطار الموضوع",
"userLocalTime": "{userTime} الوقت المحلي",
"@userLocalTime": {
"description": "Current time in the user's timezone",
"placeholders": {
"userTime": {"type": "DateTime", "format": "jm"}
}
}
}
7 changes: 7 additions & 0 deletions assets/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -824,5 +824,12 @@
"zulipAppTitle": "Zulip",
"@zulipAppTitle": {
"description": "The name of Zulip. This should be either 'Zulip' or a transliteration."
},
"userLocalTime": "{userTime} local time",
"@userLocalTime": {
"description": "Current time in the user's timezone",
"placeholders": {
"userTime": {"type": "DateTime", "format": "jm"}
}
}
}
9 changes: 8 additions & 1 deletion assets/l10n/app_ja.arb
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,12 @@
"userRoleGuest": "ゲスト",
"@userRoleGuest": {},
"userRoleUnknown": "不明",
"@userRoleUnknown": {}
"@userRoleUnknown": {},
"userLocalTime": "現地時間 {userTime}",
"@userLocalTime": {
"description": "Current time in the user's timezone",
"placeholders": {
"userTime": {"type": "DateTime", "format": "jm"}
}
}
}
7 changes: 7 additions & 0 deletions assets/l10n/app_pl.arb
Original file line number Diff line number Diff line change
Expand Up @@ -900,5 +900,12 @@
"unpinnedSubscriptionsLabel": "Odpięte",
"@unpinnedSubscriptionsLabel": {
"description": "Label for the list of unpinned subscribed channels."
},
"userLocalTime": "{userTime} czas lokalny",
"@userLocalTime": {
"description": "Current time in the user's timezone",
"placeholders": {
"userTime": {"type": "DateTime", "format": "jm"}
}
}
}
7 changes: 7 additions & 0 deletions assets/l10n/app_ru.arb
Original file line number Diff line number Diff line change
Expand Up @@ -772,5 +772,12 @@
"errorMessageNotSent": "Сообщение не отправлено",
"@errorMessageNotSent": {
"description": "Error message for compose box when a message could not be sent."
},
"userLocalTime": "{userTime} местное время",
"@userLocalTime": {
"description": "Current time in the user's timezone",
"placeholders": {
"userTime": {"type": "DateTime", "format": "jm"}
}
}
}
Binary file added assets/timezone/latest_all.tzf
Binary file not shown.
6 changes: 6 additions & 0 deletions lib/generated/l10n/zulip_localizations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1208,6 +1208,12 @@ abstract class ZulipLocalizations {
/// In en, this message translates to:
/// **'Zulip'**
String get zulipAppTitle;

/// Current time in the user's timezone
///
/// In en, this message translates to:
/// **'{userTime} local time'**
String userLocalTime(DateTime userTime);
}

class _ZulipLocalizationsDelegate extends LocalizationsDelegate<ZulipLocalizations> {
Expand Down
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_ar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsAr extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '$userTimeString الوقت المحلي';
}
}
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_en.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsEn extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '$userTimeString local time';
}
}
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_ja.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsJa extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '現地時間 $userTimeString';
}
}
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_nb.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsNb extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '$userTimeString local time';
}
}
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_pl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsPl extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '$userTimeString czas lokalny';
}
}
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_ru.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsRu extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '$userTimeString местное время';
}
}
8 changes: 8 additions & 0 deletions lib/generated/l10n/zulip_localizations_sk.dart
Original file line number Diff line number Diff line change
Expand Up @@ -643,4 +643,12 @@ class ZulipLocalizationsSk extends ZulipLocalizations {

@override
String get zulipAppTitle => 'Zulip';

@override
String userLocalTime(DateTime userTime) {
final intl.DateFormat userTimeDateFormat = intl.DateFormat.jm(localeName);
final String userTimeString = userTimeDateFormat.format(userTime);

return '$userTimeString local time';
}
}
9 changes: 9 additions & 0 deletions lib/model/binding.dart
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ abstract class ZulipBinding {
/// Outside tests, this just calls the [Stopwatch] constructor.
Stopwatch stopwatch();

/// Provides access to current time.
///
/// Please refer to this issue:
/// https://github.com/dart-lang/sdk/issues/28985
DateTime now();

/// Provides device and operating system information,
/// via package:device_info_plus.
///
Expand Down Expand Up @@ -368,6 +374,9 @@ class LiveZulipBinding extends ZulipBinding {
@override
Stopwatch stopwatch() => Stopwatch();

@override
DateTime now() => DateTime.now();

@override
Future<BaseDeviceInfo?> get deviceInfo => _deviceInfo;
late Future<BaseDeviceInfo?> _deviceInfo;
Expand Down
9 changes: 5 additions & 4 deletions lib/model/store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import '../api/route/realm.dart';
import '../log.dart';
import '../notifications/receive.dart';
import 'autocomplete.dart';
import 'binding.dart';
import 'database.dart';
import 'emoji.dart';
import 'localizations.dart';
Expand Down Expand Up @@ -447,7 +448,7 @@ class PerAccountStore extends ChangeNotifier with EmojiStore, ChannelStore, Mess
///
/// To determine if a user is a full member, callers must also check that the
/// user's role is at least [UserRole.member].
bool hasPassedWaitingPeriod(User user, {required DateTime byDate}) {
bool hasPassedWaitingPeriod(User user) {
// [User.dateJoined] is in UTC. For logged-in users, the format is:
// YYYY-MM-DDTHH:mm+00:00, which includes the timezone offset for UTC.
// For logged-out spectators, the format is: YYYY-MM-DD, which doesn't
Expand All @@ -459,7 +460,8 @@ class PerAccountStore extends ChangeNotifier with EmojiStore, ChannelStore, Mess
// See the related discussion:
// https://chat.zulip.org/#narrow/channel/412-api-documentation/topic/provide.20an.20explicit.20format.20for.20.60realm_user.2Edate_joined.60/near/1980194
final dateJoined = DateTime.parse(user.dateJoined);
return byDate.difference(dateJoined).inDays >= realmWaitingPeriodThreshold;
final now = ZulipBinding.instance.now();
return now.difference(dateJoined).inDays >= realmWaitingPeriodThreshold;
}

////////////////////////////////
Expand All @@ -483,7 +485,6 @@ class PerAccountStore extends ChangeNotifier with EmojiStore, ChannelStore, Mess
bool hasPostingPermission({
required ZulipStream inChannel,
required User user,
required DateTime byDate,
}) {
final role = user.role;
// We let the users with [unknown] role to send the message, then the server
Expand All @@ -495,7 +496,7 @@ class PerAccountStore extends ChangeNotifier with EmojiStore, ChannelStore, Mess
case ChannelPostPolicy.fullMembers: {
if (!role.isAtLeast(UserRole.member)) return false;
return role == UserRole.member
? hasPassedWaitingPeriod(user, byDate: byDate)
? hasPassedWaitingPeriod(user)
: true;
}
case ChannelPostPolicy.moderators: return role.isAtLeast(UserRole.moderator);
Expand Down
3 changes: 1 addition & 2 deletions lib/widgets/compose_box.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1410,8 +1410,7 @@ class _ComposeBoxState extends State<ComposeBox> with PerAccountStoreAwareStateM
case ChannelNarrow(:final streamId):
case TopicNarrow(:final streamId):
final channel = store.streams[streamId];
if (channel == null || !store.hasPostingPermission(inChannel: channel,
user: selfUser, byDate: DateTime.now())) {
if (channel == null || !store.hasPostingPermission(inChannel: channel, user: selfUser)) {
return _ErrorBanner(label:
ZulipLocalizations.of(context).errorBannerCannotPostInChannelLabel);
}
Expand Down
15 changes: 8 additions & 7 deletions lib/widgets/message_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:intl/intl.dart' hide TextDirection;

import '../api/model/model.dart';
import '../generated/l10n/zulip_localizations.dart';
import '../model/binding.dart';
import '../model/message_list.dart';
import '../model/narrow.dart';
import '../model/store.dart';
Expand Down Expand Up @@ -1271,19 +1272,19 @@ class DateText extends StatelessWidget {
),
formatHeaderDate(
zulipLocalizations,
DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
now: DateTime.now()));
DateTime.fromMillisecondsSinceEpoch(timestamp * 1000)));
}
}

@visibleForTesting
String formatHeaderDate(
ZulipLocalizations zulipLocalizations,
DateTime dateTime, {
required DateTime now,
}) {
assert(!dateTime.isUtc && !now.isUtc,
'`dateTime` and `now` need to be in local time.');
DateTime dateTime,
) {
assert(!dateTime.isUtc,
'`dateTime` need to be in local time.');

final now = ZulipBinding.instance.now();

if (dateTime.year == now.year &&
dateTime.month == now.month &&
Expand Down
73 changes: 72 additions & 1 deletion lib/widgets/profile.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:timezone/timezone.dart' as tz;

import '../api/model/initial_snapshot.dart';
import '../api/model/model.dart';
import '../generated/l10n/zulip_localizations.dart';
import '../model/binding.dart';
import '../model/content.dart';
import '../model/narrow.dart';
import '../model/store.dart';
Expand Down Expand Up @@ -90,7 +94,11 @@ class ProfilePage extends StatelessWidget {
style: _TextStyles.primaryFieldText),
// TODO(#197) render user status
// TODO(#196) render active status
// TODO(#292) render user local time
DefaultTextStyle.merge(
textAlign: TextAlign.center,
style: _TextStyles.primaryFieldText,
child: UserLocalTimeText(user: user)
),

_ProfileDataTable(profileData: user.profileData),
const SizedBox(height: 16),
Expand Down Expand Up @@ -307,3 +315,66 @@ class _UserWidget extends StatelessWidget {
])));
}
}

/// The text of current time in [user]'s timezone.
class UserLocalTimeText extends StatefulWidget {
const UserLocalTimeText({
super.key,
required this.user,
});

final User user;

/// Initialize the timezone database used to know time difference from a timezone string.
///
/// Usually, database initialization is done using `initializeTimeZones`, but it takes >100ms and not asynchronous.
/// So, we initialize database from the assets file copied from timezone library.
/// This file is checked up-to-date in `test/widgets/profile_test.dart`.
static Future<void> initializeTimezonesUsingAssets() async {
final blob = Uint8List.sublistView(await rootBundle.load('assets/timezone/latest_all.tzf'));
tz.initializeDatabase(blob);
}

@override
State<UserLocalTimeText> createState() => _UserLocalTimeTextState();
}

class _UserLocalTimeTextState extends State<UserLocalTimeText> {
late final Timer _timer;
final StreamController<DateTime> _streamController = StreamController();
Stream<DateTime> get _stream => _streamController.stream;

@override
void initState() {
_streamController.add(ZulipBinding.instance.now());
_timer = Timer.periodic(const Duration(seconds: 1), (_) { _streamController.add(ZulipBinding.instance.now()); });
super.initState();
}

@override
void dispose() {
_timer.cancel();
super.dispose();
}

Stream<String> _getDisplayLocalTimeFor(User user, ZulipLocalizations zulipLocalizations) async* {
if (!tz.timeZoneDatabase.isInitialized) await UserLocalTimeText.initializeTimezonesUsingAssets();

await for (final DateTime time in _stream) {
final location = tz.getLocation(user.timezone);
final localTime = tz.TZDateTime.from(time, location);
yield zulipLocalizations.userLocalTime(localTime);
}
}

@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _getDisplayLocalTimeFor(widget.user, ZulipLocalizations.of(context)),
builder: (context, snapshot) {
if (snapshot.hasError) Error.throwWithStackTrace(snapshot.error!, snapshot.stackTrace!);
return Text(snapshot.data ?? '');
}
);
}
}
8 changes: 8 additions & 0 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.6.8"
timezone:
dependency: "direct main"
description:
name: timezone
sha256: ffc9d5f4d1193534ef051f9254063fa53d588609418c84299956c3db9383587d
url: "https://pub.dev"
source: hosted
version: "0.10.0"
timing:
dependency: transitive
description:
Expand Down
Loading