refactor: shorten function names in allanime

This commit is contained in:
2026-06-23 17:40:32 +02:00
committed by Milas Holsting
parent ce91822a25
commit 5c8f1d6359
7 changed files with 37 additions and 34 deletions

View File

@@ -46,7 +46,7 @@ func (c *AllAnimeProvider) Name() string {
} }
func (c *AllAnimeProvider) GetStreams(ctx context.Context, animeID int, titleCandidates []string, episode string, mode string) (*domain.StreamResult, error) { func (c *AllAnimeProvider) GetStreams(ctx context.Context, animeID int, titleCandidates []string, episode string, mode string) (*domain.StreamResult, error) {
showID := c.resolveShowIDWithFallback(ctx, animeID, titleCandidates, mode) showID := c.showID(ctx, animeID, titleCandidates, mode)
if showID == "" { if showID == "" {
return nil, fmt.Errorf("allanime: show not found for malID %d", animeID) return nil, fmt.Errorf("allanime: show not found for malID %d", animeID)
} }

View File

@@ -251,7 +251,7 @@ func TestBuildStreamSource(t *testing.T) {
func TestResolveDirectSourceSkipsEmbeds(t *testing.T) { func TestResolveDirectSourceSkipsEmbeds(t *testing.T) {
t.Parallel() t.Parallel()
if _, ok := resolveDirectSource(sourceReference{ if _, ok := directSource(sourceReference{
URL: "https://ok.ru/videoembed/123", URL: "https://ok.ru/videoembed/123",
Name: "ok", Name: "ok",
}); ok { }); ok {

View File

@@ -120,7 +120,7 @@ func decodeSourceURL(encoded string) string {
} }
func responseFromTobeparsed(data map[string]any) (map[string]any, error) { func responseFromTobeparsed(data map[string]any) (map[string]any, error) {
toBeParsed := firstNonEmptyString( toBeParsed := firstString(
nestedString(data, "tobeparsed"), nestedString(data, "tobeparsed"),
nestedString(data, "episode", "tobeparsed"), nestedString(data, "episode", "tobeparsed"),
) )
@@ -138,7 +138,7 @@ func responseFromTobeparsed(data map[string]any) (map[string]any, error) {
return nil, err return nil, err
} }
sourceURLs := firstNonEmptySlice( sourceURLs := firstSlice(
nestedSlice(parsed, "sourceUrls"), nestedSlice(parsed, "sourceUrls"),
nestedSlice(parsed, "episode", "sourceUrls"), nestedSlice(parsed, "episode", "sourceUrls"),
) )
@@ -166,7 +166,8 @@ func parseGraphQLResponse(respBody []byte, decodeErrPrefix string) (map[string]a
return parsed, nil return parsed, nil
} }
func firstNonEmptyString(values ...string) string { // first non-empty
func firstString(values ...string) string {
for _, value := range values { for _, value := range values {
if value != "" { if value != "" {
return value return value
@@ -176,7 +177,8 @@ func firstNonEmptyString(values ...string) string {
return "" return ""
} }
func firstNonEmptySlice(values ...[]any) []any { // first non-empty
func firstSlice(values ...[]any) []any {
for _, value := range values { for _, value := range values {
if len(value) > 0 { if len(value) > 0 {
return value return value

View File

@@ -81,7 +81,7 @@ func (e *providerExtractor) ExtractVideoLinks(ctx context.Context, providerPath
return nil, fmt.Errorf("read provider response: %w", err) return nil, fmt.Errorf("read provider response: %w", err)
} }
return e.parseProviderResponse(ctx, string(body)), nil return e.parseResponse(ctx, string(body)), nil
} }
func (e *providerExtractor) ExtractEmbedVideoLinks(ctx context.Context, rawURL string) ([]StreamSource, error) { func (e *providerExtractor) ExtractEmbedVideoLinks(ctx context.Context, rawURL string) ([]StreamSource, error) {
@@ -98,11 +98,11 @@ func (e *providerExtractor) ExtractEmbedVideoLinks(ctx context.Context, rawURL s
return nil, fmt.Errorf("read embed response: %w", err) return nil, fmt.Errorf("read embed response: %w", err)
} }
return parseExternalEmbedResponse(rawURL, string(body), e.referer), nil return parseEmbed(rawURL, string(body), e.referer), nil
} }
// parseProviderResponse extracts stream sources from provider JSON response. // provider response
func (e *providerExtractor) parseProviderResponse(ctx context.Context, response string) []StreamSource { func (e *providerExtractor) parseResponse(ctx context.Context, response string) []StreamSource {
var root any var root any
if err := json.Unmarshal([]byte(response), &root); err != nil { if err := json.Unmarshal([]byte(response), &root); err != nil {
return []StreamSource{} return []StreamSource{}
@@ -367,12 +367,13 @@ func quality(bandwidth int) string {
} }
} }
func parseExternalEmbedResponse(rawURL string, body string, fallbackReferer string) []StreamSource { // embed page
func parseEmbed(rawURL string, body string, fallbackReferer string) []StreamSource {
switch { switch {
case strings.Contains(strings.ToLower(rawURL), "ok.ru/"): case strings.Contains(strings.ToLower(rawURL), "ok.ru/"):
return parseOKRUSources(body, fallbackReferer) return parseOKRUSources(body, fallbackReferer)
case strings.Contains(strings.ToLower(rawURL), "mp4upload.com/"): case strings.Contains(strings.ToLower(rawURL), "mp4upload.com/"):
return parseMP4UploadSources(body, fallbackReferer) return parseMP4Upload(body, fallbackReferer)
default: default:
return nil return nil
} }
@@ -386,7 +387,7 @@ func parseOKRUSources(body string, referer string) []StreamSource {
return nil return nil
} }
playlistURL := decodeEscapedMediaURL(firstNonEmptyString(match[1], match[2])) playlistURL := mediaURL(firstString(match[1], match[2]))
if playlistURL == "" { if playlistURL == "" {
return nil return nil
} }
@@ -400,27 +401,27 @@ func parseOKRUSources(body string, referer string) []StreamSource {
}} }}
} }
func parseMP4UploadSources(body string, referer string) []StreamSource { func parseMP4Upload(body string, referer string) []StreamSource {
srcPattern := regexp.MustCompile(`(?m)src:\s*"([^"]+)"`) srcPattern := regexp.MustCompile(`(?m)src:\s*"([^"]+)"`)
match := srcPattern.FindStringSubmatch(body) match := srcPattern.FindStringSubmatch(body)
if len(match) < 2 { if len(match) < 2 {
return nil return nil
} }
mediaURL := decodeEscapedMediaURL(match[1]) url := mediaURL(match[1])
if mediaURL == "" { if url == "" {
return nil return nil
} }
return []StreamSource{{ return []StreamSource{{
URL: mediaURL, URL: url,
Provider: "mp4upload", Provider: "mp4upload",
Type: sourceType(mediaURL), Type: sourceType(url),
Referer: referer, Referer: referer,
}} }}
} }
func decodeEscapedMediaURL(raw string) string { func mediaURL(raw string) string {
if unquoted, err := strconv.Unquote(`"` + raw + `"`); err == nil { if unquoted, err := strconv.Unquote(`"` + raw + `"`); err == nil {
raw = unquoted raw = unquoted
} }

View File

@@ -539,7 +539,7 @@ func TestParseProviderResponse(t *testing.T) {
referer: allAnimeReferer, referer: allAnimeReferer,
} }
sources := extractor.parseProviderResponse(context.Background(), body) sources := extractor.parseResponse(context.Background(), body)
if len(sources) == 0 { if len(sources) == 0 {
t.Fatal("expected at least one source") t.Fatal("expected at least one source")
} }
@@ -566,7 +566,7 @@ func TestParseProviderResponse(t *testing.T) {
referer: allAnimeReferer, referer: allAnimeReferer,
} }
sources := extractor.parseProviderResponse(context.Background(), "not json") sources := extractor.parseResponse(context.Background(), "not json")
if len(sources) != 0 { if len(sources) != 0 {
t.Errorf("expected empty, got %d sources", len(sources)) t.Errorf("expected empty, got %d sources", len(sources))
} }
@@ -580,7 +580,7 @@ func TestParseProviderResponse(t *testing.T) {
referer: allAnimeReferer, referer: allAnimeReferer,
} }
sources := extractor.parseProviderResponse(context.Background(), "{}") sources := extractor.parseResponse(context.Background(), "{}")
if len(sources) != 0 { if len(sources) != 0 {
t.Errorf("expected empty, got %d sources", len(sources)) t.Errorf("expected empty, got %d sources", len(sources))
} }
@@ -594,7 +594,7 @@ func TestParseExternalEmbedResponse(t *testing.T) {
t.Parallel() t.Parallel()
body := `{"flashvars":{"metadata":"{\"hlsManifestUrl\":\"https://ok.example.test/playlist.m3u8\"}"}}` body := `{"flashvars":{"metadata":"{\"hlsManifestUrl\":\"https://ok.example.test/playlist.m3u8\"}"}}`
sources := parseExternalEmbedResponse("https://ok.ru/video/123", body, allAnimeReferer) sources := parseEmbed("https://ok.ru/video/123", body, allAnimeReferer)
if len(sources) != 1 { if len(sources) != 1 {
t.Fatalf("got %d sources, want 1", len(sources)) t.Fatalf("got %d sources, want 1", len(sources))
} }
@@ -610,7 +610,7 @@ func TestParseExternalEmbedResponse(t *testing.T) {
t.Parallel() t.Parallel()
body := `src: "https://mp4upload.example.test/video.mp4"` body := `src: "https://mp4upload.example.test/video.mp4"`
sources := parseExternalEmbedResponse("https://mp4upload.com/e/abc", body, allAnimeReferer) sources := parseEmbed("https://mp4upload.com/e/abc", body, allAnimeReferer)
if len(sources) != 1 { if len(sources) != 1 {
t.Fatalf("got %d sources, want 1", len(sources)) t.Fatalf("got %d sources, want 1", len(sources))
} }
@@ -625,7 +625,7 @@ func TestParseExternalEmbedResponse(t *testing.T) {
t.Run("unknown embed returns empty", func(t *testing.T) { t.Run("unknown embed returns empty", func(t *testing.T) {
t.Parallel() t.Parallel()
sources := parseExternalEmbedResponse("https://unknown.example.com/video", "<html></html>", allAnimeReferer) sources := parseEmbed("https://unknown.example.com/video", "<html></html>", allAnimeReferer)
if len(sources) != 0 { if len(sources) != 0 {
t.Errorf("expected empty, got %d sources", len(sources)) t.Errorf("expected empty, got %d sources", len(sources))
} }

View File

@@ -99,7 +99,7 @@ func (c *AllAnimeProvider) Search(ctx context.Context, query string, mode string
return out, nil return out, nil
} }
func (c *AllAnimeProvider) resolveShowIDWithFallback(ctx context.Context, animeID int, titleCandidates []string, mode string) string { func (c *AllAnimeProvider) showID(ctx context.Context, animeID int, titleCandidates []string, mode string) string {
targetMalIDStr := strconv.Itoa(animeID) targetMalIDStr := strconv.Itoa(animeID)
fallbackID := "" fallbackID := ""
@@ -131,7 +131,7 @@ func exactMatchShowID(searchResults []searchResult, targetMalID string) string {
func (c *AllAnimeProvider) ResolveEpisodeProviderID(ctx context.Context, animeID int, titleCandidates []string) (string, error) { func (c *AllAnimeProvider) ResolveEpisodeProviderID(ctx context.Context, animeID int, titleCandidates []string) (string, error) {
for _, mode := range []string{"sub", "dub"} { for _, mode := range []string{"sub", "dub"} {
showID, err := c.resolveShowIDStrict(ctx, animeID, titleCandidates, mode) showID, err := c.strictShowID(ctx, animeID, titleCandidates, mode)
if err == nil { if err == nil {
return showID, nil return showID, nil
} }
@@ -139,7 +139,7 @@ func (c *AllAnimeProvider) ResolveEpisodeProviderID(ctx context.Context, animeID
return "", fmt.Errorf("allanime: no exact mal id match for %d", animeID) return "", fmt.Errorf("allanime: no exact mal id match for %d", animeID)
} }
func (c *AllAnimeProvider) resolveShowIDStrict(ctx context.Context, animeID int, titleCandidates []string, mode string) (string, error) { func (c *AllAnimeProvider) strictShowID(ctx context.Context, animeID int, titleCandidates []string, mode string) (string, error) {
targetMalIDStr := strconv.Itoa(animeID) targetMalIDStr := strconv.Itoa(animeID)
for _, title := range titleCandidates { for _, title := range titleCandidates {
searchResults, err := c.Search(ctx, title, mode) searchResults, err := c.Search(ctx, title, mode)

View File

@@ -25,7 +25,7 @@ func (c *AllAnimeProvider) GetEpisodeSources(ctx context.Context, showID string,
result, err := c.graphqlRequestWithHash(ctx, showID, episode, mode) result, err := c.graphqlRequestWithHash(ctx, showID, episode, mode)
if err == nil { if err == nil {
sources := c.extractSourceURLsFromData(ctx, result) sources := c.sourcesFrom(ctx, result)
if len(sources) > 0 { if len(sources) > 0 {
return sources, nil return sources, nil
} }
@@ -69,7 +69,7 @@ func (c *AllAnimeProvider) GetEpisodeSources(ctx context.Context, showID string,
return out, nil return out, nil
} }
func (c *AllAnimeProvider) extractSourceURLsFromData(ctx context.Context, data map[string]any) []StreamSource { func (c *AllAnimeProvider) sourcesFrom(ctx context.Context, data map[string]any) []StreamSource {
episodeData, ok := data["episode"].(map[string]any) episodeData, ok := data["episode"].(map[string]any)
if !ok { if !ok {
return nil return nil
@@ -91,7 +91,7 @@ func (c *AllAnimeProvider) extractSourceURLsFromData(ctx context.Context, data m
func (c *AllAnimeProvider) resolveRefs(ctx context.Context, references []sourceReference) []StreamSource { func (c *AllAnimeProvider) resolveRefs(ctx context.Context, references []sourceReference) []StreamSource {
out := make([]StreamSource, 0, len(references)) out := make([]StreamSource, 0, len(references))
for _, ref := range references { for _, ref := range references {
if source, ok := resolveDirectSource(ref); ok { if source, ok := directSource(ref); ok {
out = append(out, source) out = append(out, source)
return out return out
} }
@@ -106,7 +106,7 @@ func (c *AllAnimeProvider) resolveRefs(ctx context.Context, references []sourceR
return out return out
} }
func resolveDirectSource(ref sourceReference) (StreamSource, bool) { func directSource(ref sourceReference) (StreamSource, bool) {
target := strings.TrimSpace(ref.URL) target := strings.TrimSpace(ref.URL)
if target == "" { if target == "" {
return StreamSource{}, false return StreamSource{}, false
@@ -240,7 +240,7 @@ func stringMapValue(item map[string]any, key string) (string, bool) {
} }
func (c *AllAnimeProvider) graphqlRequestWithHash(ctx context.Context, showID, episode, mode string) (map[string]any, error) { func (c *AllAnimeProvider) graphqlRequestWithHash(ctx context.Context, showID, episode, mode string) (map[string]any, error) {
req, err := newEpisodeHashRequest(ctx, showID, episode, mode) req, err := newHashRequest(ctx, showID, episode, mode)
if err != nil { if err != nil {
return nil, fmt.Errorf("create GET request: %w", err) return nil, fmt.Errorf("create GET request: %w", err)
} }
@@ -289,7 +289,7 @@ func (c *AllAnimeProvider) graphqlRequestWithHash(ctx context.Context, showID, e
return nil, errors.New("no usable data in response") return nil, errors.New("no usable data in response")
} }
func newEpisodeHashRequest(ctx context.Context, showID, episode, mode string) (*http.Request, error) { func newHashRequest(ctx context.Context, showID, episode, mode string) (*http.Request, error) {
varsJSON := fmt.Sprintf(`{"showId":"%s","translationType":"%s","episodeString":"%s"}`, showID, strings.ToLower(mode), episode) varsJSON := fmt.Sprintf(`{"showId":"%s","translationType":"%s","episodeString":"%s"}`, showID, strings.ToLower(mode), episode)
extJSON := fmt.Sprintf(`{"persistedQuery":{"version":1,"sha256Hash":"%s"}}`, episodeQueryHash) extJSON := fmt.Sprintf(`{"persistedQuery":{"version":1,"sha256Hash":"%s"}}`, episodeQueryHash)