Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
271 lines (245 loc) · 9.8 KB
/
Copy pathbackground.js
File metadata and controls
271 lines (245 loc) · 9.8 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// background.js - Gemini Extension Service Worker
// 서비스워커가 (재)기동될 때마다 실행됨: 직전 생애주기에서 사용량 수집 중
// 서비스워커가 죽어버려 추적을 잃어버린 백그라운드 탭이 남아있다면 정리한다.
// (아래 activeUsageFetchTabId 등은 일반 변수라 서비스워커가 재시작되면 초기화되므로,
// chrome.storage.session에 남아있는 값은 곧 "이전 생애주기의 미완료 작업"이라는 뜻)
(async () => {
const stored = await chrome.storage.session.get(['activeUsageFetchTabId']);
const orphanTabId = stored.activeUsageFetchTabId;
if (orphanTabId != null) {
chrome.tabs.remove(orphanTabId, () => {
if (chrome.runtime.lastError) {
console.warn(
'[Background] Orphaned usage tab already gone:',
chrome.runtime.lastError.message,
);
} else {
console.log(
'[Background] Cleaned up orphaned usage tab from previous SW life:',
orphanTabId,
);
}
});
await chrome.storage.session.remove(['activeUsageFetchTabId']);
}
})();
// 확장 프로그램 설치 또는 업데이트 시 초기 셋업
chrome.runtime.onInstalled.addListener(() => {
console.log('Gemini Extension installed or updated.');
// 기본 제미나이 DOM 셀렉터 규칙 초기화 (동적 변경 대비)
const defaultSelectors = {
inputAreaContainer: '.input-area-container, .textarea-container, div.input-area',
textarea: "div[contenteditable='true'], textarea#textarea, textarea",
sendButton:
"button.send-button-container, button[aria-label*='전송'], button[aria-label*='Send']",
chatStreamContainer:
'div.chat-history, .conversation-container, main div.chat-history, .chat-view',
messageBlock: 'message-content, .message-content-container, div.message-row, .message-content',
userPromptText: '.user-query, .query-text, div.user-query-container',
modelResponseText:
'.model-response, .response-container, div.model-response-container, .markdown',
sidebarContainer: 'nav, .left-sidebar-navigation, g-sidenav, .sidebar',
sidebarChatList:
'div.recent-chats-container, .recent-chats, nav.left-sidebar-navigation div.recent',
chatItemAnchor: "a[href*='/app/'], a[href*='/c/']",
};
chrome.storage.local.set({ selectors: defaultSelectors }, () => {
console.log('Default selectors initialized in chrome.storage.local');
});
// 초기 폴더 구조 셋업 (빈 배열로 초기화)
chrome.storage.sync.get(['folders'], (result) => {
if (!result.folders) {
chrome.storage.sync.set({ folders: [] }, () => {
console.log('Empty initial folders set.');
});
}
});
// 초기 사용량 데이터 세팅
const today = new Date().toISOString().split('T')[0];
chrome.storage.local.get(['usageData'], (result) => {
if (!result.usageData) {
chrome.storage.local.set({
usageData: {
currentDate: today,
dailyCount: 0,
weeklyCount: 0,
history: {},
},
});
}
});
// 15분 주기 사용량 백그라운드 수집 알람 등록 (새로고침/프롬프트 전송 시 즉시 갱신되므로 이건 최후의 안전망)
chrome.alarms.create('fetchUsageAlarm', { periodInMinutes: 15 });
console.log('fetchUsageAlarm registered.');
// 초기 시작 시 강제 1회 수집 시도
startBackgroundUsageFetch().catch((err) =>
console.warn('[Background] Initial fetch skipped:', err.message),
);
});
// 백그라운드 임시 탭 생명주기 관리 변수
let activeUsageFetchTabId = null;
let isFetchingUsage = false;
let fetchTimeoutTimer = null;
let activeUsageFetchCallback = null;
/**
* 임시 탭 자원 정리 및 닫기
*/
function cleanupFetchTab() {
if (fetchTimeoutTimer) {
clearTimeout(fetchTimeoutTimer);
fetchTimeoutTimer = null;
}
const tabId = activeUsageFetchTabId;
activeUsageFetchTabId = null;
chrome.storage.session.remove(['activeUsageFetchTabId']);
if (tabId !== null) {
chrome.tabs.remove(tabId, () => {
if (chrome.runtime.lastError) {
console.warn('[Background] tabs.remove failed:', chrome.runtime.lastError.message);
}
});
}
isFetchingUsage = false;
activeUsageFetchCallback = null;
}
/**
* 탭의 로드가 완료되면 직접 스크래핑을 하도록 지시하는 핸들러
*/
function handleTabUpdate(tabId, changeInfo, tab) {
if (tabId === activeUsageFetchTabId && changeInfo.status === 'complete') {
console.log(
'[Background] Temporary usage tab load complete. Sending scrape request to tab:',
tabId,
);
// 페이지 로드 완료 후 200ms 대기하여 스크립트 실행의 기회를 확보
setTimeout(() => {
if (activeUsageFetchTabId !== tabId) return;
chrome.tabs.sendMessage(tabId, { action: 'scrapeUsageDirectly' }, (response) => {
if (chrome.runtime.lastError) {
console.warn(
'[Background] Error sending scrape message to temp tab:',
chrome.runtime.lastError.message,
);
} else {
console.log('[Background] Tab scraping trigger response:', response);
}
});
}, 200);
}
}
// 탭 업데이트 수신기 등록
chrome.tabs.onUpdated.addListener(handleTabUpdate);
// 백그라운드 알람 수신기
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'fetchUsageAlarm') {
console.log('[Background] Alarm fired. Triggering background usage fetch...');
startBackgroundUsageFetch().catch((err) => console.error('Alarm fetch trigger failed:', err));
}
});
/**
* 백그라운드 비활성 탭(현재 창 안, active:false)을 열어 사용량을 정밀 파싱하고
* 자동 수거합니다.
* (별도 OS 창 대신 이 방식을 쓰는 이유: gemini.google.com은 X-Frame-Options: DENY라
* iframe/Offscreen Document로는 로드 자체가 불가능하다 — 콘텐츠 스크립트가 실제
* 페이지 DOM을 읽을 수 있어야 하므로 진짜 탭이 필요하다. 예전엔 최소화된 별도 창을
* 썼지만, state:'minimized'가 즉시 반영되지 않아 순간적으로 기존 창을 덮는 현상이
* 있었다 — active:false 백그라운드 탭은 새 OS 창 자체를 만들지 않으므로 이 문제가
* 구조적으로 없다. 탭 스트립에 1~2초 잠깐 탭이 나타나는 정도의 트레이드오프는 감수.)
*/
async function startBackgroundUsageFetch() {
if (isFetchingUsage) {
console.log('[Background] Usage fetch already in progress. Skipping.');
return { status: 'already_running' };
}
isFetchingUsage = true;
console.log('[Background] Starting background inactive-tab usage fetch...');
return new Promise((resolve, reject) => {
activeUsageFetchCallback = (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
};
// 브라우저 UI 언어가 한국어면 ko, 그 외에는 en으로 Gemini 사용량 페이지를 로드
// (parseUsageText가 두 언어 텍스트를 모두 파싱할 수 있게 되어 있음)
const uiLang =
(chrome.i18n && chrome.i18n.getUILanguage && chrome.i18n.getUILanguage()) || 'en';
const usagePageLang = uiLang.toLowerCase().startsWith('ko') ? 'ko' : 'en';
chrome.tabs.create(
{
url: `https://gemini.google.com/usage?hl=${usagePageLang}`,
active: false,
},
(tab) => {
if (chrome.runtime.lastError || !tab) {
isFetchingUsage = false;
activeUsageFetchCallback = null;
reject(
new Error(
chrome.runtime.lastError ? chrome.runtime.lastError.message : 'Failed to create tab',
),
);
return;
}
activeUsageFetchTabId = tab.id;
chrome.storage.session.set({ activeUsageFetchTabId: tab.id });
console.log(
'[Background] Temporary background tab created for usage fetch. tabId:',
tab.id,
);
fetchTimeoutTimer = setTimeout(() => {
console.warn('[Background] Scrape process timed out. Closing temporary tab...');
if (activeUsageFetchCallback) {
activeUsageFetchCallback(new Error('Scrape process timed out'));
}
cleanupFetchTab();
}, 15000);
},
);
});
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'updateSelectors') {
chrome.storage.local.set({ selectors: message.selectors }, () => {
sendResponse({ status: 'success', message: 'Selectors updated successfully.' });
});
return true;
}
if (message.action === 'getSelectors') {
chrome.storage.local.get(['selectors'], (result) => {
sendResponse({ selectors: result.selectors });
});
return true;
}
// 사용량 수집 완료/실패 처리 (임시 탭 내부 스크래핑 결과)
if (message.action === 'usageScraped') {
console.log('[Background] Usage scraped successfully.', message.data);
if (activeUsageFetchCallback) {
activeUsageFetchCallback(null, message.data);
}
cleanupFetchTab();
return false;
}
if (message.action === 'usageScrapeFailed') {
console.error('[Background] Usage scrape failed:', message.error);
if (activeUsageFetchCallback) {
activeUsageFetchCallback(new Error(message.error));
}
cleanupFetchTab();
return false;
}
// 온디맨드 수집 요청 (Popup / Floating Widget / Chat Send)
if (message.action === 'requestFetchUsage') {
console.log('[Background] On-demand usage fetch requested.');
startBackgroundUsageFetch()
.then((data) => {
sendResponse({ status: 'success', data: data });
})
.catch((err) => {
console.error('[Background] On-demand fetch failed:', err);
sendResponse({ status: 'error', error: err.message });
});
return true; // 비동기 응답 처리 유지
}
});