-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecommendations.go
More file actions
562 lines (484 loc) · 13.7 KB
/
recommendations.go
File metadata and controls
562 lines (484 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package main
// Recommendation engine for suggesting movies and TV shows.
// Uses TMDB's similar/recommended endpoints combined with keyword matching
// to generate personalized suggestions. Supports group recommendations
// with shared taste scoring.
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
minSelections = 1
maxSelections = 50
)
// Cache for TMDB API responses
type cacheEntry struct {
data any
expiresAt time.Time
}
type tmdbCache struct {
mu sync.RWMutex
entries map[string]cacheEntry
}
var cache = &tmdbCache{
entries: make(map[string]cacheEntry),
}
func (c *tmdbCache) get(key string) (any, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
entry, ok := c.entries[key]
if !ok || time.Now().After(entry.expiresAt) {
return nil, false
}
return entry.data, true
}
func (c *tmdbCache) set(key string, data any, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.entries[key] = cacheEntry{
data: data,
expiresAt: time.Now().Add(ttl),
}
}
// SelectedItem represents a selected movie or TV show
type SelectedItem struct {
ID string
Type string // "movie" or "tv"
UserCount int // How many users in the group have watched this (for shared taste scoring)
}
func handleGetRecommendations(w http.ResponseWriter, r *http.Request) {
userID := getCurrentUser(r)
r.ParseMultipartForm(10 << 20) // 10 MB max
items := r.Form["items"]
watchingWith := r.Form["watchingWith"] // Other user IDs in the group
w.Header().Set("Content-Type", "application/json")
if len(items) < minSelections {
json.NewEncoder(w).Encode(map[string]any{
"error": fmt.Sprintf("Please select at least %d items", minSelections),
})
return
}
if len(items) > maxSelections {
json.NewEncoder(w).Encode(map[string]any{
"error": fmt.Sprintf("Please select no more than %d items", maxSelections),
})
return
}
// Parse items (format: "tmdbID:type:userCount") and split by type
// userCount indicates how many users have watched this item (for shared taste scoring)
var selectedMovies, selectedShows []SelectedItem
selectedIDs := make(map[int]bool)
for _, item := range items {
parts := strings.Split(item, ":")
if len(parts) >= 2 {
si := SelectedItem{ID: parts[0], Type: parts[1], UserCount: 1}
if len(parts) >= 3 {
if count, err := strconv.Atoi(parts[2]); err == nil {
si.UserCount = count
}
}
if parts[1] == "tv" {
selectedShows = append(selectedShows, si)
} else {
selectedMovies = append(selectedMovies, si)
}
if id, err := strconv.Atoi(parts[0]); err == nil {
selectedIDs[id] = true
}
}
}
// Collect all user IDs in the group (current user + watching with)
groupUserIDs := []int64{userID}
for _, idStr := range watchingWith {
if id, err := strconv.ParseInt(idStr, 10, 64); err == nil && id != userID {
groupUserIDs = append(groupUserIDs, id)
}
}
// Get items from ALL users in the group to exclude (Option 2: exclude anything anyone has seen)
existingTmdbIDs := make(map[int]bool)
for _, uid := range groupUserIDs {
allItems, _ := getAllItems(uid)
for _, item := range allItems {
if item.TmdbID != "" {
if id, err := strconv.Atoi(item.TmdbID); err == nil {
existingTmdbIDs[id] = true
}
}
}
}
// Process movies and TV shows separately - returns categorized results
var movieRecs, tvRecs map[string][]map[string]any
var wg sync.WaitGroup
if len(selectedMovies) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
movieRecs = getRecommendationsForType(selectedMovies, "movie", selectedIDs, existingTmdbIDs)
}()
}
if len(selectedShows) > 0 {
wg.Add(1)
go func() {
defer wg.Done()
tvRecs = getRecommendationsForType(selectedShows, "tv", selectedIDs, existingTmdbIDs)
}()
}
wg.Wait()
// Merge movie and TV results by category
categories := []string{"popular", "newest", "hiddenGems", "classics"}
result := make(map[string][]map[string]any)
for _, cat := range categories {
var merged []map[string]any
if movieRecs != nil {
merged = append(merged, movieRecs[cat]...)
}
if tvRecs != nil {
merged = append(merged, tvRecs[cat]...)
}
// Sort merged by ranking score
sort.Slice(merged, func(i, j int) bool {
scoreI, _ := merged[i]["rankingScore"].(float64)
scoreJ, _ := merged[j]["rankingScore"].(float64)
return scoreI > scoreJ
})
result[cat] = merged
}
json.NewEncoder(w).Encode(map[string]any{
"categories": result,
})
}
func getRecommendationsForType(selectedItems []SelectedItem, mediaType string, selectedIDs, existingTmdbIDs map[int]bool) map[string][]map[string]any {
if len(selectedItems) == 0 {
return map[string][]map[string]any{}
}
// Step 1: Get similar items, recommendations, and keywords for each selected item (parallel)
type ItemData struct {
Similar []int
Recommended []int
Keywords []int
UserCount int // How many users watched the source item
}
itemData := make(map[string]ItemData)
var dataMutex sync.Mutex
var wg sync.WaitGroup
for _, item := range selectedItems {
wg.Add(1)
go func(it SelectedItem) {
defer wg.Done()
data := ItemData{
Similar: getTmdbSimilar(it.ID, it.Type),
Recommended: getTmdbRecommended(it.ID, it.Type),
Keywords: getTmdbKeywords(it.ID, it.Type),
UserCount: it.UserCount,
}
dataMutex.Lock()
itemData[it.ID] = data
dataMutex.Unlock()
}(item)
}
wg.Wait()
// Collect all keywords from selected items (weighted by user count)
selectedKeywords := make(map[int]int)
for _, data := range itemData {
for _, kw := range data.Keywords {
selectedKeywords[kw] += data.UserCount
}
}
// Score items from multiple signals
// Weight by UserCount - items from shared watches score higher
itemScores := make(map[int]int)
// Signal 1: Similar items (weighted by how many users watched the source)
for _, data := range itemData {
for _, id := range data.Similar {
if existingTmdbIDs[id] || selectedIDs[id] {
continue
}
itemScores[id] += data.UserCount
}
}
// Signal 2: Recommended items (weighted by how many users watched the source)
for _, data := range itemData {
for _, id := range data.Recommended {
if existingTmdbIDs[id] || selectedIDs[id] {
continue
}
itemScores[id] += data.UserCount
}
}
// Signal 3: Keyword overlap - fetch keywords for top candidates
type candidate struct {
id int
score int
}
var candidates []candidate
for id, score := range itemScores {
candidates = append(candidates, candidate{id, score})
}
sort.Slice(candidates, func(i, j int) bool {
return candidates[i].score > candidates[j].score
})
if len(candidates) > 100 {
candidates = candidates[:100]
}
// Fetch keywords for top candidates in parallel
var kwWg sync.WaitGroup
sem := make(chan struct{}, 20)
candidateKeywords := make(map[int][]int)
var kwMutex sync.Mutex
for _, c := range candidates {
kwWg.Add(1)
go func(itemID int) {
defer kwWg.Done()
sem <- struct{}{}
defer func() { <-sem }()
kws := getTmdbKeywords(fmt.Sprintf("%d", itemID), mediaType)
kwMutex.Lock()
candidateKeywords[itemID] = kws
kwMutex.Unlock()
}(c.id)
}
kwWg.Wait()
// Boost score for keyword matches
for itemID, kws := range candidateKeywords {
for _, kw := range kws {
if count, ok := selectedKeywords[kw]; ok && count >= 2 {
itemScores[itemID]++
}
}
}
// Filter to items with score >= 2
for itemID, score := range itemScores {
if score < 2 {
delete(itemScores, itemID)
}
}
// Get item details and build results
currentYear := time.Now().Year()
var popular, newest, hiddenGems, classics []map[string]any
for tmdbID, score := range itemScores {
info := getTmdbItemInfo(tmdbID, mediaType)
if info.Title == "" {
continue
}
rec := map[string]any{
"tmdbId": tmdbID,
"title": info.Title,
"poster": info.Poster,
"score": score,
"popularity": info.Popularity,
"year": info.Year,
"type": mediaType,
"rankingScore": float64(score) * info.Popularity,
}
// Categorize
age := currentYear - info.Year
if info.Year >= currentYear-2 {
// Newest: released in last 2 years
newest = append(newest, rec)
} else if age >= 15 && info.Popularity > 10 {
// Classics: 15+ years old with decent popularity
classics = append(classics, rec)
} else if info.Popularity < 30 && score >= 2 {
// Hidden Gems: low popularity but good recommendation score
hiddenGems = append(hiddenGems, rec)
} else if info.Popularity >= 30 {
// Popular: high popularity
popular = append(popular, rec)
} else {
// Default to popular if doesn't fit elsewhere
popular = append(popular, rec)
}
}
// Sort each category by ranking score
sortByRanking := func(items []map[string]any) {
sort.Slice(items, func(i, j int) bool {
return items[i]["rankingScore"].(float64) > items[j]["rankingScore"].(float64)
})
}
sortByRanking(popular)
sortByRanking(newest)
sortByRanking(hiddenGems)
sortByRanking(classics)
return map[string][]map[string]any{
"popular": popular,
"newest": newest,
"hiddenGems": hiddenGems,
"classics": classics,
}
}
// getTmdbSimilar returns similar item IDs from TMDB (works for both movies and TV)
func getTmdbSimilar(tmdbID string, mediaType string) []int {
cacheKey := fmt.Sprintf("similar:%s:%s", mediaType, tmdbID)
if cached, ok := cache.get(cacheKey); ok {
return cached.([]int)
}
var itemIDs []int
endpoint := "movie"
if mediaType == "tv" {
endpoint = "tv"
}
for page := 1; page <= 2; page++ {
url := fmt.Sprintf("https://api.themoviedb.org/3/%s/%s/similar?api_key=%s&page=%d", endpoint, tmdbID, tmdbAPIKey, page)
resp, err := httpClient.Get(url)
if err != nil {
break
}
var result struct {
Results []struct {
ID int `json:"id"`
} `json:"results"`
TotalPages int `json:"total_pages"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
break
}
resp.Body.Close()
for _, r := range result.Results {
itemIDs = append(itemIDs, r.ID)
}
if page >= result.TotalPages {
break
}
}
cache.set(cacheKey, itemIDs, time.Hour)
return itemIDs
}
// getTmdbRecommended returns recommended item IDs from TMDB (works for both movies and TV)
func getTmdbRecommended(tmdbID string, mediaType string) []int {
cacheKey := fmt.Sprintf("recommended:%s:%s", mediaType, tmdbID)
if cached, ok := cache.get(cacheKey); ok {
return cached.([]int)
}
var itemIDs []int
endpoint := "movie"
if mediaType == "tv" {
endpoint = "tv"
}
for page := 1; page <= 2; page++ {
url := fmt.Sprintf("https://api.themoviedb.org/3/%s/%s/recommendations?api_key=%s&page=%d", endpoint, tmdbID, tmdbAPIKey, page)
resp, err := httpClient.Get(url)
if err != nil {
break
}
var result struct {
Results []struct {
ID int `json:"id"`
} `json:"results"`
TotalPages int `json:"total_pages"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
break
}
resp.Body.Close()
for _, r := range result.Results {
itemIDs = append(itemIDs, r.ID)
}
if page >= result.TotalPages {
break
}
}
cache.set(cacheKey, itemIDs, time.Hour)
return itemIDs
}
// getTmdbKeywords returns keyword IDs for a movie or TV show
func getTmdbKeywords(tmdbID string, mediaType string) []int {
cacheKey := fmt.Sprintf("keywords:%s:%s", mediaType, tmdbID)
if cached, ok := cache.get(cacheKey); ok {
return cached.([]int)
}
endpoint := "movie"
keyField := "keywords"
if mediaType == "tv" {
endpoint = "tv"
keyField = "results" // TV uses "results" instead of "keywords"
}
url := fmt.Sprintf("https://api.themoviedb.org/3/%s/%s/keywords?api_key=%s", endpoint, tmdbID, tmdbAPIKey)
resp, err := httpClient.Get(url)
if err != nil {
return nil
}
defer resp.Body.Close()
// Parse as generic map since field name differs
var raw map[string]json.RawMessage
if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
return nil
}
var keywords []struct {
ID int `json:"id"`
}
if data, ok := raw[keyField]; ok {
json.Unmarshal(data, &keywords)
}
var ids []int
for _, kw := range keywords {
ids = append(ids, kw.ID)
}
cache.set(cacheKey, ids, time.Hour)
return ids
}
// ItemInfo holds details about a movie or TV show
type ItemInfo struct {
Title string
Poster string
Popularity float64
Year int
}
// getTmdbItemInfo fetches title, poster URL, popularity and year for a TMDB movie or TV show
func getTmdbItemInfo(tmdbID int, mediaType string) ItemInfo {
if tmdbAPIKey == "" {
return ItemInfo{}
}
cacheKey := fmt.Sprintf("info:%s:%d", mediaType, tmdbID)
if cached, ok := cache.get(cacheKey); ok {
return cached.(ItemInfo)
}
endpoint := "movie"
if mediaType == "tv" {
endpoint = "tv"
}
url := fmt.Sprintf("https://api.themoviedb.org/3/%s/%d?api_key=%s", endpoint, tmdbID, tmdbAPIKey)
resp, err := httpClient.Get(url)
if err != nil {
return ItemInfo{}
}
defer resp.Body.Close()
var result struct {
Title string `json:"title"` // movies
Name string `json:"name"` // TV shows
PosterPath string `json:"poster_path"`
Popularity float64 `json:"popularity"`
ReleaseDate string `json:"release_date"` // movies: "2024-01-15"
FirstAirDate string `json:"first_air_date"` // TV shows
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return ItemInfo{}
}
info := ItemInfo{
Title: result.Title,
Popularity: result.Popularity,
}
if info.Title == "" {
info.Title = result.Name
}
// Parse year
dateStr := result.ReleaseDate
if dateStr == "" {
dateStr = result.FirstAirDate
}
if len(dateStr) >= 4 {
info.Year, _ = strconv.Atoi(dateStr[:4])
}
if result.PosterPath != "" {
info.Poster = "https://image.tmdb.org/t/p/w200" + result.PosterPath
}
cache.set(cacheKey, info, 24*time.Hour)
return info
}