mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-08-22 02:47:15 +00:00
Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a3b28eafe4 | |||
| 805a8df7d3 | |||
| 02be045f55 | |||
| ac3c7b7bec | |||
| e7a1e1d159 | |||
| 30b56e54cf | |||
| cc525c1c27 |
@@ -23,11 +23,10 @@ public class NotificationController {
|
|||||||
private final NotificationMapper notificationMapper;
|
private final NotificationMapper notificationMapper;
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
|
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||||
@RequestParam(value = "page", defaultValue = "0") int page,
|
|
||||||
@RequestParam(value = "size", defaultValue = "30") int size,
|
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||||
Authentication auth) {
|
Authentication auth) {
|
||||||
return notificationService.listNotifications(auth.getName(), read, page, size).stream()
|
return notificationService.listNotifications(auth.getName(), null, page, size).stream()
|
||||||
.map(notificationMapper::toDto)
|
.map(notificationMapper::toDto)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
|
|||||||
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
|
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
|
||||||
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
|
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
|
||||||
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
|
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
|
||||||
|
Page<Notification> findByUserAndTypeNotInOrderByCreatedAtDesc(User user, java.util.Collection<NotificationType> types, Pageable pageable);
|
||||||
|
Page<Notification> findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(User user, boolean read, java.util.Collection<NotificationType> types, Pageable pageable);
|
||||||
long countByUserAndRead(User user, boolean read);
|
long countByUserAndRead(User user, boolean read);
|
||||||
|
long countByUserAndReadAndTypeNotIn(User user, boolean read, java.util.Collection<NotificationType> types);
|
||||||
List<Notification> findByPost(Post post);
|
List<Notification> findByPost(Post post);
|
||||||
List<Notification> findByComment(Comment comment);
|
List<Notification> findByComment(Comment comment);
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import java.util.HashSet;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
/** Service for creating and retrieving notifications. */
|
/** Service for creating and retrieving notifications. */
|
||||||
@Service
|
@Service
|
||||||
@@ -184,19 +183,22 @@ public class NotificationService {
|
|||||||
User user = userRepository.findByUsername(username)
|
User user = userRepository.findByUsername(username)
|
||||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
||||||
org.springframework.data.domain.Pageable pageable =
|
org.springframework.data.domain.Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
|
||||||
org.springframework.data.domain.PageRequest.of(page, size);
|
org.springframework.data.domain.Page<Notification> result;
|
||||||
List<Notification> list;
|
|
||||||
if (read == null) {
|
if (read == null) {
|
||||||
list = notificationRepository
|
if (disabled.isEmpty()) {
|
||||||
.findByUserOrderByCreatedAtDesc(user, pageable)
|
result = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
|
||||||
.getContent();
|
} else {
|
||||||
|
result = notificationRepository.findByUserAndTypeNotInOrderByCreatedAtDesc(user, disabled, pageable);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
list = notificationRepository
|
if (disabled.isEmpty()) {
|
||||||
.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable)
|
result = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
|
||||||
.getContent();
|
} else {
|
||||||
|
result = notificationRepository.findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(user, read, disabled, pageable);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
|
return result.getContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void markRead(String username, List<Long> ids) {
|
public void markRead(String username, List<Long> ids) {
|
||||||
@@ -215,8 +217,10 @@ public class NotificationService {
|
|||||||
User user = userRepository.findByUsername(username)
|
User user = userRepository.findByUsername(username)
|
||||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||||
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
||||||
return notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, false).stream()
|
if (disabled.isEmpty()) {
|
||||||
.filter(n -> !disabled.contains(n.getType())).count();
|
return notificationRepository.countByUserAndRead(user, false);
|
||||||
|
}
|
||||||
|
return notificationRepository.countByUserAndReadAndTypeNotIn(user, false, disabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void notifyMentions(String content, User fromUser, Post post, Comment comment) {
|
public void notifyMentions(String content, User fromUser, Post post, Comment comment) {
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ class NotificationControllerTest {
|
|||||||
p.setId(2L);
|
p.setId(2L);
|
||||||
n.setPost(p);
|
n.setPost(p);
|
||||||
n.setCreatedAt(LocalDateTime.now());
|
n.setCreatedAt(LocalDateTime.now());
|
||||||
when(notificationService.listNotifications("alice", null))
|
when(notificationService.listNotifications("alice", null, 0, 30))
|
||||||
.thenReturn(List.of(n));
|
.thenReturn(List.of(n));
|
||||||
|
|
||||||
NotificationDto dto = new NotificationDto();
|
NotificationDto dto = new NotificationDto();
|
||||||
@@ -62,6 +62,24 @@ class NotificationControllerTest {
|
|||||||
.andExpect(jsonPath("$[0].post.id").value(2));
|
.andExpect(jsonPath("$[0].post.id").value(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listUnreadNotifications() throws Exception {
|
||||||
|
Notification n = new Notification();
|
||||||
|
n.setId(5L);
|
||||||
|
n.setType(NotificationType.POST_VIEWED);
|
||||||
|
when(notificationService.listNotifications("alice", false, 0, 30))
|
||||||
|
.thenReturn(List.of(n));
|
||||||
|
|
||||||
|
NotificationDto dto = new NotificationDto();
|
||||||
|
dto.setId(5L);
|
||||||
|
when(notificationMapper.toDto(n)).thenReturn(dto);
|
||||||
|
|
||||||
|
mockMvc.perform(get("/api/notifications/unread")
|
||||||
|
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$[0].id").value(5));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void markReadEndpoint() throws Exception {
|
void markReadEndpoint() throws Exception {
|
||||||
mockMvc.perform(post("/api/notifications/read")
|
mockMvc.perform(post("/api/notifications/read")
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ import org.mockito.Mockito;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -62,15 +65,17 @@ class NotificationServiceTest {
|
|||||||
User user = new User();
|
User user = new User();
|
||||||
user.setId(2L);
|
user.setId(2L);
|
||||||
user.setUsername("bob");
|
user.setUsername("bob");
|
||||||
|
user.setDisabledNotificationTypes(new HashSet<>());
|
||||||
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
||||||
|
|
||||||
Notification n = new Notification();
|
Notification n = new Notification();
|
||||||
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n));
|
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(n)));
|
||||||
|
|
||||||
List<Notification> list = service.listNotifications("bob", null);
|
List<Notification> list = service.listNotifications("bob", null, 0, 10);
|
||||||
|
|
||||||
assertEquals(1, list.size());
|
assertEquals(1, list.size());
|
||||||
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
|
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -87,6 +92,7 @@ class NotificationServiceTest {
|
|||||||
User user = new User();
|
User user = new User();
|
||||||
user.setId(3L);
|
user.setId(3L);
|
||||||
user.setUsername("carl");
|
user.setUsername("carl");
|
||||||
|
user.setDisabledNotificationTypes(new HashSet<>());
|
||||||
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
|
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
|
||||||
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
|
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
|
||||||
|
|
||||||
@@ -96,6 +102,56 @@ class NotificationServiceTest {
|
|||||||
verify(nRepo).countByUserAndRead(user, false);
|
verify(nRepo).countByUserAndRead(user, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listNotificationsFiltersDisabledTypes() {
|
||||||
|
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||||
|
UserRepository uRepo = mock(UserRepository.class);
|
||||||
|
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||||
|
EmailSender email = mock(EmailSender.class);
|
||||||
|
PushNotificationService push = mock(PushNotificationService.class);
|
||||||
|
Executor executor = Runnable::run;
|
||||||
|
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||||
|
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
user.setId(4L);
|
||||||
|
user.setUsername("dana");
|
||||||
|
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
|
||||||
|
|
||||||
|
Notification n = new Notification();
|
||||||
|
when(nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(n)));
|
||||||
|
|
||||||
|
List<Notification> list = service.listNotifications("dana", null, 0, 10);
|
||||||
|
|
||||||
|
assertEquals(1, list.size());
|
||||||
|
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void countUnreadFiltersDisabledTypes() {
|
||||||
|
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||||
|
UserRepository uRepo = mock(UserRepository.class);
|
||||||
|
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||||
|
EmailSender email = mock(EmailSender.class);
|
||||||
|
PushNotificationService push = mock(PushNotificationService.class);
|
||||||
|
Executor executor = Runnable::run;
|
||||||
|
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||||
|
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
user.setId(5L);
|
||||||
|
user.setUsername("erin");
|
||||||
|
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
|
||||||
|
when(nRepo.countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes())))
|
||||||
|
.thenReturn(2L);
|
||||||
|
|
||||||
|
long count = service.countUnread("erin");
|
||||||
|
|
||||||
|
assertEquals(2L, count);
|
||||||
|
verify(nRepo).countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes()));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void createRegisterRequestNotificationsDeletesOldOnes() {
|
void createRegisterRequestNotificationsDeletesOldOnes() {
|
||||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||||
|
|||||||
@@ -53,13 +53,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<BasePlaceholder
|
<BasePlaceholder
|
||||||
v-else-if="filteredNotifications.length === 0"
|
v-else-if="notifications.length === 0"
|
||||||
text="暂时没有消息 :)"
|
text="暂时没有消息 :)"
|
||||||
icon="fas fa-inbox"
|
icon="fas fa-inbox"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div class="timeline-container" v-if="filteredNotifications.length > 0">
|
<div class="timeline-container" v-if="notifications.length > 0">
|
||||||
<BaseTimeline :items="filteredNotifications">
|
<BaseTimeline :items="notifications">
|
||||||
<template #item="{ item }">
|
<template #item="{ item }">
|
||||||
<div class="notif-content" :class="{ read: item.read }">
|
<div class="notif-content" :class="{ read: item.read }">
|
||||||
<span v-if="!item.read" class="unread-dot"></span>
|
<span v-if="!item.read" class="unread-dot"></span>
|
||||||
@@ -505,32 +505,29 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</BaseTimeline>
|
</BaseTimeline>
|
||||||
<div v-if="hasMore" class="load-more">
|
<InfiniteLoadMore :key="selectedTab" :on-load="loadMore" :pause="isLoadingMessage" />
|
||||||
<button class="load-more-button" @click="loadMore">加载更多</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onMounted, ref, watch } from 'vue'
|
import { ref, watch, onActivated } from 'vue'
|
||||||
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||||
import BaseTimeline from '~/components/BaseTimeline.vue'
|
import BaseTimeline from '~/components/BaseTimeline.vue'
|
||||||
import NotificationContainer from '~/components/NotificationContainer.vue'
|
import NotificationContainer from '~/components/NotificationContainer.vue'
|
||||||
|
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
|
||||||
import { toast } from '~/main'
|
import { toast } from '~/main'
|
||||||
import { authState, getToken } from '~/utils/auth'
|
import { authState, getToken } from '~/utils/auth'
|
||||||
import { stripMarkdownLength } from '~/utils/markdown'
|
import { stripMarkdownLength } from '~/utils/markdown'
|
||||||
import {
|
import {
|
||||||
fetchAllNotifications,
|
fetchNotifications,
|
||||||
fetchUnreadNotifications,
|
|
||||||
fetchUnreadCount,
|
fetchUnreadCount,
|
||||||
isLoadingAll,
|
isLoadingMessage,
|
||||||
isLoadingUnread,
|
|
||||||
markRead,
|
markRead,
|
||||||
notificationsAll,
|
notifications,
|
||||||
notificationsUnread,
|
|
||||||
markAllRead,
|
markAllRead,
|
||||||
|
hasMore,
|
||||||
fetchNotificationPreferences,
|
fetchNotificationPreferences,
|
||||||
updateNotificationPreference,
|
updateNotificationPreference,
|
||||||
} from '~/utils/notification'
|
} from '~/utils/notification'
|
||||||
@@ -543,19 +540,25 @@ const selectedTab = ref(
|
|||||||
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
|
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
|
||||||
)
|
)
|
||||||
const notificationPrefs = ref([])
|
const notificationPrefs = ref([])
|
||||||
const pageAll = ref(0)
|
const page = ref(0)
|
||||||
const pageUnread = ref(0)
|
const pageSize = 30
|
||||||
const hasMoreAll = ref(true)
|
|
||||||
const hasMoreUnread = ref(true)
|
const loadMore = async () => {
|
||||||
const filteredNotifications = computed(() =>
|
if (!hasMore.value) return true
|
||||||
selectedTab.value === 'all' ? notificationsAll.value : notificationsUnread.value,
|
page.value++
|
||||||
)
|
await fetchNotifications({
|
||||||
const isLoadingMessage = computed(() =>
|
page: page.value,
|
||||||
selectedTab.value === 'all' ? isLoadingAll.value : isLoadingUnread.value,
|
size: pageSize,
|
||||||
)
|
unread: selectedTab.value === 'unread',
|
||||||
const hasMore = computed(() =>
|
append: true,
|
||||||
selectedTab.value === 'all' ? hasMoreAll.value : hasMoreUnread.value,
|
})
|
||||||
)
|
return !hasMore.value
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(selectedTab, async (tab) => {
|
||||||
|
page.value = 0
|
||||||
|
await fetchNotifications({ page: 0, size: pageSize, unread: tab === 'unread' })
|
||||||
|
})
|
||||||
|
|
||||||
const fetchPrefs = async () => {
|
const fetchPrefs = async () => {
|
||||||
notificationPrefs.value = await fetchNotificationPreferences()
|
notificationPrefs.value = await fetchNotificationPreferences()
|
||||||
@@ -565,14 +568,11 @@ const togglePref = async (pref) => {
|
|||||||
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
|
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
|
||||||
if (ok) {
|
if (ok) {
|
||||||
pref.enabled = !pref.enabled
|
pref.enabled = !pref.enabled
|
||||||
pageAll.value = 0
|
await fetchNotifications({
|
||||||
pageUnread.value = 0
|
page: page.value,
|
||||||
const countAll = await fetchAllNotifications(0)
|
size: pageSize,
|
||||||
const countUnread = await fetchUnreadNotifications(0)
|
unread: selectedTab.value === 'unread',
|
||||||
pageAll.value = 1
|
})
|
||||||
pageUnread.value = 1
|
|
||||||
hasMoreAll.value = countAll === 30
|
|
||||||
hasMoreUnread.value = countUnread === 30
|
|
||||||
await fetchUnreadCount()
|
await fetchUnreadCount()
|
||||||
} else {
|
} else {
|
||||||
toast.error('操作失败')
|
toast.error('操作失败')
|
||||||
@@ -652,34 +652,10 @@ const formatType = (t) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadMore = async () => {
|
onActivated(async () => {
|
||||||
if (selectedTab.value === 'all') {
|
page.value = 0
|
||||||
const c = await fetchAllNotifications(pageAll.value)
|
await fetchNotifications({ page: 0, size: pageSize, unread: selectedTab.value === 'unread' })
|
||||||
pageAll.value++
|
fetchPrefs()
|
||||||
if (c < 30) hasMoreAll.value = false
|
|
||||||
} else {
|
|
||||||
const c = await fetchUnreadNotifications(pageUnread.value)
|
|
||||||
pageUnread.value++
|
|
||||||
if (c < 30) hasMoreUnread.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(async () => {
|
|
||||||
await fetchPrefs()
|
|
||||||
await loadMore()
|
|
||||||
await fetchUnreadCount()
|
|
||||||
})
|
|
||||||
|
|
||||||
watch(selectedTab, async (tab) => {
|
|
||||||
if (tab === 'all' && notificationsAll.value.length === 0) {
|
|
||||||
pageAll.value = 0
|
|
||||||
hasMoreAll.value = true
|
|
||||||
await loadMore()
|
|
||||||
} else if (tab === 'unread' && notificationsUnread.value.length === 0) {
|
|
||||||
pageUnread.value = 0
|
|
||||||
hasMoreUnread.value = true
|
|
||||||
await loadMore()
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -741,19 +717,6 @@ watch(selectedTab, async (tab) => {
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.load-more {
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.load-more-button {
|
|
||||||
margin: 10px auto;
|
|
||||||
padding: 6px 12px;
|
|
||||||
border: 1px solid var(--normal-border-color);
|
|
||||||
border-radius: 6px;
|
|
||||||
background: transparent;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.notif-content {
|
.notif-content {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
+163
-222
@@ -116,156 +116,16 @@ export async function updateNotificationPreference(type, enabled) {
|
|||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
function createFetchNotifications() {
|
function createFetchNotifications() {
|
||||||
const notificationsAll = ref([])
|
const notifications = ref([])
|
||||||
const notificationsUnread = ref([])
|
const isLoadingMessage = ref(false)
|
||||||
const isLoadingAll = ref(false)
|
const hasMore = ref(true)
|
||||||
const isLoadingUnread = ref(false)
|
|
||||||
const pageSize = 30
|
|
||||||
|
|
||||||
function pushNotification(n, target) {
|
const fetchNotifications = async ({
|
||||||
if (n.type === 'COMMENT_REPLY') {
|
page = 0,
|
||||||
target.push({
|
size = 30,
|
||||||
...n,
|
unread = false,
|
||||||
src: n.comment.author.avatar,
|
append = false,
|
||||||
iconClick: () => {
|
} = {}) => {
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'REACTION') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
emoji: reactionEmojiMap[n.reactionType],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.fromUser) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'POST_VIEWED') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
src: n.fromUser ? n.fromUser.avatar : null,
|
|
||||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.fromUser) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'LOTTERY_WIN') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.post) {
|
|
||||||
markRead(n.id)
|
|
||||||
router.push(`/posts/${n.post.id}`)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'LOTTERY_DRAW') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.post) {
|
|
||||||
markRead(n.id)
|
|
||||||
router.push(`/posts/${n.post.id}`)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'POST_UPDATED') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
src: n.comment.author.avatar,
|
|
||||||
iconClick: () => {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'USER_ACTIVITY') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
src: n.comment.author.avatar,
|
|
||||||
iconClick: () => {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'MENTION') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.fromUser) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.fromUser) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'FOLLOWED_POST') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.post) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.post) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'POST_REVIEW_REQUEST') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
src: n.fromUser ? n.fromUser.avatar : null,
|
|
||||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
|
||||||
iconClick: () => {
|
|
||||||
if (n.post) {
|
|
||||||
markRead(n.id)
|
|
||||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} else if (n.type === 'REGISTER_REQUEST') {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
iconClick: () => {},
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
target.push({
|
|
||||||
...n,
|
|
||||||
icon: iconMap[n.type],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchAllNotifications(page = 0) {
|
|
||||||
const config = useRuntimeConfig()
|
const config = useRuntimeConfig()
|
||||||
const API_BASE_URL = config.public.apiBaseUrl
|
const API_BASE_URL = config.public.apiBaseUrl
|
||||||
try {
|
try {
|
||||||
@@ -274,93 +134,179 @@ function createFetchNotifications() {
|
|||||||
toast.error('请先登录')
|
toast.error('请先登录')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
isLoadingAll.value = true
|
if (!append) notifications.value = []
|
||||||
const res = await fetch(`${API_BASE_URL}/api/notifications?page=${page}&size=${pageSize}`, {
|
isLoadingMessage.value = true
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
|
||||||
})
|
|
||||||
isLoadingAll.value = false
|
|
||||||
if (!res.ok) {
|
|
||||||
toast.error('获取通知失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const data = await res.json()
|
|
||||||
if (page === 0) notificationsAll.value = []
|
|
||||||
for (const n of data) {
|
|
||||||
pushNotification(n, notificationsAll.value)
|
|
||||||
}
|
|
||||||
return data.length
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e)
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchUnreadNotifications(page = 0) {
|
|
||||||
const config = useRuntimeConfig()
|
|
||||||
const API_BASE_URL = config.public.apiBaseUrl
|
|
||||||
try {
|
|
||||||
const token = getToken()
|
|
||||||
if (!token) {
|
|
||||||
toast.error('请先登录')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
isLoadingUnread.value = true
|
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`${API_BASE_URL}/api/notifications/unread?page=${page}&size=${pageSize}`,
|
`${API_BASE_URL}/api/notifications${unread ? '/unread' : ''}?page=${page}&size=${size}`,
|
||||||
{ headers: { Authorization: `Bearer ${token}` } },
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
)
|
)
|
||||||
isLoadingUnread.value = false
|
isLoadingMessage.value = false
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
toast.error('获取通知失败')
|
toast.error('获取通知失败')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
if (page === 0) notificationsUnread.value = []
|
const arr = []
|
||||||
|
|
||||||
for (const n of data) {
|
for (const n of data) {
|
||||||
pushNotification(n, notificationsUnread.value)
|
if (n.type === 'COMMENT_REPLY') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
src: n.comment.author.avatar,
|
||||||
|
iconClick: () => {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'REACTION') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
emoji: reactionEmojiMap[n.reactionType],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.fromUser) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'POST_VIEWED') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
src: n.fromUser ? n.fromUser.avatar : null,
|
||||||
|
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.fromUser) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'LOTTERY_WIN' || n.type === 'LOTTERY_DRAW') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.post) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/posts/${n.post.id}`)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'POST_UPDATED' || n.type === 'USER_ACTIVITY') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
src: n.comment.author.avatar,
|
||||||
|
iconClick: () => {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'MENTION') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.fromUser) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.fromUser) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (
|
||||||
|
n.type === 'FOLLOWED_POST' ||
|
||||||
|
n.type === 'POST_SUBSCRIBED' ||
|
||||||
|
n.type === 'POST_UNSUBSCRIBED'
|
||||||
|
) {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.post) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'POST_REVIEW_REQUEST') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
src: n.fromUser ? n.fromUser.avatar : null,
|
||||||
|
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||||
|
iconClick: () => {
|
||||||
|
if (n.post) {
|
||||||
|
markRead(n.id)
|
||||||
|
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else if (n.type === 'REGISTER_REQUEST') {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
iconClick: () => {},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
arr.push({
|
||||||
|
...n,
|
||||||
|
icon: iconMap[n.type],
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return data.length
|
|
||||||
|
if (append) notifications.value.push(...arr)
|
||||||
|
else notifications.value = arr
|
||||||
|
hasMore.value = data.length === size
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e)
|
console.error(e)
|
||||||
return 0
|
isLoadingMessage.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markRead(id) {
|
const markRead = async (id) => {
|
||||||
if (!id) return
|
if (!id) return
|
||||||
const nAll = notificationsAll.value.find((n) => n.id === id)
|
const n = notifications.value.find((n) => n.id === id)
|
||||||
const nUnreadIndex = notificationsUnread.value.findIndex((n) => n.id === id)
|
if (!n || n.read) return
|
||||||
const target = nAll || notificationsUnread.value[nUnreadIndex]
|
n.read = true
|
||||||
if (!target || target.read) return
|
|
||||||
target.read = true
|
|
||||||
if (nUnreadIndex !== -1) notificationsUnread.value.splice(nUnreadIndex, 1)
|
|
||||||
if (notificationState.unreadCount > 0) notificationState.unreadCount--
|
if (notificationState.unreadCount > 0) notificationState.unreadCount--
|
||||||
const ok = await markNotificationsRead([id])
|
const ok = await markNotificationsRead([id])
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
target.read = false
|
n.read = false
|
||||||
if (nUnreadIndex !== -1) notificationsUnread.value.splice(nUnreadIndex, 0, target)
|
|
||||||
notificationState.unreadCount++
|
notificationState.unreadCount++
|
||||||
} else {
|
} else {
|
||||||
fetchUnreadCount()
|
fetchUnreadCount()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markAllRead() {
|
const markAllRead = async () => {
|
||||||
const ids = [
|
// 除了 REGISTER_REQUEST 类型消息
|
||||||
...new Set(
|
const idsToMark = notifications.value
|
||||||
[...notificationsAll.value, ...notificationsUnread.value]
|
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
|
||||||
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
|
.map((n) => n.id)
|
||||||
.map((n) => n.id),
|
if (idsToMark.length === 0) return
|
||||||
),
|
notifications.value.forEach((n) => {
|
||||||
]
|
|
||||||
if (ids.length === 0) return
|
|
||||||
notificationsAll.value.forEach((n) => {
|
|
||||||
if (n.type !== 'REGISTER_REQUEST') n.read = true
|
if (n.type !== 'REGISTER_REQUEST') n.read = true
|
||||||
})
|
})
|
||||||
notificationsUnread.value = []
|
notificationState.unreadCount = notifications.value.filter((n) => !n.read).length
|
||||||
notificationState.unreadCount = 0
|
const ok = await markNotificationsRead(idsToMark)
|
||||||
const ok = await markNotificationsRead(ids)
|
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
|
notifications.value.forEach((n) => {
|
||||||
|
if (idsToMark.includes(n.id)) n.read = false
|
||||||
|
})
|
||||||
await fetchUnreadCount()
|
await fetchUnreadCount()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -371,26 +317,21 @@ function createFetchNotifications() {
|
|||||||
toast.success('已读所有消息')
|
toast.success('已读所有消息')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
fetchAllNotifications,
|
fetchNotifications,
|
||||||
fetchUnreadNotifications,
|
|
||||||
markRead,
|
markRead,
|
||||||
notificationsAll,
|
notifications,
|
||||||
notificationsUnread,
|
isLoadingMessage,
|
||||||
isLoadingAll,
|
|
||||||
isLoadingUnread,
|
|
||||||
markAllRead,
|
markAllRead,
|
||||||
|
hasMore,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const {
|
export const {
|
||||||
fetchAllNotifications,
|
fetchNotifications,
|
||||||
fetchUnreadNotifications,
|
|
||||||
markRead,
|
markRead,
|
||||||
notificationsAll,
|
notifications,
|
||||||
notificationsUnread,
|
isLoadingMessage,
|
||||||
isLoadingAll,
|
|
||||||
isLoadingUnread,
|
|
||||||
markAllRead,
|
markAllRead,
|
||||||
|
hasMore,
|
||||||
} = createFetchNotifications()
|
} = createFetchNotifications()
|
||||||
|
|||||||
Reference in New Issue
Block a user