initial commit

This commit is contained in:
rustmailer
2025-11-19 02:14:37 +08:00
commit 1a8f95117e
355 changed files with 54089 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { get_top_tags } from '@/api/search/api';
import { useQuery } from '@tanstack/react-query';
import React from 'react';
export interface TagCount {
tag: string;
count: number;
}
interface UseAvailableTagsResult {
tags: string[];
tagsCount: TagCount[];
isLoading: boolean;
isError: boolean;
error: unknown;
refetch: () => void;
}
export function useAvailableTags(): UseAvailableTagsResult {
const {
data: tagsCount = [],
isLoading,
isError,
error,
refetch,
} = useQuery<TagCount[]>({
queryKey: ['all-tags'],
queryFn: get_top_tags,
staleTime: 60 * 1000,
retry: false,
refetchOnWindowFocus: false,
});
const tags = React.useMemo(() => {
return tagsCount.map(f => f.tag).sort();
}, [tagsCount]);
return {
tags,
tagsCount,
isLoading,
isError,
error,
refetch,
};
}
+37
View File
@@ -0,0 +1,37 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { useState } from 'react'
/**
* Custom hook for confirm dialog
* @param initialState string | null
* @returns A stateful value, and a function to update it.
* @example const [open, setOpen] = useDialogState<"approve" | "reject">()
*/
export default function useDialogState<T extends string | boolean>(
initialState: T | null = null
) {
const [open, _setOpen] = useState<T | null>(initialState)
const setOpen = (str: T | null) =>
_setOpen((prev) => (prev === str ? null : str))
return [open, setOpen] as const
}
@@ -0,0 +1,51 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { minimal_account_list } from "@/api/account/api";
import { useQuery } from "@tanstack/react-query";
const useMinimalAccountList = () => {
const { data: minimalList, ...rest } = useQuery({
queryKey: ['minimal-account-list'],
queryFn: minimal_account_list,
});
const accountsOptions = minimalList
? minimalList.map(account => ({
label: account.email,
value: `${account.id}`,
}))
: [];
const getEmailById = (accountId: string | number) => {
if (!minimalList) return null;
const account = minimalList.find(a => `${a.id}` === `${accountId}`);
return account?.email || null;
};
return {
accountsOptions,
minimalList,
getEmailById,
...rest
};
};
export default useMinimalAccountList;
+38
View File
@@ -0,0 +1,38 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import * as React from 'react'
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener('change', onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener('change', onChange)
}, [])
return !!isMobile
}
+52
View File
@@ -0,0 +1,52 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { list_proxy } from "@/api/system/api";
import { useQuery } from "@tanstack/react-query";
const useProxyList = () => {
const { data: proxyList, ...rest } = useQuery({
queryKey: ['proxy-list'],
queryFn: list_proxy,
staleTime: 10 * 60 * 1000
});
const proxyOptions = proxyList
? proxyList.map(proxy => ({
label: proxy.url,
value: `${proxy.id}`,
}))
: [];
const getUrlById = (id: string | number) => {
if (!proxyList) return null;
const proxy = proxyList.find(a => `${a.id}` === `${id}`);
return proxy?.url || null;
};
return {
proxyOptions,
proxyList,
getUrlById,
...rest
};
};
export default useProxyList;
+89
View File
@@ -0,0 +1,89 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { EmailEnvelope, PaginatedResponse } from '@/api';
import { search_messages } from '@/api/search/api';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
export function useSearchMessages() {
// const queryClient = useQueryClient();
const [filter, setFilter] = useState<Record<string, any>>({});
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(30);
const onSubmit = (cleaned: Record<string, any>) => {
if ('has_attachment' in cleaned && cleaned.has_attachment === false) {
delete cleaned.has_attachment;
}
if (Object.keys(cleaned).length > 0) {
const payload = {
...cleaned,
...(cleaned.since && { since: cleaned.since.getTime() }),
...(cleaned.before && { before: cleaned.before.getTime() }),
};
setFilter(payload);
setPage(1);
} else {
setFilter({});
}
};
const reset = () => {
setFilter({});
setPage(1);
}
const {
data,
isLoading,
isError,
error,
isFetching,
} = useQuery<PaginatedResponse<EmailEnvelope>>({
queryKey: ['search-messages', filter, page, pageSize],
queryFn: () =>
search_messages({
filter: filter,
page,
page_size: pageSize,
}),
staleTime: 1000,
retry: false,
});
return {
emails: data?.items ?? [],
total: data?.total_items ?? 0,
totalPages: data?.total_pages ?? 1,
pageSize: data?.page_size ?? pageSize,
setPageSize,
isLoading,
isError,
error: error as Error | null,
isFetching,
page,
setPage,
onSubmit,
reset,
filter
};
}
+208
View File
@@ -0,0 +1,208 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Inspired by react-hot-toast library
import * as React from 'react'
import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const actionTypes = {
ADD_TOAST: 'ADD_TOAST',
UPDATE_TOAST: 'UPDATE_TOAST',
DISMISS_TOAST: 'DISMISS_TOAST',
REMOVE_TOAST: 'REMOVE_TOAST',
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType['ADD_TOAST']
toast: ToasterToast
}
| {
type: ActionType['UPDATE_TOAST']
toast: Partial<ToasterToast>
}
| {
type: ActionType['DISMISS_TOAST']
toastId?: ToasterToast['id']
}
| {
type: ActionType['REMOVE_TOAST']
toastId?: ToasterToast['id']
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: 'REMOVE_TOAST',
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'ADD_TOAST':
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case 'UPDATE_TOAST':
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case 'DISMISS_TOAST': {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case 'REMOVE_TOAST':
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, 'id'>
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: 'UPDATE_TOAST',
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: 'DISMISS_TOAST', toastId: id })
dispatch({
type: 'ADD_TOAST',
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }),
}
}
export { useToast, toast }
+58
View File
@@ -0,0 +1,58 @@
//
// Copyright (c) 2025 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { update_tags } from '@/api/search/api';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from './use-toast';
export interface UpdateTagsParams {
updates: Record<number, number[]>;
tags: string[];
}
export function useUpdateTags() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (params: UpdateTagsParams) => {
const { updates, tags } = params;
const payload = {
updates,
tags
};
return update_tags(payload);
},
onSuccess: () => {
toast({
title: 'Tags updated',
description: `Successfully applied to these email(s).`,
});
queryClient.invalidateQueries({ queryKey: ['search-messages'], exact: false });
queryClient.invalidateQueries({ queryKey: ['all-tags'] });
},
onError: (error: any) => {
toast({
title: 'Failed to update tags',
description: error?.message || 'Please try again later.',
variant: 'destructive',
});
},
});
}