-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
328 lines (299 loc) · 13.4 KB
/
Copy pathscript.js
File metadata and controls
328 lines (299 loc) · 13.4 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const emailInput = document.getElementById('email-address');
const customPrefixInput = document.getElementById('custom-prefix');
const notification = document.getElementById('notification');
const notificationText = document.getElementById('notification-text');
const emailList = document.getElementById('email-list');
const systemStatus = document.getElementById('system-status');
const messageModal = document.getElementById('message-modal');
const modalFrom = document.getElementById('modal-from');
const modalSubject = document.getElementById('modal-subject');
const modalTime = document.getElementById('modal-time');
const modalBody = document.getElementById('modal-body');
const apiBase = 'https://sumitbuild.hemlatadevi198.workers.dev';
let inboxMessages = [];
function getBrandIcon(fromAddress) {
const fallbackStr = `
<div class="w-full h-full bg-gray-100 flex items-center justify-center text-gray-800">
<svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path>
<polyline points="22,6 12,13 2,6"></polyline>
</svg>
</div>`;
return `<div class="w-10 h-10 rounded-xl bg-gray-100 overflow-hidden flex items-center justify-center shrink-0 shadow-sm border border-gray-200">${fallbackStr}</div>`;
}
function showNotification(text) {
notificationText.innerText = text;
notification.classList.add('show');
setTimeout(() => {
notification.classList.remove('show');
}, 2500);
}
async function api(path, options = {}) {
const response = await fetch(`${apiBase}${path}`, {
headers: {
'Content-Type': 'application/json',
...(options.headers || {})
},
...options
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || 'Request failed');
}
return response.json();
}
function formatRelativeTime(dateString) {
const date = new Date(dateString);
const diffSec = Math.max(0, Math.floor((Date.now() - date.getTime()) / 1000));
if (diffSec < 60) return `${diffSec}s ago`;
const diffMin = Math.floor(diffSec / 60);
if (diffMin < 60) return `${diffMin}m ago`;
const diffHr = Math.floor(diffMin / 60);
if (diffHr < 24) return `${diffHr}h ago`;
const diffDay = Math.floor(diffHr / 24);
return `${diffDay}d ago`;
}
function escapeHtml(text = '') {
return text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
function renderInbox() {
if (!inboxMessages.length) {
emailList.innerHTML = `
<div class="py-32 flex flex-col items-center justify-center text-gray-400">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="mb-4 opacity-70"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline></svg>
<span class="text-[12px] font-black tracking-[0.2em] opacity-80 uppercase">No Messages Received</span>
</div>
`;
return;
}
emailList.innerHTML = inboxMessages.map((message) => {
return `
<div onclick="openMessage('${message.id}')" class="flex flex-col md:grid md:grid-cols-12 gap-2 md:gap-4 px-6 md:px-8 py-6 hover:bg-white/[0.02] cursor-pointer group transition-all">
<div class="md:col-span-4 flex items-center gap-4">
${getBrandIcon(message.rawAddress)}
<div class="flex flex-col min-w-0">
<span class="font-bold text-sm text-gray-900">${escapeHtml(message.sender)}</span>
<span class="text-[10px] text-gray-500 font-bold uppercase tracking-tight truncate">${escapeHtml(message.from)}</span>
</div>
<span class="md:hidden ml-auto text-[10px] text-gray-500 font-black">${escapeHtml(message.time)}</span>
</div>
<div class="md:col-span-8 flex justify-between items-start mt-2 md:mt-0 min-w-0">
<div class="flex flex-col pr-4 min-w-0 flex-1">
<span class="font-bold text-sm text-gray-700 mb-0.5 truncate">${escapeHtml(message.subject)}</span>
<span class="text-xs text-gray-500 line-clamp-1 md:line-clamp-2 leading-relaxed break-all">${escapeHtml(message.snippet)}</span>
</div>
<div class="hidden md:flex items-center gap-4 shrink-0 pt-1">
<span class="text-[10px] text-gray-500 font-black whitespace-nowrap shrink-0">${escapeHtml(message.time)}</span>
<svg class="text-gray-400 group-hover:text-gray-900 transition-colors shrink-0" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
<polyline points="9 18 15 12 9 6"></polyline>
</svg>
</div>
</div>
</div>
`;
}).join('');
}
function copyEmail() {
emailInput.select();
emailInput.setSelectionRange(0, 99999);
try {
const tempInput = document.createElement('input');
tempInput.value = emailInput.value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
showNotification('Address Copied!');
} catch (err) {
console.error('Failed to copy', err);
}
}
async function refreshEmail() {
await refreshInbox();
}
async function ensureAccount() {
try {
const localSession = localStorage.getItem('tempmail_session');
if (localSession) {
const state = JSON.parse(localSession);
const ageMs = Date.now() - new Date(state.createdAt).getTime();
if (ageMs > 24 * 60 * 60 * 1000) {
await api('/api/messages/purge', { method: 'POST', body: JSON.stringify({ address: state.address }) }).catch(() => {});
localStorage.removeItem('tempmail_session');
} else {
emailInput.value = state.address;
systemStatus.innerText = 'System Online';
return state;
}
}
const created = await api('/api/account/new', { method: 'POST', body: JSON.stringify({}) });
localStorage.setItem('tempmail_session', JSON.stringify(created));
emailInput.value = created.address;
systemStatus.innerText = 'System Online';
showNotification('Mailbox Ready');
return created;
} catch (error) {
const created = await api('/api/account/new', { method: 'POST', body: JSON.stringify({}) });
emailInput.value = created.address;
systemStatus.innerText = 'System Online';
return created;
}
}
async function newEmail() {
try {
await api('/api/messages/purge', { method: 'POST', body: JSON.stringify({ address: emailInput.value }) }).catch(() => {});
const created = await api('/api/account/new', { method: 'POST', body: JSON.stringify({}) });
localStorage.setItem('tempmail_session', JSON.stringify(created));
emailInput.value = created.address;
inboxMessages = [];
renderInbox();
showNotification('New Address Active');
} catch (error) {
showNotification('Unable to create mailbox');
}
}
async function setCustomEmail() {
const prefix = customPrefixInput.value.trim().toLowerCase().replace(/[^a-z0-9]/g, '');
if (prefix.length < 3) {
showNotification('Handle too short.');
return;
}
try {
await api('/api/messages/purge', { method: 'POST', body: JSON.stringify({ address: emailInput.value }) }).catch(() => {});
const created = await api('/api/account/custom', {
method: 'POST',
body: JSON.stringify({ prefix })
});
localStorage.setItem('tempmail_session', JSON.stringify(created));
emailInput.value = created.address;
customPrefixInput.value = '';
inboxMessages = [];
renderInbox();
showNotification('Identity Updated');
} catch (error) {
showNotification('Alias unavailable');
}
}
async function refreshInbox() {
try {
const targetAddress = encodeURIComponent(emailInput.value);
showNotification('Syncing Inbox...');
const payload = await api('/api/messages?address=' + targetAddress);
inboxMessages = payload.messages.map((message) => {
const senderName = message.from?.name || message.from?.address || 'Unknown Sender';
const fromAddress = message.from?.address ? `@${message.from.address.split('@').pop()}` : '@unknown';
const snippet = (message.intro || '').trim() || 'Open to read full message.';
const rawAddr = message.from?.address || '';
return {
id: message.id,
sender: senderName,
from: fromAddress,
rawAddress: rawAddr,
subject: message.subject || 'No Subject',
snippet,
rawText: message.text || '',
rawHtml: message.html || '',
time: formatRelativeTime(message.createdAt || new Date().toISOString()),
createdAt: message.createdAt || new Date().toISOString()
};
});
renderInbox();
} catch (error) {
console.error(error);
showNotification('Sync failed: ' + error.message);
}
}
function openMessage(messageId) {
try {
const detail = inboxMessages.find((m) => m.id === messageId);
if (!detail) {
showNotification('Message missing locally, refresh inbox');
return;
}
modalFrom.innerText = detail.sender;
modalSubject.innerText = detail.subject || 'No Subject';
modalTime.innerText = detail.time;
const rawHtml = detail.rawHtml || '';
const rawText = detail.rawText || '';
modalBody.innerHTML = '';
if (rawHtml.trim()) {
const iframe = document.createElement('iframe');
iframe.style.width = '100%';
iframe.style.height = '70vh';
iframe.style.border = 'none';
iframe.style.display = 'block';
modalBody.appendChild(iframe);
iframe.srcdoc = rawHtml;
} else {
const div = document.createElement('div');
div.className = 'p-8 text-base text-gray-800 leading-relaxed whitespace-pre-wrap font-sans';
div.innerText = rawText.trim() || 'No message body available.';
modalBody.appendChild(div);
}
const smartBtn = document.getElementById('modal-smart-btn');
smartBtn.classList.add('hidden');
smartBtn.onclick = null;
const fallbackTextForLinks = rawText || rawHtml;
const linkMatch = fallbackTextForLinks.match(/https?:\/\/[^\s"'>]+/);
const codeMatch = fallbackTextForLinks.match(/\b(\d{4,8})\b/);
if (linkMatch) {
smartBtn.classList.remove('hidden');
smartBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="inline w-3 h-3 mr-1 -mt-0.5"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg> OPEN LINK`;
smartBtn.onclick = () => window.open(linkMatch[0], '_blank');
} else if (codeMatch && codeMatch[1].length > 3) {
smartBtn.classList.remove('hidden');
smartBtn.innerHTML = `COPY CODE: <span class="bg-blue-500/20 px-1 py-0.5 rounded ml-1 text-blue-300">${codeMatch[1]}</span>`;
smartBtn.onclick = () => {
navigator.clipboard.writeText(codeMatch[1]);
smartBtn.innerHTML = 'COPIED!';
};
}
messageModal.classList.remove('hidden');
messageModal.classList.add('flex');
setTimeout(() => messageModal.classList.remove('opacity-0'), 10);
} catch (error) {
showNotification('Unable to open message');
}
}
function closeMessageModal() {
messageModal.classList.add('opacity-0');
setTimeout(() => {
messageModal.classList.remove('flex');
messageModal.classList.add('hidden');
}, 300);
}
function onModalBackdrop(event) {
if (event.target === messageModal) {
closeMessageModal();
}
}
async function deleteAll() {
try {
await api('/api/messages/purge', { method: 'POST', body: JSON.stringify({ address: emailInput.value }) });
inboxMessages = [];
renderInbox();
showNotification('Inbox Purged');
} catch (error) {
showNotification('Unable to purge inbox');
}
}
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closeMessageModal();
}
});
(async () => {
try {
await ensureAccount();
await refreshInbox();
} catch (error) {
systemStatus.innerText = 'Backend Offline';
showNotification('Start local backend first');
renderInbox();
}
})();