fc2

package
v1.7.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2024 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package fc2 provides a way to watch a FC2 channel.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrQualityNotExpected is returned when the quality is not expected.
	ErrQualityNotExpected = errors.New("requested quality is not expected")
	// ErrQualityNotAvailable is returned when the quality is not available.
	ErrQualityNotAvailable = errors.New("requested quality is not available")
)
View Source
var (
	// ErrLiveStreamNotOnline is returned when the live stream is not online.
	ErrLiveStreamNotOnline = errors.New("live stream is not online")
	// ErrRateLimit is returned when the API is rate limited.
	ErrRateLimit = errors.New("API rate limited")
)
View Source
var (
	// ErrWebSocketServerDisconnection is returned when the server disconnects.
	ErrWebSocketServerDisconnection = errors.New("server disconnected")
	// ErrWebSocketPaidProgram is returned when the server returns a paid program error.
	ErrWebSocketPaidProgram = errors.New("paid program")
	// ErrWebSocketLoginRequired is returned when the server returns a login required error.
	ErrWebSocketLoginRequired = errors.New("login required")
	// ErrWebSocketMultipleConnection is returned when the server returns a multiple connection error.
	ErrWebSocketMultipleConnection = errors.New("multiple connection error")
	// ErrWebSocketStreamEnded is returned when the server ends the stream.
	ErrWebSocketStreamEnded = errors.New("stream ended")
	// ErrWebSocketEmptyPlaylist is returned when the server does not return a valid playlist.
	ErrWebSocketEmptyPlaylist = errors.New("server did not return a valid playlist")
)
View Source
var DefaultParams = Params{
	Quality:                    Quality1_2MBps,
	Latency:                    LatencyMid,
	PacketLossMax:              20,
	OutFormat:                  "{{ .Date }} {{ .Title }} ({{ .ChannelName }}).{{ .Ext }}",
	WriteChat:                  false,
	WriteInfoJSON:              false,
	WriteThumbnail:             false,
	WaitForLive:                true,
	WaitForQualityMaxTries:     60,
	AllowQualityUpgrade:        false,
	PollQualityUpgradeInterval: 10 * time.Second,
	WaitPollInterval:           5 * time.Second,
	CookiesFile:                "",
	CookiesRefreshDuration:     24 * time.Hour,
	Remux:                      true,
	RemuxFormat:                "mp4",
	Concat:                     true,
	KeepIntermediates:          false,
	ScanDirectory:              "",
	EligibleForCleaningAge:     48 * time.Hour,
	DeleteCorrupted:            true,
	ExtractAudio:               false,
	Labels:                     nil,
}

DefaultParams is the default set of parameters.

View Source
var ErrUnknownLatency = errors.New("unknown latency")

ErrUnknownLatency is returned when the latency is unknown.

View Source
var ErrUnknownQuality = errors.New("unknown quality")

ErrUnknownQuality is returned when the quality is unknown.

Functions

func FormatOutput added in v1.6.0

func FormatOutput(
	outFormat string,
	meta *GetMetaData,
	labels map[string]string,
	ext string,
) (string, error)

FormatOutput formats the output file name.

func Login added in v1.3.0

func Login(ctx context.Context, opts ...LoginOption) error

Login to FC2 and fill the CookieJar.

You need to probably need to

func LoginLoop added in v1.3.0

func LoginLoop(
	ctx context.Context,
	duration time.Duration,
	opts ...LoginOption,
)

LoginLoop will try to login to FC2 every duration.

func PrepareFile added in v1.6.0

func PrepareFile(
	outFormat string,
	meta *GetMetaData,
	labels map[string]string,
	ext string,
) (fName string, err error)

PrepareFile prepares a file with a unique name.

Types

type Channel added in v1.6.4

type Channel struct {
	Result      int           `json:"result"`
	UserID      int           `json:"userid"`
	Fc2ID       int           `json:"fc2id"`
	Adult       int           `json:"adult"`
	Title       string        `json:"title"`
	Description string        `json:"description"`
	URL         string        `json:"url"`
	Images      []interface{} `json:"images"`
}

Channel describes the FC2 channel.

type ChannelData

type ChannelData struct {
	ChannelID           string                `json:"channelid"`
	UserID              string                `json:"userid"`
	Adult               int                   `json:"adult"`
	Twoshot             int                   `json:"twoshot"`
	Title               string                `json:"title"`
	Info                string                `json:"info"`
	Image               string                `json:"image"`
	LoginOnly           int                   `json:"login_only"`
	GiftLimit           int                   `json:"gift_limit"`
	GiftList            []ChannelDataGiftList `json:"gift_list"`
	CommentLimit        string                `json:"comment_limit"`
	Tfollow             int                   `json:"tfollow"`
	Tname               string                `json:"tname"`
	Fee                 int                   `json:"fee"`
	Amount              int                   `json:"amount"`
	Interval            int                   `json:"interval"`
	Category            string                `json:"category"`
	CategoryName        string                `json:"category_name"`
	IsOfficial          int                   `json:"is_official"`
	IsPremiumPublisher  int                   `json:"is_premium_publisher"`
	IsLinkShare         int                   `json:"is_link_share"`
	Ticketid            int                   `json:"ticketid"`
	IsPremium           int                   `json:"is_premium"`
	TicketPrice         int                   `json:"ticket_price"`
	TicketOnly          int                   `json:"ticket_only"`
	IsApp               int                   `json:"is_app"`
	IsVideo             int                   `json:"is_video"`
	IsREST              int                   `json:"is_rest"`
	Count               int                   `json:"count"`
	IsPublish           int                   `json:"is_publish"`
	IsLimited           int                   `json:"is_limited"`
	Start               int                   `json:"start"`
	Version             string                `json:"version"`
	FC2Channel          Channel               `json:"fc2_channel"`
	ControlTag          string                `json:"control_tag"`
	PublishMethod       string                `json:"publish_method"`
	VideoStereo3D       interface{}           `json:"video_stereo3d"`
	VideoMapping        interface{}           `json:"video_mapping"`
	VideoHorizontalView interface{}           `json:"video_horizontal_view"`
}

ChannelData describes the FC2 channel and stream.

type ChannelDataGiftList

type ChannelDataGiftList struct {
	ID   int      `json:"id"`
	Type int      `json:"type"`
	URL  []string `json:"url"`
	Name string   `json:"name"`
}

ChannelDataGiftList describes the gifts that can be sent to the FC2 user.

type Comment

type Comment struct {
	UserName        string `json:"user_name"`
	Comment         string `json:"comment"`
	Timestamp       int    `json:"timestamp"`
	EncryptedUserID string `json:"encrypted_user_id"`
	OrzToken        string `json:"orz_token"`
	Hash            string `json:"hash"`
	Color           string `json:"color"`
	Size            string `json:"size"`
	Lang            string `json:"lang"`
	Anonymous       int    `json:"anonymous"`
	History         int    `json:"history"`
}

Comment is the response from the websocket.

type CommentArguments

type CommentArguments struct {
	Comments []Comment `json:"comments"`
}

CommentArguments is the type of response corresponding to the "comment" event.

type ControlDisconnectionArguments

type ControlDisconnectionArguments struct {
	Code int `json:"code"`
}

ControlDisconnectionArguments is the type of response corresponding to the "control_disconnection" event.

type ControlToken

type ControlToken struct {
	ChannelID string `json:"channel_id,omitempty"`
	UserID    string `json:"user_id,omitempty"`
	// Fc2ID is either a string when logged in, or the integer 0.
	Fc2ID          any `json:"fc2_id,omitempty"`
	OrzToken       any `json:"orz_token,omitempty"`
	SessionToken   any `json:"session_token,omitempty"`
	Premium        any `json:"premium,omitempty"`
	Mode           any `json:"mode,omitempty"`
	Language       any `json:"language,omitempty"`
	ClientType     any `json:"client_type,omitempty"`
	ClientApp      any `json:"client_app,omitempty"`
	ClientVersion  any `json:"client_version,omitempty"`
	AppInstallKey  any `json:"app_install_key,omitempty"`
	ChannelVersion any `json:"channel_version,omitempty"`
	ControlTag     any `json:"control_tag,omitempty"`
	Ipv6           any `json:"ipv6,omitempty"`
	Commentable    any `json:"commentable,omitempty"`
	ServiceID      any `json:"service_id,omitempty"`
	IP             any `json:"ip,omitempty"`
	UserName       any `json:"user_name,omitempty"`
	AdultAccess    any `json:"adult_access,omitempty"`
	AgentID        any `json:"agent_id,omitempty"`
	CountryCode    any `json:"country_code,omitempty"`
	PayMode        any `json:"pay_mode,omitempty"`
	jwt.RegisteredClaims
}

ControlToken is the token used to authenticate with the FC2 API.

type FC2

type FC2 struct {
	*http.Client
	// contains filtered or unexported fields
}

FC2 is responsible to watch a FC2 channel.

func New added in v0.4.0

func New(client *http.Client, params *Params, channelID string) *FC2

New creates a new FC2.

func (*FC2) FetchPlaylist

func (f *FC2) FetchPlaylist(
	ctx context.Context,
	ws *WebSocket,
	conn *websocket.Conn,
	msgChan chan *WSResponse,
	verbose bool,
) (*Playlist, error)

FetchPlaylist fetches the playlist.

func (*FC2) HandleWS

func (f *FC2) HandleWS(
	ctx context.Context,
	wsURL string,
	fnameStream string,
	fnameChat string,
) error

HandleWS handles the websocket connection.

func (*FC2) Watch added in v0.4.0

func (f *FC2) Watch(ctx context.Context) (*GetMetaData, error)

Watch watches the channel for any new live stream.

type GetControlServerResponse

type GetControlServerResponse struct {
	URL          string `json:"url"`
	Orz          string `json:"orz"`
	OrzRaw       string `json:"orz_raw"`
	ControlToken string `json:"control_token"`
	Status       int    `json:"status"`
}

GetControlServerResponse is the response from the get_control_server endpoint.

type GetMetaData

type GetMetaData struct {
	ChannelData ChannelData `json:"channel_data"`
	ProfileData ProfileData `json:"profile_data"`
	UserData    UserData    `json:"user_data"`
}

GetMetaData is the data of the response from the get_meta endpoint.

type GetMetaOption added in v1.2.0

type GetMetaOption func(*GetMetaOptions)

GetMetaOption is a function that sets options for GetMeta.

func WithRefetch added in v1.2.0

func WithRefetch() GetMetaOption

WithRefetch forces a refetch of the meta.

type GetMetaOptions

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

GetMetaOptions contains options for GetMeta.

type GetMetaResponse

type GetMetaResponse struct {
	Status int         `json:"status"`
	Data   GetMetaData `json:"data"`
}

GetMetaResponse is the response from the get_meta endpoint.

type HLSInformation

type HLSInformation struct {
	Status                 int        `json:"status"`
	Playlists              []Playlist `json:"playlists"`
	PlaylistsHighLatency   []Playlist `json:"playlists_high_latency"`
	PlaylistsMiddleLatency []Playlist `json:"playlists_middle_latency"`
}

HLSInformation is the response from the get_hls_information endpoint.

type Latency

type Latency int

Latency represents the latency of the live stream.

const (
	// LatencyUnknown represents an unknown latency.
	LatencyUnknown Latency = 0
	// LatencyLow represents a low latency.
	LatencyLow Latency = 1
	// LatencyHigh represents a high latency.
	LatencyHigh Latency = 2
	// LatencyMid represents a mid latency.
	LatencyMid Latency = 3
)

func LatencyFromMode

func LatencyFromMode(mode int) Latency

LatencyFromMode returns a Latency from a mode.

func LatencyParseString

func LatencyParseString(value string) Latency

LatencyParseString parses a string into a Latency.

func (Latency) String

func (l Latency) String() string

String returns the string representation of a Latency.

func (*Latency) UnmarshalText

func (l *Latency) UnmarshalText(text []byte) error

UnmarshalText unmarshals a string into a Latency.

type LiveStream

type LiveStream struct {
	*http.Client
	ChannelID string
	// contains filtered or unexported fields
}

LiveStream encapsulates the FC2 live stream.

func NewLiveStream

func NewLiveStream(client *http.Client, channelID string) *LiveStream

NewLiveStream creates a new LiveStream.

func (*LiveStream) GetMeta

func (ls *LiveStream) GetMeta(
	ctx context.Context,
	options ...GetMetaOption,
) (*GetMetaData, error)

GetMeta gets the metadata of the live stream.

func (*LiveStream) GetWebSocketURL

func (ls *LiveStream) GetWebSocketURL(ctx context.Context) (string, error)

GetWebSocketURL gets the WebSocket URL for the live stream.

func (*LiveStream) IsOnline

func (ls *LiveStream) IsOnline(ctx context.Context, options ...GetMetaOption) (bool, error)

IsOnline checks if the live stream is online.

func (*LiveStream) WaitForOnline

func (ls *LiveStream) WaitForOnline(ctx context.Context, interval time.Duration) error

WaitForOnline waits for the live stream to be online.

type LoginOption added in v1.3.0

type LoginOption func(*LoginOptions)

LoginOption is used to configure the login process.

func WithHTTPClient added in v1.3.0

func WithHTTPClient(client *http.Client) LoginOption

WithHTTPClient is used to set the HTTP client used to login.

type LoginOptions added in v1.3.0

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

LoginOptions is used to configure the login process.

type OptionalParams

type OptionalParams struct {
	Quality                    *Quality          `yaml:"quality,omitempty"`
	Latency                    *Latency          `yaml:"latency,omitempty"`
	PacketLossMax              *int              `yaml:"packetLossMax,omitempty"`
	OutFormat                  *string           `yaml:"outFormat,omitempty"`
	WriteChat                  *bool             `yaml:"writeChat,omitempty"`
	WriteInfoJSON              *bool             `yaml:"writeInfoJson,omitempty"`
	WriteThumbnail             *bool             `yaml:"writeThumbnail,omitempty"`
	WaitForLive                *bool             `yaml:"waitForLive,omitempty"`
	WaitForQualityMaxTries     *int              `yaml:"waitForQualityMaxTries,omitempty"`
	AllowQualityUpgrade        *bool             `yaml:"allowQualityUpgrade,omitempty"`
	PollQualityUpgradeInterval *time.Duration    `yaml:"pollQualityUpgradeInterval,omitempty"`
	WaitPollInterval           *time.Duration    `yaml:"waitPollInterval,omitempty"`
	CookiesFile                *string           `yaml:"cookiesFile,omitempty"`
	CookiesRefreshDuration     *time.Duration    `yaml:"cookiesRefreshDuration,omitempty"`
	Remux                      *bool             `yaml:"remux,omitempty"`
	RemuxFormat                *string           `yaml:"remuxFormat,omitempty"`
	Concat                     *bool             `yaml:"concat,omitempty"`
	KeepIntermediates          *bool             `yaml:"keepIntermediates,omitempty"`
	ScanDirectory              *string           `yaml:"scanDirectory,omitempty"`
	EligibleForCleaningAge     *time.Duration    `yaml:"eligibleForCleaningAge,omitempty"`
	DeleteCorrupted            *bool             `yaml:"deleteCorrupted,omitempty"`
	ExtractAudio               *bool             `yaml:"extractAudio,omitempty"`
	Labels                     map[string]string `yaml:"labels,omitempty"`
}

OptionalParams represents the optional parameters for the download.

func (*OptionalParams) Override

func (override *OptionalParams) Override(params *Params)

Override applies the values from the OptionalParams to the Params.

type Params

type Params struct {
	Quality                    Quality           `yaml:"quality,omitempty"`
	Latency                    Latency           `yaml:"latency,omitempty"`
	PacketLossMax              int               `yaml:"packetLossMax,omitempty"`
	OutFormat                  string            `yaml:"outFormat,omitempty"`
	WriteChat                  bool              `yaml:"writeChat,omitempty"`
	WriteInfoJSON              bool              `yaml:"writeInfoJson,omitempty"`
	WriteThumbnail             bool              `yaml:"writeThumbnail,omitempty"`
	WaitForLive                bool              `yaml:"waitForLive,omitempty"`
	WaitForQualityMaxTries     int               `yaml:"waitForQualityMaxTries,omitempty"`
	AllowQualityUpgrade        bool              `yaml:"allowQualityUpgrade,omitempty"`
	PollQualityUpgradeInterval time.Duration     `yaml:"pollQualityUpgradeInterval,omitempty"`
	WaitPollInterval           time.Duration     `yaml:"waitPollInterval,omitempty"`
	CookiesFile                string            `yaml:"cookiesFile,omitempty"`
	CookiesRefreshDuration     time.Duration     `yaml:"cookiesRefreshDuration,omitempty"`
	Remux                      bool              `yaml:"remux,omitempty"`
	RemuxFormat                string            `yaml:"remuxFormat,omitempty"`
	Concat                     bool              `yaml:"concat,omitempty"`
	KeepIntermediates          bool              `yaml:"keepIntermediates,omitempty"`
	ScanDirectory              string            `yaml:"scanDirectory,omitempty"`
	EligibleForCleaningAge     time.Duration     `yaml:"eligibleForCleaningAge,omitempty"`
	DeleteCorrupted            bool              `yaml:"deleteCorrupted,omitempty"`
	ExtractAudio               bool              `yaml:"extractAudio,omitempty"`
	Labels                     map[string]string `yaml:"labels,omitempty"`
}

Params represents the parameters for the download.

func (*Params) Clone

func (p *Params) Clone() *Params

Clone creates a deep copy of the Params struct.

type Playlist

type Playlist struct {
	Mode   int    `json:"mode"`
	Status int    `json:"status"`
	URL    string `json:"url"`
}

Playlist describes a m3u8 playlist and its specifications.

func ExtractAndMergePlaylists

func ExtractAndMergePlaylists(hlsInfo *HLSInformation) []Playlist

ExtractAndMergePlaylists extracts and merges the playlists.

func GetPlaylistOrBest

func GetPlaylistOrBest(sortedPlaylists []Playlist, expectMode int) (*Playlist, error)

GetPlaylistOrBest returns the playlist that matches the mode or the best.

func SortPlaylists

func SortPlaylists(playlists []Playlist) []Playlist

SortPlaylists sorts the playlists by mode.

type ProfileData

type ProfileData struct {
	UserID string `json:"userid"`
	Fc2ID  string `json:"fc2id"`
	Name   string `json:"name"`
	Info   string `json:"info"`
	Icon   string `json:"icon"`
	Image  string `json:"image"`
	Sex    string `json:"sex"`
	Age    string `json:"age"`
}

ProfileData describes the FC2 user's profile.

type Quality

type Quality int

Quality represents the quality of the live stream.

const (
	// QualityUnknown represents an unknown quality.
	QualityUnknown Quality = 0
	// Quality150KBps represents a 150Kbps bitrate.
	Quality150KBps Quality = 10
	// Quality400KBps represents a 400Kbps bitrate.
	Quality400KBps Quality = 20
	// Quality1_2MBps represents a 1.2Mbps bitrate.
	Quality1_2MBps Quality = 30
	// Quality2MBps represents a 2Mbps bitrate.
	Quality2MBps Quality = 40
	// Quality3MBps represents a 3Mbps bitrate.
	Quality3MBps Quality = 50
	// QualitySound represents a sound only stream.
	QualitySound Quality = 90
)

func QualityFromMode

func QualityFromMode(mode int) Quality

QualityFromMode returns a Quality from a live stream mode.

func QualityParseString

func QualityParseString(value string) Quality

QualityParseString parses a string into a Quality.

func (Quality) String

func (q Quality) String() string

String implements the fmt.Stringer interface.

func (*Quality) UnmarshalText

func (q *Quality) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type UserData

type UserData struct {
	IsLogin       int         `json:"is_login"`
	UserID        int         `json:"userid"`
	Fc2ID         int         `json:"fc2id"`
	Icon          string      `json:"icon"`
	Name          string      `json:"name"`
	Point         interface{} `json:"point"`
	AdultAccess   interface{} `json:"adult_access"`
	Recauth       interface{} `json:"recauth"`
	IsPremiumUser interface{} `json:"is_premium_user"`
	GiftList      interface{} `json:"gift_list"`
	Stamina       interface{} `json:"stamina"`
}

UserData describes the FC2 user.

type WSResponse

type WSResponse struct {
	ID        int             `json:"id,omitempty"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

WSResponse is the response from the websocket.

type WebSocket

type WebSocket struct {
	*http.Client
	// contains filtered or unexported fields
}

WebSocket is used to interact with the FC2 WebSocket.

func NewWebSocket

func NewWebSocket(
	client *http.Client,
	url string,
	healthCheckInterval time.Duration,
) *WebSocket

NewWebSocket creates a new WebSocket.

func (*WebSocket) Dial

func (w *WebSocket) Dial(ctx context.Context) (*websocket.Conn, error)

Dial connects to the WebSocket server.

func (*WebSocket) GetHLSInformation

func (w *WebSocket) GetHLSInformation(
	ctx context.Context,
	conn *websocket.Conn,
	msgChan <-chan *WSResponse,
) (*HLSInformation, error)

GetHLSInformation returns the HLS information.

func (*WebSocket) HeartbeatLoop added in v0.3.0

func (w *WebSocket) HeartbeatLoop(
	ctx context.Context,
	conn *websocket.Conn,
	msgChan <-chan *WSResponse,
) error

HeartbeatLoop sends a heartbeat to keep the ws alive.

The only way to exit the heartbeat loop is to have the WS socket closed or to cancel the context.

func (*WebSocket) Listen

func (w *WebSocket) Listen(
	ctx context.Context,
	conn *websocket.Conn,
	msgChan chan<- *WSResponse,
	commentChan chan<- *Comment,
) error

Listen listens for messages from the WebSocket server.

Directories

Path Synopsis
Package cleaner provides functions to clean old .ts files.
Package cleaner provides functions to clean old .ts files.

Jump to

Keyboard shortcuts

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