|
| 1 | +import { convertAvatarToBase64 } from '../utils.js' |
| 2 | + |
| 3 | +/** |
| 4 | + * Cnblogs (博客园) detection logic |
| 5 | + * Strategy: |
| 6 | + * 1. Collect cookies via chrome.cookies.getAll (MV3 service worker compatible) |
| 7 | + * 2. Fetch user info via account.cnblogs.com/user/userinfo with cookies attached manually |
| 8 | + * 3. Extract username and avatar from API response |
| 9 | + */ |
| 10 | +export async function detectCnblogsUser() { |
| 11 | + try { |
| 12 | + const cookies = await chrome.cookies.getAll({ domain: '.cnblogs.com' }) |
| 13 | + const wwwCookies = await chrome.cookies.getAll({ url: 'https://www.cnblogs.com' }) |
| 14 | + const accountCookies = await chrome.cookies.getAll({ url: 'https://account.cnblogs.com' }) |
| 15 | + const allCookies = [...cookies, ...wwwCookies, ...accountCookies] |
| 16 | + const seen = new Set() |
| 17 | + const uniqueCookies = allCookies.filter(c => { |
| 18 | + const key = `${c.name}=${c.value}` |
| 19 | + if (seen.has(key)) return false |
| 20 | + seen.add(key) |
| 21 | + return true |
| 22 | + }) |
| 23 | + const cookieStr = uniqueCookies.map(c => `${c.name}=${c.value}`).join('; ') |
| 24 | + |
| 25 | + if (!cookieStr) return { loggedIn: false } |
| 26 | + |
| 27 | + const response = await fetch('https://account.cnblogs.com/user/userinfo', { |
| 28 | + method: 'GET', |
| 29 | + headers: { |
| 30 | + 'Accept': 'application/json', |
| 31 | + 'Cookie': cookieStr, |
| 32 | + }, |
| 33 | + }) |
| 34 | + |
| 35 | + if (!response.ok) return { loggedIn: false } |
| 36 | + |
| 37 | + const data = await response.json() |
| 38 | + if (!data?.spaceUserId) return { loggedIn: false } |
| 39 | + |
| 40 | + const username = data.displayName || '' |
| 41 | + let avatar = data.iconName || '' |
| 42 | + |
| 43 | + if (avatar && !avatar.startsWith('http')) { |
| 44 | + avatar = 'https:' + avatar |
| 45 | + } |
| 46 | + if (avatar && avatar.includes('cnblogs.com')) { |
| 47 | + avatar = await convertAvatarToBase64(avatar, 'https://www.cnblogs.com/') |
| 48 | + } |
| 49 | + |
| 50 | + return { loggedIn: true, username, avatar } |
| 51 | + } catch (e) { |
| 52 | + console.error('[COSE] Cnblogs Detection Error:', e) |
| 53 | + return { loggedIn: false, error: e.message } |
| 54 | + } |
| 55 | +} |
0 commit comments