CoolFace
Apppublic

zhemima/msmail

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
batch.ts119 linesDownload Raw Back to mail
1import { authApiToken, authMiddleware } from "../../utils/auth.js";2import { addCorsHeaders } from "../../utils/cors.js";3import { AuthService } from "../../utils/authService.js";4 5// 并发处理函数6async function processBatch<T>(7    items: T[],8    processor: (item: T) => Promise<any>,9    concurrency: number = 210): Promise<any[]> {11    // 创建一个队列来存储所有的 promise12    const queue: Promise<any>[] = [];13    const results: any[] = new Array(items.length);14    let nextIndex = 0;15 16    // 创建指定数量的worker17    const workers = new Array(concurrency).fill(null).map(async () => {18        while (nextIndex < items.length) {19            const currentIndex = nextIndex++;20            try {21                const result = await processor(items[currentIndex]);22                results[currentIndex] = result;23            } catch (error) {24                results[currentIndex] = {25                    error: error instanceof Error ? error.message : 'Unknown error'26                };27            }28        }29    });30 31    // 等待所有worker完成32    await Promise.all(workers);33    return results;34}35 36// 检查认证状态和时间戳37async function checkAuthStatus(email: string, env: Env): Promise<{ needsAuth: boolean, reason?: string }> {38    const tokenInfoStr = await env.KV.get(`refresh_token_${email}`);39    if (!tokenInfoStr) {40        return { needsAuth: true, reason: "未认证" };41    }42 43    const tokenInfo = JSON.parse(tokenInfoStr);44    const threeMonths = 90 * 24 * 60 * 60 * 1000; // 90天转换为毫秒45    const isExpired = Date.now() - tokenInfo.timestamp > threeMonths;46 47    if (isExpired) {48        return { needsAuth: true, reason: "认证已过期" };49    }50 51    return { needsAuth: false };52}53 54export const onRequest = async (context: RouteContext): Promise<Response> => {55    const request = context.request;56    const env: Env = context.env;57 58    const authResponse = await authMiddleware(request, env);59    const apiResponse = await authApiToken(request, env);60    if (authResponse && apiResponse) {61        return addCorsHeaders(authResponse);62    }63 64    try {65        const { emails } = await request.json() as { emails: string[] };66        if (!emails || !Array.isArray(emails)) {67            throw new Error("Emails array is required");68        }69 70        const authService = new AuthService(env);71        const results = await processBatch(72            emails,73            async (email) => {74                try {75                    // 检查认证状态76                    const authStatus = await checkAuthStatus(email, env);77                    if (!authStatus.needsAuth) {78                        return {79                            email,80                            success: true,81                            message: "已认证且在有效期内"82                        };83                    }84 85                    // 需要重新认证86                    const result = await authService.authenticateEmail(email);87                    return {88                        email,89                        success: result.success,90                        message: authStatus.reason,91                        error: result.error92                    };93                } catch (error: any) {94                    return {95                        email,96                        success: false,97                        error: error.message || 'Failed to process'98                    };99                }100            },101            2102        );103 104        return new Response(105            JSON.stringify(results),106            {107                status: 200,108                headers: { 'Content-Type': 'application/json' }109            }110        );111 112    } catch (error: any) {113        return new Response(114            JSON.stringify({ error: error.message }),115            { status: 500 }116        );117    }118};119