epg

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 18, 2021 License: MIT Imports: 11 Imported by: 0

README

epg

Build Status Go Report Card GoDoc License MIT

Go client for the C More EPG Web API.

Status

Still under active development. Expect breaking changes.

Installation

go get -u github.com/TV4/epg

Usage examples

The TV4 schedule for today

package main

import (
	"context"
	"fmt"
	"time"

	epg "github.com/TV4/epg"
)

func main() {
	var (
		ec   = epg.NewClient()
		ctx  = context.Background()
		date = epg.DateAtTime(time.Now())
	)

	if r, err := ec.Get(ctx, epg.Sweden, epg.Swedish, date); err == nil {
		c := r.Day().Channel(epg.TV4)

		for _, s := range c.Schedules {
			fmt.Println(s.CalendarDate.Format("15:04"), s.Program.Title)
		}
	}
}

Drama on CMoreStarsHD

package main

import (
	"context"
	"encoding/json"
	"net/url"
	"os"

	epg "github.com/TV4/epg"
)

func main() {
	c := epg.NewClient()

	if r, err := c.GetChannel(
		context.Background(),
		epg.Sweden,
		epg.Swedish,
		epg.Date(2017, 1, 26),
		epg.Date(2017, 1, 28),
		epg.CMoreStarsHD,
		url.Values{
			"genre": {"Drama"},
		},
	); err == nil {
		enc := json.NewEncoder(os.Stdout)
		enc.SetIndent("", " ")
		enc.Encode(r)
	}
}

Primetime movies in Sweden 2017-05-24

package main

import (
	"context"
	"encoding/json"
	"net/url"
	"os"

	epg "github.com/TV4/epg"
)

func main() {
	r, err := epg.NewClient().Get(
		context.Background(),
		epg.Sweden,
		epg.Swedish,
		epg.Date(2017, 5, 24),
		url.Values{
			"filter": {"primetimemovies"},
		},
	)
	if err != nil {
		return
	}

	d := r.Day()

	programs := map[string]epg.Program{}

	for _, c := range d.Channels {
		for _, s := range c.Schedules {
			programs[s.Program.ID] = s.Program
		}
	}

	var movies []movie

	for _, p := range programs {
		var cover string

		for _, m := range p.Images {
			if m.Category == "Cover" {
				cover = m.URL("164").String()
			}
		}

		movies = append(movies, movie{
			Title: p.Title,
			Facts: p.SynopsisFacts,
			Cover: cover,
		})
	}

	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", " ")
	enc.Encode(movies)
}

type movie struct {
	Title string `json:"title"`
	Facts string `json:"facts,omitempty"`
	Cover string `json:"cover,omitempty"`
}

API documentation

https://api.cmore.se/

License (MIT)

Copyright © 2017-2018 TV4

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package epg contains a client for the C More EPG Web API

Installation

Just go get the package:

go get -u github.com/TV4/epg

Usage

A small usage example

package main

import (
	"context"
	"fmt"
	"time"

	epg "github.com/TV4/epg"
)

func main() {
	var (
		ec   = epg.NewClient()
		ctx  = context.Background()
		date = epg.DateAtTime(time.Now())
	)

	if r, err := ec.Get(ctx, epg.Sweden, epg.Swedish, date); err == nil {
		c := r.Day().Channel(epg.TV4)

		for _, s := range c.Schedules {
			fmt.Println(s.CalendarDate, s.Program.Title)
		}
	}
}

Documentation

http://api.cmore.se/

Index

Examples

Constants

View Source
const (
	CanalExtra1            = "3"
	CanalExtra2            = "4"
	CanalExtra3            = "5"
	CanalExtraHD           = "7"
	CanalFilm1             = "8"
	CanalFilm2             = "9"
	CanalFilm3             = "11"
	CanalHD                = "12"
	CanalPanNordic         = "15"
	CanalPlusHD            = "17"
	CanalPlusHitsHD        = "18"
	CanalSport2            = "21"
	CanalSport3            = "22"
	CanalSportFotboll      = "25"
	CanalSportHockey       = "26"
	CanalSportNorway       = "27"
	CanalSportSweden       = "28"
	CF4                    = "29"
	SFK                    = "32"
	SFKBoxer               = "33"
	SHD                    = "34"
	SeriesHD               = "52"
	TV2SportPremium4HD     = "53"
	CMoreFotbollHockeyKids = "54"
	CMoreLive2HD           = "65"
	CMoreLive3HD           = "66"
	CMoreLive4HD           = "67"
	CMoreHockeyHD          = "68"
	CMoreGolfHD            = "70"
	CMoreGolfDenmarkHD     = "71"
	CMoreGolf              = "72"
	CMoreGolfDenmark       = "73"
	SVT1                   = "74"
	SVT2                   = "75"
	TV4                    = "76"
	TV4Sport               = "78"
	Sjuan                  = "79"
	TV12                   = "80"
	TV4FaktaXL             = "81"
	TV4Fakta               = "82"
	TV4Film                = "83"
	TV4Guld                = "84"
	TV4Komedi              = "85"
	SVT24                  = "86"
	SVTKunskapskanalen     = "87"
	Barnkanalen            = "88"
	CMoreStars             = "89"
	CMoreStarsHD           = "90"
	CMoreLive5             = "94"
	CMoreLive5HD           = "95"
	Sportkanalen           = "97"
	SportkanalenHD         = "98"
)

Channel constants

Data retrieved like this:

curl -H "Accept: application/xml" "https://api.cmore.se/epg/se/sv/2017-01-26/2017-02-13" | xmllint --format - |
grep ChannelId | awk -F '"' '{print $2 " " $4 " = \"" $2 "\""}' | sort -n | uniq | awk '{print $2 " " $3 " " $4}' | pbcopy

Variables

View Source
var (
	// ErrNotFound means that the resource could not be found
	ErrNotFound = errors.New("not found")

	// ErrUnknown means that an unexpected error occurred
	ErrUnknown = errors.New("unknown error")
)
View Source
var ImageBaseURL = &url.URL{Scheme: "https", Host: "img-cdn-cmore.b17g.services"}

ImageBaseURL is the base URL for images

View Source
var Stockholm *time.Location

Stockholm is the Time Zone in Sweden

Functions

func BaseURL

func BaseURL(rawurl string) func(*Client)

BaseURL changes the *client base URL based on the provided rawurl

func ChannelID

func ChannelID(name string) string

ChannelID returns the channel ID based on provided channel name

func Date

func Date(year int, month time.Month, day int) string

Date formats a year, month, day into the format yyyy-mm-dd

func DateAtTime

func DateAtTime(t time.Time) string

DateAtTime returns the date string for the provided time.Time

func HTTPClient

func HTTPClient(hc *http.Client) func(*Client)

HTTPClient changes the *client HTTP client to the provided *http.Client

func Names

func Names(s string) []string

Names takes a string of comma separated names, splits them into a slice, trims any space around each name

Example
fmt.Printf("%#v\n", Names("August Diehl,Sara Hjort Ditlevsen, Jo Adrian Haavind"))
Output:

[]string{"August Diehl", "Sara Hjort Ditlevsen", "Jo Adrian Haavind"}

func UserAgent

func UserAgent(ua string) func(*Client)

UserAgent changes the User-Agent used in requests sent by the *client

Types

type Channel

type Channel struct {
	ID          string     `xml:"ChannelId,attr" json:"channel_id"`
	Name        string     `xml:"Name,attr" json:"name"`
	Title       string     `xml:"Title,attr" json:"title"`
	LogoID      string     `xml:"LogoId,attr" json:"logo_id"`
	LogoDarkID  string     `xml:"LogoDarkId,attr" json:"logo_dark_id"`
	LogoLightID string     `xml:"LogoLightId,attr" json:"logo_light_id"`
	IsHD        bool       `xml:"IsHd,attr" json:"hd"`
	Schedules   []Schedule `xml:"Schedule" json:"schedules,omitempty"`
}

Channel is a TV channel in the EPG

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client for the EPG Web API

func NewClient

func NewClient(options ...func(*Client)) *Client

NewClient creates an EPG Client

func (*Client) Get

func (c *Client) Get(ctx context.Context, country Country, language Language, date string, attributes ...url.Values) (*Response, error)

Get retrieves a response for the given country, language and date

func (*Client) GetChannel

func (c *Client) GetChannel(ctx context.Context, country Country, language Language, fromDate, toDate, channelID string, attributes ...url.Values) (*Response, error)

GetChannel retrieves a channel in the period fromDate until toDate

func (*Client) GetChannelGroup

func (c *Client) GetChannelGroup(ctx context.Context, country Country, language Language, fromDate, toDate, channelGroup string, attributes ...url.Values) (*Response, error)

GetChannelGroup retrieves the channel group in the period fromDate until toDate

func (*Client) GetPeriod

func (c *Client) GetPeriod(ctx context.Context, country Country, language Language, fromDate, toDate string, attributes ...url.Values) (*Response, error)

GetPeriod retrieves the response for the period fromDate until toDate

type Country

type Country string

Country is the type used for lowercase ISO 3166-1 alpha-2 country codes as per https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

const (
	// Sweden is the country code se
	Sweden Country = "se"

	// Norway is the country code no
	Norway Country = "no"

	// Denmark is the country code dk
	Denmark Country = "dk"

	// Finland is the country code fi
	Finland Country = "fi"
)

type Day

type Day struct {
	BroadcastDate Time      `xml:"BroadcastDate,attr" json:"broadcast_date"`
	Channels      []Channel `xml:"Channel" json:"channels,omitempty"`
}

Day is an EPG day

func (Day) Channel

func (d Day) Channel(id string) Channel

Channel returns the channel with the given id. Returns empty Channel if not found

type Image

type Image struct {
	ID       string `xml:"Id,attr" json:"id"`
	Category string `xml:"Category,attr" json:"category"`
}

Image is a typed identifier for an image that can be retrieved at https://img-cdn-cmore.b17g.services/:id/:format.img

(format 164 can be used to retrieve the full size image)

func (Image) URL

func (m Image) URL(format string) *url.URL

URL returns an *url.URL based on the ImageBaseURL, image ID and provided format

type Language

type Language string

Language is the type used for ISO 639-1 language codes as per https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes

const (
	// Swedish is the language code sv
	Swedish Language = "sv"

	// Norwegian is the language code no
	Norwegian Language = "no"

	// Danish is the language code da
	Danish Language = "da"

	// Finnish is the language code fi
	Finnish Language = "fi"
)

type Meta

type Meta map[string]interface{}

Meta is a type used for request/response metadata

type Program

type Program struct {
	ID                       string  `xml:"ProgramId,attr" json:"program_id"`
	Title                    string  `xml:"Title,attr" json:"title"`
	OriginalTitle            string  `xml:"OriginalTitle,attr" json:"original_title"`
	Genre                    string  `xml:"Genre,attr" json:"genre"`
	GenreKey                 string  `xml:"GenreKey,attr" json:"genre_key"`
	FirstCalendarDate        Time    `xml:"FirstCalendarDate,attr" json:"first_calendar_date"`
	LastCalendarDate         Time    `xml:"LastCalendarDate,attr" json:"last_calendar_date"`
	VodStart                 Time    `xml:"VodStart,attr" json:"vod_start"`
	VodEnd                   Time    `xml:"VodEnd,attr" json:"vod_end"`
	Duration                 int     `xml:"Duration,attr" json:"duration"`
	ContentSourceID          string  `xml:"ContentSourceId,attr" json:"content_source_id"`
	ProductionYear           string  `xml:"ProductionYear,attr" json:"production_year"`
	Rating                   string  `xml:"Rating,attr" json:"rating"`
	Actors                   string  `xml:"Actors,attr" json:"actors"`
	Directors                string  `xml:"Directors,attr" json:"directors"`
	Class                    string  `xml:"Class,attr" json:"class"`
	Type                     string  `xml:"Type,attr" json:"type"`
	Category                 string  `xml:"Category,attr" json:"category"`
	IsDubbedVersionAvailable bool    `xml:"IsDubbedVersionAvailable,attr" json:"dubbed_version_available"`
	VOD                      bool    `xml:"Vod,attr" json:"vod"`
	OTTBlackout              bool    `xml:"OTTBlackout,attr" json:"ott_blackout"`
	IsDubbed                 bool    `xml:"IsDubbed,attr" json:"dubbed"`
	Images                   []Image `xml:"Resources>Image" json:"images"`
	SeriesID                 string  `xml:"SeriesId,attr" json:"series_id"`
	SeasonNumber             int     `xml:"SeasonNumber,attr" json:"season_number"`
	EpisodeNumber            int     `xml:"EpisodeNumber,attr" json:"episode_number"`
	NumberOfEpisodes         int     `xml:"NumberOfEpisodes,attr" json:"number_of_episodes"`
	SynopsisExtraShort       string  `xml:"Synopsis>ExtraShort" json:"extra_short"`
	SynopsisShort            string  `xml:"Synopsis>Short" json:"short"`
	SynopsisMedium           string  `xml:"Synopsis>Medium" json:"medium"`
	SynopsisLong             string  `xml:"Synopsis>Long" json:"long"`
	SynopsisFacts            string  `xml:"Synopsis>Facts" json:"facts"`
}

Program is the program that is scheduled in the EPG

type Response

type Response struct {
	Days      []Day `xml:"Day,omitempty" json:"days,omitempty"`
	FromDate  Time  `xml:"FromDate,attr" json:"from_date,omitempty"`
	UntilDate Time  `xml:"UntilDate,attr" json:"until_date,omitempty"`
	Meta      *Meta `xml:"-" json:"meta,omitempty"`
}

Response data from the EPG API

func (*Response) Day

func (r *Response) Day(dates ...string) Day

Day returns the first day in the response, or the (optional) provided date. Returns empty Day if not found

type Schedule

type Schedule struct {
	ID                string  `xml:"ScheduleId,attr" json:"schedule_id"`
	NextStart         Time    `xml:"NextStart,attr" json:"next_start"`
	CalendarDate      Time    `xml:"CalendarDate,attr" json:"calendar_date"`
	IsPremiere        bool    `xml:"IsPremiere,attr" json:"premiere"`
	IsDubbed          bool    `xml:"IsDubbed,attr" json:"dubbed"`
	Type              string  `xml:"Type,attr" json:"type"`
	AlsoAvailableInHD bool    `xml:"AlsoAvailableInHD,attr" json:"also_available_in_hd"`
	AlsoAvailableIn3D bool    `xml:"AlsoAvailableIn3D,attr" json:"also_available_in_3d"`
	Is3D              bool    `xml:"Is3D,attr" json:"is_3d"`
	IsPPV             bool    `xml:"IsPPV,attr" json:"is_ppv"`
	PlayAssetID       string  `xml:"PlayAssetId1,attr" json:"play_asset_id"`
	Program           Program `xml:"Program" json:"program"`
}

Schedule is the TV program schedule of a channel in the EPG

type Time

type Time struct {
	time.Time
}

Time wraps time.Time

func (*Time) MarshalJSON

func (t *Time) MarshalJSON() ([]byte, error)

MarshalJSON marshals the Time

func (*Time) UnmarshalXMLAttr

func (t *Time) UnmarshalXMLAttr(attr xml.Attr) error

UnmarshalXMLAttr handles special cases like 0001-01-01T00:00:00+01:00 and 9999-12-31T23:59:59+01:00

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL