Skip to content

Commit

Permalink
Merge pull request #3 from miutaku/develop
Browse files Browse the repository at this point in the history
不要になった関数の整理やパラメータのデフォルト値を指定
  • Loading branch information
miutaku authored Jan 25, 2025
2 parents eda783f + c6a2760 commit 4986ac6
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 127 deletions.
14 changes: 14 additions & 0 deletions .env_sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
TWITCASTING_CLIENT_ID=<YOUR_TWITCASTING_CLIENT_ID>
TWITCASTING_CLIENT_SECRET=<YOUR_TWITCASTING_CLIENT_SECRET>
FETCH_INTERVAL_SEC=1

POSTGRES_USER=rec-twitcasting-user
POSTGRES_PASSWORD=rec-twitcasting-pass
POSTGRES_DB=rec_twitcasting
DB_HOST=postgres-rec-twitcasting
DB_PORT=5432
DB_USER=$POSTGRES_USER
DB_PASSWORD=$POSTGRES_PASSWORD
DB_NAME=$POSTGRES_DB
DB_TABLE_NAME=speakers
TZ=Asia/Tokyo
56 changes: 22 additions & 34 deletions api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,7 @@ sudo dnf install ffmpeg
```bash
export TWITCASTING_CLIENT_ID=<your_client_id>
export TWITCASTING_CLIENT_SECRET=<your_client_secret>
export DB_HOST=localhost
export DB_PORT=5432
export DB_USER=user
export DB_PASSWORD=password
export DB_NAME=dbname
export DB_TABLE_NAME=tablename
export OUTPUT_DIR=./recorded
export LOG_LEVEL=debug
export MANAGE_BACKEND_HOST=<manage-backend>
```

4. Run the server:
Expand All @@ -56,14 +49,9 @@ go run main.go
|-------------------------|-----------------------------------------------------------------------------|---------------------|
| `TWITCASTING_CLIENT_ID`| Your TwitCasting Client ID. | None (required) |
| `TWITCASTING_CLIENT_SECRET`| Your TwitCasting Client Secret. | None (required) |
| `DB_HOST` | Database host. | `localhost` |
| `DB_PORT` | Database port. | `5432` |
| `DB_USER` | Database user. | `user` |
| `DB_PASSWORD` | Database password. | `password` |
| `DB_NAME` | Database name. | `dbname` |
| `DB_TABLE_NAME` | Database table name. | `tablename` |
| `OUTPUT_DIR` | Directory to save recorded videos. | `./recorded` |
| `LOG_LEVEL` | Set to `debug` to see detailed logs. | None |
| `MANAGE_BACKEND_HOST` | Host for managing backend recording state. | `manage-backend`(required) |

## Endpoints

Expand All @@ -74,7 +62,7 @@ Checks if a TwitCasting user is live streaming and records their stream if live.
#### Request

- **URL Query Parameters**:
- `username` (string): The TwitCasting username to check and record.
- `username` (string): The TwitCasting username to check and record.

#### Example

Expand All @@ -85,34 +73,34 @@ curl "http://localhost:8080/check-live?username=<twitcasting_username>"
#### Responses

- **200 OK**:
- User is not live streaming:
```
User is not live streaming.
```
- Recording finished:
```
Recording finished. Saved as: <output_file_path>
```
- User is not live streaming:
```
User is not live streaming.
```
- Recording finished:
```
Recording finished. Saved as: <output_file_path>
```
- **400 Bad Request**:
- Missing `username` parameter:
```
username parameter is required
```
- Missing `username` parameter:
```
username parameter is required
```
- **500 Internal Server Error**:
- Errors while checking stream or updating recording state:
```
Failed to get current live information: <error_details>
```
- Errors while checking stream or updating recording state:
```
Failed to get current live information: <error_details>
```
## Recording Output
Recorded streams are saved in the directory specified by the `OUTPUT_DIR` environment variable. The directory structure is as follows:
```
recorded/
└── <username>/
└── <YYYY-MM-DD>/
└── <HH-MM>_<title>.mp4
└── <username>/
└── <YYYY-MM-DD>/
└── <HH-MM>_<title>.mp4
```
- `<username>`: The TwitCasting username.
Expand Down
6 changes: 1 addition & 5 deletions api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ require (
)

require (
github.com/go-co-op/gocron v1.37.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/uuid v1.4.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
go.uber.org/atomic v1.9.0 // indirect
github.com/lib/pq v1.10.9
)
47 changes: 7 additions & 40 deletions api/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"database/sql"
"fmt"
"log"
"net/http"
Expand All @@ -15,55 +14,24 @@ import (
"github.com/nobuf/cas"
)

type DBConfig struct {
Host string
Port string
User string
Password string
DbName string
TableName string
}

func getDBConfig() DBConfig {
return DBConfig{
Host: getEnv("DB_HOST", "localhost"),
Port: getEnv("DB_PORT", "5432"), // Default to 5432 if DB_PORT is not set
User: getEnv("DB_USER", "user"),
Password: getEnv("DB_PASSWORD", "password"),
DbName: getEnv("DB_NAME", "dbname"),
TableName: getEnv("DB_TABLE_NAME", "tablename"),
}
}

func getEnv(key, fallback string) string {
value := os.Getenv(key)
if value == "" {
return fallback
}
return value
}

func updateRecordingState(username string, state bool) error {
config := getDBConfig()
db, err := sql.Open("postgres", fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
config.Host,
config.Port,
config.User,
config.Password,
config.DbName,
))
manageBackendHost := getEnv("MANAGE_BACKEND_HOST", "manage-backend-rec-twitcasting:8888")
updateURL := fmt.Sprintf("http://%s/update-recording-state?username=%s&recording_state=%t", manageBackendHost, username, state)
resp, err := http.Get(updateURL)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
return fmt.Errorf("failed to update recording state: %v", err)
}
defer db.Close()

query := fmt.Sprintf("UPDATE %s SET recording_state = $1 WHERE username = $2", config.TableName)
_, err = db.Exec(query, state, username)
if err != nil {
return err
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to update recording state, status code: %d", resp.StatusCode)
}

return nil
}

Expand Down Expand Up @@ -111,7 +79,6 @@ func main() {
http.Error(w, fmt.Sprintf("Failed to update recording state: %v", err), http.StatusInternalServerError)
return
}

// 配信中のタイトルを取得
title := liveInfo.Movie.Title
fmt.Printf("User is live streaming. Title: %s\n", title)
Expand Down
5 changes: 4 additions & 1 deletion batch/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ func task() {
return
}
apiURL := os.Getenv("API_REC_TWITCASTING_URL")
if apiURL == "" {
apiURL = "http://api-rec-twitcasting:8080"
}
resp, err := http.Get(fmt.Sprintf("%s/check-live?username=%s", apiURL, name))
if err != nil {
fmt.Fprintf(os.Stderr, "HTTP request failed: %v\n", err)
Expand Down Expand Up @@ -94,7 +97,7 @@ func main() {
s1.Every(interval).Seconds().Do(task)
s1.StartAsync()

quit := make(chan os.Signal)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
}
78 changes: 32 additions & 46 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,60 +2,50 @@
services:
# rec-api
api-rec-twitcasting:
image: ghcr.io/miutaku/api-rec-twitcasting:latest
#build:
# context: .
# dockerfile: api/Dockerfile
#image: ghcr.io/miutaku/api-rec-twitcasting:latest
build:
context: .
dockerfile: api/Dockerfile
container_name: api-rec-twitcasting
restart: unless-stopped
volumes:
- ./recorded:/root/recorded
# - /your/path/to/dir:./recorded
environment:
- TZ=Asia/Tokyo
- TWITCASTING_CLIENT_ID=YOUR_TWITCASTING_CLIENT_ID
- TWITCASTING_CLIENT_SECRET=YOUR_TWITCASTING_CLIENT_SECRET
- DB_HOST=postgres-rec-twitcasting
- DB_PORT=5432
- DB_USER=rec-twitcasting-user
- DB_PASSWORD=rec-twitcasting-pass
- DB_NAME=rec_twitcasting
- DB_TABLE_NAME=speakers
#- LOG_LEVEL=debug
ports:
- 18080:8080
env_file:
- .env

# batch
batch-rec-twitcasting:
image: ghcr.io/miutaku/batch-rec-twitcasting:latest
#build:
# context: .
# dockerfile: batch/Dockerfile
#image: ghcr.io/miutaku/batch-rec-twitcasting:latest
build:
context: .
dockerfile: batch/Dockerfile
depends_on:
- postgres-rec-twitcasting
postgres-rec-twitcasting:
condition: service_healthy
restart: unless-stopped
container_name: batch-rec-twitcasting
environment:
- FETCH_INTERVAL_SEC=1
- API_REC_TWITCASTING_URL=http://api-rec-twitcasting:8080
- DB_HOST=postgres-rec-twitcasting
- DB_PORT=5432
- DB_USER=rec-twitcasting-user
- DB_PASSWORD=rec-twitcasting-pass
- DB_NAME=rec_twitcasting
- DB_TABLE_NAME=speakers
#- LOG_LEVEL=debug
env_file:
- .env

# db
postgres-rec-twitcasting:
image: postgres:17.2
container_name: postgres-rec-twitcasting
restart: unless-stopped
environment:
- POSTGRES_USER=rec-twitcasting-user
- POSTGRES_PASSWORD=rec-twitcasting-pass
- POSTGRES_DB=rec_twitcasting
volumes:
- ./postgres/init.sql:/docker-entrypoint-initdb.d/init.sql
- ./postgres/data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB} || exit 1"]
interval: 1m30s
timeout: 30s
retries: 5
start_period: 30s
env_file:
- .env

# manage
# manage-frontend-rec-twitcasting:
Expand All @@ -69,17 +59,13 @@ services:
# - 8888:8888

manage-backend-rec-twitcasting:
image: ghcr.io/miutaku/manage-backend-rec-twitcasting:latest
#build:
# context: .
# dockerfile: manage-backend/Dockerfile
#image: ghcr.io/miutaku/manage-backend-rec-twitcasting:latest
build:
context: .
dockerfile: manage-backend/Dockerfile
container_name: manage-backend-rec-twitcasting
restart: unless-stopped
environment:
- TZ=Asia/Tokyo
- DB_HOST=postgres-rec-twitcasting
- DB_PORT=5432
- DB_USER=rec-twitcasting-user
- DB_PASSWORD=rec-twitcasting-pass
- DB_NAME=rec_twitcasting
- DB_TABLE_NAME=speakers
ports:
- 18888:8888
env_file:
- .env
2 changes: 1 addition & 1 deletion manage-backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ module miutaku.dev/rec-manage-backend

go 1.22.2

require github.com/lib/pq v1.10.9 // indirect
require github.com/lib/pq v1.10.9

0 comments on commit 4986ac6

Please sign in to comment.