From 86c44e913beb5185e7d63855daed23d4fb25f12f Mon Sep 17 00:00:00 2001 From: Senis Date: Sat, 6 Jan 2024 22:16:20 +0800 Subject: [PATCH] Refactor EPG filtering and time parsing functions This commit includes the refactoring of EPG filtering function inside the EPG struct instead of being stand-alone. It also changes the time parsing to use a centralized function from the newly introduced infra package. The transformation optimizes code maintenance and usage by localizing related functions and promoting code reusability. --- common/epg/epg.go | 32 ++++++++++++++++---------------- infra/infra.go | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 16 deletions(-) create mode 100644 infra/infra.go diff --git a/common/epg/epg.go b/common/epg/epg.go index 20ebb37..ab14651 100644 --- a/common/epg/epg.go +++ b/common/epg/epg.go @@ -8,6 +8,8 @@ import ( "time" "github.com/mitchellh/mapstructure" + + "github.com/thank243/iptvChannel/infra" ) func BytesToAllEPGs(resp []byte) ([]Epg, error) { @@ -49,39 +51,37 @@ func BytesToValidEPGs(resp []byte) ([]Epg, error) { } var epgs []Epg - tz := time.FixedZone("CST", 3600*8) + tz := time.FixedZone("CST", 8*60*60) for i := range allEPGs { - epg, err := filterEPGs(&allEPGs[i], tz) - if err != nil { - continue + if err := allEPGs[i].filterValidEPG(tz); err == nil { + epgs = append(epgs, allEPGs[i]) } - - epgs = append(epgs, *epg) } return epgs, nil } -func filterEPGs(e *Epg, tz *time.Location) (*Epg, error) { +func (e *Epg) filterValidEPG(tz *time.Location) error { // time format: 20231228001700 - endTime, err := time.ParseInLocation("20060102150405", e.EndTimeFormat, tz) + endTime, err := infra.StrToTime(e.EndTimeFormat, tz) if err != nil { - return nil, err + return err } - beginTime, err := time.ParseInLocation("20060102150405", e.BeginTimeFormat, tz) + beginTime, err := infra.StrToTime(e.BeginTimeFormat, tz) if err != nil { - return nil, err + return err } - if beginTime.Sub(endTime) > 0 { - endTime = beginTime + if beginTime.Sub(*endTime) > 0 { + *endTime = endTime.AddDate(0, 0, 1) + e.EndTimeFormat = endTime.Format("20060102150405") } - if time.Since(endTime) > time.Hour { - return nil, fmt.Errorf("not a valid EPG: %s [%s] -> %s", e.ChannelId, e.ProgramName, e.EndTimeFormat) + if time.Since(*endTime) > time.Hour { + return fmt.Errorf("not a valid EPG: %s [%s] -> %s", e.ChannelId, e.ProgramName, e.EndTimeFormat) } - return e, nil + return nil } diff --git a/infra/infra.go b/infra/infra.go new file mode 100644 index 0000000..15f525f --- /dev/null +++ b/infra/infra.go @@ -0,0 +1,14 @@ +package infra + +import ( + "time" +) + +func StrToTime(t string, tz *time.Location) (*time.Time, error) { + toTime, err := time.ParseInLocation("20060102150405", t, tz) + if err != nil { + return nil, err + } + + return &toTime, nil +}