1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Models;
7
8use Carbon\Carbon;
9
10/**
11 * @property Beatmapset $beatmapset
12 * @property int $beatmapset_id
13 * @property \Carbon\Carbon|null $created_at
14 * @property int $id
15 * @property \Carbon\Carbon|null $last_notified
16 * @property \Carbon\Carbon $last_read
17 * @property \Carbon\Carbon|null $updated_at
18 * @property User $user
19 * @property int $user_id
20 */
21class BeatmapsetWatch extends Model
22{
23 protected $casts = [
24 'last_notified' => 'datetime',
25 'last_read' => 'datetime',
26 ];
27
28 public static function check($beatmapset, $user)
29 {
30 if ($beatmapset === null || $user === null) {
31 return false;
32 }
33
34 return static
35 ::where('beatmapset_id', '=', $beatmapset->getKey())
36 ->where('user_id', '=', $user->getKey())
37 ->exists();
38 }
39
40 public static function markRead($beatmapset, $user)
41 {
42 if ($beatmapset === null || $user === null) {
43 return;
44 }
45
46 return static
47 ::where('beatmapset_id', '=', $beatmapset->getKey())
48 ->where('user_id', '=', $user->getKey())
49 ->update(['last_read' => Carbon::now()]);
50 }
51
52 public function beatmapset()
53 {
54 return $this->belongsTo(Beatmapset::class, 'beatmapset_id');
55 }
56
57 public function user()
58 {
59 return $this->belongsTo(User::class, 'user_id');
60 }
61
62 public function scopeRead($query)
63 {
64 $query->where(function ($query) {
65 $query
66 ->whereColumn('last_read', '>=', 'last_notified')
67 ->orWhereNull('last_notified');
68 });
69 }
70
71 public function scopeUnread($query)
72 {
73 $query->whereColumn('last_read', '<', 'last_notified');
74 }
75
76 public function scopeVisible($query)
77 {
78 $query->whereHas('beatmapset', function ($q) {
79 $q->active();
80 });
81 }
82
83 public function isRead()
84 {
85 return $this->last_read >= $this->last_notified;
86 }
87}