refactor: shorten verbose variable names across codebase

This commit is contained in:
2026-06-23 17:23:27 +02:00
committed by Milas Holsting
parent 4c7abea589
commit 3515476374
12 changed files with 47 additions and 46 deletions

View File

@@ -195,7 +195,7 @@ func buildAllowedWatchOrderEntries(result watchorder.WatchOrderResult, mode Watc
break break
} }
} }
shouldIncludeAllTypes := mode == WatchOrderModeComplete || !hasTVEntry allTypes := mode == WatchOrderModeComplete || !hasTVEntry
for _, entry := range result.WatchOrder { for _, entry := range result.WatchOrder {
if len(allowedEntries) >= maxWatchOrderEntries { if len(allowedEntries) >= maxWatchOrderEntries {
@@ -204,8 +204,8 @@ func buildAllowedWatchOrderEntries(result watchorder.WatchOrderResult, mode Watc
if seen[entry.ID] { if seen[entry.ID] {
continue continue
} }
normalizedType := strings.ToLower(strings.TrimSpace(entry.Type)) typ := strings.ToLower(strings.TrimSpace(entry.Type))
if !shouldIncludeAllTypes && normalizedType != "tv" && normalizedType != "movie" { if !allTypes && typ != "tv" && typ != "movie" {
continue continue
} }

View File

@@ -293,13 +293,13 @@ func parseM3U8Sources(body string, masterURL string, referer string) []StreamSou
lines := strings.Split(body, "\n") lines := strings.Split(body, "\n")
baseURL := playlistBaseURL(masterURL) baseURL := playlistBaseURL(masterURL)
bwPattern := regexp.MustCompile(`BANDWIDTH=(\d+)`) bwPattern := regexp.MustCompile(`BANDWIDTH=(\d+)`)
currentBandwidth := 0 bw := 0
sources := make([]StreamSource, 0) sources := make([]StreamSource, 0)
for _, line := range lines { for _, line := range lines {
trimmed := strings.TrimSpace(line) trimmed := strings.TrimSpace(line)
if bandwidth, ok := parseStreamBandwidth(trimmed, bwPattern); ok { if bandwidth, ok := parseStreamBandwidth(trimmed, bwPattern); ok {
currentBandwidth = bandwidth bw = bandwidth
continue continue
} }
if trimmed == "" || strings.HasPrefix(trimmed, "#") { if trimmed == "" || strings.HasPrefix(trimmed, "#") {
@@ -313,7 +313,7 @@ func parseM3U8Sources(body string, masterURL string, referer string) []StreamSou
sources = append(sources, StreamSource{ sources = append(sources, StreamSource{
URL: streamURL, URL: streamURL,
Quality: qualityFromBandwidth(currentBandwidth), Quality: qualityFromBandwidth(bw),
Provider: "hls", Provider: "hls",
Type: "m3u8", Type: "m3u8",
Referer: referer, Referer: referer,

View File

@@ -101,7 +101,7 @@ func (c *AllAnimeProvider) Search(ctx context.Context, query string, mode string
func (c *AllAnimeProvider) resolveShowIDWithFallback(ctx context.Context, animeID int, titleCandidates []string, mode string) string { func (c *AllAnimeProvider) resolveShowIDWithFallback(ctx context.Context, animeID int, titleCandidates []string, mode string) string {
targetMalIDStr := strconv.Itoa(animeID) targetMalIDStr := strconv.Itoa(animeID)
firstAvailableShowID := "" fallbackID := ""
for _, title := range titleCandidates { for _, title := range titleCandidates {
searchResults, err := c.Search(ctx, title, mode) searchResults, err := c.Search(ctx, title, mode)
@@ -111,12 +111,12 @@ func (c *AllAnimeProvider) resolveShowIDWithFallback(ctx context.Context, animeI
if showID := exactMatchShowID(searchResults, targetMalIDStr); showID != "" { if showID := exactMatchShowID(searchResults, targetMalIDStr); showID != "" {
return showID return showID
} }
if firstAvailableShowID == "" { if fallbackID == "" {
firstAvailableShowID = searchResults[0].ID fallbackID = searchResults[0].ID
} }
} }
return firstAvailableShowID return fallbackID
} }
func exactMatchShowID(searchResults []searchResult, targetMalID string) string { func exactMatchShowID(searchResults []searchResult, targetMalID string) string {

View File

@@ -212,7 +212,7 @@ func buildSourceReferences(rawSourceURLs []any) []sourceReference {
ref := sourceReference{URL: sourceURL, Name: sourceName} ref := sourceReference{URL: sourceURL, Name: sourceName}
normalized := strings.ToLower(sourceName) normalized := strings.ToLower(sourceName)
if _, prioritizedProvider := prioritySet[normalized]; prioritizedProvider { if _, priority := prioritySet[normalized]; priority {
if _, exists := prioritized[normalized]; !exists { if _, exists := prioritized[normalized]; !exists {
prioritized[normalized] = ref prioritized[normalized] = ref
} }

View File

@@ -156,13 +156,13 @@ func extractRows(doc *goquery.Document) []watchOrderRow {
} }
title := strings.TrimSpace(selection.Find(".wo_title").First().Text()) title := strings.TrimSpace(selection.Find(".wo_title").First().Text())
alternativeTitle := strings.TrimSpace(selection.Find(".uk-text-small").First().Text()) alt := strings.TrimSpace(selection.Find(".uk-text-small").First().Text())
rows = append(rows, watchOrderRow{ rows = append(rows, watchOrderRow{
id: id, id: id,
typeID: typeID, typeID: typeID,
title: title, title: title,
alternativeTitle: alternativeTitle, alternativeTitle: alt,
}) })
}) })

View File

@@ -317,13 +317,13 @@ func (h *AnimeHandler) HandleHTMLWatchOrder(c *gin.Context) {
return return
} }
relationAnimeIDs := make([]int64, 0, len(relations)) ids := make([]int64, 0, len(relations))
for _, relation := range relations { for _, relation := range relations {
if relation.Anime.MalID > 0 { if relation.Anime.MalID > 0 {
relationAnimeIDs = append(relationAnimeIDs, int64(relation.Anime.MalID)) ids = append(ids, int64(relation.Anime.MalID))
} }
} }
watchlistMap := h.watchlistMapForIDs(c.Request.Context(), userID, relationAnimeIDs) watchlistMap := h.watchlistMapForIDs(c.Request.Context(), userID, ids)
c.HTML(http.StatusOK, "anime.gohtml", gin.H{ c.HTML(http.StatusOK, "anime.gohtml", gin.H{
"_fragment": "watch_order", "_fragment": "watch_order",

View File

@@ -10,11 +10,11 @@ import (
func rerankRecommendationCandidates(candidates []recommendationCandidate, limit int) []domain.Anime { func rerankRecommendationCandidates(candidates []recommendationCandidate, limit int) []domain.Anime {
selected := make([]domain.Anime, 0, min(limit, len(candidates))) selected := make([]domain.Anime, 0, min(limit, len(candidates)))
remaining := slices.Clone(candidates) remaining := slices.Clone(candidates)
seenFeatures := newDiversityFeatureCounts() seen := newDiversityFeatureCounts()
recentFeatures := make([]diversityFeatureSet, 0, recentDiversityWindow) recent := make([]diversityFeatureSet, 0, recentDiversityWindow)
for len(selected) < limit && len(remaining) > 0 { for len(selected) < limit && len(remaining) > 0 {
bestIndex := bestDiverseCandidateIndex(remaining, seenFeatures, recentFeatures) bestIndex := bestDiverseCandidateIndex(remaining, seen, recent)
candidate := remaining[bestIndex] candidate := remaining[bestIndex]
remaining = slices.Delete(remaining, bestIndex, bestIndex+1) remaining = slices.Delete(remaining, bestIndex, bestIndex+1)
@@ -26,10 +26,10 @@ func rerankRecommendationCandidates(candidates []recommendationCandidate, limit
selected = append(selected, domain.Anime{Anime: candidate.anime}) selected = append(selected, domain.Anime{Anime: candidate.anime})
features := diversityFeatures(candidate.anime) features := diversityFeatures(candidate.anime)
seenFeatures.add(features) seen.add(features)
recentFeatures = append(recentFeatures, features) recent = append(recent, features)
if len(recentFeatures) > recentDiversityWindow { if len(recent) > recentDiversityWindow {
recentFeatures = recentFeatures[1:] recent = recent[1:]
} }
} }

View File

@@ -29,25 +29,25 @@ func scoreRecommendationCandidate(
collaborativeScore float64, collaborativeScore float64,
profileSearchScore float64, profileSearchScore float64,
) recommendationCandidate { ) recommendationCandidate {
genreMatches, genreScore := weightedEntityMatch(profile.genres, candidate.Genres) genres, genreScore := weightedEntityMatch(profile.genres, candidate.Genres)
themeMatches, themeScore := weightedEntityMatch(profile.themes, candidate.Themes) themes, themeScore := weightedEntityMatch(profile.themes, candidate.Themes)
studioMatches, studioScore := weightedEntityMatch(profile.studios, candidate.Studios) studios, studioScore := weightedEntityMatch(profile.studios, candidate.Studios)
demographicMatches, demographicScore := weightedEntityMatch(profile.demographics, candidate.Demographics) demos, demoScore := weightedEntityMatch(profile.demographics, candidate.Demographics)
score := rankedCandidateRetrievalScore(collaborativeScore, profileSearchScore) score := rankedCandidateRetrievalScore(collaborativeScore, profileSearchScore)
score += genreScore * genreMatchWeight score += genreScore * genreMatchWeight
score += themeScore * themeMatchWeight score += themeScore * themeMatchWeight
score += studioScore * studioMatchWeight score += studioScore * studioMatchWeight
score += demographicScore * demographicMatchWeight score += demoScore * demographicMatchWeight
score += recommendationCandidateScoreAdjustments(now, profile, candidate) score += recommendationCandidateScoreAdjustments(now, profile, candidate)
return recommendationCandidate{ return recommendationCandidate{
anime: candidate, anime: candidate,
score: score, score: score,
genreMatches: genreMatches, genreMatches: genres,
themeMatches: themeMatches, themeMatches: themes,
studioMatches: studioMatches, studioMatches: studios,
demographicMatches: demographicMatches, demographicMatches: demos,
} }
} }

View File

@@ -13,16 +13,16 @@ type candidateStore struct {
} }
func newCandidateStore(watchlist []db.GetUserWatchListRow) *candidateStore { func newCandidateStore(watchlist []db.GetUserWatchListRow) *candidateStore {
watchlistAnimeIDs := make(map[int]struct{}, len(watchlist)) watched := make(map[int]struct{}, len(watchlist))
for _, entry := range watchlist { for _, entry := range watchlist {
if entry.AnimeID <= 0 { if entry.AnimeID <= 0 {
continue continue
} }
watchlistAnimeIDs[int(entry.AnimeID)] = struct{}{} watched[int(entry.AnimeID)] = struct{}{}
} }
return &candidateStore{ return &candidateStore{
watchlistAnimeIDs: watchlistAnimeIDs, watchlistAnimeIDs: watched,
byID: map[int]rankedCandidate{}, byID: map[int]rankedCandidate{},
} }
} }

View File

@@ -138,7 +138,7 @@ func (s *EpisodeService) refresh(ctx context.Context, anime domain.Anime) (domai
) )
} }
providerAvailability, source, providerErr := s.fetchProviderAvailability(ctx, anime) availability, source, providerErr := s.fetchProviderAvailability(ctx, anime)
if providerErr != nil { if providerErr != nil {
s.markFailure(ctx, anime, providerErr) s.markFailure(ctx, anime, providerErr)
if cached, ok := s.getDecodedCached(ctx, anime); ok { if cached, ok := s.getDecodedCached(ctx, anime); ok {
@@ -165,7 +165,7 @@ func (s *EpisodeService) refresh(ctx context.Context, anime domain.Anime) (domai
return domain.CanonicalEpisodeList{}, providerErr return domain.CanonicalEpisodeList{}, providerErr
} }
return s.store(ctx, anime, jikanEpisodes, providerAvailability, source, now, true) return s.store(ctx, anime, jikanEpisodes, availability, source, now, true)
} }
func (s *EpisodeService) fetchProviderAvailability(ctx context.Context, anime domain.Anime) (domain.EpisodeAvailability, string, error) { func (s *EpisodeService) fetchProviderAvailability(ctx context.Context, anime domain.Anime) (domain.EpisodeAvailability, string, error) {

View File

@@ -36,10 +36,10 @@ func TestFormatLogEntryFormatsHTTPRequestCompactly(t *testing.T) {
} }
func TestFormatHTTPStatusColorsByStatusFamily(t *testing.T) { func TestFormatHTTPStatusColorsByStatusFamily(t *testing.T) {
previousColorLogs := colorLogs prev := colorLogs
colorLogs = true colorLogs = true
t.Cleanup(func() { t.Cleanup(func() {
colorLogs = previousColorLogs colorLogs = prev
}) })
tests := map[any]string{ tests := map[any]string{

View File

@@ -26,18 +26,19 @@ func (s *playbackService) BuildWatchData(ctx context.Context, animeID int, title
) )
} }
searchTitles := buildSearchTitles(animeData, titleCandidates) searchTitles := buildSearchTitles(animeData, titleCandidates)
canonicalEpisodes, err := s.episodes.GetCanonicalEpisodes(ctx, animeData, false) eps, err := s.episodes.GetCanonicalEpisodes(ctx, animeData, false)
if err != nil { if err != nil {
return domain.WatchPageData{}, fmt.Errorf("failed to fetch episodes: %w", err) return domain.WatchPageData{}, fmt.Errorf("failed to fetch episodes: %w", err)
} }
mode, modeSwitchedFrom := resolveMode(episode, mode, canonicalEpisodes.Episodes) // mode fallback
modeSources, result, resolvedMode, resolvedModeSwitchedFrom := s.resolveModeSources(ctx, animeID, searchTitles, episode, mode) mode, from := resolveMode(episode, mode, eps.Episodes)
modeSources, result, resolvedMode, switchedFrom := s.resolveModeSources(ctx, animeID, searchTitles, episode, mode)
if resolvedMode != "" { if resolvedMode != "" {
mode = resolvedMode mode = resolvedMode
} }
if resolvedModeSwitchedFrom != "" { if switchedFrom != "" {
modeSwitchedFrom = resolvedModeSwitchedFrom from = switchedFrom
} }
startTime, watchlistStatus, watchlistIDs := s.loadWatchProgress(ctx, userID, animeID, anime.Episodes, episode) startTime, watchlistStatus, watchlistIDs := s.loadWatchProgress(ctx, userID, animeID, anime.Episodes, episode)
seasons := s.loadSeasons(ctx, animeID) seasons := s.loadSeasons(ctx, animeID)
@@ -48,8 +49,8 @@ func (s *playbackService) BuildWatchData(ctx context.Context, animeID int, title
err, err,
) )
} }
watchData := buildWatchDataPayload(animeData, animeID, episode, startTime, canonicalEpisodes.Episodes, modeSources, mode, modeSwitchedFrom, segments) watchData := buildWatchDataPayload(animeData, animeID, episode, startTime, eps.Episodes, modeSources, mode, from, segments)
pageData := buildWatchPageData(animeData, canonicalEpisodes.Episodes, episode, watchlistStatus, watchlistIDs, seasons, watchData) pageData := buildWatchPageData(animeData, eps.Episodes, episode, watchlistStatus, watchlistIDs, seasons, watchData)
if len(modeSources) == 0 { if len(modeSources) == 0 {
return pageData, fmt.Errorf("no streams found") return pageData, fmt.Errorf("no streams found")
} }