swagger: '2.0'
info:
  version: 2.0.1
  title: Alvaria&trade; Cloud Messaging Public Chat Client REST API
  contact:
    name: Alvaria&trade;
    url: 'https://www.alvaria.com'
  license:
    name: 'License: Creative Commons Attribution 4.0 International Public License'
    url: 'https://creativecommons.org/licenses/by/4.0/legalcode'
  description: |
    # Overview
    The Alvaria&trade; Cloud Messaging Public Chat Client REST APIs enable a custom Chat application to send messages to the Alvaria&trade; Cloud system in a Streaming session. Backoff procedures should be implemented for when error conditions occur (e.g. network outages, throttling, etc).

    **Note**: These endpoints are for unauthenticated customers, not authenticated Agents. Agent sessions are defined in [Alvaria™ Cloud Streaming REST API](ViaStreamingClientExternalSwagger.html)

    # Steps to establish a Chat session

    ## Get Web Token
    The first step is to get an Alvaria&trade; Web Token, which provides organization and IP based rate limiting without requiring a user login. The return value's `tokenId` is used as the Bearer token in all subsequent REST calls.

    ```
      // Alvaria&trade; Web Token example response
      {
        "tokenId": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcmdJZCI6InBhdHMiLCJpYXQiOjE1NzYxNzc1MDQsImV4cCI6MTU3NjE4MTEwNH0.5AGaoYV0bw6bwC6NiIIK0eS5-yMbszHHN3Cnf1PMvOE",
        "expirationTime": "2020-06-02T20:28:30Z"
      }
    ```

    The Alvaria&trade; Web Token is defined in [Alvaria&trade; Cloud Web Token API](ViaJWTExternalSwagger.html).

    ## Establish a Streaming session
      ```
      // Alvaria&trade; Public Web Streaming Create Session example response
      {
        "sessionId": "ab7dbcbc-c041-4ac0-8ca0-5a0961f7be5",
        "creationTime": "1985-04-12T23:20:50.525Z",
        "inactivityDelay": 60
      }
    ```

    The end-user's browser receives server-side messages (from an agent or a self-service script) using long polling. This is initialized by creating a Streaming session to the [Create Session](ViaStreamingClientPublicChatSwagger.html#create-session) endpoint, which responds with a Streaming `sessionId`. Each poll request must contain this Streaming `sessionId` and previously created Alvaria Web Token `tokenId`.
    
    To create a Streaming `sessionId`, the following endpoint requires the newly created `tokenId`. The Streaming endpoint will internally validate the `tokenId` before returning a 200 OK and the Streaming `sessionId`. We have a default server-side Streaming session timeout of 60 seconds, which will clean up server-side session information if the end-user's browser is closed and stops polling for messages. This timeout is of particular importance to mobile web browsers and desktop browsers where the end-user will navigate to a different tab or window. Each browser implements power saving differently, so there is no guarantee a browser will continue to send long polling messages if the current browser tab/window is not active. The default timeout can be overridden during Streaming session initialization if 60 seconds is insufficient.

    After establishing a streaming session, we have a `tokenId` and a value for `via-client-sessionid`, which will be passed on all subsequent REST calls to the server.

    ### Long Polling
    ```
    // jQuery long polling example
    function LongPoll() {
      var orgId = "viademo"
      var tokenURL = new URL("https://" + orgId + ".via.aspect-cloud.net/via/v2/organizations/" + orgId + "/streaming/events/webClient?maxEvents=1")
      // Example: https://viademo.via.aspect-cloud.net/via/v2/organizations/viademo/streaming/events/webClient?maxEvents=1
    
      return $.ajax({
          url: tokenURL,
          type: 'GET',
          dataType: 'json',
          crossDomain: true,
          xhrFields: {
            withCredentials: false          // Needs to be false in order to allow cross domain calls to our endpoint.
          },
          beforeSend: function(xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + tokenId)
          },
          headers: {
            'Accept': 'application/json',
            'x-api-key': string,            // Unique to each organization.
            'via-client-sessionid': string
          },
          success: function(result) {
            if (result.totalItems && result.totalItems > 0) {
              for (const event of result.events) {
                const messageObject = JSON.parse(event.payload)
              }
            }
            // If there are no events on the server side queue after 15 seconds, 
            // the server will respond with "totalItems": 0 in the JSON payload.
    
    
            // Either way, time for the next long poll to the server
            LongPoll();
          },
          error: function(error) {
            if (error && error.responseJSON.code == 429 || error.responseJSON.code === 500)) {
              // Too many requests or server side issue - wait and try again
              window.setTimeout(LongPoll(), 5000);
            }
            else {
              // Session was closed server-side. Clean up chat session on client side, s 
              // and stop long polling server.
            }
          }
      });
    }
    ```
    To retrieve server-side messages, a long polling loop should be implemented. If no messages are available after 15 seconds, the REST GET request will return with an empty event array (see below for examples with and without an event from the server). Another GET request should be sent immediately after the response. If there are server-side messages to be retrieved within the 15 second window, it will be immediately returned and another GET request should also be sent immediately.

    Multiple events can be requested from the server in each request using the URL parameter maxEvents, which will return an array of events, but for this example we will request one event.

    Alvaria&trade; Streaming is defined in [Alvaria&trade; Cloud Streaming Public Chat Client REST API](ViaStreamingClientPublicChatSwagger.html).

    ## Connect to Messaging
    ```
      // Example connect body for Web Chat sessions
      requestBody = {
        "workTypeId": 79,
        "contactName": "Ryan Tucker",
        "contactEmail": "Ryan.Tucker@alvaria.com",
        "contactDataCollection": [{
          "contactDataKey": "szUserDefined1",
          "contactDataValue": "12345"
        }]
      }
    ```

    To send messages to the server, the Alvaria Messaging endpoint is used. The Alvaria Web Token and Streaming `sessionId` from the previous two steps needs to be passed in each message. 

    ### Messaging for WebChat

    For Web Chat sessions, the [Connect](#connect) message body must contain the `workTypeId` so the session can be properly routed and a `contactName` to be displayed to the Agent. Optional fields include an `contactEmail` address and an array of up to 20 `UserDefined` fields.

    ### Messaging for scheduling a Voice Call Back
    ```
    // Example scheduleCallBack body for Voice Call Back
    requestBody = {
      "workTypeId": 32,
      "contactName": "Joe Bloggs",
      "digits": "555 1234",
      "callBackTime": "2017-11-12T18:00:00.000Z",
      "delayStartDuration": 30,
      "contactDataCollection": [{
        "contactDataKey": "Account Number",
        "contactDataValue": "1234-5678-9999"
      }]
    }
    ```

    For Voice Call Back, the [Schedule](#schedule-callback) message body must contain the `workTypeId` so the session can be properly routed to an Outbound Voice WorkType, a `contactName` to be displayed to the Agent, a phone number (`digits`) the agent should call, and either a specific timestamp (`callBackTime`) when, or number of minutes (`delayStartDuration`) until, the call should be made. Optionally, an array of up to 20 `UserDefined` fields can be added.

    # Ending a WebChat session
    The client can end a Web Chat session one of two ways. The preferred method is to send a POST to the messaging [Disconnect](#disconnect) endpoint, which will immediately send a wrap message to the Agent (if there is one in the session), and properly dispose server-side resources related to the session. The other method is to stop sending long poll GET requests for more than sixty seconds or the value of the `inactivityDelay` override parameter optionally passed on session initialization. In this case, the server will wait the specified `inactivityDelay` seconds before cleaning up the session. 
    
    Use cases for the second method include the customer closing the browser/tab associated with the long polling requests, network disconnect, or the browser entering a sleep/power save state due to the end-user no longer focusing on the browser/tab. See [Create Session](ViaStreamingClientPublicChatSwagger.html#create-session) for more details.

    # Troubleshooting
    If you receive 401 status from the GET [Get Events](ViaStreamingClientPublicChatSwagger.html#get-events) endpoint and it contains the content shown in the panel to the right:

    ```
      {
        "message": "Invalid or expired session"
      }
    ```

    You must create a new streaming session using the POST [Create Session](ViaStreamingClientPublicChatSwagger.html#create-session) endpoint. Do not use the sessionId that caused the error in any further streaming API calls.

    # More Information
    To see all Alvaria&trade; Cloud API documentation, see the [Alvaria&trade; Cloud REST API Developer's Guide](ViaRestDeveloperGuide.html).

host: org.via.aspect-cloud.net
schemes:
  - https
consumes:
  - application/json
produces:
  - application/json
paths:
  '/via/v2/organizations/{orgId}/messaging/connect':
    post:
      operationId: Connect
      summary: Connect Messaging Session
      description: For Web Chat sessions, the first [SendText](#send-text) message must contain the `workTypeId` so the session can be properly routed and a `contactName` to be displayed to the Agent. Optional fields include an `contactEmail` address and an array of up to 20 `UserDefined` fields.
      tags:
        - Connect
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
        - name: Request
          in: body
          required: true
          schema:
            $ref: '#/definitions/Connect'
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
  '/via/v2/organizations/{orgId}/messaging/sendText':
    post:
      operationId: Send Text
      summary: A message from the client to the server can be sent asynchronously to the server using the messaging endpoint.
      description: This sends a request to the Messaging subsystem containing text on an interaction. The maximum length of the message string is 2000 characters.
      tags:
        - SendText
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
        - name: Request
          in: body
          required: true
          schema:
            $ref: '#/definitions/SendText'
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
  '/via/v2/organizations/{orgId}/messaging/pushUrl':
    post:
      operationId: Push Url
      summary: Sends Url
      description: This sends a request to the Messaging subsystem containing a URL for an interaction.
      tags:
        - PushUrl
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
        - name: Request
          in: body
          required: true
          schema:
            $ref: '#/definitions/PushUrl'
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
  '/via/v2/organizations/{orgId}/messaging/dial':
    post:
      operationId: Dial Number
      summary: Sends Phone Number
      description: Sends phone number on a text interaction to request an escalation to voice.
      tags:
        - Dial
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
        - name: Request
          in: body
          required: true
          schema:
            $ref: '#/definitions/DialRequest'
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
  '/via/v2/organizations/{orgId}/messaging/notification':
    post:
      operationId: Notification
      summary: A notification message from the client to the server can be sent asynchronously to the server using the messaging endpoint.
      description: To allow for slight message delays in transit, the next `composing` notification should be sent before the `expiresAfterSeconds` timeframe. For example, if the `expiresAfterSeconds` field is set to ten seconds, it is recommended to send the `composing` state at least once every nine seconds while the user is actively typing. The receiving entity will reset its typing indicator expiration after each `composing` notification. After the typing indicator expiration (ten seconds in this example) of not receiving the `composing` notification, the receiving party's UI will hide the typing indicator.
      tags:
        - Notification
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
        - name: Request
          in: body
          required: true
          schema:
            $ref: '#/definitions/Notification'
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
  '/via/v2/organizations/{orgId}/messaging/disconnect':
    post:
      operationId: Disconnect
      summary: Disconnect Messaging Session
      description: The client can end a Web Chat session one of two ways. The preferred method is to send a POST to this messaging endpoint, which will immediately send a wrap message to the Agent (if there is one in the session), and properly dispose server-side resources related to the session. The other method is to stop sending long poll GET requests for more than sixty seconds or the value of the `inactivityDelay` override parameter optionally passed on Streaming session initialization. In this case, the server will wait the specified `inactivityDelay` seconds before cleaning up the session. Use cases for the second method include the customer closing the browser/tab associated with the long polling requests, network disconnect, or the browser entering a sleep/power save state due to the end-user no longer focusing on the browser/tab. See [Create Session](ViaStreamingClientPublicChatSwagger.html#create-session) for more details about Streaming session initialization.
      tags:
        - Disconnect
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
  '/via/v2/organizations/{orgId}/messaging/scheduleCallBack':
    post:
      operationId: Schedule CallBack
      summary: Schedule a Voice CallBack
      description: Schedule a Voice Call Back from an Agent at a future time as either a timestamp or number of minutes in the future
      tags:
        - ScheduleCallBack
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - name: orgId
          in: path
          required: true
          type: string
          description: Name of customer organization.
        - name: x-api-key
          in: header
          required: true
          type: string
          description: Alvaria-provided value used to track API endpoint usage
        - name: via-client-sessionid
          in: header
          required: true
          type: string
          description: Identifier representing a long-lived HTTP interchange between Alvaria&trade; Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
        - name: Request
          in: body
          required: true
          schema:
            $ref: '#/definitions/ScheduleCallback'
      security:
        - Bearer: []
      responses:
        '202':
          description: Accepted
          headers:
            Access-Control-Allow-Origin:
              type: string
        '400':
          description: Bad Request
          schema:
            $ref: '#/definitions/ErrorResponse'
        '401':
          description: Unauthorized
        '404':
          description: Not Found
          schema:
            $ref: '#/definitions/ErrorResponse'
        '405':
          description: Method Not Allowed
          schema:
            $ref: '#/definitions/ErrorResponse'
        '429':
          description: Too Many Requests
          schema:
            $ref: '#/definitions/ErrorResponse'
        '500':
          description: Internal Server Error
          schema:
            $ref: '#/definitions/ErrorResponse'
definitions:
  Error:
    type: object
    properties:
      scope:
        type: string
        example: <placeholder>
      reason:
        type: string
        example: <placeholder>
      message:
        type: string
        example: <placeholder>
  ErrorResponse:
    type: object
    properties:
      code:
        type: integer
        description: HTTP error status
        example: 404
      message:
        type: string
        example: <placeholder>
      errors:
        type: array
        items:
          $ref: '#/definitions/Error'
  Connect:
    type: object
    required:
      - workTypeId
      - contactName  
    properties:
      workTypeId:
        type: string
        description: Alvaria-generated unique identifier for the WorkType.
        example: 32
      contactName:
        type: string
        description: Name of the contact client.
        example: Joe Bloggs
      contactEmail:
        type: string
        description: Email address of the contact client.
        example: Joe.Bloggs@somewhere.com
      contactDataCollection:
        type: array
        items:
          $ref: '#/definitions/ContactData'
        description: 'Name/Value pairs for use be the WorkType handler. Names to be the same format as UIP user defined data, eg szUserDefined1.'
  ContactData:
    type: object
    properties:
      contactDataKey:
        type: string
        example: UserDefined1
      contactDataValue:
        type: string
        example: 1234-5678-9999
  SendText:
    type: object
    properties:
      text:
        type: string
        description: Text entered by user
        example: Hello World!
  PushUrl:
    type: object
    properties:
      url:
        type: string
        description: Url entered by user
        example: 'https://www.bing.com/#'
  DialRequest:
    type: object
    properties:
      digits:
        type: string
        description: Contact information entered by user
        example: 555 1234
  Notification:
    type: object
    required:
      - state
      - expiresAfterSeconds
    properties:
      state:
        type: string
        enum: [composing]
        description: Client change of state notification, e.g. composing.
        example: composing
      expiresAfterSeconds:
        type: number
        description: Number of seconds the notification should be considered active. Maximum value is 30 seconds.
        example: 10
  ScheduleCallback:
    type: object
    required:
      - workTypeId
      - contactName
      - digits
    properties:
      workTypeId:
        type: string
        description: Alvaria-generated unique identifier for the WorkType.
        example: 32
      contactName:
        type: string
        description: Contact information entered by user.
        example: Joe Bloggs
      digits:
        type: string
        description: Phone number the Agent should call.
        example: 555 1234
      callBackTime:
        type: string
        format: date-time
        description: 'Time at which the call should be placed, specified in ISO 8601 format. The timezone must be sent as UTC. The request should have either callbackTime or delayStartDuration, but not both.'
        example: '2017-11-12T18:00:00.000Z'
      delayStartDuration:
        type: integer
        description: 'Number of minutes to wait before the call should be placed. The request should have either callbackTime or delayStartDuration, but not both.'
        example: 30
      contactDataCollection:
        type: array
        items:
          $ref: '#/definitions/ContactData'
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
    description: "Alvaria&trade; Web Token Authorization header using the Bearer scheme.<br/><br/>Example: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcmdJZCI6InBhdHMiLCJpYXQiOjE1NzYxNzc1MDQsImV4cCI6MTU3NjE4MTEwNH0.5AGaoYV0bw6bwC6NiIIK0eS5-yMbszHHN3Cnf1PMvOE\""
