rapid interations of server side app and firefox extension

This commit is contained in:
Bryan Van Deusen
2026-01-24 22:52:51 -05:00
commit b9b8048a2d
81 changed files with 9675 additions and 0 deletions
+215
View File
@@ -0,0 +1,215 @@
/**
* Background script - handles cookie operations and API calls
*/
// Initialize API on startup
browser.runtime.onInstalled.addListener(async () => {
console.log('GallerySubscriber extension installed');
await api.init();
});
browser.runtime.onStartup.addListener(async () => {
await api.init();
});
// Handle messages from popup and options pages
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
handleMessage(message)
.then(sendResponse)
.catch(error => {
console.error('Message handler error:', error);
sendResponse({ error: error.message });
});
return true; // Keep channel open for async response
});
/**
* Route messages to appropriate handlers
* @param {object} message - Message object with type property
* @returns {Promise<object>} - Response data
*/
async function handleMessage(message) {
switch (message.type) {
case 'EXPORT_COOKIES':
return await exportCookies(message.platform);
case 'EXPORT_ALL_COOKIES':
return await exportAllCookies();
case 'GET_PLATFORM_STATUS':
return await getPlatformStatus();
case 'TEST_CONNECTION':
return await testConnection();
case 'GET_CONFIG':
return await getConfig();
case 'SAVE_CONFIG':
return await saveConfig(message.config);
default:
throw new Error(`Unknown message type: ${message.type}`);
}
}
/**
* Export cookies for a single platform to the backend
* @param {string} platformKey - Platform identifier
* @returns {Promise<object>} - Result object
*/
async function exportCookies(platformKey) {
await api.init();
const platform = PLATFORMS[platformKey];
if (!platform) {
throw new Error(`Unknown platform: ${platformKey}`);
}
let credentialData;
let credentialType;
if (platform.authType === 'token') {
// Discord and other token-based platforms require manual entry
throw new Error(`${platform.name} requires manual token entry in the web UI. Token extraction is not supported for security reasons.`);
}
// Cookie-based auth
const cookies = await extractCookiesForPlatform(platformKey);
if (cookies.length === 0) {
throw new Error(`No cookies found for ${platform.name}. Please ensure you are logged in.`);
}
credentialData = toNetscapeFormat(cookies);
credentialType = 'cookies';
// Send to backend
const result = await api.uploadCredentials(platformKey, credentialType, credentialData);
return {
success: true,
platform: platformKey,
cookieCount: cookies.length,
message: result.message || 'Credentials exported successfully'
};
}
/**
* Export cookies for all cookie-based platforms
* @returns {Promise<object>} - Results for each platform
*/
async function exportAllCookies() {
await api.init();
const results = {};
const platforms = Object.keys(PLATFORMS);
for (const platformKey of platforms) {
const platform = PLATFORMS[platformKey];
// Skip token-based platforms
if (platform.authType === 'token') {
results[platformKey] = {
success: false,
platform: platformKey,
skipped: true,
message: 'Token-based auth requires manual entry'
};
continue;
}
try {
results[platformKey] = await exportCookies(platformKey);
} catch (error) {
results[platformKey] = {
success: false,
platform: platformKey,
error: error.message
};
}
}
return results;
}
/**
* Get status information for all platforms
* @returns {Promise<object>} - Status for each platform
*/
async function getPlatformStatus() {
const status = {};
for (const [key, platform] of Object.entries(PLATFORMS)) {
try {
if (platform.authType === 'token') {
// Token-based platforms
status[key] = {
name: platform.name,
authType: 'token',
hasCookies: false,
cookieCount: 0,
note: platform.note || 'Requires manual token entry'
};
} else {
// Cookie-based platforms
const cookies = await extractCookiesForPlatform(key);
status[key] = {
name: platform.name,
authType: 'cookies',
hasCookies: cookies.length > 0,
cookieCount: cookies.length
};
}
} catch (error) {
status[key] = {
name: platform.name,
authType: platform.authType,
hasCookies: false,
cookieCount: 0,
error: error.message
};
}
}
return status;
}
/**
* Test connection to the backend
* @returns {Promise<object>} - Connection status
*/
async function testConnection() {
await api.init();
if (!api.isConfigured()) {
return { connected: false, error: 'Not configured' };
}
try {
await api.testConnection();
return { connected: true };
} catch (error) {
return { connected: false, error: error.message };
}
}
/**
* Get current configuration
* @returns {Promise<object>} - Config object
*/
async function getConfig() {
const config = await browser.storage.local.get(['apiUrl', 'apiKey']);
return config;
}
/**
* Save configuration
* @param {object} config - Config object with apiUrl and apiKey
* @returns {Promise<object>} - Success status
*/
async function saveConfig(config) {
await browser.storage.local.set(config);
await api.init();
return { success: true };
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""
Create minimal placeholder PNG icons using only standard library.
These are simple solid-color squares that Firefox will accept.
"""
import struct
import zlib
from pathlib import Path
def create_png(width, height, rgb_color):
"""Create a minimal PNG file with a solid color."""
r, g, b = rgb_color
def png_chunk(chunk_type, data):
"""Create a PNG chunk with CRC."""
chunk = chunk_type + data
crc = zlib.crc32(chunk) & 0xffffffff
return struct.pack('>I', len(data)) + chunk + struct.pack('>I', crc)
# PNG signature
signature = b'\x89PNG\r\n\x1a\n'
# IHDR chunk (image header)
ihdr_data = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
ihdr = png_chunk(b'IHDR', ihdr_data)
# IDAT chunk (image data)
# Create raw pixel data: each row starts with filter byte 0, then RGB pixels
raw_data = b''
for y in range(height):
raw_data += b'\x00' # Filter byte (none)
for x in range(width):
raw_data += bytes([r, g, b])
compressed = zlib.compress(raw_data, 9)
idat = png_chunk(b'IDAT', compressed)
# IEND chunk
iend = png_chunk(b'IEND', b'')
return signature + ihdr + idat + iend
def main():
icons_dir = Path(__file__).parent / 'icons'
icons_dir.mkdir(exist_ok=True)
# Primary blue color (#1976d2)
color = (25, 118, 210)
sizes = [16, 32, 48, 128]
for size in sizes:
png_data = create_png(size, size, color)
output_path = icons_dir / f'icon-{size}.png'
with open(output_path, 'wb') as f:
f.write(png_data)
print(f'Created {output_path} ({len(png_data)} bytes)')
print('\nPlaceholder icons created!')
print('Replace with custom icons for a better look.')
if __name__ == '__main__':
main()
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""
Generate placeholder icons for the GallerySubscriber extension.
Run this script from the extension directory.
Requirements: Pillow (pip install Pillow)
"""
import os
from pathlib import Path
try:
from PIL import Image, ImageDraw
except ImportError:
print("Pillow not installed. Install with: pip install Pillow")
print("Or manually create icon-16.png, icon-32.png, icon-48.png, icon-128.png")
exit(1)
# Icon configuration
BACKGROUND_COLOR = '#1976d2' # Primary blue
SIZES = [16, 32, 48, 128]
def create_icon(size):
"""Create a simple colored square icon with rounded corners effect."""
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Draw filled rounded rectangle (approximated with circle corners for small sizes)
margin = max(1, size // 16)
radius = max(2, size // 8)
# For simplicity, just draw a solid square with the primary color
draw.rectangle([margin, margin, size - margin - 1, size - margin - 1],
fill=BACKGROUND_COLOR)
# Draw a simple "G" or download arrow for larger sizes
if size >= 32:
# Draw a simple download arrow
center_x = size // 2
center_y = size // 2
arrow_size = size // 3
# Arrow body (vertical line)
line_width = max(2, size // 12)
draw.rectangle([
center_x - line_width // 2,
center_y - arrow_size // 2,
center_x + line_width // 2,
center_y + arrow_size // 4
], fill='white')
# Arrow head (triangle pointing down)
head_size = arrow_size // 2
draw.polygon([
(center_x - head_size, center_y),
(center_x + head_size, center_y),
(center_x, center_y + head_size)
], fill='white')
# Base line
draw.rectangle([
center_x - arrow_size // 2,
center_y + arrow_size // 2,
center_x + arrow_size // 2,
center_y + arrow_size // 2 + line_width
], fill='white')
return img
def main():
icons_dir = Path(__file__).parent / 'icons'
icons_dir.mkdir(exist_ok=True)
for size in SIZES:
icon = create_icon(size)
output_path = icons_dir / f'icon-{size}.png'
icon.save(output_path, 'PNG')
print(f'Created {output_path}')
print('\nDone! Icons created successfully.')
print('You can replace these with custom icons later.')
if __name__ == '__main__':
main()
+40
View File
@@ -0,0 +1,40 @@
# Extension Icons
This directory should contain PNG icons for the extension in the following sizes:
- icon-16.png (16x16 pixels)
- icon-32.png (32x32 pixels)
- icon-48.png (48x48 pixels)
- icon-128.png (128x128 pixels)
## Quick Setup
You can generate placeholder icons using any image editor or online tool.
The icons should ideally be a simple "GS" logo or download icon.
## Recommended Design
- Background: #1976d2 (primary blue)
- Foreground: White
- Style: Simple, recognizable at small sizes
- Consider a download arrow or gallery grid icon
## Generate with ImageMagick
If you have ImageMagick installed:
```bash
# Create a simple colored square as placeholder
for size in 16 32 48 128; do
convert -size ${size}x${size} xc:#1976d2 icon-${size}.png
done
```
## Generate with Python/Pillow
```python
from PIL import Image, ImageDraw
for size in [16, 32, 48, 128]:
img = Image.new('RGB', (size, size), '#1976d2')
img.save(f'icon-{size}.png')
```
Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 B

+51
View File
@@ -0,0 +1,51 @@
{
"manifest_version": 2,
"name": "GallerySubscriber",
"version": "1.0.0",
"description": "Export cookies from supported platforms to GallerySubscriber for automated downloads",
"permissions": [
"cookies",
"storage",
"tabs",
"activeTab",
"*://*.patreon.com/*",
"*://*.subscribestar.com/*",
"*://*.subscribestar.adult/*",
"*://*.hentai-foundry.com/*",
"*://*.discord.com/*"
],
"browser_action": {
"default_popup": "popup/popup.html",
"default_icon": {
"16": "icons/icon-16.png",
"32": "icons/icon-32.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
},
"default_title": "GallerySubscriber"
},
"background": {
"scripts": [
"lib/platforms.js",
"lib/cookies.js",
"lib/api.js",
"background/background.js"
],
"persistent": false
},
"options_ui": {
"page": "options/options.html",
"browser_style": true
},
"icons": {
"16": "icons/icon-16.png",
"32": "icons/icon-32.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
}
}
+287
View File
@@ -0,0 +1,287 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GallerySubscriber Settings</title>
<style>
:root {
--primary-color: #1976d2;
--success-color: #4caf50;
--error-color: #f44336;
--bg-color: #f5f5f5;
--card-bg: #ffffff;
--text-color: #212121;
--text-secondary: #757575;
--border-color: #e0e0e0;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
color: var(--text-color);
background: var(--bg-color);
padding: 24px;
min-height: 100vh;
}
.container {
max-width: 600px;
margin: 0 auto;
}
h1 {
font-size: 24px;
font-weight: 500;
margin-bottom: 24px;
color: var(--text-color);
}
.card {
background: var(--card-bg);
border-radius: 8px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.card h2 {
font-size: 16px;
font-weight: 600;
margin-bottom: 16px;
color: var(--text-color);
}
.form-group {
margin-bottom: 16px;
}
.form-group:last-child {
margin-bottom: 0;
}
label {
display: block;
font-weight: 500;
margin-bottom: 6px;
color: var(--text-color);
}
input[type="text"],
input[type="url"],
input[type="password"] {
width: 100%;
padding: 10px 12px;
border: 1px solid var(--border-color);
border-radius: 6px;
font-size: 14px;
transition: border-color 0.15s;
}
input:focus {
outline: none;
border-color: var(--primary-color);
}
.help-text {
font-size: 12px;
color: var(--text-secondary);
margin-top: 4px;
}
.input-with-button {
display: flex;
gap: 8px;
}
.input-with-button input {
flex: 1;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s ease;
}
.btn-primary {
background: var(--primary-color);
color: white;
}
.btn-primary:hover {
background: #1565c0;
}
.btn-secondary {
background: #f5f5f5;
color: var(--text-color);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background: #eeeeee;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-small {
padding: 8px 12px;
font-size: 13px;
}
.actions {
display: flex;
gap: 12px;
align-items: center;
margin-top: 20px;
}
.result {
font-size: 13px;
padding: 4px 8px;
border-radius: 4px;
}
.result.success {
background: #e8f5e9;
color: #2e7d32;
}
.result.error {
background: #ffebee;
color: #c62828;
}
.connection-test {
display: flex;
align-items: center;
gap: 12px;
margin-top: 12px;
}
.status-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #9e9e9e;
}
.status-dot.connected {
background: var(--success-color);
}
.status-dot.error {
background: var(--error-color);
}
.instructions {
background: #e3f2fd;
border-radius: 6px;
padding: 16px;
margin-bottom: 16px;
}
.instructions h3 {
font-size: 14px;
font-weight: 600;
margin-bottom: 8px;
color: #1565c0;
}
.instructions ol {
margin-left: 20px;
font-size: 13px;
color: var(--text-color);
}
.instructions li {
margin-bottom: 4px;
}
.instructions code {
background: rgba(0,0,0,0.08);
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div class="container">
<h1>GallerySubscriber Extension Settings</h1>
<div class="instructions">
<h3>Setup Instructions</h3>
<ol>
<li>Open your GallerySubscriber web interface</li>
<li>Go to <strong>Settings</strong> page</li>
<li>Copy the <strong>Extension API Key</strong></li>
<li>Paste the API URL and key below</li>
</ol>
</div>
<div class="card">
<h2>Backend Connection</h2>
<div class="form-group">
<label for="api-url">API URL</label>
<input
type="url"
id="api-url"
placeholder="http://localhost:8080/api"
>
<p class="help-text">
The URL of your GallerySubscriber backend. Include <code>/api</code> at the end.
</p>
</div>
<div class="form-group">
<label for="api-key">Extension API Key</label>
<div class="input-with-button">
<input
type="password"
id="api-key"
placeholder="Your API key from Settings page"
>
<button type="button" id="toggle-key-btn" class="btn btn-secondary btn-small">
Show
</button>
</div>
<p class="help-text">
Find this in GallerySubscriber: Settings > Extension API Key
</p>
</div>
<div class="connection-test">
<button id="test-btn" class="btn btn-secondary btn-small">Test Connection</button>
<span id="test-status" class="status-dot"></span>
<span id="test-message"></span>
</div>
</div>
<div class="actions">
<button id="save-btn" class="btn btn-primary">Save Settings</button>
<span id="save-result" class="result"></span>
</div>
</div>
<script src="options.js"></script>
</body>
</html>
+183
View File
@@ -0,0 +1,183 @@
/**
* Options page script
*/
document.addEventListener('DOMContentLoaded', async () => {
await loadSettings();
setupEventListeners();
});
/**
* Load saved settings into form
*/
async function loadSettings() {
const config = await browser.storage.local.get(['apiUrl', 'apiKey']);
document.getElementById('api-url').value = config.apiUrl || '';
document.getElementById('api-key').value = config.apiKey || '';
}
/**
* Setup event listeners
*/
function setupEventListeners() {
// Toggle API key visibility
const toggleBtn = document.getElementById('toggle-key-btn');
const apiKeyInput = document.getElementById('api-key');
toggleBtn.addEventListener('click', () => {
if (apiKeyInput.type === 'password') {
apiKeyInput.type = 'text';
toggleBtn.textContent = 'Hide';
} else {
apiKeyInput.type = 'password';
toggleBtn.textContent = 'Show';
}
});
// Test connection
document.getElementById('test-btn').addEventListener('click', testConnection);
// Save settings
document.getElementById('save-btn').addEventListener('click', saveSettings);
// Auto-save on enter key
document.getElementById('api-url').addEventListener('keypress', (e) => {
if (e.key === 'Enter') saveSettings();
});
document.getElementById('api-key').addEventListener('keypress', (e) => {
if (e.key === 'Enter') saveSettings();
});
}
/**
* Test connection to backend
*/
async function testConnection() {
const testBtn = document.getElementById('test-btn');
const statusDot = document.getElementById('test-status');
const testMessage = document.getElementById('test-message');
testBtn.disabled = true;
testBtn.textContent = 'Testing...';
statusDot.className = 'status-dot';
testMessage.textContent = '';
// Get current values
const apiUrl = normalizeApiUrl(document.getElementById('api-url').value.trim());
const apiKey = document.getElementById('api-key').value.trim();
if (!apiUrl || !apiKey) {
statusDot.className = 'status-dot error';
testMessage.textContent = 'Please fill in both fields';
testBtn.disabled = false;
testBtn.textContent = 'Test Connection';
return;
}
// Temporarily save for testing
await browser.storage.local.set({ apiUrl, apiKey });
try {
const result = await browser.runtime.sendMessage({ type: 'TEST_CONNECTION' });
if (result.connected) {
statusDot.className = 'status-dot connected';
testMessage.textContent = 'Connected successfully!';
} else {
statusDot.className = 'status-dot error';
testMessage.textContent = result.error || 'Connection failed';
}
} catch (error) {
statusDot.className = 'status-dot error';
testMessage.textContent = error.message;
} finally {
testBtn.disabled = false;
testBtn.textContent = 'Test Connection';
}
}
/**
* Save settings
*/
async function saveSettings() {
const saveBtn = document.getElementById('save-btn');
const saveResult = document.getElementById('save-result');
saveBtn.disabled = true;
saveResult.textContent = '';
saveResult.className = 'result';
let apiUrl = document.getElementById('api-url').value.trim();
const apiKey = document.getElementById('api-key').value.trim();
// Validate
if (!apiUrl) {
showSaveResult('API URL is required', 'error');
saveBtn.disabled = false;
return;
}
if (!apiKey) {
showSaveResult('API Key is required', 'error');
saveBtn.disabled = false;
return;
}
// Normalize URL
apiUrl = normalizeApiUrl(apiUrl);
document.getElementById('api-url').value = apiUrl;
// Save
try {
await browser.storage.local.set({ apiUrl, apiKey });
await browser.runtime.sendMessage({
type: 'SAVE_CONFIG',
config: { apiUrl, apiKey }
});
showSaveResult('Settings saved!', 'success');
} catch (error) {
showSaveResult(`Failed to save: ${error.message}`, 'error');
} finally {
saveBtn.disabled = false;
}
}
/**
* Normalize API URL to ensure it ends with /api
* @param {string} url - Input URL
* @returns {string} - Normalized URL
*/
function normalizeApiUrl(url) {
if (!url) return '';
// Remove trailing slash
url = url.replace(/\/+$/, '');
// Ensure it ends with /api
if (!url.endsWith('/api')) {
url = url + '/api';
}
return url;
}
/**
* Show save result message
* @param {string} message - Message to display
* @param {string} type - 'success' or 'error'
*/
function showSaveResult(message, type) {
const saveResult = document.getElementById('save-result');
saveResult.textContent = message;
saveResult.className = `result ${type}`;
// Auto-hide success messages
if (type === 'success') {
setTimeout(() => {
saveResult.textContent = '';
saveResult.className = 'result';
}, 3000);
}
}
+282
View File
@@ -0,0 +1,282 @@
:root {
--primary-color: #1976d2;
--success-color: #4caf50;
--warning-color: #ff9800;
--error-color: #f44336;
--bg-color: #ffffff;
--text-color: #212121;
--text-secondary: #757575;
--border-color: #e0e0e0;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
color: var(--text-color);
background: var(--bg-color);
min-width: 320px;
max-width: 400px;
}
.popup-container {
padding: 12px;
}
.header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 1px solid var(--border-color);
}
.header h1 {
font-size: 16px;
font-weight: 600;
flex: 1;
}
.logo {
width: 24px;
height: 24px;
}
.status-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--error-color);
cursor: help;
}
.status-indicator.connected {
background: var(--success-color);
}
.section {
margin-bottom: 16px;
}
.section h2 {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
color: var(--text-secondary);
margin-bottom: 8px;
letter-spacing: 0.5px;
}
.platforms-grid {
display: grid;
gap: 8px;
}
.platform-card {
display: flex;
align-items: center;
padding: 10px 12px;
border: 1px solid var(--border-color);
border-radius: 6px;
cursor: pointer;
transition: all 0.15s ease;
background: var(--bg-color);
}
.platform-card:hover:not(.disabled) {
border-color: var(--primary-color);
background: #f5f9ff;
}
.platform-card.disabled {
opacity: 0.6;
cursor: not-allowed;
}
.platform-card .platform-icon {
width: 32px;
height: 32px;
border-radius: 6px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 10px;
color: white;
font-weight: bold;
font-size: 14px;
}
.platform-card .info {
flex: 1;
min-width: 0;
}
.platform-card .name {
font-weight: 500;
font-size: 14px;
}
.platform-card .status {
font-size: 12px;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.platform-card .status.ready {
color: var(--success-color);
}
.platform-card .status.no-cookies {
color: var(--warning-color);
}
.platform-card .status.error {
color: var(--error-color);
}
.platform-card .action-icon {
width: 20px;
height: 20px;
opacity: 0.5;
flex-shrink: 0;
}
.platform-card.loading .action-icon {
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 10px 16px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s ease;
}
.btn-primary {
background: var(--primary-color);
color: white;
}
.btn-primary:hover {
background: #1565c0;
}
.btn-secondary {
background: #f5f5f5;
color: var(--text-color);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background: #eeeeee;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-icon {
background: none;
border: none;
padding: 6px;
cursor: pointer;
border-radius: 4px;
color: var(--text-secondary);
transition: background 0.15s ease;
}
.btn-icon:hover {
background: #f5f5f5;
color: var(--text-color);
}
.full-width {
width: 100%;
}
.mt-2 {
margin-top: 8px;
}
.alert {
padding: 12px;
border-radius: 6px;
margin-bottom: 12px;
}
.alert strong {
display: block;
margin-bottom: 4px;
}
.alert p {
font-size: 13px;
margin: 0;
}
.alert-warning {
background: #fff8e1;
border: 1px solid #ffcc02;
color: #795548;
}
.status-message {
padding: 10px 12px;
border-radius: 6px;
margin-bottom: 12px;
font-size: 13px;
}
.status-message.success {
background: #e8f5e9;
color: #2e7d32;
border: 1px solid #a5d6a7;
}
.status-message.error {
background: #ffebee;
color: #c62828;
border: 1px solid #ef9a9a;
}
.status-message.warning {
background: #fff8e1;
color: #795548;
border: 1px solid #ffcc02;
}
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 12px;
border-top: 1px solid var(--border-color);
}
.version {
font-size: 11px;
color: #9e9e9e;
}
.hidden {
display: none !important;
}
+56
View File
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div class="popup-container">
<header class="header">
<img src="../icons/icon-32.png" alt="GallerySubscriber" class="logo">
<h1>GallerySubscriber</h1>
<span id="connection-status" class="status-indicator" title="Disconnected"></span>
</header>
<!-- Not Configured State -->
<div id="setup-required" class="section hidden">
<div class="alert alert-warning">
<strong>Setup Required</strong>
<p>Please configure your API URL and key in settings.</p>
</div>
<button id="open-settings-btn" class="btn btn-primary full-width">
Open Settings
</button>
</div>
<!-- Main Content -->
<div id="main-content" class="hidden">
<!-- Cookie Export Section -->
<section class="section">
<h2>Export Cookies</h2>
<div id="platforms-list" class="platforms-grid">
<!-- Populated by JavaScript -->
</div>
<button id="export-all-btn" class="btn btn-secondary full-width mt-2">
Export All Platforms
</button>
</section>
<!-- Status Messages -->
<div id="status-message" class="status-message hidden"></div>
</div>
<footer class="footer">
<button id="settings-btn" class="btn-icon" title="Settings">
<svg width="20" height="20" viewBox="0 0 24 24">
<path fill="currentColor" d="M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z"/>
</svg>
</button>
<span class="version">v1.0.0</span>
</footer>
</div>
<script src="../lib/platforms.js"></script>
<script src="popup.js"></script>
</body>
</html>
+272
View File
@@ -0,0 +1,272 @@
/**
* Popup script - handles UI interactions
*/
document.addEventListener('DOMContentLoaded', async () => {
await init();
});
/**
* Initialize the popup
*/
async function init() {
// Check configuration
const config = await browser.runtime.sendMessage({ type: 'GET_CONFIG' });
if (!config.apiUrl || !config.apiKey) {
showSetupRequired();
return;
}
// Test connection
const connectionStatus = await browser.runtime.sendMessage({ type: 'TEST_CONNECTION' });
updateConnectionIndicator(connectionStatus.connected);
// Show main content
document.getElementById('setup-required').classList.add('hidden');
document.getElementById('main-content').classList.remove('hidden');
if (!connectionStatus.connected) {
showError(`Cannot connect to backend: ${connectionStatus.error}`);
}
// Load platform status
await loadPlatformStatus();
// Setup event listeners
setupEventListeners();
}
/**
* Show the setup required message
*/
function showSetupRequired() {
document.getElementById('setup-required').classList.remove('hidden');
document.getElementById('main-content').classList.add('hidden');
document.getElementById('open-settings-btn').addEventListener('click', () => {
browser.runtime.openOptionsPage();
});
}
/**
* Update the connection status indicator
* @param {boolean} connected - Whether connected to backend
*/
function updateConnectionIndicator(connected) {
const indicator = document.getElementById('connection-status');
indicator.classList.toggle('connected', connected);
indicator.title = connected ? 'Connected to GallerySubscriber' : 'Disconnected';
}
/**
* Load and display platform status
*/
async function loadPlatformStatus() {
const status = await browser.runtime.sendMessage({ type: 'GET_PLATFORM_STATUS' });
const container = document.getElementById('platforms-list');
container.innerHTML = '';
for (const [key, platform] of Object.entries(PLATFORMS)) {
const platformStatus = status[key] || {};
const card = createPlatformCard(key, platform, platformStatus);
container.appendChild(card);
}
}
/**
* Create a platform card element
* @param {string} key - Platform key
* @param {object} platform - Platform definition
* @param {object} status - Platform status
* @returns {HTMLElement}
*/
function createPlatformCard(key, platform, status) {
const card = document.createElement('div');
card.className = 'platform-card';
card.dataset.platform = key;
const isDisabled = platform.authType === 'token';
if (isDisabled) {
card.classList.add('disabled');
}
const statusText = getStatusText(status, platform);
const statusClass = getStatusClass(status, platform);
card.innerHTML = `
<div class="platform-icon" style="background-color: ${platform.color}">
${platform.name.charAt(0)}
</div>
<div class="info">
<div class="name">${platform.name}</div>
<div class="status ${statusClass}">${statusText}</div>
</div>
<span class="action-icon">
<svg width="20" height="20" viewBox="0 0 24 24">
<path fill="currentColor" d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"/>
</svg>
</span>
`;
if (!isDisabled) {
card.addEventListener('click', () => exportPlatformCookies(key, card));
}
return card;
}
/**
* Get status text for display
* @param {object} status - Platform status
* @param {object} platform - Platform definition
* @returns {string}
*/
function getStatusText(status, platform) {
if (platform.authType === 'token') {
return 'Manual token entry required';
}
if (status.error) {
return 'Error checking cookies';
}
if (!status.hasCookies || status.cookieCount === 0) {
return 'No cookies found - log in first';
}
return `${status.cookieCount} cookies ready`;
}
/**
* Get status CSS class
* @param {object} status - Platform status
* @param {object} platform - Platform definition
* @returns {string}
*/
function getStatusClass(status, platform) {
if (platform.authType === 'token') {
return 'no-cookies';
}
if (status.error) {
return 'error';
}
if (!status.hasCookies || status.cookieCount === 0) {
return 'no-cookies';
}
return 'ready';
}
/**
* Export cookies for a single platform
* @param {string} platformKey - Platform key
* @param {HTMLElement} cardElement - The card element
*/
async function exportPlatformCookies(platformKey, cardElement) {
cardElement.classList.add('loading');
hideStatusMessage();
try {
const result = await browser.runtime.sendMessage({
type: 'EXPORT_COOKIES',
platform: platformKey
});
if (result.error) {
showError(result.error);
} else {
showSuccess(`${PLATFORMS[platformKey].name}: ${result.cookieCount} cookies exported!`);
// Refresh status
await loadPlatformStatus();
}
} catch (error) {
showError(error.message);
} finally {
cardElement.classList.remove('loading');
}
}
/**
* Export cookies for all platforms
*/
async function exportAllCookies() {
const btn = document.getElementById('export-all-btn');
btn.disabled = true;
btn.textContent = 'Exporting...';
hideStatusMessage();
try {
const results = await browser.runtime.sendMessage({ type: 'EXPORT_ALL_COOKIES' });
const successes = Object.values(results).filter(r => r.success).length;
const skipped = Object.values(results).filter(r => r.skipped).length;
const failures = Object.values(results).filter(r => !r.success && !r.skipped).length;
if (failures === 0 && successes > 0) {
showSuccess(`Exported ${successes} platform(s) successfully!`);
} else if (successes > 0) {
showWarning(`${successes} succeeded, ${failures} failed`);
} else if (failures > 0) {
showError('All exports failed. Are you logged in?');
} else {
showWarning('No platforms to export');
}
await loadPlatformStatus();
} catch (error) {
showError(error.message);
} finally {
btn.disabled = false;
btn.textContent = 'Export All Platforms';
}
}
/**
* Setup event listeners
*/
function setupEventListeners() {
document.getElementById('export-all-btn').addEventListener('click', exportAllCookies);
document.getElementById('settings-btn').addEventListener('click', () => {
browser.runtime.openOptionsPage();
});
}
/**
* Show success message
* @param {string} message - Message to display
*/
function showSuccess(message) {
showStatusMessage(message, 'success');
}
/**
* Show error message
* @param {string} message - Message to display
*/
function showError(message) {
showStatusMessage(message, 'error');
}
/**
* Show warning message
* @param {string} message - Message to display
*/
function showWarning(message) {
showStatusMessage(message, 'warning');
}
/**
* Show a status message
* @param {string} message - Message text
* @param {string} type - Message type (success, error, warning)
*/
function showStatusMessage(message, type) {
const el = document.getElementById('status-message');
el.textContent = message;
el.className = `status-message ${type}`;
el.classList.remove('hidden');
}
/**
* Hide the status message
*/
function hideStatusMessage() {
document.getElementById('status-message').classList.add('hidden');
}