Compare commits

...

26 Commits

Author SHA1 Message Date
diamondburned b5bb0c9bb9 Revert "Replace stop callbacks with contexts"
This reverts commit 410ac73469.

The rationale is that the frontend can wrap its own components with a
disposable thread-safe wrapper that doesn't work once it's invalidated
if it wants the guarantee that the component doesn't work anymore once
the context is stopped.
2021-05-04 16:19:13 -07:00
diamondburned 8bfabf58ec Make SetterMethods ContainerUpdaterMethods
This commit separated SetterMethods that are specifically for updating
containers to another method type, named ContainerUpdaterMethod. This
change is done to force a context parameter into container setters,
allowing the frontend to know if an incoming update is valid or not,
based on the state of the context given.

The validity check should be the same as any other context:

    select {
    case <-ctx.Done():
        return
    default:
        addEvent()
    }

It is crucial, however, to do the checking and updating in the same
thread or lock as the context is cancelled. This explicit
synchronization is required to prevent any race condition whatsoever
with cancellation of the context.

The backend must pass in the right context, that is, any context that
inherits the cancellation from the frontend. Passing in the invalid
context is undefined behavior and will eventually cause a data race.
2021-05-01 21:41:39 -07:00
diamondburned 410ac73469 Replace stop callbacks with contexts
This commit removes all stop callbacks in ContainerMethods. The
intention is to have backends disconnect callbacks when the context is
cancelled, rather than when the stop function is called.

This helps get rid of countless race condition flaws caused by the
duration between the context being cancelled on one thread and the stop
callback being set in another, causing the handlers to not disconnect.
2021-05-01 17:49:25 -07:00
diamondburned 4e11444f6c Configurator to be SetterMethods
This commit changes Configurator's methods to be SetterMethods instead
of IOMethods, as Configurator is specifically made for frontend-managed
settings just for the backend, so no storing/loading is needed on the
backend's side.

This commit also changes SetterMethod to allow methods done to the
backend to error out, in case the setting value is invalid somehow.
Setter methods that are called by the backend (as opposed to the
frontend) must never error.
2021-05-01 17:22:01 -07:00
diamondburned 86956a65ec Allow cancels for ContainerMethods and IOMethods
This commit changes several ContainerMethods to take in a context. It
also changes all IOMethods to take in a context.

This addition adds consistency to the API as well as allowing better
graceful cancellation and cleanups if needed when, for example, the user
wants to discard an ongoing process.
2021-05-01 17:02:02 -07:00
diamondburned f2de1cb84d Added missing text.Rich return in ListMember 2021-03-25 16:25:44 -07:00
diamondburned 0cb14b9819 ListMember to no longer use Namer
This commit broke ListMember to remove the Namer interface. This is
because the whole interface should act as a static container with
information to be updated.
2021-03-25 16:05:35 -07:00
diamondburned f24feb2002 MessageUpdate should only update the content
This commit changes MessageUpdate so that it only updates the message
content. Updating the username should be up to MessageCreate's Author.
2021-03-20 00:13:39 -07:00
diamondburned f8c644fa7e Allow empty texts with segments
This commit allows segments in an empty text segment to account for
segments with only an image.
2021-03-19 22:40:31 -07:00
diamondburned c7d4473c23 Nicknamer to embed Name instead
This commit breaks Nicknamer to embed Name instead of having its own
ContainerMethod with a similar function signature but different name.
This allows the frontend to reuse the same LabelContainer abstraction
for Nickname as well.
2021-03-19 22:15:42 -07:00
diamondburned 174496bdf9 Enforce Identifier on all Services
This commit breaks the Service interface to force all services to have a
global unique identifier. The commit does not enforce any particular
format, but the Reverse Domain Name Notation is recommended.

For reference:
https://en.wikipedia.org/wiki/Reverse_domain_name_notation
2021-03-19 16:52:41 -07:00
diamondburned da5c38eb2f Columnate to return bool
This commit breaks the previous Columnate API to return booleans instead
of constant integers. This makes handling Columnate API much simpler
with less false values (since all possible boolean values are valid).
2021-03-18 14:20:30 -07:00
diamondburned c2fb784dbf Move Columnate to Lister
This commit broke Lister to add Columnate, and the method is removed
from Server, because only Lister gets nested.
2021-03-18 12:27:50 -07:00
diamondburned d40f221221 Add missing return in Columnate 2021-03-18 10:06:52 -07:00
diamondburned ee9c2cc37c Remove redundant function 2021-03-18 09:58:13 -07:00
diamondburned 0569261f72 Enforce Columnate in Server
This commit breaks the API to enforce all servers to have a Columnate
method.

This commit also changes some of the documentation to be more obvious.
2021-03-18 09:52:14 -07:00
diamondburned 4ea6773527 Force ContainerMethod stop funcs
This commit breaks ContainerMethod to enforce explicit destructors. This
gives the frontend explicit control over when the container is
unsubscribed, but it also eases unsubscription implementations in the
backend.

With this new change, the backend can now add the container into a
global repository and unsubscribe from it explicitly from the callback.
2021-03-12 22:41:46 -08:00
diamondburned 1ece6ea076 Rename Author to Namer; Namer to use LabelContainer
This commit breaks more of the API to force all implementations of Namer
to use a LabelContainer instead of just returning a text. This is done
to allow updating of all labels instead of having to update the whole
parent context. This allows the backend to do book-keeping of labels and
images and trivially update them simultaneously without updating the
parent context.

The Author interface is also renamed to User. This allows the user
interface to be used everywhere else outside of Message.
2021-03-10 15:09:48 -08:00
diamondburned 1251001e8c Removed Icon interfaces, added ReadIndicator
This commit introduced a big breaking change of changing Author and
Namer to no longer have any reference to Icon or Image containers and
interfaces.

Instead, in the case of Author and Namer, it relies on the label being
updated by either an update setter or LabelContainer. The frontend
should get the first image/avatar to display that instead.

This commit also added ReadIndicator and related interfaces to support
the read receipts feature seen in Matrix, Telegram, Messenger and co.

The UnreadIndicator interface was broken to add the MarkRead method,
which hands explicit control of setting read messages for the current
user to the frontend instead.
2021-03-08 22:20:10 -08:00
diamondburned 41a7dac033 Added Columnator
This commit added the Columnator interface. This interface accommodates
the fact that some services (such as Discord) stylizes certain nested
servers in the same column.

This commit also fixed a minor test case.
2021-03-08 16:22:30 -08:00
diamondburned 02c686f994 Added helper methods to Package 2021-01-13 18:44:26 -08:00
diamondburned 1460ee6b4b Allow IOMethods to be explicit disposers
This commit changes IOMethods and clarifies stop functions that they
will act as destructors or disposers for whatever interface that
implements the methods, and that both the backend and frontend should
free that interface when they're called.

This commit is added as part of the IPC protocol.
2021-01-13 16:17:55 -08:00
diamondburned 06a26af5ba Slightly cleaner generation structure 2021-01-08 19:55:35 -08:00
diamondburned 903fe9fbfd Fixed ReplyingTo invalid type 2021-01-01 14:28:30 -08:00
diamondburned 7cb512f8b1 Added Replier and renamed Attachments
This commit renamed Attachments to Attacher, as the new name is more
idiomatic.

This commit also added the Replier interface, which is used to indicate
that a message being sent is a reply towards something.
2021-01-01 14:09:42 -08:00
diamondburned 24fc2c9bbb Fixed invalid types and bugs in MessageReferencer 2020-12-17 17:18:02 -08:00
16 changed files with 604 additions and 373 deletions

295
cchat.go
View File

@ -143,6 +143,17 @@ type MessageAttachment struct {
Name string
}
// ReadIndication represents a read indication of a user/author in a messager
// server. It relates to a message ID within the server and is meant to imply
// that the user/author has read up to the given message ID.
//
// The frontend should override an existing author with the received ones. This
// could be treated as upsert operations.
type ReadIndication struct {
User User
MessageID ID
}
// ErrInvalidConfigAtField is the structure for an error at a specific
// configuration field. Frontends can use this and highlight fields if the
// backends support it.
@ -165,7 +176,7 @@ type Actioner interface {
// Do executes a message action on the given messageID, which would be taken
// from MessageHeader.ID(). This method is allowed to do IO; the frontend should
// take care of running it asynchronously.
Do(action string, id ID) error // Blocking
Do(ctx context.Context, action string, id ID) error // Blocking
// MessageActions returns a list of possible actions to a message in pretty
// strings that the frontend will use to directly display. This method must not
// do IO.
@ -174,9 +185,8 @@ type Actioner interface {
Actions(id ID) []string
}
// Attachments extends SendableMessage which adds attachments into the message.
// Backends that can use this interface should implement AttachmentSender.
type Attachments interface {
// Attacher adds attachments into the message being sent.
type Attacher interface {
Attachments() []MessageAttachment
}
@ -207,7 +217,7 @@ type AuthenticateError interface {
type Authenticator interface {
// Authenticate will be called with a list of values with indices correspond to
// the returned slice of AuthenticateEntry.
Authenticate([]string) (Session, AuthenticateError) // Blocking
Authenticate(context.Context, []string) (Session, AuthenticateError) // Blocking
// AuthenticateForm should return a list of authentication entries for the
// frontend to render.
AuthenticateForm() []AuthenticateEntry
@ -218,27 +228,9 @@ type Authenticator interface {
Name() text.Rich
}
// Author is the interface for an identifiable author. The interface defines
// that an author always have an ID and a name.
//
// An example of where this interface is used would be in MessageCreate's Author
// method or embedded in Typer. The returned ID may or may not be used by the
// frontend, but backends must guarantee that the Author's ID is in fact a user
// ID.
//
// The frontend may use the ID to squash messages with the same author together.
type Author interface {
Identifier
// Avatar returns the URL to the user's avatar or an empty string if they have
// no avatar or the service does not have any avatars.
Avatar() (url string)
Name() text.Rich
}
// Backlogger adds message history capabilities into a message container. The
// backend should send old messages using the MessageCreate method of the
// MessageContainer, and the frontend should automatically sort messages based
// MessagesContainer, and the frontend should automatically sort messages based
// on the timestamp.
//
// As there is no stop callback, if the backend needs to fetch messages
@ -303,7 +295,7 @@ type Commander interface {
// A helper function for this kind of behavior is available in package split,
// under the ArgsIndexed function. This implementation also provides the rough
// specifications.
Run(words []string) ([]byte, error) // Blocking
Run(ctx context.Context, words []string) ([]byte, error) // Blocking
// Asserters.
@ -326,19 +318,17 @@ type Completer interface {
}
// Configurator is an interface which the backend can implement for a primitive
// configuration API. Since these methods do return an error, they are allowed
// to do IO. The frontend should handle this appropriately, including running
// them asynchronously.
// configuration API.
type Configurator interface {
SetConfiguration(map[string]string) error // Blocking
Configuration() (map[string]string, error) // Blocking
SetConfiguration(map[string]string) error
Configuration() map[string]string
}
// Editor adds message editing to the messenger. Only EditMessage can do IO.
type Editor interface {
// Edit edits the message with the given ID to the given content, which is the
// edited string from RawMessageContent. This method can do IO.
Edit(id ID, content string) error // Blocking
Edit(ctx context.Context, id ID, content string) error // Blocking
// RawContent gets the original message text for editing. This method must not
// do IO.
RawContent(id ID) (string, error)
@ -347,27 +337,6 @@ type Editor interface {
IsEditable(id ID) bool
}
// IconContainer is a generic interface for any container that can hold an
// image. It's typically used for icons that can update itself. Frontends should
// round these icons. For images that shouldn't be rounded, use ImageContainer.
//
// Methods may call SetIcon at any time in its main thread, so the frontend must
// do any I/O (including downloading the image) in another goroutine to avoid
// blocking the backend.
type IconContainer interface {
SetIcon(url string)
}
// Iconer adds icon support into Namer, which in turn is returned by other
// interfaces. Typically, Service would return the service logo, Session would
// return the user's avatar, and Server would return the server icon.
//
// For session, the avatar should be the same as the one returned by messages
// sent by the current user.
type Iconer interface {
Icon(context.Context, IconContainer) (stop func(), err error)
}
// Identifier requires ID() to return a uniquely identifiable string for
// whatever this is embedded into. Typically, servers and messages have IDs. It
// is worth mentioning that IDs should be consistent throughout the lifespan of
@ -376,40 +345,27 @@ type Identifier interface {
ID() ID
}
// ImageContainer is a generic interface for any container that can hold an
// image. It's typically used for icons that can update itself. Frontends should
// not round these icons. For images that should be rounded, use IconContainer.
//
// Methods may call SetIcon at any time in its main thread, so the frontend must
// do any I/O (including downloading the image) in another goroutine to avoid
// blocking the backend.
type ImageContainer interface {
SetImage(url string)
}
// LabelContainer is a generic interface for any container that can hold texts.
// It's typically used for rich text labelling for usernames and server names.
//
// Methods that takes in a LabelContainer typically holds it in the state and
// may call SetLabel any time it wants. Thus, the frontend should synchronize
// calls with the main thread if needed.
//
// Labels given to the frontend may contain images or avatars, and the frontend
// has the choice to display them or not.
type LabelContainer interface {
SetLabel(text.Rich)
SetLabel(context.Context, text.Rich)
}
// ListMember represents a single member in the member list. This is a base
// interface that may implement more interfaces, such as Iconer for the user's
// avatar.
// ListMember represents a single member in the member list. Note that this
// interface should be treated as a static container: updating a member will
// involve a completely new ListMember instance with the same ID.
//
// Note that the frontend may give everyone an avatar regardless, or it may not
// show any avatars at all.
type ListMember interface {
// Identifier identifies the individual member. This works similarly to
// MessageAuthor.
Identifier
// Namer returns the name of the member. This works similarly to a
// MessageAuthor.
Namer
// Secondary returns the subtext of this member. This could be anything, such as
// a user's custom status or away reason.
@ -418,6 +374,9 @@ type ListMember interface {
// offline members with the offline status if it doesn't want to show offline
// menbers at all.
Status() Status
// Name returns the username or the nickname of the member, whichever the
// backend should prefer.
Name() text.Rich
}
// Lister is for servers that contain children servers. This is similar to
@ -433,7 +392,18 @@ type Lister interface {
// Servers should call SetServers() on the given ServersContainer to render all
// servers. This function can do IO, and the frontend should run this in a
// goroutine.
Servers(ServersContainer) (err error)
Servers(ServersContainer) (stop func(), err error)
// Columnate is optionally used by servers to tell the frontend whether or not
// its children should be put onto a new column instead of underneath it within
// the same tree. If the method returns false, then the frontend can treat its
// children as normal and show it as children within the same tree.
//
// For example, in Discord, guilds can be placed in guild folders, but guilds
// and guild folders are put in the same column while guilds are actually
// children of the folders. To replicate this behavior, guild folders should
// return false, and guilds should return true. Both channels and categories can
// return false.
Columnate() bool
}
// MemberDynamicSection represents a dynamically loaded member list section. The
@ -449,14 +419,14 @@ type MemberDynamicSection interface {
// The client can call this method exactly as many times as it has called
// LoadMore. However, false should be returned if the client should stop, and
// future calls without LoadMore should still return false.
LoadLess() bool // Blocking
LoadLess(context.Context) bool // Blocking
// LoadMore is a method which the client can call to ask for more members. This
// method can do IO.
//
// Clients may call this method on the last section in the section slice;
// however, calling this method on any section is allowed. Clients may not call
// this method if the number of members in this section is equal to Total.
LoadMore() bool // Blocking
LoadMore(context.Context) bool // Blocking
}
// MemberListContainer is a generic interface for any container that can display
@ -482,18 +452,22 @@ type MemberDynamicSection interface {
type MemberListContainer interface {
// RemoveMember removes a member from a section. If neither the member nor the
// section exists, then the client should ignore it.
RemoveMember(sectionID ID, memberID ID)
RemoveMember(ctx context.Context, sectionID ID, memberID ID)
// SetMember adds or updates (or upsert) a member into a section. This operation
// must not change the section's member count. As such, changes should be done
// separately in SetSection. If the section does not exist, then the client
// should ignore this member. As such, backends must call SetSections first
// before SetMember on a new section.
SetMember(sectionID ID, member ListMember)
// should ignore this member, so, backends must call SetSections first before
// SetMember on a new section.
//
// Typically, the backend should try and avoid calling this method and instead
// update the labeler in the name. This method should only be used for adding
// members.
SetMember(ctx context.Context, sectionID ID, member ListMember)
// SetSections (re)sets the list of sections to be the given slice. Members from
// the old section list should be transferred over to the new section entry if
// the section name's content is the same. Old sections that don't appear in the
// new slice should be removed.
SetSections(sections []MemberSection)
SetSections(ctx context.Context, sections []MemberSection)
}
// MemberLister adds a member list into a message server.
@ -531,7 +505,7 @@ type MessageCreate interface {
// backend does not implement mentioning, then false can be returned.
Mentioned() bool
Content() text.Rich
Author() Author
Author() User
}
// MessageDelete is the interface for a message delete event.
@ -546,14 +520,13 @@ type MessageHeader interface {
Time() time.Time
}
// MessageUpdate is the interface for a message update (or edit) event. If the
// returned text.Rich returns true for Empty(), then the element shouldn't be
// changed.
// MessageUpdate is the interface for a message update (or edit) event. It is
// only responsible for updating a message's content. The author's name should
// be updated using MessageCreate's Author.
type MessageUpdate interface {
MessageHeader
Content() text.Rich
Author() Author
}
// MessagesContainer is a view implementation that displays a list of messages
@ -564,12 +537,12 @@ type MessageUpdate interface {
// allowed to have multiple views. This is usually done with tabs or splits, but
// the backend should update them all nonetheless.
type MessagesContainer interface {
DeleteMessage(MessageDelete)
UpdateMessage(MessageUpdate)
DeleteMessage(context.Context, MessageDelete)
UpdateMessage(context.Context, MessageUpdate)
// CreateMessage inserts a message into the container. The frontend must
// guarantee that the messages are in order based on what's returned from
// Time().
CreateMessage(MessageCreate)
CreateMessage(context.Context, MessageCreate)
}
// Messenger is for servers that contain messages. This is similar to Discord or
@ -600,12 +573,15 @@ type Messenger interface {
// Namer requires Name() to return the name of the object. Typically, this
// implies usernames for sessions or service names for services.
//
// Frontends can show the ID of the object when a name hasn't yet been set. The
// backend may immediately update the name afterwards, but assumptions should
// not be made.
type Namer interface {
Name() text.Rich
// Asserters.
AsIconer() Iconer // Optional
// Name sets the given container to contain the name of the parent context. The
// method has no stop method; stopping is implied to be dependent on the parent
// context. As such, it's only used for updating.
Name(context.Context, LabelContainer) (stop func(), err error)
}
// Nicknamer adds the current user's nickname.
@ -615,7 +591,7 @@ type Namer interface {
// implement ServerMessage also don't need to implement ServerNickname. By
// default, the session name should be used.
type Nicknamer interface {
Nickname(context.Context, LabelContainer) (stop func(), err error)
Namer
}
// Noncer adds nonce support. A nonce is defined in this context as a unique
@ -634,6 +610,38 @@ type Noncer interface {
Nonce() string
}
// ReadContainer is an interface that a frontend container can implement to show
// the read bubbles on messages. This container typically implies the message
// container, but that is up to the frontend's implementation.
type ReadContainer interface {
// DeleteIndications deletes a list of unused users/authors associated with
// their read indicators. The backend can use this to free up users/authors that
// are no longer in the server, for example when they are offline or have left
// the server.
DeleteIndications(ctx context.Context, authorIDs []ID)
// AddIndications adds a map of users/authors to the respective message ID of
// the server that implements ReadIndicator.
AddIndications(context.Context, []ReadIndication)
}
// ReadIndicator adds a read indicator API for frontends to show. An example of
// the read indicator is in Matrix, where each message can have a small avatar
// indicating that the user in the room has read the message.
type ReadIndicator interface {
// ReadIndicate subscribes the given container for read activities. The backend
// must keep track of which read states to send over to not overwhelm the
// frontend, and the frontend must either keep track of them, or it should not
// display it at all.
ReadIndicate(context.Context, ReadContainer) (stop func(), err error)
}
// Replier indicates that the message being sent is a reply to something.
// Frontends that support replies can assume that all messages in a Sender can
// be replied to, and the backend can choose to do nothing to the replied ID.
type Replier interface {
ReplyingTo() ID
}
// SendableMessage is the bare minimum interface of a sendable message, that is,
// a message that can be sent with SendMessage(). This allows the frontend to
// implement its own message data implementation.
@ -647,8 +655,9 @@ type SendableMessage interface {
// Asserters.
AsNoncer() Noncer // Optional
AsAttachments() Attachments // Optional
AsNoncer() Noncer // Optional
AsReplier() Replier // Optional
AsAttacher() Attacher // Optional
}
// Sender adds message sending to a messenger. Messengers that don't implement
@ -657,7 +666,7 @@ type Sender interface {
// CanAttach returns whether or not the client is allowed to upload files.
CanAttach() bool
// Send is called by the frontend to send a message to this channel.
Send(SendableMessage) error // Blocking
Send(context.Context, SendableMessage) error // Blocking
// Asserters.
@ -667,6 +676,9 @@ type Sender interface {
// Server is a single server-like entity that could translate to a guild, a
// channel, a chat-room, and such. A server must implement at least ServerList
// or ServerMessage, else the frontend must treat it as a no-op.
//
// Note that the Server is allowed to implement both Lister and Messenger. This
// is useful when the messenger contains sub-servers, such as threads.
type Server interface {
Identifier
Namer
@ -709,16 +721,22 @@ type ServerUpdate interface {
// as servers can be infinitely nested. Frontends should also reset the entire
// node and its children when SetServers is called again.
type ServersContainer interface {
UpdateServer(ServerUpdate)
UpdateServer(context.Context, ServerUpdate)
// SetServer is called by the backend service to request a reset of the server
// list. The frontend can choose to call Servers() on each of the given servers,
// or it can call that later. The backend should handle both cases.
SetServers([]Server)
//
// If the backend sets a nil server slice, then the frontend should take that as
// an unavailable server list rather than an empty server list. The server list
// should only be considered empty if it's an empty non-nil slice. An
// unavailable list, on the other hand, can be treated as backend issues, e.g. a
// connection issue.
SetServers(context.Context, []Server)
}
// A service is a complete service that's capable of multiple sessions. It has
// to implement the Authenticate() method, which returns multiple
// implementations of Authenticator.
// Service is a complete service that's capable of multiple sessions. It has to
// implement the Authenticate() method, which returns multiple implementations
// of Authenticator.
//
// A service can implement SessionRestorer, which would indicate the frontend
// that it can restore past sessions. Sessions are saved using the SessionSaver
@ -730,6 +748,13 @@ type ServersContainer interface {
// configurations must be optional, as frontends may not implement a
// configurator UI.
type Service interface {
// Identifier returns the unique identifier for the service. There is no
// enforced representation, but services are recommended to follow the Reverse
// Domain Name Notation for consistency. An example of that would be:
//
// com.github.diamondburned.cchat-discord
// com.github.username.service
Identifier
// Namer returns the name of the service.
Namer
@ -741,14 +766,14 @@ type Service interface {
AsSessionRestorer() SessionRestorer // Optional
}
// A session is returned after authentication on the service. Session implements
// Session is returned after authentication on the service. It implements
// Name(), which should return the username most of the time. It also implements
// ID(), which might be used by frontends to check against MessageAuthor.ID()
// and other things.
// ID(), which might be used by frontends to check against User.ID() and other
// things.
//
// A session can implement SessionSaver, which would allow the frontend to save
// the session into its keyring at any time. Whether the keyring is completely
// secure or not is up to the frontend. For a Gtk client, that would be using
// secure or not is up to the frontend. For a GTK client, that would be using
// the GNOME Keyring daemon.
type Session interface {
// Identifier should typically return the user ID.
@ -769,7 +794,7 @@ type Session interface {
// When this function fails, the frontend may display the error upfront.
// However, it will treat the session as actually disconnected. If needed, the
// backend must implement reconnection by itself.
Disconnect() error // Blocking
Disconnect(context.Context) error // Blocking, Disposer
// Asserters.
@ -783,7 +808,7 @@ type Session interface {
//
// To save a session, refer to SessionSaver.
type SessionRestorer interface {
RestoreSession(map[string]string) (Session, error) // Blocking
RestoreSession(context.Context, map[string]string) (Session, error) // Blocking
}
// SessionSaver extends Session and is called by the frontend to save the
@ -799,15 +824,6 @@ type SessionSaver interface {
SaveSession() map[string]string
}
// Typer is an individual user that's typing. This interface is used
// interchangably in TypingIndicator and thus ServerMessageTypingIndicator as
// well.
type Typer interface {
Author
Time() time.Time
}
// TypingContainer is a generic interface for any container that can display
// users typing in the current chatbox. The typing indicator must adhere to the
// TypingTimeout returned from ServerMessageTypingIndicator. The backend should
@ -819,10 +835,11 @@ type TypingContainer interface {
// of typers. This function is usually not needed, as the client will take care
// of removing them after TypingTimeout has been reached or other conditions
// listed in ServerMessageTypingIndicator are met.
RemoveTyper(typerID ID)
// AddTyper appends the typer into the frontend's list of typers, or it pushes
// this typer on top of others.
AddTyper(typer Typer)
RemoveTyper(ctx context.Context, authorID ID)
// AddTyper appends the typer (author) into the frontend's list of typers, or it
// pushes this typer on top of others. The frontend should assume current time
// every time AddTyper is called.
AddTyper(context.Context, User)
}
// TypingIndicator optionally extends ServerMessage to provide bidirectional
@ -840,7 +857,7 @@ type TypingIndicator interface {
// This method does not take in a context, as it's supposed to only use event
// handlers and not do any IO calls. Nonetheless, the client must treat it like
// it does and call it asynchronously.
TypingSubscribe(TypingContainer) (stop func(), err error)
TypingSubscribe(context.Context, TypingContainer) (stop func(), err error)
// TypingTimeout returns the interval between typing events sent by the client
// as well as the timeout before the client should remove the typer. Typically,
// a constant should be returned.
@ -849,7 +866,7 @@ type TypingIndicator interface {
// function can do IO calls, and the client must take care of calling it in a
// goroutine (or an asynchronous queue) as well as throttling it to
// TypingTimeout.
Typing() error // Blocking
Typing(context.Context) error // Blocking
}
// UnreadContainer is an interface that a single server container (such as a
@ -868,10 +885,13 @@ type TypingIndicator interface {
type UnreadContainer interface {
// SetUnread sets the container's unread state to the given boolean. The
// frontend may choose how to represent this.
SetUnread(unread bool, mentioned bool)
SetUnread(ctx context.Context, unread bool, mentioned bool)
}
// UnreadIndicator adds an unread state API for frontends to use.
// UnreadIndicator adds an unread state API for frontends to use. The unread
// state describes whether a channel has been read or not by the current user.
// It is not to be confused with ReadIndicator, which indicates the unread state
// of others.
type UnreadIndicator interface {
// UnreadIndicate subscribes the given unread indicator for unread and mention
// events. Examples include when a new message is arrived and the backend needs
@ -879,5 +899,28 @@ type UnreadIndicator interface {
//
// This function must provide a way to remove callbacks, as clients must call
// this when the old server is destroyed, such as when Servers is called.
UnreadIndicate(UnreadContainer) (stop func(), err error)
UnreadIndicate(context.Context, UnreadContainer) (stop func(), err error)
// MarkRead marks a message in the server messenger as read. Backends that
// implement the UnreadIndicator interface must give control of marking messages
// as read to the frontend if possible.
//
// This method is assumed to be a setter method that does not error out, because
// the frontend has no use in knowing the error. As such, marking messages as
// read is best-effort. The backend is in charge of synchronizing the read state
// with the server and coordinating it with reasonable rate limits, if needed.
MarkRead(ctx context.Context, messageID ID)
}
// User is the interface for an identifiable author. The interface defines that
// an author always have an ID and a name.
//
// An example of where this interface is used would be in MessageCreate's User
// method or embedded in Typer. The returned ID may or may not be used by the
// frontend, but backends must guarantee that the User's ID is in fact a user
// ID.
//
// The frontend may use the ID to squash messages with the same author together.
type User interface {
Identifier
Namer
}

View File

@ -5,6 +5,7 @@ import (
"log"
"os"
"path"
"path/filepath"
"sort"
"strings"
@ -74,7 +75,7 @@ func main() {
}
}
f, err := os.Create("empty.go")
f, err := os.Create(filepath.Join(os.Args[1], "empty.go"))
if err != nil {
log.Fatalln("Failed to create output file:", err)
}

View File

@ -66,10 +66,18 @@ func generateInterfaces(ifaces []repository.Interface) jen.Code {
stmt.Params(generateFuncParams(method.Returns, method.ErrorType)...)
case repository.SetterMethod:
stmt.Params(generateFuncParams(method.Parameters, "")...)
stmt.Params(generateFuncParamsErr(repository.NamedType{}, method.ErrorType)...)
case repository.ContainerUpdaterMethod:
stmt.Params(generateFuncParamsCtx(method.Parameters, "")...)
stmt.Params(generateFuncParamsErr(repository.NamedType{}, method.ErrorType)...)
case repository.IOMethod:
stmt.Params(generateFuncParams(method.Parameters, "")...)
stmt.Params(generateFuncParamErr(method.ReturnValue, method.ErrorType)...)
stmt.Comment("// Blocking")
stmt.Params(generateFuncParamsCtx(method.Parameters, "")...)
stmt.Params(generateFuncParamsErr(method.ReturnValue, method.ErrorType)...)
var comment = "Blocking"
if method.Disposer {
comment += ", Disposer"
}
stmt.Comment("// " + comment)
case repository.ContainerMethod:
stmt.Params(generateContainerFuncParams(method)...)
stmt.Params(generateContainerFuncReturns(method)...)
@ -92,7 +100,7 @@ func generateInterfaces(ifaces []repository.Interface) jen.Code {
return stmt
}
func generateFuncParamErr(param repository.NamedType, errorType string) []jen.Code {
func generateFuncParamsErr(param repository.NamedType, errorType string) []jen.Code {
stmt := make([]jen.Code, 0, 2)
if !param.IsZero() {
@ -117,6 +125,18 @@ func generateFuncParam(param repository.NamedType) jen.Code {
return jen.Id(param.Name).Add(genutils.GenerateType(param))
}
func generateFuncParamsCtx(params []repository.NamedType, errorType string) []jen.Code {
var name string
if len(params) > 0 && params[0].Name != "" {
name = "ctx"
}
p := []repository.NamedType{{Name: name, Type: "context.Context"}}
p = append(p, params...)
return generateFuncParams(p, errorType)
}
func generateFuncParams(params []repository.NamedType, errorType string) []jen.Code {
if len(params) == 0 {
return nil
@ -141,9 +161,7 @@ func generateFuncParams(params []repository.NamedType, errorType string) []jen.C
func generateContainerFuncReturns(method repository.ContainerMethod) []jen.Code {
var stmt jen.Statement
if method.HasStopFn {
stmt.Add(jen.Id("stop").Func().Params())
}
stmt.Add(jen.Id("stop").Func().Params())
stmt.Add(jen.Err().Error())
return stmt

View File

@ -21,8 +21,11 @@ func main() {
for pkgPath, pkg := range repository.Main {
g := generate(pkgPath, pkg)
var destDir = filepath.FromSlash(trimPrefix(repository.RootPath, pkgPath))
var destFle = filepath.Base(pkgPath)
destDir := filepath.Join(
os.Args[1],
filepath.FromSlash(trimPrefix(repository.RootPath, pkgPath)),
)
destFile := filepath.Base(pkgPath) + ".go"
// Guarantee that the directory exists.
if destDir != "" {
@ -31,7 +34,7 @@ func main() {
}
}
f, err := os.Create(filepath.Join(destDir, destFle+".go"))
f, err := os.Create(filepath.Join(destDir, destFile))
if err != nil {
log.Fatalln("Failed to create output file:", err)
}

View File

@ -1,6 +1,7 @@
package cchat
//go:generate go run ./cmd/internal/cchat-generator
//go:generate go run ./cmd/internal/cchat-generator ./
//go:generate go run ./cmd/internal/cchat-empty-gen ./utils/empty/
type authenticateError struct{ error }

View File

@ -31,6 +31,10 @@ func (c Comment) IsEmpty() bool {
// prefix each line with "// ". The ident argument controls the nested level. If
// less than or equal to zero, then it is changed to 1, which is the top level.
func (c Comment) GoString(ident int) string {
if c.Raw == "" {
return ""
}
if ident < 1 {
ident = 1
}
@ -40,7 +44,12 @@ func (c Comment) GoString(ident int) string {
var lines = strings.Split(c.WrapText(80-len("// ")-ident), "\n")
for i, line := range lines {
lines[i] = "// " + line
if line != "" {
line = "// " + line
} else {
line = "//"
}
lines[i] = line
}
return strings.Join(lines, "\n")

View File

@ -8,26 +8,8 @@ import (
const _goComment = `
// The authenticator interface allows for a multistage initial authentication
// API that the backend could use. Multistage is done by calling
// AuthenticateForm then Authenticate again forever until no errors are
// returned.
//
// var s *cchat.Session
// var err error
//
// for {
// // Pseudo-function to render the form and return the results of those
// // forms when the user confirms it.
// outputs := renderAuthForm(svc.AuthenticateForm())
//
// s, err = svc.Authenticate(outputs)
// if err != nil {
// renderError(errors.Wrap(err, "Error while authenticating"))
// continue // retry
// }
//
// break // success
// }`
// API that the backend could use. Multistage is done by calling Authenticate
// and check for AuthenticateError's NextStage method.`
// Trim away the prefix new line.
var goComment = _goComment[1:]

Binary file not shown.

View File

@ -10,6 +10,7 @@ func init() {
gob.Register(AsserterMethod{})
gob.Register(GetterMethod{})
gob.Register(SetterMethod{})
gob.Register(ContainerUpdaterMethod{})
gob.Register(IOMethod{})
}
@ -67,18 +68,39 @@ func (m GetterMethod) ReturnError() bool {
}
// SetterMethod is a method that sets values. These methods must not do IO, and
// they have to be non-blocking. They're used only for containers. Actual setter
// methods implemented by the backend belongs to IOMethods.
// they have to be non-blocking.
type SetterMethod struct {
method
// Parameters is the list of parameters in the function. These parameters
// should be the parameters to set.
Parameters []NamedType
// ErrorType is non-empty if the function returns an error at the end of
// returns. An error may be returned from the backend if the input is
// invalid, but it must not do IO. Frontend setters must never error.
ErrorType string
}
// ContainerUpdaterMethod is a SetterMethod that passes to the container the
// current context to prevent race conditions when synchronizing.
// The rule of thumb is that any setter method done inside a method with a
// context is usually this type of method.
type ContainerUpdaterMethod struct {
method
// Parameters is the list of parameters in the function. These parameters
// should be the parameters to set.
Parameters []NamedType
// ErrorType is non-empty if the function returns an error at the end of
// returns. An error may be returned from the backend if the input is
// invalid, but it must not do IO. Frontend setters must never error.
ErrorType string
}
// IOMethod is a regular method that can do IO and thus is blocking. These
// methods usually always return errors.
// methods usually always return errors. IOMethods must always have means of
// cancelling them in the API, but implementations don't have to use it; as
// such, the user should always have a timeout to gracefully wait.
type IOMethod struct {
method
@ -90,6 +112,17 @@ type IOMethod struct {
// returns. For the most part, this field should be "error" if that is the
// case, but some methods may choose to extend the error base type.
ErrorType string
// Disposer indicates that this method signals the disposal of the interface
// that implements it. This is used similarly to stop functions, except all
// disposer functions can be synchronous, and the frontend should handle
// indicating such. The frontend can also ignore the result and run the
// method in a dangling goroutine, but it must gracefully wait for it to be
// done on exit.
//
// Similarly to the stop function, the instance that the disposer method belongs
// to will also be considered invalid and should be freed once the function
// returns regardless of the error.
Disposer bool
}
// ReturnError returns true if the method can error out.
@ -98,7 +131,7 @@ func (m IOMethod) ReturnError() bool {
}
// ContainerMethod is a method that uses a Container. These methods can do IO
// and always return an error.
// and always return a stop callback and an error.
type ContainerMethod struct {
method
@ -107,10 +140,6 @@ type ContainerMethod struct {
// ContainerType is the name of the container interface. The name will
// almost always have "Container" as its suffix.
ContainerType string
// HasStopFn is true if the function returns a callback of type func() as
// its first return. The function will return an error in addition. If this
// is false, then only the error is returned.
HasStopFn bool
}
// Qual returns what TypeQual returns with m.ContainerType.

View File

@ -113,6 +113,7 @@ var Main = Packages{
AsserterMethod{ChildType: "Attributor"},
AsserterMethod{ChildType: "Codeblocker"},
AsserterMethod{ChildType: "Quoteblocker"},
AsserterMethod{ChildType: "MessageReferencer"},
},
}, {
Comment: Comment{`
@ -128,7 +129,7 @@ var Main = Packages{
Methods: []Method{
GetterMethod{
method: method{Name: "MessageID"},
Returns: []NamedType{{Type: "cchat.ID"}},
Returns: []NamedType{{Type: "string"}},
},
},
}, {
@ -531,6 +532,21 @@ var Main = Packages{
{NamedType: NamedType{"", "io.Reader"}},
{NamedType: NamedType{"Name", "string"}},
},
}, {
Comment: Comment{`
ReadIndication represents a read indication of a user/author in
a messager server. It relates to a message ID within the server
and is meant to imply that the user/author has read up to the
given message ID.
The frontend should override an existing author with the
received ones. This could be treated as upsert operations.
`},
Name: "ReadIndication",
Fields: []StructField{
{NamedType: NamedType{"User", "User"}},
{NamedType: NamedType{"MessageID", "ID"}},
},
}},
ErrorStructs: []ErrorStruct{{
Struct: Struct{
@ -570,36 +586,25 @@ var Main = Packages{
Namer requires Name() to return the name of the object.
Typically, this implies usernames for sessions or service
names for services.
Frontends can show the ID of the object when a name hasn't yet
been set. The backend may immediately update the name
afterwards, but assumptions should not be made.
`},
Name: "Namer",
Methods: []Method{
GetterMethod{
method: method{Name: "Name"},
Returns: []NamedType{{
Type: MakeQual("text", "Rich"),
}},
},
AsserterMethod{
ChildType: "Iconer",
},
},
}, {
Comment: Comment{`
Iconer adds icon support into Namer, which in turn is returned
by other interfaces. Typically, Service would return the service
logo, Session would return the user's avatar, and Server would
return the server icon.
For session, the avatar should be the same as the one returned
by messages sent by the current user.
`},
Name: "Iconer",
Methods: []Method{
ContainerMethod{
method: method{Name: "Icon"},
method: method{
Comment: Comment{`
Name sets the given container to contain the name of
the parent context. The method has no stop method;
stopping is implied to be dependent on the parent
context. As such, it's only used for updating.
`},
Name: "Name",
},
HasContext: true,
ContainerType: "IconContainer",
HasStopFn: true,
ContainerType: "LabelContainer",
},
},
}, {
@ -628,43 +633,25 @@ var Main = Packages{
},
}, {
Comment: Comment{`
Author is the interface for an identifiable author. The
User is the interface for an identifiable author. The
interface defines that an author always have an ID and a name.
An example of where this interface is used would be in
MessageCreate's Author method or embedded in Typer. The returned
MessageCreate's User method or embedded in Typer. The returned
ID may or may not be used by the frontend, but backends must
guarantee that the Author's ID is in fact a user ID.
guarantee that the User's ID is in fact a user ID.
The frontend may use the ID to squash messages with the same
author together.
`},
Name: "Author",
Name: "User",
Embeds: []EmbeddedInterface{
{InterfaceName: "Identifier"},
},
Methods: []Method{
GetterMethod{
method: method{Name: "Name"},
Returns: []NamedType{{
Type: MakeQual("text", "Rich"),
}},
},
GetterMethod{
method: method{
Comment: Comment{`
Avatar returns the URL to the user's avatar or an
empty string if they have no avatar or the service
does not have any avatars.
`},
Name: "Avatar",
},
Returns: []NamedType{{Name: "url", Type: "string"}},
},
{InterfaceName: "Namer"},
},
}, {
Comment: Comment{`
A service is a complete service that's capable of multiple
Service is a complete service that's capable of multiple
sessions. It has to implement the Authenticate() method, which
returns multiple implementations of Authenticator.
@ -681,6 +668,17 @@ var Main = Packages{
`},
Name: "Service",
Embeds: []EmbeddedInterface{{
Comment: Comment{`
Identifier returns the unique identifier for the service. There
is no enforced representation, but services are recommended to
follow the Reverse Domain Name Notation for consistency. An
example of that would be:
com.github.diamondburned.cchat-discord
com.github.username.service
`},
InterfaceName: "Identifier",
}, {
Comment: Comment{`
Namer returns the name of the service.
`},
@ -819,18 +817,15 @@ var Main = Packages{
}, {
Comment: Comment{`
Configurator is an interface which the backend can implement for a
primitive configuration API. Since these methods do return an error,
they are allowed to do IO. The frontend should handle this
appropriately, including running them asynchronously.
primitive configuration API.
`},
Name: "Configurator",
Methods: []Method{
IOMethod{
method: method{Name: "Configuration"},
ReturnValue: NamedType{Type: "map[string]string"},
ErrorType: "error",
GetterMethod{
method: method{Name: "Configuration"},
Returns: []NamedType{{Type: "map[string]string"}},
},
IOMethod{
SetterMethod{
method: method{Name: "SetConfiguration"},
Parameters: []NamedType{{Type: "map[string]string"}},
ErrorType: "error",
@ -838,16 +833,15 @@ var Main = Packages{
},
}, {
Comment: Comment{`
A session is returned after authentication on the service.
Session implements Name(), which should return the username
most of the time. It also implements ID(), which might be
used by frontends to check against MessageAuthor.ID() and
other things.
Session is returned after authentication on the service. It
implements Name(), which should return the username most of the
time. It also implements ID(), which might be used by frontends
to check against User.ID() and other things.
A session can implement SessionSaver, which would allow the
frontend to save the session into its keyring at any time.
Whether the keyring is completely secure or not is up to the
frontend. For a Gtk client, that would be using the GNOME
frontend. For a GTK client, that would be using the GNOME
Keyring daemon.
`},
Name: "Session",
@ -887,6 +881,7 @@ var Main = Packages{
Name: "Disconnect",
},
ErrorType: "error",
Disposer: true,
},
AsserterMethod{ChildType: "Commander"},
AsserterMethod{ChildType: "SessionSaver"},
@ -983,6 +978,10 @@ var Main = Packages{
guild, a channel, a chat-room, and such. A server must implement
at least ServerList or ServerMessage, else the frontend must
treat it as a no-op.
Note that the Server is allowed to implement both Lister and
Messenger. This is useful when the messenger contains
sub-servers, such as threads.
`},
Name: "Server",
Embeds: []EmbeddedInterface{
@ -1010,6 +1009,28 @@ var Main = Packages{
`},
Name: "Lister",
Methods: []Method{
GetterMethod{
method: method{
Comment: Comment{`
Columnate is optionally used by servers to tell the
frontend whether or not its children should be put
onto a new column instead of underneath it within
the same tree. If the method returns false, then the
frontend can treat its children as normal and show
it as children within the same tree.
For example, in Discord, guilds can be placed in
guild folders, but guilds and guild folders are put
in the same column while guilds are actually
children of the folders. To replicate this behavior,
guild folders should return false, and guilds should
return true. Both channels and categories can return
false.
`},
Name: "Columnate",
},
Returns: []NamedType{{"", "bool"}},
},
ContainerMethod{
method: method{
Comment: Comment{`
@ -1050,7 +1071,6 @@ var Main = Packages{
},
HasContext: true,
ContainerType: "MessagesContainer",
HasStopFn: true,
},
AsserterMethod{ChildType: "Sender"},
AsserterMethod{ChildType: "Editor"},
@ -1188,20 +1208,13 @@ var Main = Packages{
implement ServerNickname. By default, the session name should be
used.
`},
Name: "Nicknamer",
Methods: []Method{
ContainerMethod{
method: method{Name: "Nickname"},
HasContext: true,
ContainerType: "LabelContainer",
HasStopFn: true,
},
},
Name: "Nicknamer",
Embeds: []EmbeddedInterface{{InterfaceName: "Namer"}},
}, {
Comment: Comment{`
Backlogger adds message history capabilities into a message
container. The backend should send old messages using the
MessageCreate method of the MessageContainer, and the frontend
MessageCreate method of the MessagesContainer, and the frontend
should automatically sort messages based on the timestamp.
As there is no stop callback, if the backend needs to fetch
@ -1235,7 +1248,6 @@ var Main = Packages{
Name: "Backlog",
},
Parameters: []NamedType{
{"ctx", "context.Context"},
{"before", "ID"},
{"msgc", "MessagesContainer"},
},
@ -1264,15 +1276,61 @@ var Main = Packages{
},
HasContext: true,
ContainerType: "MemberListContainer",
HasStopFn: true,
},
},
}, {
Comment: Comment{`
ReadIndicator adds a read indicator API for frontends to show.
An example of the read indicator is in Matrix, where each
message can have a small avatar indicating that the user in the
room has read the message.
`},
Name: "ReadIndicator",
Methods: []Method{
ContainerMethod{
method: method{
Comment: Comment{`
ReadIndicate subscribes the given container for read
activities. The backend must keep track of which
read states to send over to not overwhelm the
frontend, and the frontend must either keep track of
them, or it should not display it at all.
`},
Name: "ReadIndicate",
},
HasContext: true,
ContainerType: "ReadContainer",
},
},
}, {
Comment: Comment{`
UnreadIndicator adds an unread state API for frontends to use.
The unread state describes whether a channel has been read or
not by the current user. It is not to be confused with
ReadIndicator, which indicates the unread state of others.
`},
Name: "UnreadIndicator",
Methods: []Method{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
MarkRead marks a message in the server messenger as
read. Backends that implement the UnreadIndicator
interface must give control of marking messages as
read to the frontend if possible.
This method is assumed to be a setter method that
does not error out, because the frontend has no use
in knowing the error. As such, marking messages as
read is best-effort. The backend is in charge of
synchronizing the read state with the server and
coordinating it with reasonable rate limits, if
needed.
`},
Name: "MarkRead",
},
Parameters: []NamedType{{"messageID", "ID"}},
},
ContainerMethod{
method: method{
Comment: Comment{`
@ -1287,8 +1345,8 @@ var Main = Packages{
`},
Name: "UnreadIndicate",
},
HasContext: true,
ContainerType: "UnreadContainer",
HasStopFn: true,
},
},
}, {
@ -1343,8 +1401,8 @@ var Main = Packages{
`},
Name: "TypingSubscribe",
},
HasContext: true,
ContainerType: "TypingContainer",
HasStopFn: true,
},
},
}, {
@ -1394,7 +1452,7 @@ var Main = Packages{
`},
Name: "ServersContainer",
Methods: []Method{
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
SetServer is called by the backend service to
@ -1402,12 +1460,20 @@ var Main = Packages{
choose to call Servers() on each of the given
servers, or it can call that later. The backend
should handle both cases.
If the backend sets a nil server slice, then the
frontend should take that as an unavailable server
list rather than an empty server list. The server
list should only be considered empty if it's an
empty non-nil slice. An unavailable list, on the
other hand, can be treated as backend issues, e.g. a
connection issue.
`},
Name: "SetServers",
},
Parameters: []NamedType{{Type: "[]Server"}},
},
SetterMethod{
ContainerUpdaterMethod{
method: method{Name: "UpdateServer"},
Parameters: []NamedType{{Type: "ServerUpdate"}},
},
@ -1467,7 +1533,7 @@ var Main = Packages{
`},
Name: "MessagesContainer",
Methods: []Method{
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
CreateMessage inserts a message into the container.
@ -1478,11 +1544,11 @@ var Main = Packages{
},
Parameters: []NamedType{{Type: "MessageCreate"}},
},
SetterMethod{
ContainerUpdaterMethod{
method: method{Name: "UpdateMessage"},
Parameters: []NamedType{{Type: "MessageUpdate"}},
},
SetterMethod{
ContainerUpdaterMethod{
method: method{Name: "DeleteMessage"},
Parameters: []NamedType{{Type: "MessageDelete"}},
},
@ -1512,7 +1578,7 @@ var Main = Packages{
Methods: []Method{
GetterMethod{
method: method{Name: "Author"},
Returns: []NamedType{{Type: "Author"}},
Returns: []NamedType{{Type: "User"}},
},
GetterMethod{
method: method{Name: "Content"},
@ -1535,16 +1601,13 @@ var Main = Packages{
}, {
Comment: Comment{`
MessageUpdate is the interface for a message update (or edit)
event. If the returned text.Rich returns true for Empty(), then
the element shouldn't be changed.
event. It is only responsible for updating a message's content.
The author's name should be updated using MessageCreate's
Author.
`},
Name: "MessageUpdate",
Embeds: []EmbeddedInterface{{InterfaceName: "MessageHeader"}},
Methods: []Method{
GetterMethod{
method: method{Name: "Author"},
Returns: []NamedType{{Type: "Author"}},
},
GetterMethod{
method: method{Name: "Content"},
Returns: []NamedType{{
@ -1568,10 +1631,13 @@ var Main = Packages{
state and may call SetLabel any time it wants. Thus, the
frontend should synchronize calls with the main thread if
needed.
Labels given to the frontend may contain images or avatars, and
the frontend has the choice to display them or not.
`},
Name: "LabelContainer",
Methods: []Method{
SetterMethod{
ContainerUpdaterMethod{
method: method{Name: "SetLabel"},
Parameters: []NamedType{{
Type: MakeQual("text", "Rich"),
@ -1580,38 +1646,36 @@ var Main = Packages{
},
}, {
Comment: Comment{`
IconContainer is a generic interface for any container that can
hold an image. It's typically used for icons that can update
itself. Frontends should round these icons. For images that
shouldn't be rounded, use ImageContainer.
Methods may call SetIcon at any time in its main thread, so the
frontend must do any I/O (including downloading the image) in
another goroutine to avoid blocking the backend.
ReadContainer is an interface that a frontend container can
implement to show the read bubbles on messages. This container
typically implies the message container, but that is up to the
frontend's implementation.
`},
Name: "IconContainer",
Name: "ReadContainer",
Methods: []Method{
SetterMethod{
method: method{Name: "SetIcon"},
Parameters: []NamedType{{Name: "url", Type: "string"}},
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
AddIndications adds a map of users/authors to the
respective message ID of the server that implements
ReadIndicator.
`},
Name: "AddIndications",
},
Parameters: []NamedType{{"", "[]ReadIndication"}},
},
},
}, {
Comment: Comment{`
ImageContainer is a generic interface for any container that can
hold an image. It's typically used for icons that can update
itself. Frontends should not round these icons. For images that
should be rounded, use IconContainer.
Methods may call SetIcon at any time in its main thread, so the
frontend must do any I/O (including downloading the image) in
another goroutine to avoid blocking the backend.
`},
Name: "ImageContainer",
Methods: []Method{
SetterMethod{
method: method{Name: "SetImage"},
Parameters: []NamedType{{Name: "url", Type: "string"}},
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
DeleteIndications deletes a list of unused
users/authors associated with their read indicators.
The backend can use this to free up users/authors
that are no longer in the server, for example when
they are offline or have left the server.
`},
Name: "DeleteIndications",
},
Parameters: []NamedType{{"authorIDs", "[]ID"}},
},
},
}, {
@ -1634,7 +1698,7 @@ var Main = Packages{
`},
Name: "UnreadContainer",
Methods: []Method{
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
SetUnread sets the container's unread state to the
@ -1660,17 +1724,19 @@ var Main = Packages{
`},
Name: "TypingContainer",
Methods: []Method{
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
AddTyper appends the typer into the frontend's list
of typers, or it pushes this typer on top of others.
AddTyper appends the typer (author) into the
frontend's list of typers, or it pushes this typer
on top of others. The frontend should assume current
time every time AddTyper is called.
`},
Name: "AddTyper",
},
Parameters: []NamedType{{Name: "typer", Type: "Typer"}},
Parameters: []NamedType{{"", "User"}},
},
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
RemoveTyper explicitly removes the typer with the
@ -1682,21 +1748,7 @@ var Main = Packages{
`},
Name: "RemoveTyper",
},
Parameters: []NamedType{{Name: "typerID", Type: "ID"}},
},
},
}, {
Comment: Comment{`
Typer is an individual user that's typing. This interface is
used interchangably in TypingIndicator and thus
ServerMessageTypingIndicator as well.
`},
Name: "Typer",
Embeds: []EmbeddedInterface{{InterfaceName: "Author"}},
Methods: []Method{
GetterMethod{
method: method{Name: "Time"},
Returns: []NamedType{{Type: "time.Time"}},
Parameters: []NamedType{{Name: "authorID", Type: "ID"}},
},
},
}, {
@ -1724,7 +1776,7 @@ var Main = Packages{
`},
Name: "MemberListContainer",
Methods: []Method{
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
SetSections (re)sets the list of sections to be the
@ -1740,7 +1792,7 @@ var Main = Packages{
{Name: "sections", Type: "[]MemberSection"},
},
},
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
SetMember adds or updates (or upsert) a member into
@ -1748,8 +1800,13 @@ var Main = Packages{
section's member count. As such, changes should be
done separately in SetSection. If the section does
not exist, then the client should ignore this
member. As such, backends must call SetSections
first before SetMember on a new section.
member, so, backends must call SetSections first
before SetMember on a new section.
Typically, the backend should try and avoid calling
this method and instead update the labeler in the
name. This method should only be used for adding
members.
`},
Name: "SetMember",
},
@ -1758,7 +1815,7 @@ var Main = Packages{
{"member", "ListMember"},
},
},
SetterMethod{
ContainerUpdaterMethod{
method: method{
Comment: Comment{`
RemoveMember removes a member from a section. If
@ -1775,28 +1832,29 @@ var Main = Packages{
},
}, {
Comment: Comment{`
ListMember represents a single member in the member list. This
is a base interface that may implement more interfaces, such as
Iconer for the user's avatar.
ListMember represents a single member in the member list. Note
that this interface should be treated as a static container:
updating a member will involve a completely new ListMember
instance with the same ID.
Note that the frontend may give everyone an avatar regardless,
or it may not show any avatars at all.
`},
Name: "ListMember",
Embeds: []EmbeddedInterface{{
Comment: Comment{`
Identifier identifies the individual member. This works
similarly to MessageAuthor.
`},
InterfaceName: "Identifier",
}, {
Comment: Comment{`
Namer returns the name of the member. This works similarly
to a MessageAuthor.
`},
InterfaceName: "Namer",
}},
Embeds: []EmbeddedInterface{
{InterfaceName: "Identifier"},
},
Methods: []Method{
GetterMethod{
method: method{
Name: "Name",
Comment: Comment{`
Name returns the username or the nickname of the
member, whichever the backend should prefer.
`},
},
Returns: []NamedType{{Type: MakeQual("text", "Rich")}},
},
GetterMethod{
method: method{
Comment: Comment{`
@ -1911,15 +1969,28 @@ var Main = Packages{
Returns: []NamedType{{Type: "string"}},
},
AsserterMethod{ChildType: "Noncer"},
AsserterMethod{ChildType: "Attachments"},
AsserterMethod{ChildType: "Replier"},
AsserterMethod{ChildType: "Attacher"},
},
}, {
Comment: Comment{`
Attachments extends SendableMessage which adds attachments into
the message. Backends that can use this interface should
implement AttachmentSender.
Replier indicates that the message being sent is a reply to
something. Frontends that support replies can assume that all
messages in a Sender can be replied to, and the backend can
choose to do nothing to the replied ID.
`},
Name: "Attachments",
Name: "Replier",
Methods: []Method{
GetterMethod{
method: method{Name: "ReplyingTo"},
Returns: []NamedType{{Type: "ID"}},
},
},
}, {
Comment: Comment{`
Attacher adds attachments into the message being sent.
`},
Name: "Attacher",
Methods: []Method{
GetterMethod{
method: method{Name: "Attachments"},

View File

@ -37,14 +37,68 @@ type Package struct {
// Interface finds an interface. Nil is returned if none is found.
func (p Package) Interface(name string) *Interface {
for _, iface := range p.Interfaces {
for i, iface := range p.Interfaces {
if iface.Name == name {
return &iface
return &p.Interfaces[i]
}
}
return nil
}
// Struct finds a struct or an error struct. Nil is returned if none is found.
func (p Package) Struct(name string) *Struct {
for i, sstruct := range p.Structs {
if sstruct.Name == name {
return &p.Structs[i]
}
}
for i, estruct := range p.ErrorStructs {
if estruct.Name == name {
return &p.ErrorStructs[i].Struct
}
}
return nil
}
// Enum finds an enumeration. Nil is returned if none is found.
func (p Package) Enum(name string) *Enumeration {
for i, enum := range p.Enums {
if enum.Name == name {
return &p.Enums[i]
}
}
return nil
}
// TypeAlias finds a type alias. Nil is returned if none is found.
func (p Package) TypeAlias(name string) *TypeAlias {
for i, alias := range p.TypeAliases {
if alias.Name == name {
return &p.TypeAliases[i]
}
}
return nil
}
// FindType finds any type. Nil is returned if nothing is found; a pointer to
// any of the type is returned if name is found.
func (p Package) FindType(name string) interface{} {
if iface := p.Interface(name); iface != nil {
return iface
}
if sstr := p.Struct(name); sstr != nil {
return sstr
}
if enum := p.Enum(name); enum != nil {
return enum
}
if alias := p.TypeAlias(name); alias != nil {
return alias
}
return nil
}
// NamedType is an optionally named value with a type.
type NamedType struct {
Name string // optional
Type string // import/path.Type OR (import/path).Type

View File

@ -0,0 +1,34 @@
package repository
import "testing"
func TestTypeQual(t *testing.T) {
type test struct {
typePath string
path string
typ string
}
var tests = []test{
{"string", "", "string"},
{"context.Context", "context", "Context"},
{
"github.com/diamondburned/cchat/text.Rich",
"github.com/diamondburned/cchat/text", "Rich",
},
{
"(github.com/diamondburned/cchat/text).Rich",
"github.com/diamondburned/cchat/text", "Rich",
},
}
for _, test := range tests {
path, typ := TypeQual(test.typePath)
if path != test.path {
t.Errorf("Unexpected path %q != %q", path, test.path)
}
if typ != test.typ {
t.Errorf("Unexpected type %q != %q", typ, test.typ)
}
}
}

View File

@ -11,8 +11,6 @@
// shouldn't be.
package text
import cchat "cchat"
// Attribute is the type for basic rich text markup attributes.
type Attribute uint32
@ -147,7 +145,7 @@ type Mentioner interface {
// and highlight it, though this is also for appearance, so the frontend may
// decide in detail how to display it.
type MessageReferencer interface {
MessageID() cchat.ID
MessageID() string
}
// Quoteblocker represents a quoteblock that behaves similarly to the blockquote
@ -172,12 +170,13 @@ type Segment interface {
// Asserters.
AsColorer() Colorer // Optional
AsLinker() Linker // Optional
AsImager() Imager // Optional
AsAvatarer() Avatarer // Optional
AsMentioner() Mentioner // Optional
AsAttributor() Attributor // Optional
AsCodeblocker() Codeblocker // Optional
AsQuoteblocker() Quoteblocker // Optional
AsColorer() Colorer // Optional
AsLinker() Linker // Optional
AsImager() Imager // Optional
AsAvatarer() Avatarer // Optional
AsMentioner() Mentioner // Optional
AsAttributor() Attributor // Optional
AsCodeblocker() Codeblocker // Optional
AsQuoteblocker() Quoteblocker // Optional
AsMessageReferencer() MessageReferencer // Optional
}

View File

@ -11,7 +11,9 @@ func SolidColor(rgb uint32) uint32 {
return (rgb << 8) | 0xFF
}
// IsEmpty returns true if the given rich segment's content is empty.
// IsEmpty returns true if the given rich segment's content is empty. Note that
// a rich text is not necessarily empty if the content is empty, because there
// may be images within the segments.
func (r Rich) IsEmpty() bool {
return r.Content == ""
return r.Content == "" && len(r.Segments) == 0
}

View File

@ -9,18 +9,9 @@ import (
"github.com/diamondburned/cchat/text"
)
// Namer provides no-op asserters for cchat.Namer.
type Namer struct{}
// AsIconer returns nil.
func (Namer) AsIconer() cchat.Iconer { return nil }
// Service provides no-op asserters for cchat.Service.
type Service struct{}
// AsIconer returns nil.
func (Service) AsIconer() cchat.Iconer { return nil }
// AsConfigurator returns nil.
func (Service) AsConfigurator() cchat.Configurator { return nil }
@ -30,9 +21,6 @@ func (Service) AsSessionRestorer() cchat.SessionRestorer { return nil }
// Session provides no-op asserters for cchat.Session.
type Session struct{}
// AsIconer returns nil.
func (Session) AsIconer() cchat.Iconer { return nil }
// AsCommander returns nil.
func (Session) AsCommander() cchat.Commander { return nil }
@ -48,9 +36,6 @@ func (Commander) AsCompleter() cchat.Completer { return nil }
// Server provides no-op asserters for cchat.Server.
type Server struct{}
// AsIconer returns nil.
func (Server) AsIconer() cchat.Iconer { return nil }
// AsLister returns nil.
func (Server) AsLister() cchat.Lister { return nil }
@ -99,9 +84,6 @@ func (Sender) AsCompleter() cchat.Completer { return nil }
// MemberSection provides no-op asserters for cchat.MemberSection.
type MemberSection struct{}
// AsIconer returns nil.
func (MemberSection) AsIconer() cchat.Iconer { return nil }
// AsMemberDynamicSection returns nil.
func (MemberSection) AsMemberDynamicSection() cchat.MemberDynamicSection { return nil }
@ -111,8 +93,11 @@ type SendableMessage struct{}
// AsNoncer returns nil.
func (SendableMessage) AsNoncer() cchat.Noncer { return nil }
// AsAttachments returns nil.
func (SendableMessage) AsAttachments() cchat.Attachments { return nil }
// AsReplier returns nil.
func (SendableMessage) AsReplier() cchat.Replier { return nil }
// AsAttacher returns nil.
func (SendableMessage) AsAttacher() cchat.Attacher { return nil }
// TextSegment provides no-op asserters for cchat.TextSegment.
type TextSegment struct{}
@ -140,3 +125,6 @@ func (TextSegment) AsCodeblocker() text.Codeblocker { return nil }
// AsQuoteblocker returns nil.
func (TextSegment) AsQuoteblocker() text.Quoteblocker { return nil }
// AsMessageReferencer returns nil.
func (TextSegment) AsMessageReferencer() text.MessageReferencer { return nil }

View File

@ -1,3 +0,0 @@
package empty
//go:generate go run ../../cmd/internal/cchat-empty-gen