File size: 8,318 Bytes
8314b51
 
 
 
b6f7b56
8314b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/**
 * 邮箱激活器 - 专门处理邮箱休眠问题
 */

import { get_access_token, getEmails, activateMailbox, syncMailbox } from './mail.js';

export interface ActivationResult {
    success: boolean;
    activated: boolean;
    emailCount: number;
    latestEmailTime?: string;
    error?: string;
    activationMethods: string[];
}

export class MailboxActivator {
    private accessToken: string;

    constructor(accessToken: string) {
        this.accessToken = accessToken;
    }

    /**
     * 检测邮箱是否可能处于休眠状态
     */
    async detectDormantState(): Promise<{ isDormant: boolean; reason: string }> {
        try {
            // 1. 尝试获取最新邮件
            const emails = await getEmails(this.accessToken, 5, false);
            
            if (emails.length === 0) {
                return { isDormant: true, reason: "邮箱中没有邮件" };
            }

            // 2. 检查最新邮件的时间
            const latestEmail = emails[0];
            const latestTime = new Date(latestEmail.date.received || latestEmail.date.created);
            const now = new Date();
            const hoursDiff = (now.getTime() - latestTime.getTime()) / (1000 * 60 * 60);

            // 如果最新邮件超过24小时,可能处于休眠状态
            if (hoursDiff > 24) {
                return { isDormant: true, reason: `最新邮件时间过旧: ${hoursDiff.toFixed(1)}小时前` };
            }

            // 3. 检查邮件数量是否异常少
            if (emails.length < 3) {
                return { isDormant: true, reason: "邮件数量异常少" };
            }

            return { isDormant: false, reason: "邮箱状态正常" };
        } catch (error) {
            return { isDormant: true, reason: `检测失败: ${error}` };
        }
    }

    /**
     * 执行全面的邮箱激活
     */
    async performFullActivation(): Promise<ActivationResult> {
        const activationMethods: string[] = [];
        let activated = false;

        try {
            console.log('开始执行邮箱激活...');

            // 方法1: 基础激活
            try {
                await activateMailbox(this.accessToken);
                activationMethods.push('基础激活');
            } catch (error) {
                console.warn('基础激活失败:', error);
            }

            // 方法2: 强制同步
            try {
                await syncMailbox(this.accessToken);
                activationMethods.push('强制同步');
            } catch (error) {
                console.warn('强制同步失败:', error);
            }

            // 方法3: 深度激活 - 访问多个端点
            try {
                await this.deepActivation();
                activationMethods.push('深度激活');
            } catch (error) {
                console.warn('深度激活失败:', error);
            }

            // 方法4: 模拟用户活动
            try {
                await this.simulateUserActivity();
                activationMethods.push('模拟用户活动');
            } catch (error) {
                console.warn('模拟用户活动失败:', error);
            }

            // 等待激活生效
            await new Promise(resolve => setTimeout(resolve, 5000));

            // 验证激活效果
            const emails = await getEmails(this.accessToken, 10, false);
            const emailCount = emails.length;
            const latestEmailTime = emails.length > 0 ? emails[0].date.received : undefined;

            activated = activationMethods.length > 0;

            return {
                success: true,
                activated,
                emailCount,
                latestEmailTime,
                activationMethods
            };

        } catch (error: any) {
            return {
                success: false,
                activated: false,
                emailCount: 0,
                error: error.message,
                activationMethods
            };
        }
    }

    /**
     * 深度激活 - 访问更多Microsoft Graph端点
     */
    private async deepActivation(): Promise<void> {
        const endpoints = [
            'https://graph.microsoft.com/v1.0/me/calendar',
            'https://graph.microsoft.com/v1.0/me/contacts',
            'https://graph.microsoft.com/v1.0/me/drive',
            'https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$top=1',
            'https://graph.microsoft.com/v1.0/me/mailFolders/sentitems',
            'https://graph.microsoft.com/v1.0/me/mailFolders/drafts'
        ];

        const promises = endpoints.map(endpoint => 
            fetch(endpoint, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json'
                }
            }).catch(error => {
                console.warn(`访问端点失败 ${endpoint}:`, error);
            })
        );

        await Promise.allSettled(promises);
    }

    /**
     * 模拟用户活动
     */
    private async simulateUserActivity(): Promise<void> {
        try {
            // 1. 获取邮箱设置
            await fetch('https://graph.microsoft.com/v1.0/me/mailboxSettings', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json'
                }
            });

            // 2. 获取用户照片(触发用户会话)
            await fetch('https://graph.microsoft.com/v1.0/me/photo', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`
                }
            }).catch(() => {}); // 忽略错误,因为用户可能没有照片

            // 3. 获取最近活动
            await fetch('https://graph.microsoft.com/v1.0/me/activities/recent', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json'
                }
            }).catch(() => {}); // 忽略错误

            // 4. 检查邮件规则
            await fetch('https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json'
                }
            }).catch(() => {}); // 忽略错误

        } catch (error) {
            console.warn('模拟用户活动时出错:', error);
        }
    }

    /**
     * 智能激活 - 根据检测结果决定激活策略
     */
    async smartActivation(): Promise<ActivationResult> {
        // 首先检测邮箱状态
        const dormantCheck = await this.detectDormantState();
        
        if (!dormantCheck.isDormant) {
            // 邮箱状态正常,只做轻量级激活
            try {
                await activateMailbox(this.accessToken);
                const emails = await getEmails(this.accessToken, 5, false);
                
                return {
                    success: true,
                    activated: true,
                    emailCount: emails.length,
                    latestEmailTime: emails.length > 0 ? emails[0].date.received : undefined,
                    activationMethods: ['轻量级激活']
                };
            } catch (error: any) {
                return {
                    success: false,
                    activated: false,
                    emailCount: 0,
                    error: error.message,
                    activationMethods: []
                };
            }
        } else {
            // 邮箱可能休眠,执行全面激活
            console.log(`检测到邮箱可能休眠: ${dormantCheck.reason}`);
            return await this.performFullActivation();
        }
    }
}

/**
 * 便捷函数:激活指定邮箱
 */
export async function activateMailboxSmart(accessToken: string): Promise<ActivationResult> {
    const activator = new MailboxActivator(accessToken);
    return await activator.smartActivation();
}