Skip to content

Prepare API models to support polls (read-only) #823

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

Merged
merged 6 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions lib/api/model/model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,6 @@ sealed class Message {
final String senderRealmStr;
@JsonKey(name: 'subject')
String topic;
// final List<string> submessages; // TODO handle
final int timestamp;
String get type;

Expand All @@ -493,23 +492,23 @@ sealed class Message {
@JsonKey(name: 'match_subject')
final String? matchTopic;

static MessageEditState _messageEditStateFromJson(dynamic json) {
static MessageEditState _messageEditStateFromJson(Object? json) {
// This is a no-op so that [MessageEditState._readFromMessage]
// can return the enum value directly.
return json as MessageEditState;
}

static Reactions? _reactionsFromJson(dynamic json) {
final list = (json as List<dynamic>);
static Reactions? _reactionsFromJson(Object? json) {
final list = (json as List<Object?>);
return list.isNotEmpty ? Reactions.fromJson(list) : null;
}

static Object _reactionsToJson(Reactions? value) {
return value ?? [];
}

static List<MessageFlag> _flagsFromJson(dynamic json) {
final list = json as List<dynamic>;
static List<MessageFlag> _flagsFromJson(Object? json) {
final list = json as List<Object?>;
return list.map((raw) => MessageFlag.fromRawString(raw as String)).toList();
}

Expand Down
315 changes: 315 additions & 0 deletions lib/api/model/submessage.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
import 'package:json_annotation/json_annotation.dart';

part 'submessage.g.dart';

/// Data used for Zulip "widgets" within messages, like polls and todo lists.
///
/// For docs, see:
/// https://zulip.com/api/get-messages#response (search for "submessage")
/// https://zulip.readthedocs.io/en/latest/subsystems/widgets.html
///
/// This is an underdocumented part of the Zulip Server API.
/// So in addition to docs, see other clients:
/// https://github.com/zulip/zulip-mobile/blob/2217c858e/src/api/modelTypes.js#L800-L861
/// https://github.com/zulip/zulip-mobile/blob/2217c858e/src/webview/html/message.js#L118-L192
/// https://github.com/zulip/zulip/blob/40f59a05c/web/src/submessage.ts
/// https://github.com/zulip/zulip/blob/40f59a05c/web/shared/src/poll_data.ts
@JsonSerializable(fieldRename: FieldRename.snake)
class Submessage {
const Submessage({
required this.senderId,
required this.msgType,
required this.content,
});

// TODO(server): should we be sorting a message's submessages by ID? Web seems to:
// https://github.com/zulip/zulip/blob/40f59a05c55e0e4f26ca87d2bca646770e94bff0/web/src/submessage.ts#L88
// final int id; // ignored because we don't use it

/// The sender of this submessage (not necessarily of the [Message] it's on).
final int senderId;

// final int messageId; // ignored; redundant with [Message.id]

@JsonKey(unknownEnumValue: SubmessageType.unknown)
final SubmessageType msgType;

/// A JSON encoding of a [SubmessageData].
// We cannot parse the String into one of the [SubmessageData] classes because
// information from other submessages are required. Specifically, we need:
// * the index of this submessage in [Message.submessages];
// * the [WidgetType] of the first [Message.submessages].
final String content;

factory Submessage.fromJson(Map<String, Object?> json) =>
_$SubmessageFromJson(json);

Map<String, Object?> toJson() => _$SubmessageToJson(this);
}

/// As in [Submessage.msgType].
///
/// The only type of submessage that actually exists in Zulip (as of 2024,
/// and since this "submessages" subsystem was created in 2017–2018)
/// is [SubmessageType.widget].
enum SubmessageType {
widget,
unknown,
}

/// The data encoded in a submessage at [Submessage.content].
///
/// For widgets (the only existing use of submessages), the submessages
/// on a [Message] consist of:
/// * One submessage with content [WidgetData]; then
/// * Zero or more submessages with content [PollEventSubmessage] if the
/// message is a poll (i.e. if the first submessage was a [PollWidgetData]),
/// and similarly for other types of widgets.
sealed class SubmessageData {}

/// The data encoded in a submessage to make the message a Zulip widget.
///
/// Expected from the first [Submessage.content] in the "submessages" field on
/// the message when there is an widget.
///
/// See https://zulip.readthedocs.io/en/latest/subsystems/widgets.html
sealed class WidgetData extends SubmessageData {
WidgetType get widgetType;

WidgetData();

factory WidgetData.fromJson(Object? json) {
final map = json as Map<String, Object?>;
final rawWidgetType = map['widget_type'] as String;
return switch (WidgetType.fromRawString(rawWidgetType)) {
WidgetType.poll => PollWidgetData.fromJson(map),
WidgetType.unknown => UnsupportedWidgetData.fromJson(map),
};
}

Object? toJson();
}

/// As in [WidgetData.widgetType].
@JsonEnum(alwaysCreate: true)
enum WidgetType {
poll,
// todo, // TODO(#882)
// zform, // This exists in web but is more a demo than a real feature.
unknown;

static WidgetType fromRawString(String raw) => _byRawString[raw] ?? unknown;

static final _byRawString = _$WidgetTypeEnumMap
.map((key, value) => MapEntry(value, key));
}

/// The data in the first submessage on a poll widget message.
///
/// Subsequent submessages on the same message will be [PollEventSubmessage].
@JsonSerializable(fieldRename: FieldRename.snake)
class PollWidgetData extends WidgetData {
@override
@JsonKey(includeToJson: true)
WidgetType get widgetType => WidgetType.poll;

/// The initial question and options on the poll.
final PollWidgetExtraData extraData;
Comment on lines +116 to +117
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

zulip-mobile expects that this might be missing in some cases, with this explanation:

  if (pollWidgetContent.extra_data == null) {
    // We don't expect this to happen in general, but there are some malformed
    // messages lying around that will trigger this [1]. The code here is slightly
    // different the webapp code, but mostly because the current webapp
    // behaviour seems accidental: an error is printed to the console, and the
    // code that is written to handle the situation is never reached.  Instead
    // of doing that, we've opted to catch this case here, and print out the
    // message (which matches the behaviour of the webapp, minus the console
    // error, although it gets to that behaviour in a different way). The bug
    // tracking fixing this on the webapp side is zulip/zulip#19145.
    // [1]: https://chat.zulip.org/#narrow/streams/public/near/582872
    return template`$!${message.content}`;
  }

So it seems like we should make this optional, with an explanation like the one in zulip-mobile.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this does not happen to the linked message anymore. {widget_type: poll, extra_data: {question: , options: []}} is what I got. Maybe it got fixed at some point?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, interesting. @gnprice, thoughts?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

@PIG208 PIG208 Jul 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this fix addresses the missing "extra_data" case, and ensures that "options" is always there ("question" predated "options" and was mandatory).

For the Flutter implementation, it might be cleaner to define the "correct" data model, and reject malformed polls near the edge without throwing a runtime error. Because there will be less branching to handle unexpected behavior. The only concern is whether we can and want to attempt recovering from the known cases of failure.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! Thanks for finding that discussion—I agree it seems like the malformed data on CZO has been cleaned up. And from that discussion, it also seems like we don't expect this kind of malformed data to be present on other servers either. It came from some experiments on CZO before the API was settled.

So I'm content to not handle a missing extra_data case.


PollWidgetData({required this.extraData});

factory PollWidgetData.fromJson(Map<String, Object?> json) =>
_$PollWidgetDataFromJson(json);

@override
Map<String, Object?> toJson() => _$PollWidgetDataToJson(this);
}

/// As in [PollWidgetData.extraData].
@JsonSerializable(fieldRename: FieldRename.snake)
class PollWidgetExtraData {
// The [question] and [options] fields seem to be always present.
// But both web and zulip-mobile accept them as optional, with default values:
// https://github.com/zulip/zulip-flutter/pull/823#discussion_r1697656896
// https://github.com/zulip/zulip/blob/40f59a05c55e0e4f26ca87d2bca646770e94bff0/web/src/poll_widget.ts#L29
// And the server doesn't really enforce any structure on submessage data.
// So match the web and zulip-mobile behavior.
@JsonKey(defaultValue: "")
final String question;
@JsonKey(defaultValue: [])
final List<String> options;

const PollWidgetExtraData({required this.question, required this.options});

factory PollWidgetExtraData.fromJson(Map<String, Object?> json) =>
_$PollWidgetExtraDataFromJson(json);

Map<String, Object?> toJson() => _$PollWidgetExtraDataToJson(this);
}

class UnsupportedWidgetData extends WidgetData {
@override
@JsonKey(includeToJson: true)
WidgetType get widgetType => WidgetType.unknown;

final Object? json;

UnsupportedWidgetData.fromJson(this.json);

@override
Object? toJson() => json;
}

/// The data in a submessage that acts on a poll.
///
/// The first submessage on the message should be a [PollWidgetData].
sealed class PollEventSubmessage extends SubmessageData {
PollEventSubmessageType get type;

PollEventSubmessage();

/// The key for identifying the [idx]'th option added by user
/// [senderId] to a poll.
///
/// For options that are a part of the initial [PollWidgetData], the
/// [senderId] should be `null`.
static String optionKey({required int? senderId, required int idx}) =>
// "canned" is a canonical constant coined by the web client:
// https://github.com/zulip/zulip/blob/40f59a05c/web/shared/src/poll_data.ts#L238
'${senderId ?? 'canned'},$idx';

factory PollEventSubmessage.fromJson(Map<String, Object?> json) {
final rawPollEventType = json['type'] as String;
switch (PollEventSubmessageType.fromRawString(rawPollEventType)) {
case PollEventSubmessageType.newOption: return PollNewOptionEventSubmessage.fromJson(json);
case PollEventSubmessageType.question: return PollQuestionEventSubmessage.fromJson(json);
case PollEventSubmessageType.vote: return PollVoteEventSubmessage.fromJson(json);
case PollEventSubmessageType.unknown: return UnknownPollEventSubmessage.fromJson(json);
}
}

Map<String, Object?> toJson();
}

/// As in [PollEventSubmessage.type].
@JsonEnum(fieldRename: FieldRename.snake)
enum PollEventSubmessageType {
newOption,
question,
vote,
unknown;

static PollEventSubmessageType fromRawString(String raw) => _byRawString[raw]!;

static final _byRawString = _$PollEventSubmessageTypeEnumMap
.map((key, value) => MapEntry(value, key));
}

/// A poll event when an option is added.
///
/// See: https://github.com/zulip/zulip/blob/40f59a05c/web/shared/src/poll_data.ts#L112-L159
@JsonSerializable(fieldRename: FieldRename.snake)
class PollNewOptionEventSubmessage extends PollEventSubmessage {
@override
@JsonKey(includeToJson: true)
PollEventSubmessageType get type => PollEventSubmessageType.newOption;

final String option;
/// A sequence number for this option, among options added to this poll
/// by this [Submessage.senderId].
///
/// See [PollEventSubmessage.optionKey].
final int idx;

PollNewOptionEventSubmessage({required this.option, required this.idx});

@override
factory PollNewOptionEventSubmessage.fromJson(Map<String, Object?> json) =>
_$PollNewOptionEventSubmessageFromJson(json);

@override
Map<String, Object?> toJson() => _$PollNewOptionEventSubmessageToJson(this);
}

/// A poll event when the question has been edited.
///
/// See: https://github.com/zulip/zulip/blob/40f59a05c/web/shared/src/poll_data.ts#L161-186
@JsonSerializable(fieldRename: FieldRename.snake)
class PollQuestionEventSubmessage extends PollEventSubmessage {
@override
@JsonKey(includeToJson: true)
PollEventSubmessageType get type => PollEventSubmessageType.question;

final String question;

PollQuestionEventSubmessage({required this.question});

@override
factory PollQuestionEventSubmessage.fromJson(Map<String, Object?> json) =>
_$PollQuestionEventSubmessageFromJson(json);

@override
Map<String, Object?> toJson() => _$PollQuestionEventSubmessageToJson(this);
}

/// A poll event when a vote has been cast or removed.
///
/// See: https://github.com/zulip/zulip/blob/40f59a05c/web/shared/src/poll_data.ts#L188-234
@JsonSerializable(fieldRename: FieldRename.snake)
class PollVoteEventSubmessage extends PollEventSubmessage {
@override
@JsonKey(includeToJson: true)
PollEventSubmessageType get type => PollEventSubmessageType.vote;

/// The key of the affected option.
///
/// See [PollEventSubmessage.optionKey].
final String key;
@JsonKey(name: 'vote', unknownEnumValue: PollVoteOp.unknown)
final PollVoteOp op;

PollVoteEventSubmessage({required this.key, required this.op});

@override
factory PollVoteEventSubmessage.fromJson(Map<String, Object?> json) {
final result = _$PollVoteEventSubmessageFromJson(json);
// Crunchy-shell validation
final segments = result.key.split(',');
final [senderId, idx] = segments;
if (senderId != 'canned') {
int.parse(senderId, radix: 10);
}
int.parse(idx, radix: 10);
return result;
}

@override
Map<String, Object?> toJson() => _$PollVoteEventSubmessageToJson(this);
}

/// As in [PollVoteEventSubmessage.op].
@JsonEnum(valueField: 'apiValue')
enum PollVoteOp {
add(apiValue: 1),
remove(apiValue: -1),
unknown(apiValue: null);

const PollVoteOp({required this.apiValue});

final int? apiValue;

int? toJson() => apiValue;
}

class UnknownPollEventSubmessage extends PollEventSubmessage {
@override
@JsonKey(includeToJson: true)
PollEventSubmessageType get type => PollEventSubmessageType.unknown;

final Map<String, Object?> json;

UnknownPollEventSubmessage.fromJson(this.json);

@override
Map<String, Object?> toJson() => json;
}
Loading