Exchanging data with the server
*******************************

Pages normally send information to the server by submitting an answer
and moving to the next page. To exchange data with the server at other
times without leaving the page, define a custom HTTP route in
"experiment.py" and call it from the page's JavaScript.


Defining a route
================

Decorate a class method of the experiment with "experiment_route".
This route from "demos/experiments/timeline" returns a string:

   @experiment_route("/custom_route", methods=["POST", "GET"])
   @classmethod
   def custom_route(cls):
       return f"A custom route for {cls.__name__}."

"experiment_route" is imported from "dallinger.experiment". In debug
mode, this route is available at "http://localhost:5000/custom_route".
A route can return a string, a tuple, or a dictionary.

Routes are class methods (or static methods), so they have no
experiment instance. To read or write experiment variables, get one
with "get_experiment()".


Reading input and checking the participant
==========================================

Routes are publicly accessible, so check the participant's "unique_id"
before returning or changing their data. This route from
"demos/features/websocket_chatroom" reads URL parameters with Flask's
"request.args" and returns a chat room's history only to a participant
the demo has recorded as a member of that room. The demo records
membership from websocket frames whose sender nobody checks, so any
participant can join any room; real experiments should use "ChatRoom"
instead:

   @experiment_route("/chatroom_history", methods=["GET"])
   @classmethod
   def chatroom_history(cls):
       """Return the message history for a single room."""
       from flask import request

       room_id = request.args.get("room_id", "")
       participant_id = request.args.get("participant_id", "")
       unique_id = request.args.get("unique_id", "")
       participant = Participant.query.filter_by(id=participant_id).first()
       if (
           not participant
           or participant.unique_id != unique_id
           or participant.var.get("current_room") != room_id
       ):
           return success_response(messages=[])
       messages = [
           {
               "type": "message",
               "content": m.content,
               "sender": str(m.sender_id),
               "timestamp": m.creation_time.isoformat() if m.creation_time else None,
           }
           for m in (
               ChatroomDemoMessage.query.filter_by(failed=False, room_id=room_id)
               .order_by(ChatroomDemoMessage.creation_time)
               .all()
           )
       ]
       return success_response(messages=messages)

URL parameters are always strings; convert them where needed.
"success_response", from "dallinger.experiment_server.utils", returns
a JSON response with ""status": "success"" and the given keyword
arguments.


Calling a route from JavaScript
===============================

The demo's page module calls the route with "fetch", passing the
participant's identity from "psynet.uniqueId":

   async function fetchHistory() {
       const query = new URLSearchParams({
           room_id: roomId,
           participant_id: participantId,
           unique_id: psynet.uniqueId,
       });
       try {
           const response = await fetch("/chatroom_history?" + query, {
               signal: historyAbortController.signal,
           });
           const data = await response.json();
           if (!pageActive || !data.messages || data.messages.length === 0) return;
           const feed = root.querySelector("#chatroom-messages");
           feed.innerHTML = "";
           data.messages.forEach(renderMessage);
       } catch (error) {
           if (pageActive && error.name !== "AbortError") {
               psynet.log.warn("Could not load chatroom history.", error);
           }
       }
   }


The abort controller lets the page's cleanup function cancel a request
that is still running when the participant leaves the page.

"dallinger.get()" and "dallinger.post()" are shorter alternatives.
They take the parameters as an object and return a jQuery deferred:

   dallinger.get("/chatroom_history", {
       room_id: roomId,
       participant_id: psynet.participantId,
       unique_id: psynet.uniqueId,
   }).done((resp) => {
       console.log(resp.messages);
   });


Exposing a function with "expose_to_api"
========================================

For a route that doesn't need Flask's request object,
"expose_to_api()" is shorter. It makes a module-level function, or a
static method on a page class, callable at "/api/<endpoint>". These
functions from "demos/features/api" return a greeting and a random
number:

   @expose_to_api("hello")
   def hello(name):
       return f"Hello {name}!"

   @expose_to_api("random_digit_input")
   @staticmethod
   def random_number():
       return {"random_number": random.randint(0, 9999999)}

Arguments come from the query string for GET requests and from the
JSON body for POST requests (for example "/api/hello?name=world"), and
the return value is sent back as the response. A string arrives as
plain text, so a browser never runs it as HTML, and a dictionary
arrives as JSON:

   const response = await fetch("/api/random_digit_input");
   const {random_number} = await response.json();

PsyNet commits the database session after the function returns. These
endpoints are public too, so check the participant's "unique_id"
before returning or changing their data.


Saving data with POST routes
============================

By convention, GET routes only retrieve information and do not change
the server's state. Routes that save information use
"methods=["POST"]" and are called with "dallinger.post()". They must
call "db.session.commit()" after changing database objects:

       @experiment_route("/set_dollars", methods=["POST"])
       @classmethod
       def set_dollars(cls):
           try:
               participant_id = int(request.values["participant_id"])
               dollars = float(request.values["dollars"])
           except (KeyError, ValueError):
               return error_response(error_text="Invalid request")
           participant = Participant.query.filter_by(id=participant_id).one_or_none()
           if (
               participant is None
               or participant.unique_id != request.values.get("unique_id")
               or not math.isfinite(dollars)
           ):
               return error_response(error_text="Invalid request")
           participant.var.dollars = dollars
           db.session.commit()
           return success_response()

   dallinger.post("/set_dollars", {
       participant_id: psynet.participantId,
       unique_id: psynet.uniqueId,
       dollars: 1.5,
   });

Nested dictionaries and lists, and blobs such as raw media files, can
also be sent to the server. PsyNet's own response submission does
this: "submitGenericResponse" in "psynet/resources/scripts/psynet.js"
sends a JSON field plus blobs as "FormData", and "route_response" in
"psynet/experiment.py" reads them on the server.
