Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt.Printlnをやめてslogを使う #8

Merged
merged 2 commits into from
Mar 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config.yml.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ discord:
mirakc:
host: tuner
port: 40772
log:
level: INFO
3 changes: 3 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ type Config struct {
Host string `default:"tuner" env:"MIRAKC_HOST"`
Port uint `default:"40772" env:"MIRAKC_PORT"`
}
Log struct {
Level string `default:"INFO" env:"LOG_LEVEL"`
}
}
1 change: 0 additions & 1 deletion discord/discord_client/discordclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ func (d *DiscordClient) SendMessage(category string, channel string, message str
if err != nil {
return "", err
} else {
// fmt.Println(category, channel, chID, msg)
return msg.ID, nil
}
}
10 changes: 5 additions & 5 deletions discord/discord_handler/discordhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package discord_handler

import (
"context"
"fmt"

"github.com/bwmarrin/discordgo"
"github.com/kounoike/dtv-discord-go/discord"
"github.com/kounoike/dtv-discord-go/dtv"
"golang.org/x/exp/slog"
)

type DiscordHandler struct {
Expand All @@ -22,25 +22,25 @@ func NewDiscordHandler(dtv *dtv.DTVUsecase, session *discordgo.Session) *Discord
}

func (h *DiscordHandler) reactionAdd(session *discordgo.Session, reaction *discordgo.MessageReactionAdd) {
fmt.Println("add", reaction.Emoji.Name, reaction.UserID, reaction.ChannelID)
slog.Debug("add reaction emoji", "emoji", reaction.Emoji.Name, "UserID", reaction.UserID, "ChannelID", reaction.ChannelID, "MessageID", reaction.MessageID)

if reaction.Emoji.Name == discord.RecordingReactionEmoji {
ctx := context.Background()
err := h.dtv.OnRecordingEmojiAdd(ctx, reaction)
if err != nil {
fmt.Println(err)
slog.Error("onrecording emoji add error", err, "UserID", reaction.UserID, "ChannelID", reaction.ChannelID, "MessageID", reaction.MessageID)
}
}
}

func (h *DiscordHandler) reactionRemove(session *discordgo.Session, reaction *discordgo.MessageReactionRemove) {
fmt.Println("remove", reaction.Emoji.Name, reaction.UserID, reaction.ChannelID)
slog.Debug("remove reaction emoji", "emoji", reaction.Emoji.Name, "UserID", reaction.UserID, "ChannelID", reaction.ChannelID, "MessageID", reaction.MessageID)

if reaction.Emoji.Name == discord.RecordingReactionEmoji {
ctx := context.Background()
err := h.dtv.OnRecordingEmojiRemove(ctx, reaction)
if err != nil {
fmt.Println(err)
slog.Error("onrecoding emoji remove error", err, "UserID", reaction.UserID, "ChannelID", reaction.ChannelID, "MessageID", reaction.MessageID)
}
}
}
Expand Down
15 changes: 7 additions & 8 deletions dtv/on_program_updated.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,27 @@ import (
"github.com/kounoike/dtv-discord-go/db"
"github.com/kounoike/dtv-discord-go/template"
"github.com/pkg/errors"
"golang.org/x/exp/slog"
)

func (dtv *DTVUsecase) OnProgramsUpdated(serviceId uint) {
service, err := dtv.mirakc.GetService(serviceId)
_ = service
if err != nil {
fmt.Println(err)
slog.Error("mirakc GetService Error", err)
return
}
_, err = dtv.discord.SendMessage("録画-情報", "動作ログ", fmt.Sprintf("programs updated: %s", service.Name))
if err != nil {
fmt.Println(err)
slog.Error("discord SendMessage error", err)
return
}
programs, err := dtv.mirakc.ListPrograms(serviceId)
if err != nil {
fmt.Println(err)
slog.Error("mirakc ListPrograms Error", err)
return
}
// if len(programs) > 0 {
// fmt.Println(channel, len(programs), programs[0])
// }

ctx := context.Background()
for _, p := range programs {
if p.Name == "" {
Expand All @@ -40,12 +39,12 @@ func (dtv *DTVUsecase) OnProgramsUpdated(serviceId uint) {
if errors.Cause(err) == sql.ErrNoRows {
msg, err := template.GetProgramMessage(p, *service)
if err != nil {
fmt.Println(err)
slog.Error("template GetProgramMessage error", err)
return
}
msgID, err := dtv.discord.SendMessage("録画-番組情報", service.Name, msg)
if err != nil {
fmt.Println(err)
slog.Error("discord SendMessage error", err)
return
}
p.InsertDb(ctx, *dtv.queries)
Expand Down
1 change: 0 additions & 1 deletion dtv/on_recording_emoji_remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
)

func (dtv *DTVUsecase) OnRecordingEmojiRemove(ctx context.Context, reaction *discordgo.MessageReactionRemove) error {
fmt.Println("remove", reaction.Emoji.Name, reaction.UserID, reaction.ChannelID)
msg, err := dtv.discord.GetChannelMessage(reaction.ChannelID, reaction.MessageID)
if err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
github.com/r3labs/sse/v2 v2.10.0 // indirect
github.com/rubenv/sql-migrate v1.4.0 // indirect
golang.org/x/crypto v0.7.0 // indirect
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sys v0.6.0 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand Down
40 changes: 32 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"database/sql"
"fmt"
"os"

_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/configor"
Expand All @@ -14,54 +15,77 @@ import (
"github.com/kounoike/dtv-discord-go/mirakc/mirakc_client"
"github.com/kounoike/dtv-discord-go/mirakc/mirakc_handler"
migrate "github.com/rubenv/sql-migrate"
"golang.org/x/exp/slog"
)

func main() {
// programs, err := getPrograms()
var config config.Config
configor.Load(&config, "config.yml")

var logLevel slog.Level
switch config.Log.Level {
case "DEBUG":
logLevel = slog.LevelDebug
case "INFO":
logLevel = slog.LevelInfo
case "WARN":
logLevel = slog.LevelWarn
case "ERROR":
logLevel = slog.LevelError
default:
logLevel = slog.LevelInfo
slog.Error("unknown log level", "log.level", config.Log.Level)
}

slog.SetDefault(slog.New(slog.HandlerOptions{
Level: logLevel,
AddSource: true,
}.NewTextHandler(os.Stderr)))

db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true", config.DB.User, config.DB.Password, config.DB.Host, config.DB.Name))
if err != nil {
fmt.Println(err)
slog.Error("can't connect to db server", err)
return
}
queries := sqlcdb.New(db)
migrations := migrate.FileMigrationSource{Dir: "db/migrations"}
n, err := migrate.Exec(db, "mysql", migrations, migrate.Up)
if err != nil {
fmt.Println(err)
slog.Error("db migration error", err)
return
}
fmt.Printf("Applied %d migrations\n", n)
slog.Info("Applied migrations", "count", n)

mirakcClient := mirakc_client.NewMirakcClient(config.Mirakc.Host, config.Mirakc.Port)
discordClient, err := discord_client.NewDiscordClient(config, queries)
if err != nil {
fmt.Println(err)
slog.Error("can't connect to discord", err)
return
}

usecase := dtv.NewDTVUsecase(discordClient, mirakcClient, queries)

err = discordClient.Open()
if err != nil {
fmt.Println(err)
slog.Error("can't open discord session", err)
return
}
fmt.Println("Connected!")
slog.Info("Connected!")
slog.Debug("Debug!")
discordHandler := discord_handler.NewDiscordHandler(usecase, discordClient.Session())

err = usecase.CreateChannels()
if err != nil {
fmt.Println(err)
slog.Error("can't create program infomation channel", err)
return
}
slog.Info("CreateChannels OK")

discordHandler.AddReactionAddHandler()
discordHandler.AddReactionRemoveHandler()

sseHandler := mirakc_handler.NewSSEHandler(*usecase, config.Mirakc.Host, config.Mirakc.Port)
sseHandler.Subscribe()
fmt.Println("Subscribed!")
slog.Info("Subscribed!")
}
34 changes: 2 additions & 32 deletions mirakc/mirakc_client/mirakc-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
jsoniter "github.com/json-iterator/go"
"github.com/kounoike/dtv-discord-go/db"
"github.com/kounoike/dtv-discord-go/mirakc/mirakc_model"
"golang.org/x/exp/slog"

"github.com/go-resty/resty/v2"
)
Expand Down Expand Up @@ -68,33 +69,6 @@ func (m *MirakcClient) ListPrograms(serviceId uint) ([]db.Program, error) {
return nil, err
}

// // Explore response object
// fmt.Println("Response Info:")
// fmt.Println(" Error :", err)
// fmt.Println(" Status Code:", resp.StatusCode())
// fmt.Println(" Status :", resp.Status())
// fmt.Println(" Proto :", resp.Proto())
// fmt.Println(" Time :", resp.Time())
// fmt.Println(" Received At:", resp.ReceivedAt())
// // fmt.Println(" Body :\n", resp)
// fmt.Println()

// // Explore trace info
// fmt.Println("Request Trace Info:")
// ti := resp.Request.TraceInfo()
// fmt.Println(" DNSLookup :", ti.DNSLookup)
// fmt.Println(" ConnTime :", ti.ConnTime)
// fmt.Println(" TCPConnTime :", ti.TCPConnTime)
// fmt.Println(" TLSHandshake :", ti.TLSHandshake)
// fmt.Println(" ServerTime :", ti.ServerTime)
// fmt.Println(" ResponseTime :", ti.ResponseTime)
// fmt.Println(" TotalTime :", ti.TotalTime)
// fmt.Println(" IsConnReused :", ti.IsConnReused)
// fmt.Println(" IsConnWasIdle :", ti.IsConnWasIdle)
// fmt.Println(" ConnIdleTime :", ti.ConnIdleTime)
// fmt.Println(" RequestAttempt:", ti.RequestAttempt)
// fmt.Println(" RemoteAddr :", ti.RemoteAddr.String())

if resp.StatusCode() != 200 {
return nil, fmt.Errorf("HTTP Error status code: %d", resp.StatusCode())
}
Expand All @@ -110,10 +84,6 @@ func (m *MirakcClient) ListPrograms(serviceId uint) ([]db.Program, error) {
programs = append(programs, program)
}

// fmt.Printf("%+v\n", programs[0])
// fmt.Println("Start:", programs[0].GetStartTime().Local().Format(time.RFC1123))
// fmt.Println("End:", programs[0].GetEndTime().Local().Format(time.RFC1123))

return programs, nil
}

Expand All @@ -128,7 +98,7 @@ func (m *MirakcClient) AddRecordingSchedule(programID int64) error {
if err != nil {
return err
}
fmt.Println("録画予約: StatusCode:", resp.StatusCode())
slog.Info("録画予約完了", "StatusCode", resp.StatusCode())
if resp.StatusCode() == 201 {
return nil
}
Expand Down
5 changes: 3 additions & 2 deletions mirakc/mirakc_handler/sse_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/kounoike/dtv-discord-go/dtv"
"github.com/kounoike/dtv-discord-go/mirakc/mirakc_model"
"github.com/r3labs/sse/v2"
"golang.org/x/exp/slog"
)

type SSEHandler struct {
Expand All @@ -31,12 +32,12 @@ func (h *SSEHandler) Subscribe() {
h.sse.Subscribe("messages", func(msg *sse.Event) {
// Got some data!
eventName := string(msg.Event)
fmt.Printf("%s: %s\n", eventName, string(msg.Data))
slog.Debug("sse event received", "eventName", eventName, "Data", string(msg.Data))
if eventName == "epg.programs-updated" {
var data mirakc_model.ProgramsUpdatedEventData
err := json.Unmarshal(msg.Data, &data)
if err != nil {
fmt.Println(err)
slog.Error("json Unmarshal error", err)
return
}
h.onProgramsUpdated(data.ServiceId)
Expand Down