github.com/oinume/lekcije@v0.0.0-20231017100347-5b4c5eb6ab24/backend/cmd/notifier2/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"time"
    10  
    11  	"go.uber.org/zap"
    12  
    13  	"github.com/oinume/lekcije/backend/cli"
    14  	"github.com/oinume/lekcije/backend/domain/config"
    15  	"github.com/oinume/lekcije/backend/infrastructure/dmm_eikaiwa"
    16  	"github.com/oinume/lekcije/backend/infrastructure/mysql"
    17  	"github.com/oinume/lekcije/backend/logger"
    18  	"github.com/oinume/lekcije/backend/model"
    19  	"github.com/oinume/lekcije/backend/model2"
    20  	"github.com/oinume/lekcije/backend/usecase"
    21  )
    22  
    23  func main() {
    24  	m := &notifierMain{
    25  		outStream: os.Stdout,
    26  		errStream: os.Stderr,
    27  	}
    28  	if err := m.run(os.Args); err != nil {
    29  		cli.WriteError(m.errStream, err)
    30  		os.Exit(cli.ExitError)
    31  	}
    32  	os.Exit(cli.ExitOK)
    33  }
    34  
    35  type notifierMain struct {
    36  	outStream io.Writer
    37  	errStream io.Writer
    38  }
    39  
    40  func (m *notifierMain) run(args []string) error {
    41  	flagSet := flag.NewFlagSet("notifier", flag.ContinueOnError)
    42  	flagSet.SetOutput(m.errStream)
    43  	var (
    44  		concurrency = flagSet.Int("concurrency", 1, "Concurrency of fetcher")
    45  		//		dryRun               = flagSet.Bool("dry-run", false, "Don't update database with fetched lessons")
    46  		fetcherCache         = flagSet.Bool("fetcher-cache", false, "Cache teacher and lesson data in Fetcher")
    47  		notificationInterval = flagSet.Int("notification-interval", 0, "Notification interval")
    48  		//		sendEmail            = flagSet.Bool("send-email", true, "Flag to send email")
    49  		logLevel = flagSet.String("log-level", "info", "Log level")
    50  	)
    51  	if err := flagSet.Parse(args[1:]); err != nil {
    52  		return err
    53  	}
    54  	if *notificationInterval == 0 {
    55  		return fmt.Errorf("-notification-interval is required")
    56  	}
    57  
    58  	ctx := context.Background()
    59  	config.MustProcessDefault()
    60  
    61  	startedAt := time.Now().UTC()
    62  	appLogger := logger.NewAppLogger(os.Stderr, logger.NewLevel(*logLevel))
    63  	appLogger.Info(fmt.Sprintf("notifier started (interval=%d)", *notificationInterval))
    64  	defer func() {
    65  		elapsed := time.Now().UTC().Sub(startedAt) / time.Millisecond
    66  		appLogger.Info(
    67  			fmt.Sprintf("notifier finished (interval=%d)", *notificationInterval),
    68  			zap.Int("elapsed", int(elapsed)),
    69  		)
    70  	}()
    71  
    72  	gormDB, err := model.OpenDB(config.DefaultVars.DBURL(), 1, config.DefaultVars.DebugSQL)
    73  	if err != nil {
    74  		return err
    75  	}
    76  	defer func() { _ = gormDB.Close() }()
    77  
    78  	dbRepo := mysql.NewDBRepository(gormDB.DB())
    79  	//	lessonRepo := mysql.NewLessonRepository(gormDB.DB())
    80  	userRepo := mysql.NewUserRepository(gormDB.DB())
    81  	userGoogleRepo := mysql.NewUserGoogleRepository(gormDB.DB())
    82  	userUsecase := usecase.NewUser(dbRepo, userRepo, userGoogleRepo)
    83  
    84  	users, err := userUsecase.FindAllByEmailVerified(ctx, *notificationInterval)
    85  	if err != nil {
    86  		return err
    87  	}
    88  	mCountries, err := mysql.NewMCountryRepository(gormDB.DB()).FindAll(ctx)
    89  	if err != nil {
    90  		return err
    91  	}
    92  	mCountryList := model2.NewMCountryList(mCountries)
    93  
    94  	lessonFetcher := dmm_eikaiwa.NewLessonFetcher(nil, *concurrency, *fetcherCache, mCountryList, appLogger)
    95  	notificationUsecase := usecase.NewNotification()
    96  	notifier := notificationUsecase.NewLessonNotifier(lessonFetcher)
    97  	defer notifier.Close(ctx, &model2.StatNotifier{
    98  		Datetime:             startedAt,
    99  		Interval:             uint8(*notificationInterval),
   100  		Elapsed:              0,
   101  		UserCount:            uint(len(users)),
   102  		FollowedTeacherCount: 0,
   103  	})
   104  	for _, user := range users {
   105  		if err := notifier.SendNotification(ctx, user); err != nil {
   106  			return err
   107  		}
   108  	}
   109  
   110  	// lessonFetcher := fetcher.NewLessonFetcher(nil, *concurrency, *fetcherCache, mCountries, appLogger)
   111  
   112  	return nil
   113  }