1 parent
51a320b31f
commit
d700543eba
28 files changed
+559
-19
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Loader2, Tv } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { t } from '../../i18n'
|
||||
import { listNotifications, markNotificationsRead, type AppNotification, type NotificationKind } from '../../lib/cloud/notifications'
|
||||
@@ -9,16 +9,19 @@ import Sheet from './Sheet'
|
||||
|
||||
const PAGE = 30
|
||||
const FOLLOW_KINDS: NotificationKind[] = ['follow_request', 'follow_accepted', 'new_follower']
|
||||
const EPISODE_KINDS: NotificationKind[] = ['new_episode', 'new_season']
|
||||
|
||||
const VERB: Record<NotificationKind, () => string> = {
|
||||
follow_request: () => t('notif.follow_request'),
|
||||
follow_accepted: () => t('notif.follow_accepted'),
|
||||
new_follower: () => t('notif.new_follower'),
|
||||
reaction: () => t('notif.reaction'),
|
||||
new_episode: () => '',
|
||||
new_season: () => '',
|
||||
}
|
||||
|
||||
/** Liste des notifications (abonnements, demandes acceptées, réactions). Marque comme lues à l'ouverture. */
|
||||
export default function Notifications({ onClose, onOpenProfile }: { onClose: () => void; onOpenProfile: (username: string) => void }) {
|
||||
/** Liste des notifications (abonnements, réactions, nouveaux épisodes). Marque comme lues à l'ouverture. */
|
||||
export default function Notifications({ onClose, onOpenProfile, onOpenItem }: { onClose: () => void; onOpenProfile: (username: string) => void; onOpenItem: (itemId: string) => void }) {
|
||||
const [items, setItems] = useState<AppNotification[] | undefined>(undefined)
|
||||
const [done, setDone] = useState(false)
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
@@ -37,7 +40,6 @@ export default function Notifications({ onClose, onOpenProfile }: { onClose: ()
|
||||
setDone(true)
|
||||
}
|
||||
}
|
||||
// Marque comme lu (feu et oubli) pour vider le badge
|
||||
markNotificationsRead().catch(() => {})
|
||||
})()
|
||||
return () => {
|
||||
@@ -72,7 +74,7 @@ export default function Notifications({ onClose, onOpenProfile }: { onClose: ()
|
||||
) : (
|
||||
<ul>
|
||||
{items.map((n) => (
|
||||
<Row key={n.id} n={n} onOpenProfile={onOpenProfile} />
|
||||
<Row key={n.id} n={n} onOpenProfile={onOpenProfile} onOpenItem={onOpenItem} />
|
||||
))}
|
||||
{!done && (
|
||||
<li className="p-4">
|
||||
@@ -87,10 +89,43 @@ export default function Notifications({ onClose, onOpenProfile }: { onClose: ()
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ n, onOpenProfile }: { n: AppNotification; onOpenProfile: (username: string) => void }) {
|
||||
function Row({ n, onOpenProfile, onOpenItem }: { n: AppNotification; onOpenProfile: (username: string) => void; onOpenItem: (itemId: string) => void }) {
|
||||
const unread = n.read_at === null
|
||||
const isEpisode = EPISODE_KINDS.includes(n.kind)
|
||||
const base = cx('flex items-center gap-3 border-b border-line px-4 py-3 text-start', unread && 'bg-surface-2')
|
||||
|
||||
// ── Nouvel épisode / nouvelle saison ──
|
||||
if (isEpisode) {
|
||||
const title = n.title ?? '—'
|
||||
const inner = (
|
||||
<>
|
||||
{unread && <span className="size-2 shrink-0 rounded-full bg-accent-fill" aria-hidden="true" />}
|
||||
<span className="grid size-[38px] shrink-0 place-items-center rounded-full bg-surface-2 text-accent">
|
||||
<Tv size={18} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 text-sm leading-snug text-ink-2">
|
||||
<b className="text-ink">{t(n.kind === 'new_season' ? 'notif.new_season' : 'notif.new_episode', { title })}</b>
|
||||
{n.episode != null && <span className="text-ink-3"> · {t('episodes.short', { n: n.episode })}</span>}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-ink-3">{formatDate(n.created_at)}</span>
|
||||
</>
|
||||
)
|
||||
return (
|
||||
<li>
|
||||
{n.item_id ? (
|
||||
<button onClick={() => onOpenItem(n.item_id!)} className={cx(base, 'w-full')}>
|
||||
{inner}
|
||||
</button>
|
||||
) : (
|
||||
<div className={base}>{inner}</div>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Abonnements / réactions ──
|
||||
const actor = n.actor
|
||||
const actorName = actor?.display_name ?? t('notif.someone')
|
||||
const unread = n.read_at === null
|
||||
const username = actor?.username
|
||||
const target = username != null && FOLLOW_KINDS.includes(n.kind) ? username : null
|
||||
|
||||
@@ -111,8 +146,6 @@ function Row({ n, onOpenProfile }: { n: AppNotification; onOpenProfile: (usernam
|
||||
</>
|
||||
)
|
||||
|
||||
const base = cx('flex items-center gap-3 border-b border-line px-4 py-3 text-start', unread && 'bg-surface-2')
|
||||
|
||||
return (
|
||||
<li>
|
||||
{target != null ? (
|
||||
|
||||
@@ -170,7 +170,18 @@ export function SocialProvider({ children, onOpenOwnItem }: { children: ReactNod
|
||||
) : o.kind === 'reviews' ? (
|
||||
<TitleReviews key={k} externalId={o.externalId} title={o.title} onClose={pop} onOpenProfile={(u) => push({ kind: 'profile', username: u })} />
|
||||
) : (
|
||||
<Notifications key={k} onClose={pop} onOpenProfile={(u) => push({ kind: 'profile', username: u })} />
|
||||
<Notifications
|
||||
key={k}
|
||||
onClose={pop}
|
||||
onOpenProfile={(u) => push({ kind: 'profile', username: u })}
|
||||
onOpenItem={(id) => {
|
||||
const it = items.find((i) => i.id === id)
|
||||
if (it) {
|
||||
pop()
|
||||
onOpenOwnItem(it)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{children}
|
||||
|
||||
@@ -234,6 +234,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'تثبيت التطبيق',
|
||||
'settings.installHint': 'أضِف AzuuCine إلى شاشتك الرئيسية أو سطح المكتب.',
|
||||
'settings.installed': 'تم تثبيت التطبيق',
|
||||
'settings.notifs': 'الإشعارات',
|
||||
'settings.notifsHint': 'اختر ما يُفعّل الجرس.',
|
||||
'settings.notifEpisodes': 'حلقات جديدة',
|
||||
'settings.notifFollows': 'متابعون جدد',
|
||||
'settings.notifAccepted': 'طلبات مقبولة',
|
||||
'settings.notifReactions': 'تفاعلات على تقييماتي',
|
||||
'notif.new_episode': 'حلقة جديدة من {title}',
|
||||
'notif.new_season': 'موسم جديد من {title}',
|
||||
'reviews.title': 'التقييمات',
|
||||
'reviews.friends': 'أصدقاؤك',
|
||||
'reviews.others': 'أعضاء آخرون',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'App installieren',
|
||||
'settings.installHint': 'Füge AzuuCine zum Startbildschirm oder Desktop hinzu.',
|
||||
'settings.installed': 'App installiert',
|
||||
'settings.notifs': 'Mitteilungen',
|
||||
'settings.notifsHint': 'Lege fest, was die Glocke auslöst.',
|
||||
'settings.notifEpisodes': 'Neue Folgen',
|
||||
'settings.notifFollows': 'Neue Follower',
|
||||
'settings.notifAccepted': 'Angenommene Anfragen',
|
||||
'settings.notifReactions': 'Reaktionen auf meine Rezensionen',
|
||||
'notif.new_episode': 'Neue Folge von {title}',
|
||||
'notif.new_season': 'Neue Staffel von {title}',
|
||||
'reviews.title': 'Rezensionen',
|
||||
'reviews.friends': 'Deine Freunde',
|
||||
'reviews.others': 'Andere Mitglieder',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Install the app',
|
||||
'settings.installHint': 'Add AzuuCine to your home screen or desktop.',
|
||||
'settings.installed': 'App installed',
|
||||
'settings.notifs': 'Notifications',
|
||||
'settings.notifsHint': 'Choose what triggers the bell.',
|
||||
'settings.notifEpisodes': 'New episodes',
|
||||
'settings.notifFollows': 'New followers',
|
||||
'settings.notifAccepted': 'Accepted requests',
|
||||
'settings.notifReactions': 'Reactions to my reviews',
|
||||
'notif.new_episode': 'New episode of {title}',
|
||||
'notif.new_season': 'New season of {title}',
|
||||
'reviews.title': 'Reviews',
|
||||
'reviews.friends': 'Your friends',
|
||||
'reviews.others': 'Other members',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Instalar la aplicación',
|
||||
'settings.installHint': 'Añade AzuuCine a tu pantalla de inicio o escritorio.',
|
||||
'settings.installed': 'Aplicación instalada',
|
||||
'settings.notifs': 'Notificaciones',
|
||||
'settings.notifsHint': 'Elige qué activa la campana.',
|
||||
'settings.notifEpisodes': 'Nuevos episodios',
|
||||
'settings.notifFollows': 'Nuevos seguidores',
|
||||
'settings.notifAccepted': 'Solicitudes aceptadas',
|
||||
'settings.notifReactions': 'Reacciones a mis opiniones',
|
||||
'notif.new_episode': 'Nuevo episodio de {title}',
|
||||
'notif.new_season': 'Nueva temporada de {title}',
|
||||
'reviews.title': 'Opiniones',
|
||||
'reviews.friends': 'Tus amigos',
|
||||
'reviews.others': 'Otros miembros',
|
||||
|
||||
@@ -230,6 +230,14 @@ const dict = {
|
||||
'settings.installApp': 'Installer l\'application',
|
||||
'settings.installHint': 'Ajoute AzuuCine à ton écran d\'accueil ou ton bureau.',
|
||||
'settings.installed': 'Application installée',
|
||||
'settings.notifs': 'Notifications',
|
||||
'settings.notifsHint': 'Choisis ce qui déclenche la cloche.',
|
||||
'settings.notifEpisodes': 'Nouveaux épisodes',
|
||||
'settings.notifFollows': 'Nouveaux abonnés',
|
||||
'settings.notifAccepted': 'Demandes acceptées',
|
||||
'settings.notifReactions': 'Réactions à mes avis',
|
||||
'notif.new_episode': 'Nouvel épisode de {title}',
|
||||
'notif.new_season': 'Nouvelle saison de {title}',
|
||||
'reviews.title': 'Avis',
|
||||
'reviews.friends': 'Tes amis',
|
||||
'reviews.others': 'Autres membres',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'ऐप इंस्टॉल करें',
|
||||
'settings.installHint': 'AzuuCine को अपनी होम स्क्रीन या डेस्कटॉप पर जोड़ें।',
|
||||
'settings.installed': 'ऐप इंस्टॉल हो गया',
|
||||
'settings.notifs': 'सूचनाएँ',
|
||||
'settings.notifsHint': 'चुनो कि घंटी किससे बजे।',
|
||||
'settings.notifEpisodes': 'नए एपिसोड',
|
||||
'settings.notifFollows': 'नए फ़ॉलोअर',
|
||||
'settings.notifAccepted': 'स्वीकृत अनुरोध',
|
||||
'settings.notifReactions': 'मेरी समीक्षाओं पर प्रतिक्रियाएँ',
|
||||
'notif.new_episode': '{title} का नया एपिसोड',
|
||||
'notif.new_season': '{title} का नया सीज़न',
|
||||
'reviews.title': 'समीक्षाएँ',
|
||||
'reviews.friends': 'तुम्हारे दोस्त',
|
||||
'reviews.others': 'अन्य सदस्य',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Pasang aplikasi',
|
||||
'settings.installHint': 'Tambahkan AzuuCine ke layar utama atau desktop kamu.',
|
||||
'settings.installed': 'Aplikasi terpasang',
|
||||
'settings.notifs': 'Notifikasi',
|
||||
'settings.notifsHint': 'Pilih apa yang memicu lonceng.',
|
||||
'settings.notifEpisodes': 'Episode baru',
|
||||
'settings.notifFollows': 'Pengikut baru',
|
||||
'settings.notifAccepted': 'Permintaan diterima',
|
||||
'settings.notifReactions': 'Reaksi pada ulasanku',
|
||||
'notif.new_episode': 'Episode baru {title}',
|
||||
'notif.new_season': 'Musim baru {title}',
|
||||
'reviews.title': 'Ulasan',
|
||||
'reviews.friends': 'Teman kamu',
|
||||
'reviews.others': 'Anggota lain',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Installa l\'app',
|
||||
'settings.installHint': 'Aggiungi AzuuCine alla schermata home o al desktop.',
|
||||
'settings.installed': 'App installata',
|
||||
'settings.notifs': 'Notifiche',
|
||||
'settings.notifsHint': 'Scegli cosa attiva la campana.',
|
||||
'settings.notifEpisodes': 'Nuovi episodi',
|
||||
'settings.notifFollows': 'Nuovi follower',
|
||||
'settings.notifAccepted': 'Richieste accettate',
|
||||
'settings.notifReactions': 'Reazioni alle mie recensioni',
|
||||
'notif.new_episode': 'Nuovo episodio di {title}',
|
||||
'notif.new_season': 'Nuova stagione di {title}',
|
||||
'reviews.title': 'Recensioni',
|
||||
'reviews.friends': 'I tuoi amici',
|
||||
'reviews.others': 'Altri membri',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'アプリをインストール',
|
||||
'settings.installHint': 'AzuuCine をホーム画面やデスクトップに追加します。',
|
||||
'settings.installed': 'アプリをインストール済み',
|
||||
'settings.notifs': '通知',
|
||||
'settings.notifsHint': 'ベルを鳴らす項目を選びます。',
|
||||
'settings.notifEpisodes': '新しいエピソード',
|
||||
'settings.notifFollows': '新しいフォロワー',
|
||||
'settings.notifAccepted': '承認されたリクエスト',
|
||||
'settings.notifReactions': '自分のレビューへのリアクション',
|
||||
'notif.new_episode': '「{title}」の新エピソード',
|
||||
'notif.new_season': '「{title}」の新シーズン',
|
||||
'reviews.title': 'レビュー',
|
||||
'reviews.friends': '友だち',
|
||||
'reviews.others': 'ほかのメンバー',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': '앱 설치',
|
||||
'settings.installHint': 'AzuuCine을 홈 화면이나 바탕화면에 추가하세요.',
|
||||
'settings.installed': '앱 설치됨',
|
||||
'settings.notifs': '알림',
|
||||
'settings.notifsHint': '벨을 울릴 항목을 선택하세요.',
|
||||
'settings.notifEpisodes': '새 에피소드',
|
||||
'settings.notifFollows': '새 팔로워',
|
||||
'settings.notifAccepted': '수락된 요청',
|
||||
'settings.notifReactions': '내 리뷰에 대한 반응',
|
||||
'notif.new_episode': '{title} 새 에피소드',
|
||||
'notif.new_season': '{title} 새 시즌',
|
||||
'reviews.title': '리뷰',
|
||||
'reviews.friends': '내 친구',
|
||||
'reviews.others': '다른 회원',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'App installeren',
|
||||
'settings.installHint': 'Voeg AzuuCine toe aan je startscherm of bureaublad.',
|
||||
'settings.installed': 'App geïnstalleerd',
|
||||
'settings.notifs': 'Meldingen',
|
||||
'settings.notifsHint': 'Kies wat de bel activeert.',
|
||||
'settings.notifEpisodes': 'Nieuwe afleveringen',
|
||||
'settings.notifFollows': 'Nieuwe volgers',
|
||||
'settings.notifAccepted': 'Geaccepteerde verzoeken',
|
||||
'settings.notifReactions': 'Reacties op mijn recensies',
|
||||
'notif.new_episode': 'Nieuwe aflevering van {title}',
|
||||
'notif.new_season': 'Nieuw seizoen van {title}',
|
||||
'reviews.title': 'Recensies',
|
||||
'reviews.friends': 'Je vrienden',
|
||||
'reviews.others': 'Andere leden',
|
||||
|
||||
@@ -232,6 +232,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Zainstaluj aplikację',
|
||||
'settings.installHint': 'Dodaj AzuuCine do ekranu głównego lub pulpitu.',
|
||||
'settings.installed': 'Aplikacja zainstalowana',
|
||||
'settings.notifs': 'Powiadomienia',
|
||||
'settings.notifsHint': 'Wybierz, co uruchamia dzwonek.',
|
||||
'settings.notifEpisodes': 'Nowe odcinki',
|
||||
'settings.notifFollows': 'Nowi obserwujący',
|
||||
'settings.notifAccepted': 'Zaakceptowane prośby',
|
||||
'settings.notifReactions': 'Reakcje na moje recenzje',
|
||||
'notif.new_episode': 'Nowy odcinek: {title}',
|
||||
'notif.new_season': 'Nowy sezon: {title}',
|
||||
'reviews.title': 'Recenzje',
|
||||
'reviews.friends': 'Twoi znajomi',
|
||||
'reviews.others': 'Inni użytkownicy',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Instalar o app',
|
||||
'settings.installHint': 'Adicione o AzuuCine à tela inicial ou à área de trabalho.',
|
||||
'settings.installed': 'App instalado',
|
||||
'settings.notifs': 'Notificações',
|
||||
'settings.notifsHint': 'Escolhe o que aciona o sino.',
|
||||
'settings.notifEpisodes': 'Novos episódios',
|
||||
'settings.notifFollows': 'Novos seguidores',
|
||||
'settings.notifAccepted': 'Pedidos aceites',
|
||||
'settings.notifReactions': 'Reações às minhas avaliações',
|
||||
'notif.new_episode': 'Novo episódio de {title}',
|
||||
'notif.new_season': 'Nova temporada de {title}',
|
||||
'reviews.title': 'Avaliações',
|
||||
'reviews.friends': 'Teus amigos',
|
||||
'reviews.others': 'Outros membros',
|
||||
|
||||
@@ -232,6 +232,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Установить приложение',
|
||||
'settings.installHint': 'Добавь AzuuCine на главный экран или рабочий стол.',
|
||||
'settings.installed': 'Приложение установлено',
|
||||
'settings.notifs': 'Уведомления',
|
||||
'settings.notifsHint': 'Выбери, что включает колокольчик.',
|
||||
'settings.notifEpisodes': 'Новые серии',
|
||||
'settings.notifFollows': 'Новые подписчики',
|
||||
'settings.notifAccepted': 'Принятые заявки',
|
||||
'settings.notifReactions': 'Реакции на мои отзывы',
|
||||
'notif.new_episode': 'Новая серия «{title}»',
|
||||
'notif.new_season': 'Новый сезон «{title}»',
|
||||
'reviews.title': 'Отзывы',
|
||||
'reviews.friends': 'Твои друзья',
|
||||
'reviews.others': 'Другие участники',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'ติดตั้งแอป',
|
||||
'settings.installHint': 'เพิ่ม AzuuCine ไปที่หน้าจอหลักหรือเดสก์ท็อปของคุณ',
|
||||
'settings.installed': 'ติดตั้งแอปแล้ว',
|
||||
'settings.notifs': 'การแจ้งเตือน',
|
||||
'settings.notifsHint': 'เลือกสิ่งที่จะทำให้กระดิ่งเตือน',
|
||||
'settings.notifEpisodes': 'ตอนใหม่',
|
||||
'settings.notifFollows': 'ผู้ติดตามใหม่',
|
||||
'settings.notifAccepted': 'คำขอที่ยอมรับแล้ว',
|
||||
'settings.notifReactions': 'รีแอกชันต่อรีวิวของฉัน',
|
||||
'notif.new_episode': 'ตอนใหม่ของ {title}',
|
||||
'notif.new_season': 'ซีซันใหม่ของ {title}',
|
||||
'reviews.title': 'รีวิว',
|
||||
'reviews.friends': 'เพื่อนของคุณ',
|
||||
'reviews.others': 'สมาชิกอื่น',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Uygulamayı yükle',
|
||||
'settings.installHint': 'AzuuCine’i ana ekranına veya masaüstüne ekle.',
|
||||
'settings.installed': 'Uygulama yüklendi',
|
||||
'settings.notifs': 'Bildirimler',
|
||||
'settings.notifsHint': 'Zili neyin tetikleyeceğini seç.',
|
||||
'settings.notifEpisodes': 'Yeni bölümler',
|
||||
'settings.notifFollows': 'Yeni takipçiler',
|
||||
'settings.notifAccepted': 'Kabul edilen istekler',
|
||||
'settings.notifReactions': 'Yorumlarıma tepkiler',
|
||||
'notif.new_episode': '{title} yeni bölüm',
|
||||
'notif.new_season': '{title} yeni sezon',
|
||||
'reviews.title': 'Yorumlar',
|
||||
'reviews.friends': 'Arkadaşların',
|
||||
'reviews.others': 'Diğer üyeler',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': 'Cài đặt ứng dụng',
|
||||
'settings.installHint': 'Thêm AzuuCine vào màn hình chính hoặc màn hình nền của bạn.',
|
||||
'settings.installed': 'Đã cài ứng dụng',
|
||||
'settings.notifs': 'Thông báo',
|
||||
'settings.notifsHint': 'Chọn điều kích hoạt chuông.',
|
||||
'settings.notifEpisodes': 'Tập mới',
|
||||
'settings.notifFollows': 'Người theo dõi mới',
|
||||
'settings.notifAccepted': 'Yêu cầu đã chấp nhận',
|
||||
'settings.notifReactions': 'Cảm xúc với đánh giá của tôi',
|
||||
'notif.new_episode': 'Tập mới của {title}',
|
||||
'notif.new_season': 'Mùa mới của {title}',
|
||||
'reviews.title': 'Đánh giá',
|
||||
'reviews.friends': 'Bạn bè của bạn',
|
||||
'reviews.others': 'Thành viên khác',
|
||||
|
||||
@@ -228,6 +228,14 @@ const dict: Translations = {
|
||||
'settings.installApp': '安装应用',
|
||||
'settings.installHint': '将 AzuuCine 添加到主屏幕或桌面。',
|
||||
'settings.installed': '应用已安装',
|
||||
'settings.notifs': '通知',
|
||||
'settings.notifsHint': '选择触发铃铛的内容。',
|
||||
'settings.notifEpisodes': '新剧集',
|
||||
'settings.notifFollows': '新粉丝',
|
||||
'settings.notifAccepted': '已接受的请求',
|
||||
'settings.notifReactions': '对我评价的回应',
|
||||
'notif.new_episode': '《{title}》有新一集',
|
||||
'notif.new_season': '《{title}》有新一季',
|
||||
'reviews.title': '评价',
|
||||
'reviews.friends': '你的好友',
|
||||
'reviews.others': '其他用户',
|
||||
|
||||
+6
-1
@@ -1,5 +1,5 @@
|
||||
import { t } from '../i18n'
|
||||
import type { BackupFile, Criteria, CustomList, MediaItem, MediaType, Settings, TopCategory, TopEntry, WatchStatus } from '../types'
|
||||
import type { BackupFile, Criteria, CustomList, MediaItem, MediaType, NotifPrefs, Settings, TopCategory, TopEntry, WatchStatus } from '../types'
|
||||
import { ALL_TOP_CATEGORIES, MEDIA_TYPES, STATUSES } from './constants'
|
||||
import { episodeCap } from './franchise'
|
||||
import { convertLegacyBackup, isLegacyBackup } from './legacyImport'
|
||||
@@ -130,6 +130,11 @@ export function normalizeSettings(raw: unknown): Partial<Settings> | undefined {
|
||||
if (Array.isArray(raw.topCategories)) out.topCategories = ALL_TOP_CATEGORIES.filter((c) => (raw.topCategories as unknown[]).includes(c))
|
||||
if (isHexColor(raw.accentColor)) out.accentColor = raw.accentColor.toLowerCase()
|
||||
if (raw.themeMode === 'auto' || raw.themeMode === 'light' || raw.themeMode === 'dark' || raw.themeMode === 'night' || raw.themeMode === 'starfield') out.themeMode = raw.themeMode
|
||||
if (isPlainObject(raw.notifPrefs)) {
|
||||
const np: NotifPrefs = {}
|
||||
for (const k of ['episodes', 'follows', 'accepted', 'reactions'] as const) if (typeof raw.notifPrefs[k] === 'boolean') np[k] = raw.notifPrefs[k] as boolean
|
||||
out.notifPrefs = np
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { cloudFetch } from './api'
|
||||
|
||||
/** Notifications (cloche) : abonnements, demandes acceptées, réactions reçues. */
|
||||
|
||||
export type NotificationKind = 'follow_request' | 'follow_accepted' | 'new_follower' | 'reaction'
|
||||
export type NotificationKind = 'follow_request' | 'follow_accepted' | 'new_follower' | 'reaction' | 'new_episode' | 'new_season'
|
||||
|
||||
export interface AppNotification {
|
||||
id: number
|
||||
@@ -12,11 +12,36 @@ export interface AppNotification {
|
||||
read_at: string | null
|
||||
emoji: string | null
|
||||
item_id: string | null
|
||||
/** Numéro du dernier épisode sorti (épisodes) */
|
||||
episode: number | null
|
||||
/** Nombre de nouveaux épisodes (épisodes) */
|
||||
ep_count: number | null
|
||||
actor: { username: string; display_name: string; avatar_url: string | null } | null
|
||||
/** Titre de la fiche concernée (réactions) */
|
||||
/** Titre de la fiche concernée (réactions, épisodes) */
|
||||
title: string | null
|
||||
}
|
||||
|
||||
/** Épisode/saison à signaler (envoyé après la vérification des sorties). */
|
||||
export interface EpisodeNotice {
|
||||
item_id: string
|
||||
kind: 'new_episode' | 'new_season'
|
||||
/** Dernier épisode sorti */
|
||||
episode: number
|
||||
/** Nombre de nouveaux épisodes */
|
||||
count: number
|
||||
}
|
||||
|
||||
/** Enregistre les nouveaux épisodes des séries suivies (dédoublonné côté serveur). Renvoie le nombre créé. */
|
||||
export async function addEpisodeNotifications(list: EpisodeNotice[]): Promise<number> {
|
||||
if (!list.length) return 0
|
||||
try {
|
||||
const n = await rpc<number>('add_episode_notifications', { p_list: list })
|
||||
return typeof n === 'number' ? n : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -15,7 +15,7 @@ import { cloudFetch } from './api'
|
||||
* En cas de conflit, la modification la plus récente gagne (vérifié aussi par la base).
|
||||
*/
|
||||
|
||||
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor' | 'themeMode'>
|
||||
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor' | 'themeMode' | 'notifPrefs'>
|
||||
|
||||
export interface SyncHooks {
|
||||
getLists: () => CustomList[]
|
||||
|
||||
+13
-2
@@ -11,7 +11,8 @@ import Recommendations from '../components/Recommendations'
|
||||
import HomeHero, { ContinueCard } from '../components/HomeHero'
|
||||
import type { Tab } from '../components/BottomNav'
|
||||
import { EmptyState, LinkArrow, PageHeader, SectionTitle, StatTile } from '../components/ui'
|
||||
import { CACHE_EVENT, isCaughtUp, loadAiring, needsCheck, refreshAiring, saveAiring, trackable } from '../lib/airing'
|
||||
import { CACHE_EVENT, isCaughtUp, loadAiring, needsCheck, novelties, refreshAiring, saveAiring, trackable } from '../lib/airing'
|
||||
import { addEpisodeNotifications } from '../lib/cloud/notifications'
|
||||
import { useOnResume } from '../lib/onResume'
|
||||
import { calendarEvents } from '../lib/releases'
|
||||
import { computeStats } from '../lib/stats'
|
||||
@@ -71,13 +72,23 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
|
||||
if (info.backdrop && !i.backdrop) patch.backdrop = info.backdrop
|
||||
return Object.keys(patch).length ? [{ id: i.id, patch }] : []
|
||||
})
|
||||
// Notifications : nouveaux épisodes / saisons des séries suivies (dédoublonné côté serveur)
|
||||
if (social.enabled) {
|
||||
const notices = novelties(items, next)
|
||||
.filter((nv) => nv.kind !== 'upcoming')
|
||||
.map((nv) => ({ item_id: nv.item.id, kind: nv.kind === 'new_season' ? ('new_season' as const) : ('new_episode' as const), episode: nv.info.aired, count: nv.unwatched }))
|
||||
if (notices.length)
|
||||
void addEpisodeNotifications(notices).then((n) => {
|
||||
if (n > 0) void social.refresh()
|
||||
})
|
||||
}
|
||||
if (patches.length) return patchMany(patches)
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
airingRunning.current = false
|
||||
})
|
||||
}, [patchMany])
|
||||
}, [patchMany, social])
|
||||
useEffect(() => {
|
||||
if (loading || airingStarted.current) return
|
||||
airingStarted.current = true
|
||||
|
||||
@@ -12,11 +12,19 @@ import { ALL_TOP_CATEGORIES, TOP_CATEGORIES } from '../lib/constants'
|
||||
import { isHexColor, THEME_MODES, THEME_PRESETS } from '../lib/theme'
|
||||
import { detectPlatform, useInstallPrompt } from '../lib/pwa'
|
||||
import { isAdmin } from '../lib/cloud/admin'
|
||||
import type { NotifPrefs } from '../types'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
|
||||
type Message = { kind: 'ok' | 'error'; text: string }
|
||||
|
||||
const NOTIF_PREFS: { key: keyof NotifPrefs; readonly label: () => string }[] = [
|
||||
{ key: 'episodes', label: () => t('settings.notifEpisodes') },
|
||||
{ key: 'follows', label: () => t('settings.notifFollows') },
|
||||
{ key: 'accepted', label: () => t('settings.notifAccepted') },
|
||||
{ key: 'reactions', label: () => t('settings.notifReactions') },
|
||||
]
|
||||
|
||||
function Row({ icon, title, hint, onClick, danger }: { icon: ReactNode; title: string; hint?: string; onClick: () => void; danger?: boolean }) {
|
||||
return (
|
||||
<button onClick={onClick} className={cx('flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2', danger && 'text-accent')}>
|
||||
@@ -290,6 +298,33 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
|
||||
</div>
|
||||
)}
|
||||
|
||||
{account && (
|
||||
<>
|
||||
<SectionTitle>{t('settings.notifs')}</SectionTitle>
|
||||
<p className="mb-3 text-xs text-ink-3">{t('settings.notifsHint')}</p>
|
||||
<div className="card divide-y divide-line overflow-hidden">
|
||||
{NOTIF_PREFS.map(({ key, label }) => {
|
||||
const on = settings.notifPrefs?.[key] !== false
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={on}
|
||||
onClick={() => updateSettings({ notifPrefs: { ...settings.notifPrefs, [key]: !on } })}
|
||||
className="flex w-full items-center gap-3.5 px-4 py-3.5 text-start"
|
||||
>
|
||||
<span className="flex-1 text-sm font-medium">{label()}</span>
|
||||
<span className={cx('relative h-6 w-11 shrink-0 rounded-full transition-colors', on ? 'bg-accent-fill' : 'border border-line-strong bg-surface-2')}>
|
||||
<span className={cx('absolute top-0.5 size-5 rounded-full bg-ink transition-all', on ? 'start-[22px] bg-on-accent' : 'start-0.5')} />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<SectionTitle>{t('settings.databases')}</SectionTitle>
|
||||
<div className="card space-y-4 p-4">
|
||||
<div>
|
||||
|
||||
+3
-3
@@ -168,8 +168,8 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl
|
||||
getLists: () => listsRef.current,
|
||||
applyLists: (next) => setLists(() => next, true),
|
||||
getSettings: () => {
|
||||
const { ratingScale, topCategories, accentColor, themeMode } = settingsRef.current
|
||||
return { ratingScale, topCategories, accentColor, themeMode }
|
||||
const { ratingScale, topCategories, accentColor, themeMode, notifPrefs } = settingsRef.current
|
||||
return { ratingScale, topCategories, accentColor, themeMode, notifPrefs }
|
||||
},
|
||||
applySettings: (patch) => updateSettingsRef.current(patch, true),
|
||||
itemsChanged: () => void reloadItems(),
|
||||
@@ -210,7 +210,7 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl
|
||||
}, [settings.themeMode])
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<Settings>, silent = false) => {
|
||||
if (!silent && syncRef.current && ('ratingScale' in patch || 'topCategories' in patch || 'accentColor' in patch || 'themeMode' in patch)) syncRef.current.markSettings()
|
||||
if (!silent && syncRef.current && ('ratingScale' in patch || 'topCategories' in patch || 'accentColor' in patch || 'themeMode' in patch || 'notifPrefs' in patch)) syncRef.current.markSettings()
|
||||
setSettings((prev) => {
|
||||
const next = { ...prev, ...patch }
|
||||
try {
|
||||
|
||||
@@ -86,6 +86,20 @@ export interface Settings {
|
||||
accentColor: string
|
||||
/** Apparence (clair, sombre, nuit, bleu nuit étoilé). « auto » suit le navigateur. */
|
||||
themeMode: ThemeMode
|
||||
/** Notifications reçues (true par défaut si absent). Nécessite un compte. */
|
||||
notifPrefs?: NotifPrefs
|
||||
}
|
||||
|
||||
/** Types de notifications que l'on choisit de recevoir (true par défaut). */
|
||||
export interface NotifPrefs {
|
||||
/** Nouveaux épisodes / saisons des séries suivies */
|
||||
episodes?: boolean
|
||||
/** Nouveaux abonnés et demandes d'abonnement */
|
||||
follows?: boolean
|
||||
/** Demandes d'abonnement acceptées */
|
||||
accepted?: boolean
|
||||
/** Réactions reçues sur mes avis */
|
||||
reactions?: boolean
|
||||
}
|
||||
|
||||
export interface CustomList {
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
-- ════════════════════════════════════════════════════════════════════════════
|
||||
-- AzuuCine — Avis par titre, réactions, notifications (7 octobre 2026)
|
||||
-- 1. Voir tous les avis sur un titre (amis / autres).
|
||||
-- 2. Réagir aux avis (emoji).
|
||||
-- 3. Notifications (cloche) : abonnements, demandes acceptées, réactions reçues,
|
||||
-- nouveaux épisodes / nouvelles saisons des séries suivies.
|
||||
-- 4. Préférences : chacun choisit les notifications qu'il reçoit (réglages synchronisés).
|
||||
--
|
||||
-- À coller dans Supabase → SQL Editor → Run. Idempotent (réexécutable sans risque).
|
||||
-- Remplace le fichier du 5 octobre (jamais appliqué).
|
||||
-- ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- ── Tables ──
|
||||
create table if not exists public.review_reactions (
|
||||
author_id uuid not null references auth.users(id) on delete cascade, -- auteur de l'avis
|
||||
item_id text not null,
|
||||
user_id uuid not null default auth.uid() references auth.users(id) on delete cascade, -- qui réagit
|
||||
emoji text not null,
|
||||
created_at timestamptz not null default now(),
|
||||
primary key (author_id, item_id, user_id)
|
||||
);
|
||||
create index if not exists review_reactions_target_idx on public.review_reactions (author_id, item_id);
|
||||
alter table public.review_reactions enable row level security;
|
||||
alter table public.review_reactions force row level security;
|
||||
revoke all on public.review_reactions from anon, authenticated;
|
||||
|
||||
create table if not exists public.notifications (
|
||||
id bigint generated always as identity primary key,
|
||||
user_id uuid not null references auth.users(id) on delete cascade, -- destinataire
|
||||
kind text not null,
|
||||
actor_id uuid references auth.users(id) on delete cascade,
|
||||
item_id text,
|
||||
emoji text,
|
||||
created_at timestamptz not null default now(),
|
||||
read_at timestamptz
|
||||
);
|
||||
-- Épisodes : numéro du dernier épisode sorti, nombre de nouveaux, clé anti-doublon
|
||||
alter table public.notifications add column if not exists episode integer;
|
||||
alter table public.notifications add column if not exists ep_count integer;
|
||||
alter table public.notifications add column if not exists dedup text;
|
||||
alter table public.notifications drop constraint if exists notifications_kind_check;
|
||||
alter table public.notifications add constraint notifications_kind_check
|
||||
check (kind in ('follow_request','follow_accepted','new_follower','reaction','new_episode','new_season'));
|
||||
create index if not exists notifications_user_idx on public.notifications (user_id, created_at desc);
|
||||
create unique index if not exists notifications_dedup_idx on public.notifications (user_id, dedup) where dedup is not null;
|
||||
alter table public.notifications enable row level security;
|
||||
alter table public.notifications force row level security;
|
||||
revoke all on public.notifications from anon, authenticated;
|
||||
|
||||
-- ── Préférences : la personne veut-elle ce type de notification ? (oui par défaut) ──
|
||||
-- Réglage synchronisé : settings.data.notifPrefs = { episodes, follows, accepted, reactions }
|
||||
create or replace function public.azuu_wants(p_user uuid, p_kind text)
|
||||
returns boolean language sql stable security definer set search_path = '' as $$
|
||||
select coalesce((
|
||||
select (s.data->'notifPrefs'->>(case p_kind
|
||||
when 'follow_request' then 'follows'
|
||||
when 'new_follower' then 'follows'
|
||||
when 'follow_accepted' then 'accepted'
|
||||
when 'reaction' then 'reactions'
|
||||
else 'episodes' end)) is distinct from 'false'
|
||||
from public.settings s where s.user_id = p_user
|
||||
), true)
|
||||
$$;
|
||||
|
||||
-- ── Création de notifications (abonnements, réactions) + bornage de l'historique ──
|
||||
create or replace function public.azuu_notify(p_user uuid, p_kind text, p_actor uuid, p_item text default null, p_emoji text default null)
|
||||
returns void language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if p_user is null or p_actor is null or p_user = p_actor then return; end if;
|
||||
if not public.azuu_wants(p_user, p_kind) then return; end if;
|
||||
insert into public.notifications (user_id, kind, actor_id, item_id, emoji)
|
||||
values (p_user, p_kind, p_actor, p_item, p_emoji);
|
||||
delete from public.notifications
|
||||
where user_id = p_user and id not in (
|
||||
select id from public.notifications where user_id = p_user order by created_at desc limit 300
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- Abonnement / demande -> notifie le compte suivi ; demande acceptée -> notifie le demandeur
|
||||
create or replace function public.azuu_follow_notify()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if tg_op = 'INSERT' then
|
||||
perform public.azuu_notify(new.following_id,
|
||||
case when new.status = 'pending' then 'follow_request' else 'new_follower' end, new.follower_id);
|
||||
elsif tg_op = 'UPDATE' and old.status = 'pending' and new.status = 'accepted' then
|
||||
perform public.azuu_notify(new.follower_id, 'follow_accepted', new.following_id);
|
||||
end if;
|
||||
return null;
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists follows_notify on public.follows;
|
||||
create trigger follows_notify after insert or update on public.follows
|
||||
for each row execute function public.azuu_follow_notify();
|
||||
|
||||
-- Réaction reçue -> notifie l'auteur de l'avis
|
||||
create or replace function public.azuu_reaction_notify()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
perform public.azuu_notify(new.author_id, 'reaction', new.user_id, new.item_id, new.emoji);
|
||||
return null;
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists reactions_notify on public.review_reactions;
|
||||
create trigger reactions_notify after insert on public.review_reactions
|
||||
for each row execute function public.azuu_reaction_notify();
|
||||
|
||||
-- ── Nouveaux épisodes : signalés par l'app après sa vérification des sorties ──
|
||||
-- p_list = [{ item_id, kind: 'new_episode'|'new_season', episode, count }]
|
||||
-- Une seule notification par fiche et par épisode, même si plusieurs appareils la signalent.
|
||||
create or replace function public.add_episode_notifications(p_list jsonb)
|
||||
returns integer language plpgsql security definer set search_path = '' as $$
|
||||
declare
|
||||
me uuid := auth.uid();
|
||||
e jsonb;
|
||||
k text;
|
||||
n integer := 0;
|
||||
begin
|
||||
if me is null or jsonb_typeof(p_list) is distinct from 'array' then return 0; end if;
|
||||
if not public.azuu_wants(me, 'new_episode') then return 0; end if;
|
||||
for e in select value from jsonb_array_elements(p_list) limit 50 loop
|
||||
k := e->>'kind';
|
||||
if k is null or k not in ('new_episode', 'new_season') then continue; end if;
|
||||
if coalesce(e->>'episode', '') !~ '^[0-9]{1,6}$' or coalesce(e->>'count', '1') !~ '^[0-9]{1,4}$' then continue; end if;
|
||||
if not exists (select 1 from public.items i where i.user_id = me and i.id = e->>'item_id' and not i.deleted) then continue; end if;
|
||||
insert into public.notifications (user_id, kind, actor_id, item_id, episode, ep_count, dedup)
|
||||
values (me, k, null, e->>'item_id', (e->>'episode')::int, greatest(1, coalesce((e->>'count')::int, 1)),
|
||||
'ep:' || (e->>'item_id') || ':' || (e->>'episode'))
|
||||
on conflict (user_id, dedup) where dedup is not null do nothing;
|
||||
if found then n := n + 1; end if;
|
||||
end loop;
|
||||
delete from public.notifications
|
||||
where user_id = me and id not in (
|
||||
select id from public.notifications where user_id = me order by created_at desc limit 300
|
||||
);
|
||||
return n;
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Réagir à un avis ──
|
||||
create or replace function public.react_to_review(p_author uuid, p_item text, p_emoji text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is null then raise exception 'auth'; end if;
|
||||
if p_author = auth.uid() then raise exception 'cannot react to your own review'; end if;
|
||||
if p_emoji is null or p_emoji <> all (array['👍','❤️','🔥','😂','😮','😢']) then raise exception 'bad emoji'; end if;
|
||||
if not public.can_view(p_author) or not exists (
|
||||
select 1 from public.items i join public.profiles pr on pr.id = i.user_id
|
||||
where i.user_id = p_author and i.id = p_item and not i.deleted
|
||||
and coalesce(i.data->>'notes','') <> '' and not pr.suspended
|
||||
) then
|
||||
raise exception 'review not found';
|
||||
end if;
|
||||
insert into public.review_reactions (author_id, item_id, user_id, emoji)
|
||||
values (p_author, p_item, auth.uid(), p_emoji)
|
||||
on conflict (author_id, item_id, user_id) do update set emoji = excluded.emoji, created_at = now();
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.unreact_review(p_author uuid, p_item text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is null then raise exception 'auth'; end if;
|
||||
delete from public.review_reactions where author_id = p_author and item_id = p_item and user_id = auth.uid();
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Tous les avis sur un titre (amis / autres) ──
|
||||
create or replace function public.title_reviews(p_external_id text, p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare me uuid := auth.uid(); res jsonb;
|
||||
begin
|
||||
if me is null or p_external_id !~ '^(tmdb:(movie|tv):[0-9]{1,10}|anilist:[0-9]{1,10})$' then
|
||||
return jsonb_build_object('friends', '[]'::jsonb, 'others', '[]'::jsonb);
|
||||
end if;
|
||||
with revs as (
|
||||
select i.user_id, i.id as item_id, i.updated_at,
|
||||
nullif(i.data->>'rating','')::numeric as rating,
|
||||
i.data->>'notes' as notes, pr,
|
||||
exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted') as friend
|
||||
from public.items i
|
||||
join public.profiles pr on pr.id = i.user_id
|
||||
where i.data->>'externalId' = p_external_id
|
||||
and not i.deleted and coalesce(i.data->>'notes','') <> ''
|
||||
and i.user_id <> me and not pr.suspended
|
||||
and (not pr.is_private
|
||||
or exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted'))
|
||||
),
|
||||
enriched as (
|
||||
select r.*,
|
||||
(select coalesce(jsonb_object_agg(e.emoji, e.c), '{}'::jsonb)
|
||||
from (select emoji, count(*) c from public.review_reactions rr
|
||||
where rr.author_id = r.user_id and rr.item_id = r.item_id group by emoji) e) as reactions,
|
||||
(select count(*) from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id) as total,
|
||||
(select emoji from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id and rr.user_id = me) as mine
|
||||
from revs r
|
||||
)
|
||||
select jsonb_build_object(
|
||||
'friends', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes,
|
||||
'reactions', reactions, 'total', total, 'mine', mine) entry, total, updated_at
|
||||
from enriched where friend offset greatest(p_offset, 0) limit 40) f), '[]'::jsonb),
|
||||
'others', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes,
|
||||
'reactions', reactions, 'total', total, 'mine', mine) entry, total, updated_at
|
||||
from enriched where not friend offset greatest(p_offset, 0) limit 40) o), '[]'::jsonb)
|
||||
) into res;
|
||||
return res;
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Lecture des notifications (les types désactivés sont masqués) ──
|
||||
create or replace function public.get_notifications(p_offset integer default 0)
|
||||
returns jsonb language sql stable security definer set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(x order by created_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select n.id, n.kind, n.created_at, n.read_at, n.emoji, n.item_id, n.episode, n.ep_count,
|
||||
case when p.id is null then null else
|
||||
jsonb_build_object('username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url) end as actor,
|
||||
case when n.kind in ('reaction', 'new_episode', 'new_season')
|
||||
then (select it.data->>'title' from public.items it where it.user_id = n.user_id and it.id = n.item_id) end as title
|
||||
from public.notifications n
|
||||
left join public.profiles p on p.id = n.actor_id
|
||||
where n.user_id = auth.uid() and public.azuu_wants(n.user_id, n.kind)
|
||||
order by n.created_at desc
|
||||
offset greatest(p_offset, 0) limit 30
|
||||
) x
|
||||
$$;
|
||||
|
||||
create or replace function public.notifications_unread()
|
||||
returns integer language sql stable security definer set search_path = '' as $$
|
||||
select count(*)::int from public.notifications n
|
||||
where n.user_id = auth.uid() and n.read_at is null and public.azuu_wants(n.user_id, n.kind)
|
||||
$$;
|
||||
|
||||
create or replace function public.mark_notifications_read()
|
||||
returns void language sql security definer set search_path = '' as $$
|
||||
update public.notifications set read_at = now() where user_id = auth.uid() and read_at is null
|
||||
$$;
|
||||
|
||||
-- ── Droits (gate interne : auth.uid() / can_view) ──
|
||||
revoke all on function public.azuu_wants(uuid, text) from public, anon, authenticated;
|
||||
revoke all on function public.azuu_notify(uuid, text, uuid, text, text) from public, anon, authenticated;
|
||||
revoke all on function public.react_to_review(uuid, text, text) from public, anon;
|
||||
revoke all on function public.unreact_review(uuid, text) from public, anon;
|
||||
revoke all on function public.title_reviews(text, integer) from public, anon;
|
||||
revoke all on function public.get_notifications(integer) from public, anon;
|
||||
revoke all on function public.notifications_unread() from public, anon;
|
||||
revoke all on function public.mark_notifications_read() from public, anon;
|
||||
revoke all on function public.add_episode_notifications(jsonb) from public, anon;
|
||||
grant execute on function public.react_to_review(uuid, text, text) to authenticated;
|
||||
grant execute on function public.unreact_review(uuid, text) to authenticated;
|
||||
grant execute on function public.title_reviews(text, integer) to authenticated;
|
||||
grant execute on function public.get_notifications(integer) to authenticated;
|
||||
grant execute on function public.notifications_unread() to authenticated;
|
||||
grant execute on function public.mark_notifications_read() to authenticated;
|
||||
grant execute on function public.add_episode_notifications(jsonb) to authenticated;
|
||||
Reference in new issue
Block a user