mirror of
https://github.com/Monadical-SAS/reflector.git
synced 2025-12-20 20:29:06 +00:00
Merge branch 'main' into feat-api-speaker-reassignment
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@ server/.env
|
||||
server/exportdanswer
|
||||
.vercel
|
||||
.env*.local
|
||||
dump.rdb
|
||||
|
||||
39
.vscode/launch.json
vendored
Normal file
39
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "aws-sam",
|
||||
"request": "direct-invoke",
|
||||
"name": "lambda-nodejs18.x:HelloWorldFunction (nodejs18.x)",
|
||||
"invokeTarget": {
|
||||
"target": "template",
|
||||
"templatePath": "${workspaceFolder}/aws/lambda-nodejs18.x/template.yaml",
|
||||
"logicalId": "HelloWorldFunction"
|
||||
},
|
||||
"lambda": {
|
||||
"payload": {},
|
||||
"environmentVariables": {},
|
||||
"runtime": "nodejs18.x"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "aws-sam",
|
||||
"request": "direct-invoke",
|
||||
"name": "API lambda-nodejs18.x:HelloWorldFunction (nodejs18.x)",
|
||||
"invokeTarget": {
|
||||
"target": "api",
|
||||
"templatePath": "${workspaceFolder}/aws/lambda-nodejs18.x/template.yaml",
|
||||
"logicalId": "HelloWorldFunction"
|
||||
},
|
||||
"api": {
|
||||
"path": "/hello",
|
||||
"httpMethod": "get",
|
||||
"payload": {
|
||||
"json": {}
|
||||
}
|
||||
},
|
||||
"lambda": {
|
||||
"runtime": "nodejs18.x"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
14
README.md
14
README.md
@@ -23,7 +23,7 @@ It also uses https://github.com/fief-dev for authentication, and Vercel for depl
|
||||
- [OpenAPI Code Generation](#openapi-code-generation)
|
||||
- [Back-End](#back-end)
|
||||
- [Installation](#installation-1)
|
||||
- [Start the project](#start-the-project)
|
||||
- [Start the API/Backend](#start-the-apibackend)
|
||||
- [Using docker](#using-docker)
|
||||
- [Using local GPT4All](#using-local-gpt4all)
|
||||
- [Using local files](#using-local-files)
|
||||
@@ -75,9 +75,11 @@ FIEF_URL=https://auth.reflector-ui.dev/reflector-local
|
||||
FIEF_CLIENT_ID=s03<omitted>
|
||||
FIEF_CLIENT_SECRET=<omitted>
|
||||
|
||||
EDGE_CONFIG=<omitted>
|
||||
EDGE_CONFIG=<omitted> (optional)
|
||||
```
|
||||
|
||||
Then copy config-template.ts to a new file called config.ts, this is where you will configure the features or your local project.
|
||||
|
||||
### Run the Application
|
||||
|
||||
To run the application in development mode, run:
|
||||
@@ -147,7 +149,13 @@ Start the background worker:
|
||||
celery -A reflector.worker.app worker --loglevel=info
|
||||
```
|
||||
|
||||
For crontab (only healthcheck for now), start the celery beat:
|
||||
Redis (mac specific command):
|
||||
|
||||
```bash
|
||||
redis-server
|
||||
```
|
||||
|
||||
For crontab (only healthcheck for now), start the celery beat (you don't need it on your local dev environment):
|
||||
|
||||
```bash
|
||||
celery -A reflector.worker.app beat
|
||||
|
||||
211
aws/lambda-nodejs18.x/.gitignore
vendored
Normal file
211
aws/lambda-nodejs18.x/.gitignore
vendored
Normal file
@@ -0,0 +1,211 @@
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/osx,node,linux,windows,sam
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=osx,node,linux,windows,sam
|
||||
|
||||
### Linux ###
|
||||
*~
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
|
||||
### Node ###
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
.env*.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Storybook build outputs
|
||||
.out
|
||||
.storybook-out
|
||||
storybook-static
|
||||
|
||||
# rollup.js default build output
|
||||
dist/
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# Temporary folders
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
### OSX ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### SAM ###
|
||||
# Ignore build directories for the AWS Serverless Application Model (SAM)
|
||||
# Info: https://aws.amazon.com/serverless/sam/
|
||||
# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html
|
||||
|
||||
**/.aws-sam
|
||||
|
||||
### Windows ###
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
Thumbs.db:encryptable
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
.aws-sam
|
||||
|
||||
UpdateZulipStreams/node_modules
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/osx,node,linux,windows,sam
|
||||
38
aws/lambda-nodejs18.x/README.TOOLKIT.md
Normal file
38
aws/lambda-nodejs18.x/README.TOOLKIT.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Developing AWS SAM Applications with the AWS Toolkit For Visual Studio Code
|
||||
|
||||
This project contains source code and supporting files for a serverless application that you can locally run, debug, and deploy to AWS with the AWS Toolkit For Visual Studio Code.
|
||||
|
||||
A "SAM" (serverless application model) project is a project that contains a template.yaml file which is understood by AWS tooling (such as SAM CLI, and the AWS Toolkit For Visual Studio Code).
|
||||
|
||||
## Writing and Debugging Serverless Applications
|
||||
|
||||
The code for this application will differ based on the runtime, but the path to a handler can be found in the [`template.yaml`](./template.yaml) file through a resource's `CodeUri` and `Handler` fields.
|
||||
|
||||
AWS Toolkit For Visual Studio Code supports local debugging for serverless applications through VS Code's debugger. Since this application was created by the AWS Toolkit, launch configurations for all included handlers have been generated and can be found in the menu next to the Run button:
|
||||
|
||||
* lambda-nodejs18.x:HelloWorldFunction (nodejs18.x)
|
||||
* API lambda-nodejs18.x:HelloWorldFunction (nodejs18.x)
|
||||
|
||||
You can debug the Lambda handlers locally by adding a breakpoint to the source file, then running the launch configuration. This works by using Docker on your local machine.
|
||||
|
||||
Invocation parameters, including payloads and request parameters, can be edited either by the `Edit SAM Debug Configuration` command (through the Command Palette or CodeLens) or by editing the `launch.json` file.
|
||||
|
||||
AWS Lambda functions not defined in the [`template.yaml`](./template.yaml) file can be invoked and debugged by creating a launch configuration through the CodeLens over the function declaration, or with the `Add SAM Debug Configuration` command.
|
||||
|
||||
## Deploying Serverless Applications
|
||||
|
||||
You can deploy a serverless application by invoking the `AWS: Deploy SAM application` command through the Command Palette or by right-clicking the Lambda node in the AWS Explorer and entering the deployment region, a valid S3 bucket from the region, and the name of a CloudFormation stack to deploy to. You can monitor your deployment's progress through the `AWS Toolkit` Output Channel.
|
||||
|
||||
## Interacting With Deployed Serverless Applications
|
||||
|
||||
A successfully-deployed serverless application can be found in the AWS Explorer under region and CloudFormation node that the serverless application was deployed to.
|
||||
|
||||
In the AWS Explorer, you can invoke _remote_ AWS Lambda Functions by right-clicking the Lambda node and selecting "Invoke on AWS".
|
||||
|
||||
Similarly, if the Function declaration contained an API Gateway event, the API Gateway API can be found in the API Gateway node under the region node the serverless application was deployed to, and can be invoked via right-clicking the API node and selecting "Invoke on AWS".
|
||||
|
||||
## Resources
|
||||
|
||||
General information about this SAM project can be found in the [`README.md`](./README.md) file in this folder.
|
||||
|
||||
More information about using the AWS Toolkit For Visual Studio Code with serverless applications can be found [in the AWS documentation](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/serverless-apps.html) .
|
||||
127
aws/lambda-nodejs18.x/README.md
Normal file
127
aws/lambda-nodejs18.x/README.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# lambda-nodejs18.x
|
||||
|
||||
This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
|
||||
|
||||
- hello-world - Code for the application's Lambda function.
|
||||
- events - Invocation events that you can use to invoke the function.
|
||||
- hello-world/tests - Unit tests for the application code.
|
||||
- template.yaml - A template that defines the application's AWS resources.
|
||||
|
||||
The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
|
||||
|
||||
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit.
|
||||
The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
|
||||
|
||||
* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
|
||||
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
|
||||
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
|
||||
|
||||
## Deploy the sample application
|
||||
|
||||
The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
|
||||
|
||||
To use the SAM CLI, you need the following tools.
|
||||
|
||||
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
|
||||
* Node.js - [Install Node.js 18](https://nodejs.org/en/), including the NPM package management tool.
|
||||
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
|
||||
|
||||
To build and deploy your application for the first time, run the following in your shell:
|
||||
|
||||
```bash
|
||||
sam build
|
||||
sam deploy --guided
|
||||
```
|
||||
|
||||
The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:
|
||||
|
||||
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
|
||||
* **AWS Region**: The AWS region you want to deploy your app to.
|
||||
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
|
||||
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
|
||||
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
|
||||
|
||||
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
|
||||
|
||||
## Use the SAM CLI to build and test locally
|
||||
|
||||
Build your application with the `sam build` command.
|
||||
|
||||
```bash
|
||||
lambda-nodejs18.x$ sam build
|
||||
```
|
||||
|
||||
The SAM CLI installs dependencies defined in `hello-world/package.json`, creates a deployment package, and saves it in the `.aws-sam/build` folder.
|
||||
|
||||
Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
|
||||
|
||||
Run functions locally and invoke them with the `sam local invoke` command.
|
||||
|
||||
```bash
|
||||
lambda-nodejs18.x$ sam local invoke HelloWorldFunction --event events/event.json
|
||||
```
|
||||
|
||||
The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
|
||||
|
||||
```bash
|
||||
lambda-nodejs18.x$ sam local start-api
|
||||
lambda-nodejs18.x$ curl http://localhost:3000/
|
||||
```
|
||||
|
||||
The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.
|
||||
|
||||
```yaml
|
||||
Events:
|
||||
HelloWorld:
|
||||
Type: Api
|
||||
Properties:
|
||||
Path: /hello
|
||||
Method: get
|
||||
```
|
||||
|
||||
## Add a resource to your application
|
||||
The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.
|
||||
|
||||
## Fetch, tail, and filter Lambda function logs
|
||||
|
||||
To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
|
||||
|
||||
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
|
||||
|
||||
```bash
|
||||
lambda-nodejs18.x$ sam logs -n HelloWorldFunction --stack-name lambda-nodejs18.x --tail
|
||||
```
|
||||
|
||||
You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
|
||||
|
||||
## Unit tests
|
||||
|
||||
Tests are defined in the `hello-world/tests` folder in this project. Use NPM to install the [Mocha test framework](https://mochajs.org/) and run unit tests.
|
||||
|
||||
```bash
|
||||
lambda-nodejs18.x$ cd hello-world
|
||||
hello-world$ npm install
|
||||
hello-world$ npm run test
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
|
||||
|
||||
```bash
|
||||
sam delete --stack-name lambda-nodejs18.x
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.
|
||||
|
||||
Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)
|
||||
71
aws/lambda-nodejs18.x/UpdateZulipStreams/index.js
Normal file
71
aws/lambda-nodejs18.x/UpdateZulipStreams/index.js
Normal file
@@ -0,0 +1,71 @@
|
||||
|
||||
|
||||
const AWS = require('aws-sdk');
|
||||
const s3 = new AWS.S3();
|
||||
const axios = require('axios');
|
||||
|
||||
async function getTopics(stream_id) {
|
||||
const response = await axios.get(`https://${process.env.ZULIP_REALM}/api/v1/users/me/${stream_id}/topics`, {
|
||||
auth: {
|
||||
username: process.env.ZULIP_BOT_EMAIL || "?",
|
||||
password: process.env.ZULIP_API_KEY || "?"
|
||||
}
|
||||
});
|
||||
return response.data.topics.map(topic => topic.name);
|
||||
}
|
||||
|
||||
async function getStreams() {
|
||||
|
||||
const response = await axios.get(`https://${process.env.ZULIP_REALM}/api/v1/streams`, {
|
||||
auth: {
|
||||
username: process.env.ZULIP_BOT_EMAIL || "?",
|
||||
password: process.env.ZULIP_API_KEY || "?"
|
||||
}
|
||||
});
|
||||
|
||||
const streams = [];
|
||||
for (const stream of response.data.streams) {
|
||||
console.log("Loading topics for " + stream.name);
|
||||
const topics = await getTopics(stream.stream_id);
|
||||
streams.push({ id: stream.stream_id, name: stream.name, topics });
|
||||
}
|
||||
|
||||
return streams;
|
||||
|
||||
}
|
||||
|
||||
|
||||
const handler = async (event) => {
|
||||
const streams = await getStreams();
|
||||
|
||||
// Convert the streams to JSON
|
||||
const json_data = JSON.stringify(streams);
|
||||
|
||||
const bucketName = process.env.S3BUCKET_NAME;
|
||||
const fileName = process.env.S3BUCKET_FILE_NAME;
|
||||
|
||||
// Parameters for S3 upload
|
||||
const params = {
|
||||
Bucket: bucketName,
|
||||
Key: fileName,
|
||||
Body: json_data,
|
||||
ContentType: 'application/json'
|
||||
};
|
||||
|
||||
try {
|
||||
// Write the JSON data to S3
|
||||
await s3.putObject(params).promise();
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: JSON.stringify('File written to S3 successfully')
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error writing to S3:', error);
|
||||
return {
|
||||
statusCode: 500,
|
||||
body: JSON.stringify('Error writing file to S3')
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { handler };
|
||||
1462
aws/lambda-nodejs18.x/UpdateZulipStreams/package-lock.json
generated
Normal file
1462
aws/lambda-nodejs18.x/UpdateZulipStreams/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
16
aws/lambda-nodejs18.x/UpdateZulipStreams/package.json
Normal file
16
aws/lambda-nodejs18.x/UpdateZulipStreams/package.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "updatezulipstreams",
|
||||
"version": "1.0.0",
|
||||
"description": "Updates the JSON with the zulip streams and topics on S3",
|
||||
"main": "index.js",
|
||||
"author": "Andreas Bonini",
|
||||
"license": "All rights reserved",
|
||||
"dependencies": {
|
||||
"aws-sdk": "^2.1498.0",
|
||||
"axios": "^1.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chai": "^4.3.6",
|
||||
"mocha": "^10.1.0"
|
||||
}
|
||||
}
|
||||
62
aws/lambda-nodejs18.x/events/event.json
Normal file
62
aws/lambda-nodejs18.x/events/event.json
Normal file
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"body": "{\"message\": \"hello world\"}",
|
||||
"resource": "/{proxy+}",
|
||||
"path": "/path/to/resource",
|
||||
"httpMethod": "POST",
|
||||
"isBase64Encoded": false,
|
||||
"queryStringParameters": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"pathParameters": {
|
||||
"proxy": "/path/to/resource"
|
||||
},
|
||||
"stageVariables": {
|
||||
"baz": "qux"
|
||||
},
|
||||
"headers": {
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
|
||||
"Accept-Encoding": "gzip, deflate, sdch",
|
||||
"Accept-Language": "en-US,en;q=0.8",
|
||||
"Cache-Control": "max-age=0",
|
||||
"CloudFront-Forwarded-Proto": "https",
|
||||
"CloudFront-Is-Desktop-Viewer": "true",
|
||||
"CloudFront-Is-Mobile-Viewer": "false",
|
||||
"CloudFront-Is-SmartTV-Viewer": "false",
|
||||
"CloudFront-Is-Tablet-Viewer": "false",
|
||||
"CloudFront-Viewer-Country": "US",
|
||||
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
"User-Agent": "Custom User Agent String",
|
||||
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
|
||||
"X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
|
||||
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
|
||||
"X-Forwarded-Port": "443",
|
||||
"X-Forwarded-Proto": "https"
|
||||
},
|
||||
"requestContext": {
|
||||
"accountId": "123456789012",
|
||||
"resourceId": "123456",
|
||||
"stage": "prod",
|
||||
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
|
||||
"requestTime": "09/Apr/2015:12:34:56 +0000",
|
||||
"requestTimeEpoch": 1428582896000,
|
||||
"identity": {
|
||||
"cognitoIdentityPoolId": null,
|
||||
"accountId": null,
|
||||
"cognitoIdentityId": null,
|
||||
"caller": null,
|
||||
"accessKey": null,
|
||||
"sourceIp": "127.0.0.1",
|
||||
"cognitoAuthenticationType": null,
|
||||
"cognitoAuthenticationProvider": null,
|
||||
"userArn": null,
|
||||
"userAgent": "Custom User Agent String",
|
||||
"user": null
|
||||
},
|
||||
"path": "/prod/path/to/resource",
|
||||
"resourcePath": "/{proxy+}",
|
||||
"httpMethod": "POST",
|
||||
"apiId": "1234567890",
|
||||
"protocol": "HTTP/1.1"
|
||||
}
|
||||
}
|
||||
31
aws/lambda-nodejs18.x/samconfig.toml
Normal file
31
aws/lambda-nodejs18.x/samconfig.toml
Normal file
@@ -0,0 +1,31 @@
|
||||
# More information about the configuration file can be found here:
|
||||
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
|
||||
version = 0.1
|
||||
|
||||
[default]
|
||||
[default.global.parameters]
|
||||
stack_name = "lambda-nodejs18.x"
|
||||
|
||||
[default.build.parameters]
|
||||
cached = true
|
||||
parallel = true
|
||||
|
||||
[default.validate.parameters]
|
||||
lint = true
|
||||
|
||||
[default.deploy.parameters]
|
||||
capabilities = "CAPABILITY_IAM"
|
||||
confirm_changeset = true
|
||||
resolve_s3 = true
|
||||
|
||||
[default.package.parameters]
|
||||
resolve_s3 = true
|
||||
|
||||
[default.sync.parameters]
|
||||
watch = true
|
||||
|
||||
[default.local_start_api.parameters]
|
||||
warm_containers = "EAGER"
|
||||
|
||||
[default.local_start_lambda.parameters]
|
||||
warm_containers = "EAGER"
|
||||
41
aws/lambda-nodejs18.x/template.yaml
Normal file
41
aws/lambda-nodejs18.x/template.yaml
Normal file
@@ -0,0 +1,41 @@
|
||||
AWSTemplateFormatVersion: '2010-09-09'
|
||||
Transform: AWS::Serverless-2016-10-31
|
||||
Description: >
|
||||
lambda-nodejs18.x
|
||||
|
||||
Sample SAM Template for lambda-nodejs18.x
|
||||
|
||||
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
|
||||
Globals:
|
||||
Function:
|
||||
Timeout: 3
|
||||
|
||||
Resources:
|
||||
HelloWorldFunction:
|
||||
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
|
||||
Properties:
|
||||
CodeUri: hello-world/
|
||||
Handler: app.lambdaHandler
|
||||
Runtime: nodejs18.x
|
||||
Architectures:
|
||||
- arm64
|
||||
Events:
|
||||
HelloWorld:
|
||||
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
|
||||
Properties:
|
||||
Path: /hello
|
||||
Method: get
|
||||
|
||||
Outputs:
|
||||
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
|
||||
# Find out more about other implicit resources you can reference within SAM
|
||||
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
|
||||
HelloWorldApi:
|
||||
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
|
||||
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
|
||||
HelloWorldFunction:
|
||||
Description: "Hello World Lambda Function ARN"
|
||||
Value: !GetAtt HelloWorldFunction.Arn
|
||||
HelloWorldFunctionIamRole:
|
||||
Description: "Implicit IAM Role created for Hello World function"
|
||||
Value: !GetAtt HelloWorldFunctionRole.Arn
|
||||
2
server/.gitignore
vendored
2
server/.gitignore
vendored
@@ -178,3 +178,5 @@ audio_*.wav
|
||||
# ignore local database
|
||||
reflector.sqlite3
|
||||
data/
|
||||
|
||||
dump.rdb
|
||||
|
||||
18
server/poetry.lock
generated
18
server/poetry.lock
generated
@@ -1,4 +1,4 @@
|
||||
# This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand.
|
||||
# This file is automatically @generated by Poetry 1.7.0 and should not be changed by hand.
|
||||
|
||||
[[package]]
|
||||
name = "aioboto3"
|
||||
@@ -2881,6 +2881,20 @@ cryptography = ["cryptography (>=3.4.0)"]
|
||||
pycrypto = ["pyasn1", "pycrypto (>=2.6.0,<2.7.0)"]
|
||||
pycryptodome = ["pyasn1", "pycryptodome (>=3.3.1,<4.0.0)"]
|
||||
|
||||
[[package]]
|
||||
name = "python-multipart"
|
||||
version = "0.0.6"
|
||||
description = "A streaming multipart parser for Python"
|
||||
optional = false
|
||||
python-versions = ">=3.7"
|
||||
files = [
|
||||
{file = "python_multipart-0.0.6-py3-none-any.whl", hash = "sha256:ee698bab5ef148b0a760751c261902cd096e57e10558e11aca17646b74ee1c18"},
|
||||
{file = "python_multipart-0.0.6.tar.gz", hash = "sha256:e9925a80bb668529f1b67c7fdb0a5dacdd7cbfc6fb0bff3ea443fe22bdd62132"},
|
||||
]
|
||||
|
||||
[package.extras]
|
||||
dev = ["atomicwrites (==1.2.1)", "attrs (==19.2.0)", "coverage (==6.5.0)", "hatch", "invoke (==1.7.3)", "more-itertools (==4.3.0)", "pbr (==4.3.0)", "pluggy (==1.0.0)", "py (==1.11.0)", "pytest (==7.2.0)", "pytest-cov (==4.0.0)", "pytest-timeout (==2.1.0)", "pyyaml (==5.1)"]
|
||||
|
||||
[[package]]
|
||||
name = "pyyaml"
|
||||
version = "6.0.1"
|
||||
@@ -4219,4 +4233,4 @@ multidict = ">=4.0"
|
||||
[metadata]
|
||||
lock-version = "2.0"
|
||||
python-versions = "^3.11"
|
||||
content-hash = "91d85539f5093abad70e34aa4d533272d6a2e2bbdb539c7968fe79c28b50d01a"
|
||||
content-hash = "b823010302af2dcd2ece591eaf10d5cbf945f74bd0fc35fc69f3060c0c253d57"
|
||||
|
||||
@@ -36,6 +36,7 @@ profanityfilter = "^2.0.6"
|
||||
celery = "^5.3.4"
|
||||
redis = "^5.0.1"
|
||||
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
|
||||
python-multipart = "^0.0.6"
|
||||
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
|
||||
@@ -18,6 +18,7 @@ from reflector.views.transcripts_participants import (
|
||||
router as transcripts_participants_router,
|
||||
)
|
||||
from reflector.views.transcripts_speaker import router as transcripts_speaker_router
|
||||
from reflector.views.transcripts_upload import router as transcripts_upload_router
|
||||
from reflector.views.transcripts_webrtc import router as transcripts_webrtc_router
|
||||
from reflector.views.transcripts_websocket import router as transcripts_websocket_router
|
||||
from reflector.views.user import router as user_router
|
||||
@@ -70,6 +71,7 @@ app.include_router(transcripts_router, prefix="/v1")
|
||||
app.include_router(transcripts_audio_router, prefix="/v1")
|
||||
app.include_router(transcripts_participants_router, prefix="/v1")
|
||||
app.include_router(transcripts_speaker_router, prefix="/v1")
|
||||
app.include_router(transcripts_upload_router, prefix="/v1")
|
||||
app.include_router(transcripts_websocket_router, prefix="/v1")
|
||||
app.include_router(transcripts_webrtc_router, prefix="/v1")
|
||||
app.include_router(user_router, prefix="/v1")
|
||||
|
||||
@@ -474,6 +474,15 @@ class PipelineMainWaveform(PipelineMainFromTopics):
|
||||
]
|
||||
|
||||
|
||||
@get_transcript
|
||||
async def pipeline_remove_upload(transcript: Transcript, logger: Logger):
|
||||
logger.info("Starting remove upload")
|
||||
uploads = transcript.data_path.glob("upload.*")
|
||||
for upload in uploads:
|
||||
upload.unlink(missing_ok=True)
|
||||
logger.info("Remove upload done")
|
||||
|
||||
|
||||
@get_transcript
|
||||
async def pipeline_waveform(transcript: Transcript, logger: Logger):
|
||||
logger.info("Starting waveform")
|
||||
@@ -560,6 +569,12 @@ async def pipeline_summaries(transcript: Transcript, logger: Logger):
|
||||
# ===================================================================
|
||||
|
||||
|
||||
@shared_task
|
||||
@asynctask
|
||||
async def task_pipeline_remove_upload(*, transcript_id: str):
|
||||
await pipeline_remove_upload(transcript_id=transcript_id)
|
||||
|
||||
|
||||
@shared_task
|
||||
@asynctask
|
||||
async def task_pipeline_waveform(*, transcript_id: str):
|
||||
@@ -604,6 +619,7 @@ def pipeline_post(*, transcript_id: str):
|
||||
task_pipeline_waveform.si(transcript_id=transcript_id)
|
||||
| task_pipeline_convert_to_mp3.si(transcript_id=transcript_id)
|
||||
| task_pipeline_upload_mp3.si(transcript_id=transcript_id)
|
||||
| task_pipeline_remove_upload.si(transcript_id=transcript_id)
|
||||
| task_pipeline_diarization.si(transcript_id=transcript_id)
|
||||
)
|
||||
chain_title_preview = task_pipeline_title_and_short_summary.si(
|
||||
@@ -618,3 +634,47 @@ def pipeline_post(*, transcript_id: str):
|
||||
chain_final_summaries,
|
||||
)
|
||||
chain.delay()
|
||||
|
||||
|
||||
@get_transcript
|
||||
async def pipeline_upload(transcript: Transcript, logger: Logger):
|
||||
import av
|
||||
|
||||
try:
|
||||
# open audio
|
||||
upload_filename = next(transcript.data_path.glob("upload.*"))
|
||||
container = av.open(upload_filename.as_posix())
|
||||
|
||||
# create pipeline
|
||||
pipeline = PipelineMainLive(transcript_id=transcript.id)
|
||||
pipeline.start()
|
||||
|
||||
# push audio to pipeline
|
||||
try:
|
||||
logger.info("Start pushing audio into the pipeline")
|
||||
for frame in container.decode(audio=0):
|
||||
pipeline.push(frame)
|
||||
finally:
|
||||
logger.info("Flushing the pipeline")
|
||||
pipeline.flush()
|
||||
|
||||
logger.info("Waiting for the pipeline to end")
|
||||
await pipeline.join()
|
||||
|
||||
except Exception as exc:
|
||||
logger.error("Pipeline error", exc_info=exc)
|
||||
await transcripts_controller.update(
|
||||
transcript,
|
||||
{
|
||||
"status": "error",
|
||||
},
|
||||
)
|
||||
raise
|
||||
|
||||
logger.info("Pipeline ended")
|
||||
|
||||
|
||||
@shared_task
|
||||
@asynctask
|
||||
async def task_pipeline_upload(*, transcript_id: str):
|
||||
return await pipeline_upload(transcript_id=transcript_id)
|
||||
|
||||
@@ -30,7 +30,8 @@ class PipelineRunner(BaseModel):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._q_cmd = asyncio.Queue()
|
||||
self._task = None
|
||||
self._q_cmd = asyncio.Queue(maxsize=4096)
|
||||
self._ev_done = asyncio.Event()
|
||||
self._is_first_push = True
|
||||
self._logger = logger.bind(
|
||||
@@ -49,7 +50,14 @@ class PipelineRunner(BaseModel):
|
||||
"""
|
||||
Start the pipeline as a coroutine task
|
||||
"""
|
||||
asyncio.get_event_loop().create_task(self.run())
|
||||
self._task = asyncio.get_event_loop().create_task(self.run())
|
||||
|
||||
async def join(self):
|
||||
"""
|
||||
Wait for the pipeline to finish
|
||||
"""
|
||||
if self._task:
|
||||
await self._task
|
||||
|
||||
def start_sync(self):
|
||||
"""
|
||||
|
||||
79
server/reflector/views/transcripts_upload.py
Normal file
79
server/reflector/views/transcripts_upload.py
Normal file
@@ -0,0 +1,79 @@
|
||||
from typing import Annotated, Optional
|
||||
|
||||
import av
|
||||
import reflector.auth as auth
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from pydantic import BaseModel
|
||||
from reflector.db.transcripts import transcripts_controller
|
||||
from reflector.pipelines.main_live_pipeline import task_pipeline_upload
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class UploadStatus(BaseModel):
|
||||
status: str
|
||||
|
||||
|
||||
@router.post("/transcripts/{transcript_id}/record/upload")
|
||||
async def transcript_record_upload(
|
||||
transcript_id: str,
|
||||
file: UploadFile,
|
||||
user: Annotated[Optional[auth.UserInfo], Depends(auth.current_user_optional)],
|
||||
):
|
||||
user_id = user["sub"] if user else None
|
||||
transcript = await transcripts_controller.get_by_id_for_http(
|
||||
transcript_id, user_id=user_id
|
||||
)
|
||||
|
||||
if transcript.locked:
|
||||
raise HTTPException(status_code=400, detail="Transcript is locked")
|
||||
|
||||
# ensure there is no other upload in the directory (searching data_path/upload.*)
|
||||
if any(transcript.data_path.glob("upload.*")):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="There is already an upload in progress"
|
||||
)
|
||||
|
||||
# save the file to the transcript folder
|
||||
extension = file.filename.split(".")[-1]
|
||||
upload_filename = transcript.data_path / f"upload.{extension}"
|
||||
upload_filename.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ensure the file is back to the beginning
|
||||
await file.seek(0)
|
||||
|
||||
# save the file to the transcript folder
|
||||
try:
|
||||
with open(upload_filename, "wb") as f:
|
||||
while True:
|
||||
chunk = await file.read(16384)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
except Exception:
|
||||
upload_filename.unlink()
|
||||
raise
|
||||
|
||||
# ensure the file have audio part, using av
|
||||
# XXX Trying to do this check on the initial UploadFile object is not
|
||||
# possible, dunno why. UploadFile.file has no name.
|
||||
# Trying to pass UploadFile.file with format=extension does not work
|
||||
# it never detect audio stream...
|
||||
container = av.open(upload_filename.as_posix())
|
||||
try:
|
||||
if not len(container.streams.audio):
|
||||
raise HTTPException(status_code=400, detail="File has no audio stream")
|
||||
except Exception:
|
||||
# delete the uploaded file
|
||||
upload_filename.unlink()
|
||||
raise
|
||||
finally:
|
||||
container.close()
|
||||
|
||||
# set the status to "uploaded"
|
||||
await transcripts_controller.update(transcript, {"status": "uploaded"})
|
||||
|
||||
# launch a background task to process the file
|
||||
task_pipeline_upload.delay(transcript_id=transcript_id)
|
||||
|
||||
return UploadStatus(status="ok")
|
||||
@@ -1,27 +1,32 @@
|
||||
import celery
|
||||
import structlog
|
||||
from celery import Celery
|
||||
from reflector.settings import settings
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
app = Celery(__name__)
|
||||
app.conf.broker_url = settings.CELERY_BROKER_URL
|
||||
app.conf.result_backend = settings.CELERY_RESULT_BACKEND
|
||||
app.conf.broker_connection_retry_on_startup = True
|
||||
app.autodiscover_tasks(
|
||||
if celery.current_app.main != "default":
|
||||
logger.info(f"Celery already configured ({celery.current_app})")
|
||||
app = celery.current_app
|
||||
else:
|
||||
app = Celery(__name__)
|
||||
app.conf.broker_url = settings.CELERY_BROKER_URL
|
||||
app.conf.result_backend = settings.CELERY_RESULT_BACKEND
|
||||
app.conf.broker_connection_retry_on_startup = True
|
||||
app.autodiscover_tasks(
|
||||
[
|
||||
"reflector.pipelines.main_live_pipeline",
|
||||
"reflector.worker.healthcheck",
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
# crontab
|
||||
app.conf.beat_schedule = {}
|
||||
# crontab
|
||||
app.conf.beat_schedule = {}
|
||||
|
||||
if settings.HEALTHCHECK_URL:
|
||||
if settings.HEALTHCHECK_URL:
|
||||
app.conf.beat_schedule["healthcheck_ping"] = {
|
||||
"task": "reflector.worker.healthcheck.healthcheck_ping",
|
||||
"schedule": 60.0 * 10,
|
||||
}
|
||||
logger.info("Healthcheck enabled", url=settings.HEALTHCHECK_URL)
|
||||
else:
|
||||
else:
|
||||
logger.warning("Healthcheck disabled, no url configured")
|
||||
|
||||
@@ -165,6 +165,11 @@ def celery_config():
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def celery_includes():
|
||||
return ["reflector.pipelines.main_live_pipeline"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def fake_mp3_upload():
|
||||
with patch(
|
||||
|
||||
@@ -32,7 +32,7 @@ class ThreadedUvicorn:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def appserver(tmpdir, celery_session_app, celery_session_worker):
|
||||
async def appserver(tmpdir, setup_database, celery_session_app, celery_session_worker):
|
||||
from reflector.settings import settings
|
||||
from reflector.app import app
|
||||
|
||||
@@ -57,6 +57,7 @@ def celery_includes():
|
||||
return ["reflector.pipelines.main_live_pipeline"]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("setup_database")
|
||||
@pytest.mark.usefixtures("celery_session_app")
|
||||
@pytest.mark.usefixtures("celery_session_worker")
|
||||
@pytest.mark.asyncio
|
||||
@@ -213,6 +214,7 @@ async def test_transcript_rtc_and_websocket(
|
||||
assert audio_resp.headers["Content-Type"] == "audio/mpeg"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("setup_database")
|
||||
@pytest.mark.usefixtures("celery_session_app")
|
||||
@pytest.mark.usefixtures("celery_session_worker")
|
||||
@pytest.mark.asyncio
|
||||
|
||||
61
server/tests/test_transcripts_upload.py
Normal file
61
server/tests/test_transcripts_upload.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import pytest
|
||||
import asyncio
|
||||
from httpx import AsyncClient
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("setup_database")
|
||||
@pytest.mark.usefixtures("celery_session_app")
|
||||
@pytest.mark.usefixtures("celery_session_worker")
|
||||
@pytest.mark.asyncio
|
||||
async def test_transcript_upload_file(
|
||||
tmpdir,
|
||||
ensure_casing,
|
||||
dummy_llm,
|
||||
dummy_processors,
|
||||
dummy_diarization,
|
||||
dummy_storage,
|
||||
):
|
||||
from reflector.app import app
|
||||
|
||||
ac = AsyncClient(app=app, base_url="http://test/v1")
|
||||
|
||||
# create a transcript
|
||||
response = await ac.post("/transcripts", json={"name": "test"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "idle"
|
||||
tid = response.json()["id"]
|
||||
|
||||
# upload mp3
|
||||
response = await ac.post(
|
||||
f"/transcripts/{tid}/record/upload",
|
||||
files={
|
||||
"file": (
|
||||
"test_short.wav",
|
||||
open("tests/records/test_short.wav", "rb"),
|
||||
"audio/mpeg",
|
||||
)
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
|
||||
# wait the processing to finish
|
||||
while True:
|
||||
# fetch the transcript and check if it is ended
|
||||
resp = await ac.get(f"/transcripts/{tid}")
|
||||
assert resp.status_code == 200
|
||||
if resp.json()["status"] in ("ended", "error"):
|
||||
break
|
||||
await asyncio.sleep(1)
|
||||
|
||||
# check the transcript is ended
|
||||
transcript = resp.json()
|
||||
assert transcript["status"] == "ended"
|
||||
assert transcript["short_summary"] == "LLM SHORT SUMMARY"
|
||||
assert transcript["title"] == "LLM TITLE"
|
||||
|
||||
# check topics and transcript
|
||||
response = await ac.get(f"/transcripts/{tid}/topics")
|
||||
assert response.status_code == 200
|
||||
assert len(response.json()) == 1
|
||||
assert "want to share" in response.json()[0]["transcript"]
|
||||
2
www/.gitignore
vendored
2
www/.gitignore
vendored
@@ -39,3 +39,5 @@ next-env.d.ts
|
||||
|
||||
# Sentry Auth Token
|
||||
.sentryclirc
|
||||
|
||||
config.ts
|
||||
@@ -9,9 +9,11 @@ export const DomainContext = createContext<DomainContextType>({
|
||||
requireLogin: false,
|
||||
privacy: true,
|
||||
browse: false,
|
||||
sendToZulip: false,
|
||||
},
|
||||
api_url: "",
|
||||
websocket_url: "",
|
||||
zulip_streams: "",
|
||||
});
|
||||
|
||||
export const DomainContextProvider = ({
|
||||
@@ -38,9 +40,10 @@ export const DomainContextProvider = ({
|
||||
|
||||
// Get feature config client-side with
|
||||
export const featureEnabled = (
|
||||
featureName: "requireLogin" | "privacy" | "browse",
|
||||
featureName: "requireLogin" | "privacy" | "browse" | "sendToZulip",
|
||||
) => {
|
||||
const context = useContext(DomainContext);
|
||||
|
||||
return context.features[featureName] as boolean | undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -12,11 +12,13 @@ import FinalSummary from "../finalSummary";
|
||||
import ShareLink from "../shareLink";
|
||||
import QRCode from "react-qr-code";
|
||||
import TranscriptTitle from "../transcriptTitle";
|
||||
import ShareModal from "./shareModal";
|
||||
import Player from "../player";
|
||||
import WaveformLoading from "../waveformLoading";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { faSpinner } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { featureEnabled } from "../../domainContext";
|
||||
|
||||
type TranscriptDetails = {
|
||||
params: {
|
||||
@@ -33,6 +35,7 @@ export default function TranscriptDetails(details: TranscriptDetails) {
|
||||
const waveform = useWaveform(transcriptId);
|
||||
const useActiveTopic = useState<Topic | null>(null);
|
||||
const mp3 = useMp3(transcriptId);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const statusToRedirect = ["idle", "recording", "processing"];
|
||||
@@ -53,6 +56,7 @@ export default function TranscriptDetails(details: TranscriptDetails) {
|
||||
.replace(/ +/g, " ")
|
||||
.trim() || "";
|
||||
|
||||
if (transcript && transcript.response) {
|
||||
if (transcript.error || topics?.error) {
|
||||
return (
|
||||
<Modal
|
||||
@@ -62,12 +66,20 @@ export default function TranscriptDetails(details: TranscriptDetails) {
|
||||
);
|
||||
}
|
||||
|
||||
if (transcript?.loading || topics?.loading) {
|
||||
if (!transcriptId || transcript?.loading || topics?.loading) {
|
||||
return <Modal title="Loading" text={"Loading transcript..."} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{featureEnabled("sendToZulip") && (
|
||||
<ShareModal
|
||||
transcript={transcript.response}
|
||||
topics={topics ? topics.topics : null}
|
||||
show={showModal}
|
||||
setShow={(v) => setShowModal(v)}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col">
|
||||
{transcript?.response?.title && (
|
||||
<TranscriptTitle
|
||||
@@ -103,6 +115,7 @@ export default function TranscriptDetails(details: TranscriptDetails) {
|
||||
fullTranscript={fullTranscript}
|
||||
summary={transcript.response.longSummary}
|
||||
transcriptId={transcript.response.id}
|
||||
openZulipModal={() => setShowModal(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col h-full justify-center content-center">
|
||||
@@ -110,8 +123,8 @@ export default function TranscriptDetails(details: TranscriptDetails) {
|
||||
<p>Loading Transcript</p>
|
||||
) : (
|
||||
<p>
|
||||
There was an error generating the final summary, please come
|
||||
back later
|
||||
There was an error generating the final summary, please
|
||||
come back later
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -138,4 +151,5 @@ export default function TranscriptDetails(details: TranscriptDetails) {
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
159
www/app/[domain]/transcripts/[transcriptId]/shareModal.tsx
Normal file
159
www/app/[domain]/transcripts/[transcriptId]/shareModal.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import React, { useContext, useState, useEffect } from "react";
|
||||
import SelectSearch from "react-select-search";
|
||||
import { getZulipMessage, sendZulipMessage } from "../../../lib/zulip";
|
||||
import { GetTranscript, GetTranscriptTopic } from "../../../api";
|
||||
import "react-select-search/style.css";
|
||||
import { DomainContext } from "../../domainContext";
|
||||
|
||||
type ShareModal = {
|
||||
show: boolean;
|
||||
setShow: (show: boolean) => void;
|
||||
transcript: GetTranscript | null;
|
||||
topics: GetTranscriptTopic[] | null;
|
||||
};
|
||||
|
||||
interface Stream {
|
||||
id: number;
|
||||
name: string;
|
||||
topics: string[];
|
||||
}
|
||||
|
||||
interface SelectSearchOption {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const ShareModal = (props: ShareModal) => {
|
||||
const [stream, setStream] = useState<string | undefined>(undefined);
|
||||
const [topic, setTopic] = useState<string | undefined>(undefined);
|
||||
const [includeTopics, setIncludeTopics] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [streams, setStreams] = useState<Stream[]>([]);
|
||||
const { zulip_streams } = useContext(DomainContext);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(zulip_streams + "/streams.json")
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error("Network response was not ok");
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
data = data.sort((a: Stream, b: Stream) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
setStreams(data);
|
||||
setIsLoading(false);
|
||||
// data now contains the JavaScript object decoded from JSON
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("There was a problem with your fetch operation:", error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSendToZulip = () => {
|
||||
if (!props.transcript) return;
|
||||
|
||||
const msg = getZulipMessage(props.transcript, props.topics, includeTopics);
|
||||
|
||||
if (stream && topic) sendZulipMessage(stream, topic, msg);
|
||||
};
|
||||
|
||||
if (props.show && isLoading) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
let streamOptions: SelectSearchOption[] = [];
|
||||
if (streams) {
|
||||
streams.forEach((stream) => {
|
||||
const value = stream.name;
|
||||
streamOptions.push({ name: value, value: value });
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="absolute">
|
||||
{props.show && (
|
||||
<div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
|
||||
<div className="relative top-20 mx-auto p-5 w-96 shadow-lg rounded-md bg-white">
|
||||
<div className="mt-3 text-center">
|
||||
<h3 className="font-bold text-xl">Send to Zulip</h3>
|
||||
|
||||
{/* Checkbox for 'Include Topics' */}
|
||||
<div className="mt-4 text-left ml-5">
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-checkbox rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
|
||||
checked={includeTopics}
|
||||
onChange={(e) => setIncludeTopics(e.target.checked)}
|
||||
/>
|
||||
<span className="ml-2">Include topics</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center mt-4">
|
||||
<span className="mr-2">#</span>
|
||||
<SelectSearch
|
||||
search={true}
|
||||
options={streamOptions}
|
||||
value={stream}
|
||||
onChange={(val) => {
|
||||
setTopic(undefined);
|
||||
setStream(val.toString());
|
||||
}}
|
||||
placeholder="Pick a stream"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{stream && (
|
||||
<>
|
||||
<div className="flex items-center mt-4">
|
||||
<span className="mr-2 invisible">#</span>
|
||||
<SelectSearch
|
||||
search={true}
|
||||
options={
|
||||
streams
|
||||
.find((s) => s.name == stream)
|
||||
?.topics.sort((a: string, b: string) =>
|
||||
a.localeCompare(b),
|
||||
)
|
||||
.map((t) => ({ name: t, value: t })) || []
|
||||
}
|
||||
value={topic}
|
||||
onChange={(val) => setTopic(val.toString())}
|
||||
placeholder="Pick a topic"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<button
|
||||
className={`bg-blue-400 hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded py-2 px-4 mr-3 ${
|
||||
!stream || !topic ? "opacity-50 cursor-not-allowed" : ""
|
||||
}`}
|
||||
disabled={!stream || !topic}
|
||||
onClick={() => {
|
||||
handleSendToZulip();
|
||||
props.setShow(false);
|
||||
}}
|
||||
>
|
||||
Send to Zulip
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="bg-red-500 hover:bg-red-700 focus-visible:bg-red-700 text-white rounded py-2 px-4 mt-4"
|
||||
onClick={() => props.setShow(false)}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ShareModal;
|
||||
@@ -3,11 +3,13 @@ import React from "react";
|
||||
import Markdown from "react-markdown";
|
||||
import "../../styles/markdown.css";
|
||||
import getApi from "../../lib/getApi";
|
||||
import { featureEnabled } from "../domainContext";
|
||||
|
||||
type FinalSummaryProps = {
|
||||
summary: string;
|
||||
fullTranscript: string;
|
||||
transcriptId: string;
|
||||
openZulipModal: () => void;
|
||||
};
|
||||
|
||||
export default function FinalSummary(props: FinalSummaryProps) {
|
||||
@@ -116,33 +118,48 @@ export default function FinalSummary(props: FinalSummaryProps) {
|
||||
|
||||
{!isEditMode && (
|
||||
<>
|
||||
{featureEnabled("sendToZulip") && (
|
||||
<button
|
||||
className={
|
||||
"bg-blue-400 hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base"
|
||||
}
|
||||
onClick={() => props.openZulipModal()}
|
||||
>
|
||||
<span className="text-xs">➡️ Zulip</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={onEditClick}
|
||||
className={
|
||||
"bg-blue-400 hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base text-xs"
|
||||
"bg-blue-400 hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base"
|
||||
}
|
||||
>
|
||||
Edit Summary
|
||||
<span className="text-xs">✏️ Summary</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={onCopyTranscriptClick}
|
||||
className={
|
||||
(isCopiedTranscript ? "bg-blue-500" : "bg-blue-400") +
|
||||
" hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base text-xs"
|
||||
" hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base"
|
||||
}
|
||||
style={{ minHeight: "30px" }}
|
||||
>
|
||||
<span className="text-xs">
|
||||
{isCopiedTranscript ? "Copied!" : "Copy Transcript"}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={onCopySummaryClick}
|
||||
className={
|
||||
(isCopiedSummary ? "bg-blue-500" : "bg-blue-400") +
|
||||
" hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base text-xs"
|
||||
" hover:bg-blue-500 focus-visible:bg-blue-500 text-white rounded p-2 sm:text-base"
|
||||
}
|
||||
style={{ minHeight: "30px" }}
|
||||
>
|
||||
<span className="text-xs">
|
||||
{isCopiedSummary ? "Copied!" : "Copy Summary"}
|
||||
</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,25 +1,19 @@
|
||||
import { get } from "@vercel/edge-config";
|
||||
import { isDevelopment } from "./utils";
|
||||
|
||||
const localConfig = {
|
||||
features: {
|
||||
requireLogin: true,
|
||||
privacy: true,
|
||||
browse: true,
|
||||
},
|
||||
api_url: "http://127.0.0.1:1250",
|
||||
websocket_url: "ws://127.0.0.1:1250",
|
||||
auth_callback_url: "http://localhost:3000/auth-callback",
|
||||
};
|
||||
|
||||
type EdgeConfig = {
|
||||
[domainWithDash: string]: {
|
||||
features: {
|
||||
[featureName in "requireLogin" | "privacy" | "browse"]: boolean;
|
||||
[featureName in
|
||||
| "requireLogin"
|
||||
| "privacy"
|
||||
| "browse"
|
||||
| "sendToZulip"]: boolean;
|
||||
};
|
||||
auth_callback_url: string;
|
||||
websocket_url: string;
|
||||
api_url: string;
|
||||
zulip_streams: string;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -36,8 +30,8 @@ export function edgeDomainToKey(domain: string) {
|
||||
|
||||
// get edge config server-side (prefer DomainContext when available), domain is the hostname
|
||||
export async function getConfig(domain: string) {
|
||||
if (isDevelopment()) {
|
||||
return localConfig;
|
||||
if (process.env.NEXT_PUBLIC_ENV === "development") {
|
||||
return require("../../config").localConfig;
|
||||
}
|
||||
|
||||
let config = await get(edgeDomainToKey(domain));
|
||||
|
||||
@@ -98,26 +98,41 @@ export function murmurhash3_32_gc(key: string, seed: number = 0) {
|
||||
|
||||
export const generateHighContrastColor = (
|
||||
name: string,
|
||||
backgroundColor: [number, number, number] | null = null,
|
||||
backgroundColor: [number, number, number],
|
||||
) => {
|
||||
const hash = murmurhash3_32_gc(name);
|
||||
let loopNumber = 0;
|
||||
let minAcceptedContrast = 3.5;
|
||||
while (true && /* Just as a safeguard */ loopNumber < 100) {
|
||||
++loopNumber;
|
||||
|
||||
if (loopNumber > 5) minAcceptedContrast -= 0.5;
|
||||
|
||||
const hash = murmurhash3_32_gc(name + loopNumber);
|
||||
let red = (hash & 0xff0000) >> 16;
|
||||
let green = (hash & 0x00ff00) >> 8;
|
||||
let blue = hash & 0x0000ff;
|
||||
|
||||
const getCssColor = (red: number, green: number, blue: number) =>
|
||||
`rgb(${red}, ${green}, ${blue})`;
|
||||
let contrast = getContrastRatio([red, green, blue], backgroundColor);
|
||||
|
||||
if (!backgroundColor) return getCssColor(red, green, blue);
|
||||
if (contrast > minAcceptedContrast) return `rgb(${red}, ${green}, ${blue})`;
|
||||
|
||||
const contrast = getContrastRatio([red, green, blue], backgroundColor);
|
||||
|
||||
// Adjust the color to achieve better contrast if necessary (WCAG recommends at least 4.5:1 for text)
|
||||
if (contrast < 4.5) {
|
||||
// Try to invert the color to increase contrat - this works best the more away the color is from gray
|
||||
red = Math.abs(255 - red);
|
||||
green = Math.abs(255 - green);
|
||||
blue = Math.abs(255 - blue);
|
||||
}
|
||||
|
||||
return getCssColor(red, green, blue);
|
||||
contrast = getContrastRatio([red, green, blue], backgroundColor);
|
||||
|
||||
if (contrast > minAcceptedContrast) return `rgb(${red}, ${green}, ${blue})`;
|
||||
}
|
||||
};
|
||||
|
||||
export function extractDomain(url) {
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
return parsedUrl.host;
|
||||
} catch (error) {
|
||||
console.error("Invalid URL:", error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
80
www/app/lib/zulip.ts
Normal file
80
www/app/lib/zulip.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { GetTranscript, GetTranscriptTopic } from "../api";
|
||||
import { formatTime } from "./time";
|
||||
import { extractDomain } from "./utils";
|
||||
|
||||
export async function sendZulipMessage(
|
||||
stream: string,
|
||||
topic: string,
|
||||
message: string,
|
||||
) {
|
||||
console.log("Sendiing zulip message", stream, topic);
|
||||
try {
|
||||
const response = await fetch("/api/send-zulip-message", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ stream, topic, message }),
|
||||
});
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const ZULIP_MSG_MAX_LENGTH = 10000;
|
||||
|
||||
export function getZulipMessage(
|
||||
transcript: GetTranscript,
|
||||
topics: GetTranscriptTopic[] | null,
|
||||
includeTopics: boolean,
|
||||
) {
|
||||
const date = new Date(transcript.createdAt);
|
||||
|
||||
// Get the timezone offset in minutes and convert it to hours and minutes
|
||||
const timezoneOffset = -date.getTimezoneOffset();
|
||||
const offsetHours = String(
|
||||
Math.floor(Math.abs(timezoneOffset) / 60),
|
||||
).padStart(2, "0");
|
||||
const offsetMinutes = String(Math.abs(timezoneOffset) % 60).padStart(2, "0");
|
||||
const offsetSign = timezoneOffset >= 0 ? "+" : "-";
|
||||
|
||||
// Combine to get the formatted timezone offset
|
||||
const formattedOffset = `${offsetSign}${offsetHours}:${offsetMinutes}`;
|
||||
|
||||
// Now you can format your date and time string using this offset
|
||||
const formattedDate = date.toISOString().slice(0, 10);
|
||||
const hours = String(date.getHours()).padStart(2, "0");
|
||||
const minutes = String(date.getMinutes()).padStart(2, "0");
|
||||
const seconds = String(date.getSeconds()).padStart(2, "0");
|
||||
|
||||
const dateTimeString = `${formattedDate}T${hours}:${minutes}:${seconds}${formattedOffset}`;
|
||||
|
||||
const domain = window.location.origin; // Gives you "http://localhost:3000" or your deployment base URL
|
||||
const link = `${domain}/transcripts/${transcript.id}`;
|
||||
|
||||
let headerText = `# Reflector – ${transcript.title ?? "Unnamed recording"}
|
||||
|
||||
**Date**: <time:${dateTimeString}>
|
||||
**Link**: [${extractDomain(link)}](${link})
|
||||
**Duration**: ${formatTime(transcript.duration)}
|
||||
|
||||
`;
|
||||
let topicText = "";
|
||||
|
||||
if (topics && includeTopics) {
|
||||
topicText = "```spoiler Topics\n";
|
||||
topics.forEach((topic) => {
|
||||
topicText += `1. [${formatTime(topic.timestamp)}] ${topic.title}\n`;
|
||||
});
|
||||
topicText += "```\n\n";
|
||||
}
|
||||
|
||||
let summary = "```spoiler Summary\n";
|
||||
summary += transcript.longSummary;
|
||||
summary += "```\n\n";
|
||||
|
||||
const message = headerText + summary + topicText + "-----\n";
|
||||
return message;
|
||||
}
|
||||
12
www/config-template.ts
Normal file
12
www/config-template.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export const localConfig = {
|
||||
features: {
|
||||
requireLogin: true,
|
||||
privacy: true,
|
||||
browse: true,
|
||||
sendToZulip: true,
|
||||
},
|
||||
api_url: "http://127.0.0.1:1250",
|
||||
websocket_url: "ws://127.0.0.1:1250",
|
||||
auth_callback_url: "http://localhost:3000/auth-callback",
|
||||
zulip_streams: "", // Find the value on zulip
|
||||
};
|
||||
@@ -18,7 +18,7 @@
|
||||
"@sentry/nextjs": "^7.77.0",
|
||||
"@vercel/edge-config": "^0.4.1",
|
||||
"autoprefixer": "10.4.14",
|
||||
"axios": "^1.4.0",
|
||||
"axios": "^1.6.2",
|
||||
"fontawesome": "^5.6.3",
|
||||
"jest-worker": "^29.6.2",
|
||||
"next": "^13.4.9",
|
||||
|
||||
52
www/pages/api/send-zulip-message.ts
Normal file
52
www/pages/api/send-zulip-message.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import axios from "axios";
|
||||
import { URLSearchParams } from "url";
|
||||
import { getConfig } from "../../app/lib/edgeConfig";
|
||||
|
||||
export default async function handler(req, res) {
|
||||
const domainName = req.headers.host;
|
||||
const config = await getConfig(domainName);
|
||||
const { requireLogin, privacy, browse, sendToZulip } = config.features;
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { stream, topic, message } = req.body;
|
||||
|
||||
if (!stream || !topic || !message) {
|
||||
return res.status(400).json({ error: "Missing required parameters" });
|
||||
}
|
||||
|
||||
if (!sendToZulip) {
|
||||
return res.status(403).json({ error: "Zulip integration disabled" });
|
||||
}
|
||||
|
||||
try {
|
||||
// Construct URL-encoded data
|
||||
const params = new URLSearchParams();
|
||||
params.append("type", "stream");
|
||||
params.append("to", stream);
|
||||
params.append("topic", topic);
|
||||
params.append("content", message);
|
||||
|
||||
// Send the request1
|
||||
const zulipResponse = await axios.post(
|
||||
`https://${process.env.ZULIP_REALM}/api/v1/messages`,
|
||||
params,
|
||||
{
|
||||
auth: {
|
||||
username: process.env.ZULIP_BOT_EMAIL || "?",
|
||||
password: process.env.ZULIP_API_KEY || "?",
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return res.status(200).json(zulipResponse.data);
|
||||
} catch (error) {
|
||||
return res.status(500).json({ failed: true, error: error });
|
||||
}
|
||||
} else {
|
||||
res.setHeader("Allow", ["POST"]);
|
||||
res.status(405).end(`Method ${req.method} Not Allowed`);
|
||||
}
|
||||
}
|
||||
@@ -585,10 +585,10 @@ axios@0.27.2:
|
||||
follow-redirects "^1.14.9"
|
||||
form-data "^4.0.0"
|
||||
|
||||
axios@^1.4.0:
|
||||
version "1.4.0"
|
||||
resolved "https://registry.yarnpkg.com/axios/-/axios-1.4.0.tgz#38a7bf1224cd308de271146038b551d725f0be1f"
|
||||
integrity sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==
|
||||
axios@^1.6.2:
|
||||
version "1.6.2"
|
||||
resolved "https://registry.yarnpkg.com/axios/-/axios-1.6.2.tgz#de67d42c755b571d3e698df1b6504cde9b0ee9f2"
|
||||
integrity sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==
|
||||
dependencies:
|
||||
follow-redirects "^1.15.0"
|
||||
form-data "^4.0.0"
|
||||
|
||||
Reference in New Issue
Block a user