# Automation

## Список проектов автоматизации

`GET /automation/projects`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Список проектов автоматизации",
  "description": "Каждый проект, сохраненный в лаунчере, со своими блоками и настройками запуска. Это те же проекты, которые редактирует десктопный раздел **Automation**.",
  "responses": {
    "200": {
      "description": "Список проектов.",
      "content": {
        "application/json": {
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AutomationProject"
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```

## Создать проект

`POST /automation/projects`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Создать проект",
  "requestBody": {
    "required": false,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "description": "Когда пусто, используется `Untitled`."
            }
          }
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Созданный проект.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationProject"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```

## Получить проект

`GET /automation/projects/{id}`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Получить проект",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Детали проекта.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationProject"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Проект не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Заменить проект

`PUT /automation/projects/{id}`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Заменить проект",
  "description": "Заменяет весь проект. Отправьте объект, возвращенный `GET`. Идентификатор пути имеет приоритет над идентификатором тела. Отсутствующий проект возвращает `404`; используйте `POST /automation/projects`, чтобы создать его.",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/AutomationProject"
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Сохраненный проект.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationProject"
          }
        }
      }
    },
    "400": {
      "description": "Неверный объект проекта.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Проект не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Удалить проект

`DELETE /automation/projects/{id}`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Удалить проект",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Удален.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "deleted": {
                "type": "boolean",
                "example": true
              },
              "id": {
                "type": "string",
                "format": "uuid"
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Проект не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Дублировать проект

`POST /automation/projects/{id}/duplicate`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Дублировать проект",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Дублированный проект.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationProject"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Проект не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Экспортировать пакет проектов

`GET /automation/projects/{id}/export`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Экспортировать пакет проектов",
  "description": "Параметры проекта, помеченные как секретные, при выходе очищаются, поэтому пакет можно передать, не взяв с собой пароль. Импортирующая сторона снова их запрашивает.",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Экспортный пакет.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationBundle"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Проект не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Импортировать пакет проектов

`POST /automation/import`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Импортировать пакет проектов",
  "description": "Пакет поставляется как новый проект с новым идентификатором.",
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "$ref": "#/components/schemas/AutomationBundle"
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Импортированный проект.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationProject"
          }
        }
      }
    },
    "400": {
      "description": "Неверный пакет или неподдерживаемая версия формата.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    }
  }
}
```

## Начать проект

`POST /automation/projects/{id}/run`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Начать проект",
  "description": "Запускает проект и немедленно возвращается. Блоки проекта запускают необходимые браузеры. Используйте `/status` для отслеживания прогресса.\n\nВозвращает `400`, если проект уже запущен или не имеет включенных шагов.",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Проект стартовал.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "project_id": {
                "type": "string",
                "format": "uuid"
              },
              "running": {
                "type": "boolean",
                "example": true
              }
            }
          }
        }
      }
    },
    "400": {
      "description": "Проект уже запущен или не имеет включенных шагов.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Проект не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Остановить проект

`POST /automation/projects/{id}/stop`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Остановить проект",
  "description": "Запрашивает остановку запуска. Каждый браузер завершает текущий шаг перед закрытием. Используйте `/status` для отслеживания поля `running`.",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Стоп просили.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "project_id": {
                "type": "string",
                "format": "uuid"
              },
              "stopping": {
                "type": "boolean",
                "example": true
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Получить статус запуска проекта

`GET /automation/projects/{id}/status`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Получить статус запуска проекта",
  "description": "Возвращает `null`, если проект не запущен и не запускался с момента запуска лаунчера. `log` содержит последние записи, показанные в окне запусков. Полный журнал хранится в `automation-runs/`.",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string",
        "format": "uuid"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Статус выполнения или `null`.",
      "content": {
        "application/json": {
          "schema": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/AutomationRun"
              },
              {
                "type": "null"
              }
            ]
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Список активных запусков

`GET /automation/runs`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Список активных запусков",
  "responses": {
    "200": {
      "description": "Активный список запусков.",
      "content": {
        "application/json": {
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AutomationRun"
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Список установленных модулей

`GET /automation/modules`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Список установленных модулей",
  "description": "Возвращает установленные оператором модули WebAssembly. Каждый модуль добавляет блоки вида `module:<module id>:<block>`. Модули передают действия исполнителю и не обращаются к странице напрямую.",
  "responses": {
    "200": {
      "description": "Список модулей.",
      "content": {
        "application/json": {
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AutomationModule"
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Установить модуль

`POST /automation/modules`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Установить модуль",
  "description": "`path` должен указывать на локальный файл `.wasm` на хосте средства запуска. Модули содержат собственный код, созданный оператором.",
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "required": [
            "path"
          ],
          "properties": {
            "path": {
              "type": "string",
              "example": "/home/me/module.wasm"
            }
          }
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "Установленный модуль.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/AutomationModule"
          }
        }
      }
    },
    "400": {
      "description": "Отсутствует путь или неподдерживаемый файл модуля.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```

## Удалить модуль

`DELETE /automation/modules/{id}`

```json
{
  "tags": [
    "Automation"
  ],
  "summary": "Удалить модуль",
  "description": "Проекты, использующие модуль, перестают работать. Существующие определения проекта не изменяются.",
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
        "type": "string"
      }
    }
  ],
  "responses": {
    "200": {
      "description": "Удаленный.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "properties": {
              "deleted": {
                "type": "boolean",
                "example": true
              },
              "id": {
                "type": "string"
              }
            }
          }
        }
      }
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "404": {
      "description": "Модуль не найден.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    },
    "501": {
      "description": "Эта сборка не поддерживает автоматизацию.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Error"
          }
        }
      }
    }
  }
}
```
