Merge pull request #416 from Monadical-SAS/replace-streams-json

Replace streams json
This commit is contained in:
2024-09-24 15:46:29 +02:00
committed by GitHub
19 changed files with 288 additions and 2135 deletions

View File

@@ -1,211 +0,0 @@
# 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

View File

@@ -1,38 +0,0 @@
# 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) .

View File

@@ -1,127 +0,0 @@
# 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/)

View File

@@ -1,71 +0,0 @@
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 };

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +0,0 @@
{
"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"
}
}

View File

@@ -1,62 +0,0 @@
{
"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"
}
}

View File

@@ -1,31 +0,0 @@
# 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"

View File

@@ -1,41 +0,0 @@
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

View File

@@ -24,6 +24,7 @@ from reflector.views.transcripts_upload import router as transcripts_upload_rout
from reflector.views.transcripts_webrtc import router as transcripts_webrtc_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.transcripts_websocket import router as transcripts_websocket_router
from reflector.views.user import router as user_router from reflector.views.user import router as user_router
from reflector.views.zulip import router as zulip_router
try: try:
import sentry_sdk import sentry_sdk
@@ -79,6 +80,7 @@ app.include_router(transcripts_websocket_router, prefix="/v1")
app.include_router(transcripts_webrtc_router, prefix="/v1") app.include_router(transcripts_webrtc_router, prefix="/v1")
app.include_router(transcripts_process_router, prefix="/v1") app.include_router(transcripts_process_router, prefix="/v1")
app.include_router(user_router, prefix="/v1") app.include_router(user_router, prefix="/v1")
app.include_router(zulip_router, prefix="/v1")
add_pagination(app) add_pagination(app)
# prepare celery # prepare celery

View File

@@ -0,0 +1,46 @@
from typing import Annotated, Optional
import reflector.auth as auth
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from reflector.zulip import get_zulip_streams, get_zulip_topics
router = APIRouter()
class Stream(BaseModel):
stream_id: int
name: str
class Topic(BaseModel):
name: str
@router.get("/zulip/streams")
async def zulip_get_streams(
user: Annotated[Optional[auth.UserInfo], Depends(auth.current_user_optional)],
) -> list[Stream]:
"""
Get all Zulip streams.
"""
if not user:
raise HTTPException(status_code=403, detail="Authentication required")
streams = get_zulip_streams()
return streams
@router.get("/zulip/streams/{stream_id}/topics")
async def zulip_get_topics(
stream_id: int,
user: Annotated[Optional[auth.UserInfo], Depends(auth.current_user_optional)],
) -> list[Topic]:
"""
Get all topics for a specific Zulip stream.
"""
if not user:
raise HTTPException(status_code=403, detail="Authentication required")
topics = get_zulip_topics(stream_id)
return topics

View File

@@ -10,6 +10,34 @@ class InvalidMessageError(Exception):
pass pass
def get_zulip_topics(stream_id: int) -> list[dict]:
try:
response = requests.get(
f"https://{settings.ZULIP_REALM}/api/v1/users/me/{stream_id}/topics",
auth=(settings.ZULIP_BOT_EMAIL, settings.ZULIP_API_KEY),
)
response.raise_for_status()
return response.json().get("topics", [])
except requests.RequestException as error:
raise Exception(f"Failed to get topics: {error}")
def get_zulip_streams() -> list[dict]:
try:
response = requests.get(
f"https://{settings.ZULIP_REALM}/api/v1/streams",
auth=(settings.ZULIP_BOT_EMAIL, settings.ZULIP_API_KEY),
)
response.raise_for_status()
return response.json().get("streams", [])
except requests.RequestException as error:
raise Exception(f"Failed to get streams: {error}")
def send_message_to_zulip(stream: str, topic: str, content: str): def send_message_to_zulip(stream: str, topic: str, content: str):
try: try:
response = requests.post( response = requests.post(

View File

@@ -30,18 +30,16 @@ import {
IconButton, IconButton,
Checkbox, Checkbox,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { useContext, useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Container } from "@chakra-ui/react"; import { Container } from "@chakra-ui/react";
import { FaEllipsisVertical, FaTrash, FaPencil, FaLink } from "react-icons/fa6"; import { FaEllipsisVertical, FaTrash, FaPencil, FaLink } from "react-icons/fa6";
import useApi from "../../lib/useApi"; import useApi from "../../lib/useApi";
import useRoomList from "./useRoomList"; import useRoomList from "./useRoomList";
import { DomainContext } from "../../domainContext";
import { Select, Options, OptionBase } from "chakra-react-select"; import { Select, Options, OptionBase } from "chakra-react-select";
interface Stream { interface Stream {
id: number; stream_id: number;
name: string; name: string;
topics: string[];
} }
interface SelectOption extends OptionBase { interface SelectOption extends OptionBase {
@@ -82,41 +80,63 @@ export default function RoomsList() {
const [page, setPage] = useState<number>(1); const [page, setPage] = useState<number>(1);
const { loading, response, refetch } = useRoomList(page); const { loading, response, refetch } = useRoomList(page);
const [streams, setStreams] = useState<Stream[]>([]); const [streams, setStreams] = useState<Stream[]>([]);
const [topics, setTopics] = useState<Topic[]>([]);
const [error, setError] = useState(""); const [error, setError] = useState("");
const [linkCopied, setLinkCopied] = useState(""); const [linkCopied, setLinkCopied] = useState("");
interface Stream {
stream_id: number;
name: string;
}
const { zulip_streams } = useContext(DomainContext); interface Topic {
name: string;
}
useEffect(() => { useEffect(() => {
const fetchZulipStreams = async () => { const fetchZulipStreams = async () => {
if (!api) return;
try { try {
const response = await fetch(zulip_streams + "/streams.json"); const response = await api.v1ZulipGetStreams();
if (!response.ok) { setStreams(response);
throw new Error("Network response was not ok"); } catch (error) {
} console.error("Error fetching Zulip streams:", error);
let data = await response.json();
data = data.sort((a: Stream, b: Stream) =>
a.name.localeCompare(b.name),
);
setStreams(data);
} catch (err) {
console.error("Error fetching streams:", err);
} }
}; };
if (room.zulipAutoPost) { if (room.zulipAutoPost) {
fetchZulipStreams(); fetchZulipStreams();
} }
}, [room.zulipAutoPost]); }, [room.zulipAutoPost, !api]);
useEffect(() => {
const fetchZulipTopics = async () => {
if (!api || !room.zulipStream) return;
try {
const selectedStream = streams.find((s) => s.name === room.zulipStream);
if (selectedStream) {
const response = await api.v1ZulipGetTopics({
streamId: selectedStream.stream_id,
});
setTopics(response);
}
} catch (error) {
console.error("Error fetching Zulip topics:", error);
}
};
fetchZulipTopics();
}, [room.zulipStream, streams, api]);
const streamOptions: Options<SelectOption> = streams.map((stream) => { const streamOptions: Options<SelectOption> = streams.map((stream) => {
return { label: stream.name, value: stream.name }; return { label: stream.name, value: stream.name };
}); });
const topicOptions = const topicOptions: Options<SelectOption> = topics.map((topic) => ({
streams label: topic.name,
.find((stream) => stream.name === room.zulipStream) value: topic.name,
?.topics.map((topic) => ({ label: topic, value: topic })) || []; }));
const handleCopyUrl = (roomName: string) => { const handleCopyUrl = (roomName: string) => {
const roomUrl = `${window.location.origin}/${roomName}`; const roomUrl = `${window.location.origin}/${roomName}`;

View File

@@ -1,11 +1,11 @@
import React, { useContext, useState, useEffect, useCallback } from "react"; import React, { useContext, useState, useEffect } from "react";
import SelectSearch from "react-select-search"; import SelectSearch from "react-select-search";
import { GetTranscript, GetTranscriptTopic } from "../../../api"; import { GetTranscript, GetTranscriptTopic } from "../../../api";
import "react-select-search/style.css"; import "react-select-search/style.css";
import { DomainContext } from "../../../domainContext"; import { DomainContext } from "../../../domainContext";
import useApi from "../../../lib/useApi"; import useApi from "../../../lib/useApi";
type ShareModal = { type ShareModalProps = {
show: boolean; show: boolean;
setShow: (show: boolean) => void; setShow: (show: boolean) => void;
transcript: GetTranscript | null; transcript: GetTranscript | null;
@@ -13,9 +13,12 @@ type ShareModal = {
}; };
interface Stream { interface Stream {
id: number; stream_id: number;
name: string;
}
interface Topic {
name: string; name: string;
topics: string[];
} }
interface SelectSearchOption { interface SelectSearchOption {
@@ -23,41 +26,54 @@ interface SelectSearchOption {
value: string; value: string;
} }
const ShareModal = (props: ShareModal) => { const ShareModal = (props: ShareModalProps) => {
const [stream, setStream] = useState<string | undefined>(undefined); const [stream, setStream] = useState<string | undefined>(undefined);
const [topic, setTopic] = useState<string | undefined>(undefined); const [topic, setTopic] = useState<string | undefined>(undefined);
const [includeTopics, setIncludeTopics] = useState(false); const [includeTopics, setIncludeTopics] = useState(false);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [streams, setStreams] = useState<Stream[]>([]); const [streams, setStreams] = useState<Stream[]>([]);
const { zulip_streams } = useContext(DomainContext); const [topics, setTopics] = useState<Topic[]>([]);
const api = useApi(); const api = useApi();
useEffect(() => { useEffect(() => {
fetch(zulip_streams + "/streams.json") const fetchZulipStreams = async () => {
.then((response) => { if (!api) return;
if (!response.ok) {
throw new Error("Network response was not ok"); try {
} const response = await api.v1ZulipGetStreams();
return response.json(); setStreams(response);
})
.then((data) => {
data = data.sort((a: Stream, b: Stream) =>
a.name.localeCompare(b.name),
);
setStreams(data);
setIsLoading(false); setIsLoading(false);
// data now contains the JavaScript object decoded from JSON } catch (error) {
}) console.error("Error fetching Zulip streams:", error);
.catch((error) => { }
console.error("There was a problem with your fetch operation:", error); };
});
}, []); fetchZulipStreams();
}, [!api]);
useEffect(() => {
const fetchZulipTopics = async () => {
if (!api || !stream) return;
try {
const selectedStream = streams.find((s) => s.name === stream);
if (selectedStream) {
const response = await api.v1ZulipGetTopics({
streamId: selectedStream.stream_id,
});
setTopics(response);
}
} catch (error) {
console.error("Error fetching Zulip topics:", error);
}
};
fetchZulipTopics();
}, [stream, streams, api]);
const handleSendToZulip = async () => { const handleSendToZulip = async () => {
if (!props.transcript) return; if (!api || !props.transcript) return;
if (stream && topic) { if (stream && topic) {
if (!api) return;
try { try {
await api.v1TranscriptPostToZulip({ await api.v1TranscriptPostToZulip({
transcriptId: props.transcript.id, transcriptId: props.transcript.id,
@@ -75,13 +91,15 @@ const ShareModal = (props: ShareModal) => {
return <div>Loading...</div>; return <div>Loading...</div>;
} }
let streamOptions: SelectSearchOption[] = []; const streamOptions: SelectSearchOption[] = streams.map((stream) => ({
if (streams) { name: stream.name,
streams.forEach((stream) => { value: stream.name,
const value = stream.name; }));
streamOptions.push({ name: value, value: value });
}); const topicOptions: SelectSearchOption[] = topics.map((topic) => ({
} name: topic.name,
value: topic.name,
}));
return ( return (
<div className="absolute"> <div className="absolute">
@@ -111,7 +129,7 @@ const ShareModal = (props: ShareModal) => {
options={streamOptions} options={streamOptions}
value={stream} value={stream}
onChange={(val) => { onChange={(val) => {
setTopic(undefined); setTopic(undefined); // Reset topic when stream changes
setStream(val.toString()); setStream(val.toString());
}} }}
placeholder="Pick a stream" placeholder="Pick a stream"
@@ -119,25 +137,16 @@ const ShareModal = (props: ShareModal) => {
</div> </div>
{stream && ( {stream && (
<> <div className="flex items-center mt-4">
<div className="flex items-center mt-4"> <span className="mr-2 invisible">#</span>
<span className="mr-2 invisible">#</span> <SelectSearch
<SelectSearch search={true}
search={true} options={topicOptions}
options={ value={topic}
streams onChange={(val) => setTopic(val.toString())}
.find((s) => s.name == stream) placeholder="Pick a topic"
?.topics.sort((a: string, b: string) => />
a.localeCompare(b), </div>
)
.map((t) => ({ name: t, value: t })) || []
}
value={topic}
onChange={(val) => setTopic(val.toString())}
placeholder="Pick a topic"
/>
</div>
</>
)} )}
<button <button

View File

@@ -828,6 +828,34 @@ export const $SpeakerWords = {
title: "SpeakerWords", title: "SpeakerWords",
} as const; } as const;
export const $Stream = {
properties: {
stream_id: {
type: "integer",
title: "Stream Id",
},
name: {
type: "string",
title: "Name",
},
},
type: "object",
required: ["stream_id", "name"],
title: "Stream",
} as const;
export const $Topic = {
properties: {
name: {
type: "string",
title: "Name",
},
},
type: "object",
required: ["name"],
title: "Topic",
} as const;
export const $TranscriptParticipant = { export const $TranscriptParticipant = {
properties: { properties: {
id: { id: {

View File

@@ -61,6 +61,9 @@ import type {
V1TranscriptProcessData, V1TranscriptProcessData,
V1TranscriptProcessResponse, V1TranscriptProcessResponse,
V1UserMeResponse, V1UserMeResponse,
V1ZulipGetStreamsResponse,
V1ZulipGetTopicsData,
V1ZulipGetTopicsResponse,
} from "./types.gen"; } from "./types.gen";
export class DefaultService { export class DefaultService {
@@ -762,4 +765,40 @@ export class DefaultService {
url: "/v1/me", url: "/v1/me",
}); });
} }
/**
* Zulip Get Streams
* Get all Zulip streams.
* @returns Stream Successful Response
* @throws ApiError
*/
public v1ZulipGetStreams(): CancelablePromise<V1ZulipGetStreamsResponse> {
return this.httpRequest.request({
method: "GET",
url: "/v1/zulip/streams",
});
}
/**
* Zulip Get Topics
* Get all topics for a specific Zulip stream.
* @param data The data for the request.
* @param data.streamId
* @returns Topic Successful Response
* @throws ApiError
*/
public v1ZulipGetTopics(
data: V1ZulipGetTopicsData,
): CancelablePromise<V1ZulipGetTopicsResponse> {
return this.httpRequest.request({
method: "GET",
url: "/v1/zulip/streams/{stream_id}/topics",
path: {
stream_id: data.streamId,
},
errors: {
422: "Validation Error",
},
});
}
} }

View File

@@ -168,6 +168,15 @@ export type SpeakerWords = {
words: Array<Word>; words: Array<Word>;
}; };
export type Stream = {
stream_id: number;
name: string;
};
export type Topic = {
name: string;
};
export type TranscriptParticipant = { export type TranscriptParticipant = {
id?: string; id?: string;
speaker: number | null; speaker: number | null;
@@ -427,6 +436,14 @@ export type V1TranscriptProcessResponse = unknown;
export type V1UserMeResponse = UserInfo | null; export type V1UserMeResponse = UserInfo | null;
export type V1ZulipGetStreamsResponse = Array<Stream>;
export type V1ZulipGetTopicsData = {
streamId: number;
};
export type V1ZulipGetTopicsResponse = Array<Topic>;
export type $OpenApiTs = { export type $OpenApiTs = {
"/metrics": { "/metrics": {
get: { get: {
@@ -850,4 +867,29 @@ export type $OpenApiTs = {
}; };
}; };
}; };
"/v1/zulip/streams": {
get: {
res: {
/**
* Successful Response
*/
200: Array<Stream>;
};
};
};
"/v1/zulip/streams/{stream_id}/topics": {
get: {
req: V1ZulipGetTopicsData;
res: {
/**
* Successful Response
*/
200: Array<Topic>;
/**
* Validation Error
*/
422: HTTPValidationError;
};
};
};
}; };

View File

@@ -13,7 +13,6 @@ export const DomainContext = createContext<DomainContextType>({
}, },
api_url: "", api_url: "",
websocket_url: "", websocket_url: "",
zulip_streams: "",
}); });
export const DomainContextProvider = ({ export const DomainContextProvider = ({

View File

@@ -13,7 +13,6 @@ type EdgeConfig = {
auth_callback_url: string; auth_callback_url: string;
websocket_url: string; websocket_url: string;
api_url: string; api_url: string;
zulip_streams: string;
}; };
}; };