Chatroom
********

Modular-page chat rooms on a checked WebSocket connection.

This module exists so "ModularPage" can embed a chat UI without each
experiment reimplementing occupancy, persistence, and catch-up. The
widget opens "/experiment-socket" with the participant's
"websocket_scope", so "accept_websocket_connection()" has checked who
sends each frame. "EnableChatrooms" persists "message" frames and
sends each one, and every occupancy update, as a directed message to
the room's active members only. Nothing is broadcast on the channel,
which any connection could subscribe to.

When "show_history" is true, the widget asks for the room log after
joining and waits for it before enabling Send or painting live lines.
Frames that arrive during that wait are appended after the snapshot,
consuming snapshot matches as a multiset so two identical lines are
not collapsed to one. An empty snapshot still completes the load.

In an anonymous room ("ChatRoom(names="anonymous")"), members are not
sent each other's pseudonyms or participant IDs: each anonymous member
gets their own copy of every frame, in which the others appear under
per-room aliases ("member-1", "member-2", ... by order of first
joining the room), so the page never holds another member's
participant ID. Each membership records whether its page is anonymous.
The widget then labels the others as "GroupPrompt" does with
"names="anonymous"": "Your partner" while the viewer has met only one
other member of the room, and "Another player" once there are more.

Maintainers should treat the JSON "type" values ("join_room",
"leave_room", "request_state", "message", "occupancy_update",
"history") as the public protocol between "ChatRoom" and
"EnableChatrooms".

class psynet.chatroom.ChatMessage(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   Stores a single chat message sent during a "ModularPage" chatroom.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.chatroom.ChatRoom(room_id, show_participants=False, show_history=False, names='shown')

   Bases: "JavaScriptContributor"

   A chatroom component for use with "ModularPage".

   Configures the chatroom UI for a specific room. The server-side
   WebSocket handling is provided by "EnableChatrooms", which must be
   present in the experiment timeline.

   Parameters:
      * **room_id** -- The unique identifier for this chatroom
        instance. Can be a dynamic value computed per trial (e.g. a
        group ID). A participant can only join the room that their
        current page shows.

      * **show_participants** -- Whether to display a sidebar listing
        the participants currently in the room, by pseudonym (see
        "PseudonymScheme").

      * **show_history** -- Whether to wait for the persisted room log
        before enabling the chatroom. Live messages that arrive during
        that wait are shown after the snapshot.

      * **names** --

        How the others in the room, besides the viewer ("You"), are
        named:

        * ""shown"" (default): by pseudonym;

        * ""anonymous"": all with the same neutral figure, labelled as
          by a "GroupPrompt" with "names="anonymous"": "Your partner"
          while the viewer has met only one other member of the room,
          and "Another player" once they have met more, even if some
          have left since. The page is then not sent the others'
          pseudonyms or participant IDs, which appear under per-room
          aliases instead.

        A chat writes a name next to every message, so GroupPrompt's
        ""on_hover"" is not available.

   check_enabled(experiment)

      Raise unless the timeline has the "EnableChatrooms" element this
      room needs.

   get_css()

      Page-local CSS contributed to the hosting "ModularPage".

   get_js_page_modules()

      Lifecycle-managed JavaScript activated for the hosting page.

   get_js_vars()

      Page-local configuration contributed to the hosting page.

class psynet.chatroom.ChatRoomMember(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   Tracks room membership sessions for participants.

   A new record is created each time a participant joins a room, so
   there may be multiple records per (participant_id, room_id) pair.
   "active=True" indicates the participant is currently in the room;
   "leave_time" is set when they leave. A membership counts only while
   the participant is still on the page they joined from
   ("page_uuid"), so moving on leaves the room even if the page never
   sent "leave_room".

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.chatroom.EnableChatrooms(**kwargs)

   Bases: "NullElt", "WebSocketElt"

   Timeline element that activates the chatroom WebSocket channel.

   Place this directly in the experiment timeline whenever any
   "ModularPage" in the experiment may use a "ChatRoom" component:

      class MyExperiment(Experiment):
          timeline = Timeline(
              EnableChatrooms(),
              TrialMaker(id_="trials", trial_class=MyTrial, ...),
          )

   This is a NullElt, invisible to participants.

   handle_message(message, channel_name, participant, node, receive_time, experiment)

      Called when a WebSocket message arrives on this element's
      channel.

      Subclasses must override this method.

      Parameters:
         * **message** (*str*) -- The raw message string (typically
           JSON).

         * **channel_name** (*str*) -- The name of the channel the
           message was received on.

         * **participant** (*Participant** or **None*) -- The
           participant associated with the message, if any.

         * **node** (*Node** or **None*) -- The node associated with
           the message, if any.

         * **receive_time** (*datetime.datetime** or **None*) -- The
           server time the message was received.

         * **experiment** (*Experiment*) -- The running experiment
           instance.
