You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.7 KiB
Go

package diyanetapi
import (
"context"
"fmt"
"time"
"github.com/imroc/req/v3"
"prayertimes/pkg/prayer"
)
type Provider struct {
http *req.Client
}
func New(c *req.Client) Provider {
return Provider{
http: c.Clone().SetCommonBasicAuth("diyanet", "Q6Y3vYt5F3x2txPaaMF3uPgbK99EJhpM"),
}
}
func (d Provider) GetByCoords(ctx context.Context, coords prayer.Coordinates) ([]prayer.Times, error) {
res, err := d.http.NewRequest().
SetContext(ctx).
SetQueryParams(map[string]string{
"latitude": fmt.Sprintf("%f", coords.Latitude),
"longitude": fmt.Sprintf("%f", coords.Longitude),
}).
Get("https://namazvakti.diyanet.gov.tr/api/NamazVakti/Aylik")
if err != nil {
return nil, fmt.Errorf("failed to get prayer times by coords: %w", err)
}
return d.parseResponse(res)
}
func (d Provider) Get(ctx context.Context, locationID string) ([]prayer.Times, error) {
res, err := d.http.NewRequest().
SetContext(ctx).
SetQueryParam("ilceId", locationID).
Get("https://namazvakti.diyanet.gov.tr/api/NamazVakti/Aylik")
if err != nil {
return nil, fmt.Errorf("failed to get prayer times by location id: %w", err)
}
return d.parseResponse(res)
}
func (d Provider) parseResponse(res *req.Response) ([]prayer.Times, error) {
var response struct {
Success bool `json:"success"`
ResultObject struct {
Location struct {
ID int `json:"konum_Id"`
Timezone string `json:"timezone"`
} `json:"konum"`
PrayerTimes []struct {
Date time.Time `json:"miladi_tarih_uzun_Iso8601"`
Fajr time.Time `json:"imsak"`
Sunrise time.Time `json:"gunes"`
Dhuhr time.Time `json:"ogle"`
Asr time.Time `json:"ikindi"`
Maghrib time.Time `json:"aksam"`
Isha time.Time `json:"yatsi"`
} `json:"namazVakti"`
} `json:"resultObject"`
}
if err := res.Unmarshal(&response); err != nil {
return nil, fmt.Errorf("failed to unmarshal as json: %w", err)
}
if !response.Success {
return nil, fmt.Errorf("received error: %s", res.String())
}
if len(response.ResultObject.PrayerTimes) == 0 {
return nil, nil
}
var times []prayer.Times
today := time.Now().UTC().Truncate(time.Hour * 24)
for _, pt := range response.ResultObject.PrayerTimes {
then := prayer.Date(pt.Date).Time()
if then.Before(today) {
continue
}
times = append(times, prayer.Times{
Date: pt.Date.Format(time.DateOnly),
Fajr: pt.Fajr.Format(time.TimeOnly),
Sunrise: pt.Sunrise.Format(time.TimeOnly),
Dhuhr: pt.Dhuhr.Format(time.TimeOnly),
Asr: pt.Asr.Format(time.TimeOnly),
Maghrib: pt.Maghrib.Format(time.TimeOnly),
Isha: pt.Isha.Format(time.TimeOnly),
})
}
return times, nil
}
func (d Provider) Name() string {
return "diyanetapi"
}