syncengine

package
v0.2.32 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 55 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Listenbox sync engine

Shared Go runtime for the CLI and desktop app. It owns authentication, API access, YouTube sessions, media preparation, and resumable synchronization.

Production desktop and CLI reuse one cookie jar for the same OS user. Both resolve the same profile and use youtube-cookies/jar.json beneath it. Neither application keeps a separate copy.

Seed the jar with a Netscape cookies.txt export through listenbox youtube cookies import /path/to/cookies.txt, or paste the complete export into the desktop's Settings → YouTube and choose Save cookies. See the CLI cookie instructions for the export guide and commands.

The Netscape file is an initial seed. After importing it, the engine reads the saved jar for YouTube requests and persists cookie updates from YouTube responses. The original export can be deleted. A fresh import replaces the session; listenbox youtube cookies remove or Remove cookies in desktop settings returns future requests from both apps to anonymous access.

The importer accepts UTF-8 Netscape exports starting with # Netscape HTTP Cookie File or # HTTP Cookie File, followed by seven tab-separated fields per cookie row. It keeps unexpired cookies for youtube.com and its subdomains, including session cookies with an expiry of 0. Malformed exports and exports with no usable YouTube cookies fail without replacing the saved session.

The sync engine owns persistence and coordination between processes:

  • Requests read complete snapshots; writers use an OS file lock and atomically replace the saved jar.
  • Generation and per-cookie revision checks prevent late responses from overwriting newer cookies or undoing an explicit replacement or removal.
  • Cookies are sent only to matching YouTube HTTPS endpoints. They are not uploaded to the Listenbox API or sent to media hosts.

Profiles

Build / platform Default profile
Production macOS ~/Library/Application Support/Listenbox/
Production Windows %LOCALAPPDATA%\Listenbox\
Production Linux $XDG_DATA_HOME/listenbox/, defaulting to ~/.local/share/listenbox/
Debug, all platforms ~/.cache/listenbox/dev/ (~ is the user's home directory)

LISTENBOX_PROFILE_DIR overrides the entire profile: configuration, credentials, cookies, SQLite, and downloads. Set it to the same directory for both apps if you override it; an empty value is rejected. --config PATH changes only the configuration file and does not select a different cookie jar.

Use the production CLI to seed the production desktop. Debug builds default to a separate profile, even when configured to contact production services.

Documentation

Index

Constants

View Source
const (
	CookieGuideURL = "https://listenbox.app/guides/import-youtube-as-a-podcast/#when-youtube-asks-you-" +
		"to-sign-in"
)
View Source
const RangeBytes = int64(1024 * 1024)

Variables

View Source
var (
	//nolint:revive,staticcheck // Preserve existing end-user guidance.
	ErrAuthentication = errors.New(
		"Sign in to Listenbox to continue.",
	)
	//nolint:staticcheck // Preserve existing end-user guidance.
	ErrSyncStopped = errors.New(
		"The server stopped YouTube importing for this show. Progress is saved; refresh t" +
			"he podcast list.",
	)
	//nolint:revive,staticcheck // Preserve existing end-user guidance.
	ErrMediaUnavailable = errors.New(
		"YouTube refused the media download (HTTP 403). Try syncing again.",
	)
	//nolint:staticcheck // Preserve existing end-user guidance.
	ErrSignInRequired = errors.New(
		"YouTube needs a signed-in session. Open Settings → YouTube to paste fresh cook" +
			"ies, or run listenbox youtube cookies import <cookies.txt>, then sync again.",
	)
)
View Source
var (
	Production   = "0"
	Version      string
	SourceCommit string
)
View Source
var ErrUploadStalled = errors.New("upload stalled; resumable source upload state preserved")

Functions

func BuildVersion

func BuildVersion() string

BuildVersion uses the embedded release identity unless a build overrides it.

func CollectionSource

func CollectionSource(source string) (string, error)

func CredentialValid

func CredentialValid(value string) bool

func EventString

func EventString(event map[string]any, key string) (string, error)

func FFmpegConfiguration

func FFmpegConfiguration() string

FFmpegConfiguration identifies the linked, source-built codec library in diagnostics. astiav exposes codecs but not avcodec_configuration itself.

func FastStart

func FastStart(path string) (bool, error)

func FileHash

func FileHash(path string) (int64, string, error)

func IsYouTubeSource

func IsYouTubeSource(source string) bool

func Language

func Language(value string) (string, error)

func LoadAuth

func LoadAuth(config Config) string

func Logout

func Logout(config Config) error

func MediaDuration

func MediaDuration(path string) (int64, error)

func NewHTTPClients

func NewHTTPClients() (*http.Client, *http.Client, error)

func Nonblank

func Nonblank(value string) (string, error)

func PrepareAudio

func PrepareAudio(ctx context.Context, inputPath, outputPath string) (err error)

func PrepareVideo

func PrepareVideo(
	ctx context.Context,
	directory string,
	separateAudio bool,
	maxHeight int,
	language string,
) (int64, error)

func ReadBounded

func ReadBounded(reader io.Reader, limit int64) ([]byte, error)

func Redact

func Redact(message string) string

func Slug

func Slug(value string) (string, error)

func ValidID

func ValidID(value, prefix string) bool

func WritePrivateJSON

func WritePrivateJSON(path string, value any) error

Types

type API

type API struct {
	Config     Config
	Credential string
	HTTP       *http.Client
	UploadHTTP *http.Client
	Public     *p.Client
	Clock      clockwork.Clock
}

func NewAPI

func NewAPI(config Config) (*API, error)

func NewAPIWithClients

func NewAPIWithClients(config Config, httpClient, upload *http.Client) (*API, error)

func (*API) AuthStatus

func (api *API) AuthStatus(ctx context.Context) (string, error)

func (*API) CreateEpisode

func (api *API) CreateEpisode(
	ctx context.Context,
	args EpisodeCreate,
	output, diagnostics io.Writer,
) error

func (*API) Do

func (api *API) Do(request *http.Request) (*http.Response, error)

func (*API) Episodes

func (api *API) Episodes(ctx context.Context, slug string, limit int) ([]p.EpisodeListItem, error)

func (*API) Events

func (api *API) Events(ctx context.Context, path string) (*Events, error)

func (*API) Inventory

func (api *API) Inventory(ctx context.Context, slug string) (p.SyncInventory, error)

func (*API) JSON

func (api *API) JSON(ctx context.Context, method, path string, body, out any) error

func (*API) Login

func (api *API) Login(ctx context.Context, client p.AuthorizationClient, open func(string)) error

func (*API) SetOrder

func (api *API) SetOrder(
	ctx context.Context,
	slug string,
	collection *string,
	ids []string,
) (p.EpisodeOrder, error)

func (*API) TeamID

func (api *API) TeamID(ctx context.Context) (string, error)

func (*API) UploadArtwork

func (api *API) UploadArtwork(ctx context.Context, show string, raw []byte) (string, error)

func (*API) UploadArtworkFile

func (api *API) UploadArtworkFile(ctx context.Context, show, path string) (string, error)

func (*API) UploadPart

func (api *API) UploadPart(
	ctx context.Context,
	path string,
	offset, length int64,
	method, uploadURL string,
	progress func(int64),
) (string, error)

func (*API) UploadSourceArtwork

func (api *API) UploadSourceArtwork(ctx context.Context, show, source string) (string, error)

type ByteRange

type ByteRange struct {
	Start, End, Received int64
	Complete             bool
}

type Catalog

type Catalog struct {
	Teams      []p.ClientTeam
	ImportTeam string
	Shows      []p.Show
}

type Client

type Client struct {
	Config Config
	Engine *Engine
	// contains filtered or unexported fields
}

func NewClient

func NewClient(config Config) *Client

func NewClientWithClock

func NewClientWithClock(config Config, clock clockwork.Clock) *Client

func (*Client) API

func (c *Client) API(ctx context.Context) (*API, error)

func (*Client) Artwork

func (c *Client) Artwork(ctx context.Context, target string) ([]byte, error)

Artwork retrieves a public cover through the profile's persistent HTTP cache. Revalidation stays synchronous so cancellation and logout own every request.

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context) (Catalog, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) CookieJar

func (c *Client) CookieJar() *CookieJar

func (*Client) Episodes

func (c *Client) Episodes(ctx context.Context, slug string) ([]p.EpisodeListItem, error)

func (*Client) HasCredentials

func (c *Client) HasCredentials() bool

func (*Client) Import

func (c *Client) Import(
	ctx context.Context,
	source, team string,
	kind p.ShowSourceKind,
	event func(ImportEvent),
) (p.Show, Report, error)

func (*Client) Login

func (c *Client) Login(ctx context.Context, open func(string)) error

func (*Client) Logout

func (c *Client) Logout() error

func (*Client) Sync

func (c *Client) Sync(ctx context.Context, slug string) (Report, error)

func (*Client) SyncState

func (c *Client) SyncState(ctx context.Context, slug string) (SyncState, error)

func (*Client) SyncYouTube

func (c *Client) SyncYouTube(
	ctx context.Context,
	show string,
	watch bool,
	event func(SyncEvent),
) error

type Config

type Config struct {
	APIOrigin       string `json:"api_origin"       yaml:"api_origin"`
	DashboardOrigin string `json:"dashboard_origin" yaml:"dashboard_origin"`
	Directory       string `json:"-"                yaml:"-"`
}

func LoadConfig

func LoadConfig(explicit string) (Config, error)

func LoadConfigIn

func LoadConfigIn(explicit, directory string) (Config, error)

func (Config) ShowURL

func (c Config) ShowURL(team, show string) (string, error)

func (Config) UpgradeURL

func (c Config) UpgradeURL(team string) (string, error)

type CookieJar

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

func NewCookieJar

func NewCookieJar(profile string) *CookieJar

func (*CookieJar) Enabled

func (jar *CookieJar) Enabled() (bool, error)

func (*CookieJar) Import

func (jar *CookieJar) Import(ctx context.Context, text string) error

func (*CookieJar) ImportFile

func (jar *CookieJar) ImportFile(ctx context.Context, path string) error

func (*CookieJar) Remove

func (jar *CookieJar) Remove(ctx context.Context) error

type Database

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

Database owns durable checkpoints. Once admitted, journal operations drain independently of request cancellation; the client joins them before Close.

func OpenDatabase

func OpenDatabase(ctx context.Context, directory string) (*Database, error)

func (*Database) Close

func (db *Database) Close() error

func (*Database) CompleteSync

func (db *Database) CompleteSync(ctx context.Context, origin, show string) error

func (*Database) Directory

func (db *Database) Directory(operation string) (string, error)

func (*Database) Download

func (db *Database) Download(ctx context.Context, operation, name, identity string) error

func (*Database) Forget

func (db *Database) Forget(ctx context.Context, origin, show, source string) error

func (*Database) HasPart

func (db *Database) HasPart(
	ctx context.Context,
	operation string,
	object int,
	part int32,
) (bool, error)

func (*Database) Items

func (db *Database) Items(ctx context.Context, origin, show string) ([]Download, error)

func (*Database) LastSynced

func (db *Database) LastSynced(ctx context.Context, origin, show string) (*time.Time, error)

func (*Database) Operation

func (db *Database) Operation(
	ctx context.Context,
	origin, show, source, collection string,
) (string, error)

func (*Database) Outcome

func (db *Database) Outcome(ctx context.Context, origin, show string, item Download) error

func (*Database) Prepared

func (db *Database) Prepared(
	ctx context.Context,
	operation string,
) (*p.CreateEpisodePackage, error)

func (*Database) Published

func (db *Database) Published(ctx context.Context, origin, show string, sources []string) error

func (*Database) RangeHash

func (db *Database) RangeHash(
	ctx context.Context,
	operation, name string,
	start int64,
) (string, error)

func (*Database) SavePart

func (db *Database) SavePart(ctx context.Context, operation string, object int, part int32) error

func (*Database) SavePrepared

func (db *Database) SavePrepared(ctx context.Context, manifest p.CreateEpisodePackage) error

func (*Database) SaveRange

func (db *Database) SaveRange(
	ctx context.Context,
	operation, name string,
	start int64,
	hash string,
) error

func (*Database) Session

func (db *Database) Session(ctx context.Context, operation, session string) error

func (*Database) Snapshot

func (db *Database) Snapshot(ctx context.Context,
	origin, show, collection string,
	videos []Video,
	canRemove bool,
) error

type Download

type Download struct {
	ID, SourceID, SourceTitle, SourceURL, Title string
	DurationSeconds                             *int64
	Position                                    *int64
	Phase                                       Phase
	Reason, Error                               string
	Attempt                                     int
	Received, Total, Uploaded, UploadTotal      int64
	Started                                     time.Time
	Ranges                                      []ByteRange
	// contains filtered or unexported fields
}

func (Download) BytesPerSecond

func (d Download) BytesPerSecond(now time.Time) int64

type DownloadManager

type DownloadManager struct {
	Changed func()
	// contains filtered or unexported fields
}

func NewDownloadManager

func NewDownloadManager() *DownloadManager

func (*DownloadManager) Changes

func (m *DownloadManager) Changes() <-chan struct{}

func (*DownloadManager) Clear

func (m *DownloadManager) Clear()

func (*DownloadManager) Limits

func (m *DownloadManager) Limits() (int, int)

func (*DownloadManager) Snapshot

func (m *DownloadManager) Snapshot() []Download

type Engine

type Engine struct {
	Downloads *DownloadManager
	// contains filtered or unexported fields
}

func NewEngine

func NewEngine(clock clockwork.Clock) *Engine

func (*Engine) Close

func (e *Engine) Close() error

func (*Engine) Database

func (e *Engine) Database(ctx context.Context, config Config) (*Database, error)

func (*Engine) Import

func (e *Engine) Import(
	ctx context.Context,
	api *API,
	source, team, requestedSlug string,
	kind p.ShowSourceKind,
	event func(ImportEvent),
) (p.Show, Report, error)

func (*Engine) NextScan

func (e *Engine) NextScan(ctx context.Context) bool

func (*Engine) Once

func (e *Engine) Once(ctx context.Context, api *API, slug string) (Report, error)

type EpisodeCreate

type EpisodeCreate struct {
	Show, Title, File string
	Description       *string
	Publication       p.EpisodePublication
}

type Events

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

func (*Events) Close

func (events *Events) Close() error

func (*Events) Next

func (events *Events) Next() (map[string]any, error)

type HTTPError

type HTTPError struct {
	Status  int
	Message string
	Body    json.RawMessage
}

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) Is

func (e *HTTPError) Is(target error) bool

type ImportEvent

type ImportEvent struct {
	Stage                 string
	Scan                  *PlaylistScan
	Show                  *p.Show
	Existing              bool
	VideoRemainingSeconds *int64
}

type Media

type Media struct {
	Title, Description, ArtworkURL string
	PublishedAt, EstimatedSeconds  int64
	DurationSeconds                *int64
	Video                          MediaStream
	Audio                          *MediaStream
	// contains filtered or unexported fields
}

type MediaStream

type MediaStream struct {
	URL, UserAgent, Identity string
	// contains filtered or unexported fields
}

type Phase

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

func Complete

func Complete() Phase

func Downloading

func Downloading() Phase

func Failed

func Failed() Phase

func NewPhaseFromValue

func NewPhaseFromValue(value string) (Phase, error)

func Preparing

func Preparing() Phase

func Publishing

func Publishing() Phase

func Queued

func Queued() Phase

func Resolving

func Resolving() Phase

func Retrying

func Retrying() Phase

func Skipped

func Skipped() Phase

func Uploading

func Uploading() Phase

func WaitingToPrepare

func WaitingToPrepare() Phase

func WaitingToUpload

func WaitingToUpload() Phase

func (Phase) Active

func (p Phase) Active() bool

func (Phase) String

func (p Phase) String() string

type PlaylistScan

type PlaylistScan struct {
	Title            string
	Videos           int
	EstimatedSeconds int64
	UnknownDurations int
}

type PlaylistSnapshot

type PlaylistSnapshot struct {
	Title, ArtworkURL string
	Present           []Video
	EstimatedSeconds  int64
	CanRemove         bool
}

type Report

type Report struct {
	Added, Removed, Unchanged, Skipped int
	Reordered, Stopped                 bool
}

type Stage

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

func DownloadStage

func DownloadStage() Stage

func PrepareStage

func PrepareStage() Stage

func UploadStage

func UploadStage() Stage

type StoredAuth

type StoredAuth struct {
	APIKey string `json:"api_key"`
}

type SyncEvent

type SyncEvent struct {
	Shows     []p.Show
	Slug      string
	SourceURL string
	Report    Report
	Err       error
	Items     []Download
	Finished  bool
	Failed    int
}

type SyncState

type SyncState struct {
	Items      []Download
	LastSynced *time.Time
}

type Video

type Video struct {
	ID, Title       string
	SourceTitle     *string
	DurationSeconds *int64
}

func (Video) URL

func (v Video) URL() string

type YouTube

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

func NewYouTube

func NewYouTube(ctx context.Context, api *API) (*YouTube, error)

func (*YouTube) Close

func (yt *YouTube) Close()

func (*YouTube) CompletePlaylist

func (yt *YouTube) CompletePlaylist(
	ctx context.Context,
	page youtubei.Playlist,
	progress func(PlaylistScan),
) (PlaylistSnapshot, error)

func (*YouTube) FallbackMedia

func (yt *YouTube) FallbackMedia(ctx context.Context, id string, media *Media, refused *MediaStream) (bool, error)

func (*YouTube) Media

func (yt *YouTube) Media(ctx context.Context, id, collection string) (*Media, string, error)

func (*YouTube) PlaylistHead

func (yt *YouTube) PlaylistHead(ctx context.Context, id string) (youtubei.Playlist, error)

func (*YouTube) Snapshot

func (yt *YouTube) Snapshot(ctx context.Context, id string) (PlaylistSnapshot, error)

func (*YouTube) VideoSnapshot

func (yt *YouTube) VideoSnapshot(ctx context.Context, id string) (PlaylistSnapshot, error)

Jump to

Keyboard shortcuts

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