mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-03-06 03:50:47 +08:00
Compare commits
3 Commits
codex/add-
...
codex/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c344b5b4ae | ||
|
|
3f2829cd37 | ||
|
|
3258a42b44 |
@@ -23,10 +23,11 @@ public class NotificationController {
|
||||
private final NotificationMapper notificationMapper;
|
||||
|
||||
@GetMapping
|
||||
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
|
||||
@RequestParam(value = "page", defaultValue = "0") int page,
|
||||
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||
Authentication auth) {
|
||||
return notificationService.listNotifications(auth.getName(), page, size).stream()
|
||||
return notificationService.listNotifications(auth.getName(), read, page, size).stream()
|
||||
.map(notificationMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
@@ -35,7 +36,7 @@ public class NotificationController {
|
||||
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||
Authentication auth) {
|
||||
return notificationService.listUnreadNotifications(auth.getName(), page, size).stream()
|
||||
return notificationService.listNotifications(auth.getName(), false, page, size).stream()
|
||||
.map(notificationMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@ import com.openisle.model.User;
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.model.Comment;
|
||||
import com.openisle.model.NotificationType;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -15,8 +15,8 @@ import java.util.List;
|
||||
public interface NotificationRepository extends JpaRepository<Notification, Long> {
|
||||
List<Notification> findByUserOrderByCreatedAtDesc(User user);
|
||||
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
|
||||
Page<Notification> findByUser(User user, Pageable pageable);
|
||||
Page<Notification> findByUserAndRead(User user, boolean read, Pageable pageable);
|
||||
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
|
||||
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
|
||||
long countByUserAndRead(User user, boolean read);
|
||||
List<Notification> findByPost(Post post);
|
||||
List<Notification> findByComment(Comment comment);
|
||||
|
||||
@@ -24,10 +24,6 @@ import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
/** Service for creating and retrieving notifications. */
|
||||
@Service
|
||||
@@ -184,24 +180,21 @@ public class NotificationService {
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
public List<Notification> listNotifications(String username, int page, int size) {
|
||||
return listNotifications(username, null, page, size);
|
||||
}
|
||||
|
||||
public List<Notification> listUnreadNotifications(String username, int page, int size) {
|
||||
return listNotifications(username, false, page, size);
|
||||
}
|
||||
|
||||
private List<Notification> listNotifications(String username, Boolean read, int page, int size) {
|
||||
public List<Notification> listNotifications(String username, Boolean read, int page, int size) {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
||||
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
|
||||
Page<Notification> list;
|
||||
org.springframework.data.domain.Pageable pageable =
|
||||
org.springframework.data.domain.PageRequest.of(page, size);
|
||||
List<Notification> list;
|
||||
if (read == null) {
|
||||
list = notificationRepository.findByUser(user, pageable);
|
||||
list = notificationRepository
|
||||
.findByUserOrderByCreatedAtDesc(user, pageable)
|
||||
.getContent();
|
||||
} else {
|
||||
list = notificationRepository.findByUserAndRead(user, read, pageable);
|
||||
list = notificationRepository
|
||||
.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable)
|
||||
.getContent();
|
||||
}
|
||||
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ class NotificationControllerTest {
|
||||
p.setId(2L);
|
||||
n.setPost(p);
|
||||
n.setCreatedAt(LocalDateTime.now());
|
||||
when(notificationService.listNotifications("alice", 0, 30))
|
||||
when(notificationService.listNotifications("alice", null))
|
||||
.thenReturn(List.of(n));
|
||||
|
||||
NotificationDto dto = new NotificationDto();
|
||||
@@ -62,23 +62,6 @@ class NotificationControllerTest {
|
||||
.andExpect(jsonPath("$[0].post.id").value(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listUnreadNotifications() throws Exception {
|
||||
Notification n = new Notification();
|
||||
n.setId(1L);
|
||||
when(notificationService.listUnreadNotifications("alice", 0, 30))
|
||||
.thenReturn(List.of(n));
|
||||
|
||||
NotificationDto dto = new NotificationDto();
|
||||
dto.setId(1L);
|
||||
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(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void markReadEndpoint() throws Exception {
|
||||
mockMvc.perform(post("/api/notifications/read")
|
||||
|
||||
@@ -11,7 +11,6 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -66,12 +65,12 @@ class NotificationServiceTest {
|
||||
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
||||
|
||||
Notification n = new Notification();
|
||||
when(nRepo.findByUser(eq(user), any(Pageable.class))).thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(n)));
|
||||
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n));
|
||||
|
||||
List<Notification> list = service.listNotifications("bob", 0, 30);
|
||||
List<Notification> list = service.listNotifications("bob", null);
|
||||
|
||||
assertEquals(1, list.size());
|
||||
verify(nRepo).findByUser(eq(user), any(Pageable.class));
|
||||
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -53,13 +53,13 @@
|
||||
</div>
|
||||
|
||||
<BasePlaceholder
|
||||
v-else-if="notifications.length === 0"
|
||||
v-else-if="filteredNotifications.length === 0"
|
||||
text="暂时没有消息 :)"
|
||||
icon="fas fa-inbox"
|
||||
/>
|
||||
|
||||
<div class="timeline-container" v-if="notifications.length > 0">
|
||||
<BaseTimeline :items="notifications">
|
||||
<div class="timeline-container" v-if="filteredNotifications.length > 0">
|
||||
<BaseTimeline :items="filteredNotifications">
|
||||
<template #item="{ item }">
|
||||
<div class="notif-content" :class="{ read: item.read }">
|
||||
<span v-if="!item.read" class="unread-dot"></span>
|
||||
@@ -505,27 +505,31 @@
|
||||
</div>
|
||||
</template>
|
||||
</BaseTimeline>
|
||||
<InfiniteLoadMore :key="selectedTab" :on-load="fetchMore" :pause="isLoadingMessage" />
|
||||
<div v-if="hasMore" class="load-more">
|
||||
<button class="load-more-button" @click="loadMore">加载更多</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, onActivated } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||
import BaseTimeline from '~/components/BaseTimeline.vue'
|
||||
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
|
||||
import NotificationContainer from '~/components/NotificationContainer.vue'
|
||||
import { toast } from '~/main'
|
||||
import { authState, getToken } from '~/utils/auth'
|
||||
import { stripMarkdownLength } from '~/utils/markdown'
|
||||
import {
|
||||
fetchNotifications,
|
||||
fetchAllNotifications,
|
||||
fetchUnreadNotifications,
|
||||
fetchUnreadCount,
|
||||
isLoadingMessage,
|
||||
isLoadingAll,
|
||||
isLoadingUnread,
|
||||
markRead,
|
||||
notifications,
|
||||
notificationsAll,
|
||||
notificationsUnread,
|
||||
markAllRead,
|
||||
fetchNotificationPreferences,
|
||||
updateNotificationPreference,
|
||||
@@ -539,16 +543,19 @@ const selectedTab = ref(
|
||||
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
|
||||
)
|
||||
const notificationPrefs = ref([])
|
||||
|
||||
const fetchMore = () => fetchNotifications()
|
||||
|
||||
const loadInitial = async () => {
|
||||
await fetchNotifications({ reset: true, read: selectedTab.value === 'unread' ? false : null })
|
||||
}
|
||||
|
||||
watch(selectedTab, async (t) => {
|
||||
await fetchNotifications({ reset: true, read: t === 'unread' ? false : null })
|
||||
})
|
||||
const pageAll = ref(0)
|
||||
const pageUnread = ref(0)
|
||||
const hasMoreAll = ref(true)
|
||||
const hasMoreUnread = ref(true)
|
||||
const filteredNotifications = computed(() =>
|
||||
selectedTab.value === 'all' ? notificationsAll.value : notificationsUnread.value,
|
||||
)
|
||||
const isLoadingMessage = computed(() =>
|
||||
selectedTab.value === 'all' ? isLoadingAll.value : isLoadingUnread.value,
|
||||
)
|
||||
const hasMore = computed(() =>
|
||||
selectedTab.value === 'all' ? hasMoreAll.value : hasMoreUnread.value,
|
||||
)
|
||||
|
||||
const fetchPrefs = async () => {
|
||||
notificationPrefs.value = await fetchNotificationPreferences()
|
||||
@@ -558,7 +565,14 @@ const togglePref = async (pref) => {
|
||||
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
|
||||
if (ok) {
|
||||
pref.enabled = !pref.enabled
|
||||
await fetchNotifications({ reset: true, read: selectedTab.value === 'unread' ? false : null })
|
||||
pageAll.value = 0
|
||||
pageUnread.value = 0
|
||||
const countAll = await fetchAllNotifications(0)
|
||||
const countUnread = await fetchUnreadNotifications(0)
|
||||
pageAll.value = 1
|
||||
pageUnread.value = 1
|
||||
hasMoreAll.value = countAll === 30
|
||||
hasMoreUnread.value = countUnread === 30
|
||||
await fetchUnreadCount()
|
||||
} else {
|
||||
toast.error('操作失败')
|
||||
@@ -638,9 +652,34 @@ const formatType = (t) => {
|
||||
}
|
||||
}
|
||||
|
||||
onActivated(() => {
|
||||
loadInitial()
|
||||
fetchPrefs()
|
||||
const loadMore = async () => {
|
||||
if (selectedTab.value === 'all') {
|
||||
const c = await fetchAllNotifications(pageAll.value)
|
||||
pageAll.value++
|
||||
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>
|
||||
|
||||
@@ -702,6 +741,19 @@ onActivated(() => {
|
||||
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 {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -116,224 +116,251 @@ export async function updateNotificationPreference(type, enabled) {
|
||||
* @returns
|
||||
*/
|
||||
function createFetchNotifications() {
|
||||
const notifications = ref([])
|
||||
const isLoadingMessage = ref(false)
|
||||
const page = ref(0)
|
||||
const notificationsAll = ref([])
|
||||
const notificationsUnread = ref([])
|
||||
const isLoadingAll = ref(false)
|
||||
const isLoadingUnread = ref(false)
|
||||
const pageSize = 30
|
||||
const readFilter = ref(null)
|
||||
const fetchNotifications = async ({ reset = false, read = null } = {}) => {
|
||||
|
||||
function pushNotification(n, target) {
|
||||
if (n.type === 'COMMENT_REPLY') {
|
||||
target.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
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 API_BASE_URL = config.public.apiBaseUrl
|
||||
if (isLoadingMessage.value) return false
|
||||
try {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
toast.error('请先登录')
|
||||
return true
|
||||
return
|
||||
}
|
||||
if (reset) {
|
||||
notifications.value = []
|
||||
page.value = 0
|
||||
readFilter.value = read
|
||||
}
|
||||
isLoadingMessage.value = true
|
||||
let url = `${API_BASE_URL}/api/notifications`
|
||||
if (readFilter.value === false) url += '/unread'
|
||||
url += `?page=${page.value}&size=${pageSize}`
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
isLoadingAll.value = true
|
||||
const res = await fetch(`${API_BASE_URL}/api/notifications?page=${page}&size=${pageSize}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
isLoadingMessage.value = false
|
||||
isLoadingAll.value = false
|
||||
if (!res.ok) {
|
||||
toast.error('获取通知失败')
|
||||
return true
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
|
||||
if (page === 0) notificationsAll.value = []
|
||||
for (const n of data) {
|
||||
if (n.type === 'COMMENT_REPLY') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'REACTION') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'MENTION') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.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') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {},
|
||||
})
|
||||
} else {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
})
|
||||
}
|
||||
pushNotification(n, notificationsAll.value)
|
||||
}
|
||||
const done = data.length < pageSize
|
||||
if (!done) page.value++
|
||||
return done
|
||||
return data.length
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
isLoadingMessage.value = false
|
||||
return true
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
const markRead = async (id) => {
|
||||
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(
|
||||
`${API_BASE_URL}/api/notifications/unread?page=${page}&size=${pageSize}`,
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
)
|
||||
isLoadingUnread.value = false
|
||||
if (!res.ok) {
|
||||
toast.error('获取通知失败')
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
if (page === 0) notificationsUnread.value = []
|
||||
for (const n of data) {
|
||||
pushNotification(n, notificationsUnread.value)
|
||||
}
|
||||
return data.length
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
async function markRead(id) {
|
||||
if (!id) return
|
||||
const n = notifications.value.find((n) => n.id === id)
|
||||
if (!n || n.read) return
|
||||
n.read = true
|
||||
const nAll = notificationsAll.value.find((n) => n.id === id)
|
||||
const nUnreadIndex = notificationsUnread.value.findIndex((n) => n.id === id)
|
||||
const target = nAll || notificationsUnread.value[nUnreadIndex]
|
||||
if (!target || target.read) return
|
||||
target.read = true
|
||||
if (nUnreadIndex !== -1) notificationsUnread.value.splice(nUnreadIndex, 1)
|
||||
if (notificationState.unreadCount > 0) notificationState.unreadCount--
|
||||
const ok = await markNotificationsRead([id])
|
||||
if (!ok) {
|
||||
n.read = false
|
||||
target.read = false
|
||||
if (nUnreadIndex !== -1) notificationsUnread.value.splice(nUnreadIndex, 0, target)
|
||||
notificationState.unreadCount++
|
||||
} else {
|
||||
fetchUnreadCount()
|
||||
}
|
||||
}
|
||||
|
||||
const markAllRead = async () => {
|
||||
// 除了 REGISTER_REQUEST 类型消息
|
||||
const idsToMark = notifications.value
|
||||
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
|
||||
.map((n) => n.id)
|
||||
if (idsToMark.length === 0) return
|
||||
notifications.value.forEach((n) => {
|
||||
async function markAllRead() {
|
||||
const ids = [
|
||||
...new Set(
|
||||
[...notificationsAll.value, ...notificationsUnread.value]
|
||||
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
|
||||
.map((n) => n.id),
|
||||
),
|
||||
]
|
||||
if (ids.length === 0) return
|
||||
notificationsAll.value.forEach((n) => {
|
||||
if (n.type !== 'REGISTER_REQUEST') n.read = true
|
||||
})
|
||||
notificationState.unreadCount = notifications.value.filter((n) => !n.read).length
|
||||
const ok = await markNotificationsRead(idsToMark)
|
||||
notificationsUnread.value = []
|
||||
notificationState.unreadCount = 0
|
||||
const ok = await markNotificationsRead(ids)
|
||||
if (!ok) {
|
||||
notifications.value.forEach((n) => {
|
||||
if (idsToMark.includes(n.id)) n.read = false
|
||||
})
|
||||
await fetchUnreadCount()
|
||||
return
|
||||
}
|
||||
@@ -344,14 +371,26 @@ function createFetchNotifications() {
|
||||
toast.success('已读所有消息')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
fetchNotifications,
|
||||
fetchAllNotifications,
|
||||
fetchUnreadNotifications,
|
||||
markRead,
|
||||
notifications,
|
||||
isLoadingMessage,
|
||||
notificationsAll,
|
||||
notificationsUnread,
|
||||
isLoadingAll,
|
||||
isLoadingUnread,
|
||||
markAllRead,
|
||||
}
|
||||
}
|
||||
|
||||
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
|
||||
createFetchNotifications()
|
||||
export const {
|
||||
fetchAllNotifications,
|
||||
fetchUnreadNotifications,
|
||||
markRead,
|
||||
notificationsAll,
|
||||
notificationsUnread,
|
||||
isLoadingAll,
|
||||
isLoadingUnread,
|
||||
markAllRead,
|
||||
} = createFetchNotifications()
|
||||
|
||||
Reference in New Issue
Block a user