307 lines
10 KiB
JavaScript
307 lines
10 KiB
JavaScript
/**
|
|
* Quality Label Printing Extension - Windows Service Communication
|
|
* Communicates with local Windows print service for silent printing
|
|
*/
|
|
|
|
console.log('Quality Label Printing Extension - Windows Service Mode');
|
|
|
|
// Service configuration
|
|
const PRINT_SERVICE_URL = 'http://localhost:8765';
|
|
const SERVICE_TIMEOUT = 30000; // 30 seconds
|
|
|
|
// Initialize extension
|
|
chrome.runtime.onInstalled.addListener(() => {
|
|
console.log('Quality Label Printing Service extension installed - Windows Service Mode');
|
|
testServiceConnection();
|
|
});
|
|
|
|
// Test connection to Windows service
|
|
async function testServiceConnection() {
|
|
try {
|
|
const response = await fetch(`${PRINT_SERVICE_URL}/health`, {
|
|
method: 'GET',
|
|
timeout: 5000
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
console.log('✅ Windows Print Service connected:', data);
|
|
return true;
|
|
} else {
|
|
console.warn('⚠️ Windows Print Service not responding:', response.status);
|
|
return false;
|
|
}
|
|
} catch (error) {
|
|
console.warn('❌ Windows Print Service not available:', error.message);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Handle messages from content scripts or web pages
|
|
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
|
console.log('Background script received message:', message);
|
|
|
|
switch (message.action) {
|
|
case 'print_pdf':
|
|
handleWindowsServicePrint(message)
|
|
.then(result => {
|
|
console.log('Windows service print completed:', result);
|
|
sendResponse(result);
|
|
})
|
|
.catch(error => {
|
|
console.error('Windows service print error:', error);
|
|
sendResponse({ success: false, error: error.message });
|
|
});
|
|
return true; // Keep message channel open for async response
|
|
|
|
case 'get_printers':
|
|
getAvailablePrinters()
|
|
.then(printers => {
|
|
sendResponse({ success: true, printers: printers });
|
|
})
|
|
.catch(error => {
|
|
console.error('Error getting printers:', error);
|
|
sendResponse({
|
|
success: false,
|
|
error: error.message,
|
|
printers: [{ name: 'default', display_name: 'Default Printer', is_default: true }]
|
|
});
|
|
});
|
|
return true;
|
|
|
|
case 'ping':
|
|
testServiceConnection()
|
|
.then(connected => {
|
|
sendResponse({
|
|
success: true,
|
|
extension_version: chrome.runtime.getManifest().version,
|
|
ready: true,
|
|
service_connected: connected,
|
|
mode: 'windows_service'
|
|
});
|
|
})
|
|
.catch(() => {
|
|
sendResponse({
|
|
success: true,
|
|
extension_version: chrome.runtime.getManifest().version,
|
|
ready: false,
|
|
service_connected: false,
|
|
mode: 'windows_service'
|
|
});
|
|
});
|
|
return true;
|
|
|
|
default:
|
|
sendResponse({ error: 'Unknown action', success: false });
|
|
}
|
|
});
|
|
|
|
// Handle external messages from web pages
|
|
chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
|
|
console.log('External message received:', message, 'from:', sender);
|
|
|
|
// Verify sender origin for security
|
|
const allowedOrigins = [
|
|
'http://localhost:5000',
|
|
'http://localhost:8000',
|
|
'http://127.0.0.1:5000',
|
|
'http://127.0.0.1:8000',
|
|
'http://localhost:3000',
|
|
'http://localhost:8080'
|
|
];
|
|
|
|
if (!allowedOrigins.some(origin => sender.url && sender.url.startsWith(origin))) {
|
|
console.warn('Unauthorized origin:', sender.url);
|
|
sendResponse({ error: 'Unauthorized origin', success: false });
|
|
return;
|
|
}
|
|
|
|
// Handle the message
|
|
switch (message.action) {
|
|
case 'print_pdf':
|
|
handleWindowsServicePrint(message)
|
|
.then(result => sendResponse(result))
|
|
.catch(error => {
|
|
console.error('Print PDF error:', error);
|
|
sendResponse({ success: false, error: error.message });
|
|
});
|
|
return true;
|
|
|
|
case 'ping':
|
|
testServiceConnection()
|
|
.then(connected => {
|
|
sendResponse({
|
|
success: true,
|
|
extension_version: chrome.runtime.getManifest().version,
|
|
ready: true,
|
|
service_connected: connected,
|
|
mode: 'windows_service'
|
|
});
|
|
})
|
|
.catch(() => {
|
|
sendResponse({
|
|
success: true,
|
|
extension_version: chrome.runtime.getManifest().version,
|
|
ready: false,
|
|
service_connected: false,
|
|
mode: 'windows_service'
|
|
});
|
|
});
|
|
return true;
|
|
|
|
default:
|
|
sendResponse({ error: 'Unknown action', success: false });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Get available printers from Windows service
|
|
*/
|
|
async function getAvailablePrinters() {
|
|
try {
|
|
const response = await fetch(`${PRINT_SERVICE_URL}/printers`, {
|
|
method: 'GET',
|
|
timeout: 10000
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data.printers || [];
|
|
} else {
|
|
throw new Error(`Service responded with status: ${response.status}`);
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to get printers from service:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle PDF printing via Windows Service
|
|
*/
|
|
async function handleWindowsServicePrint(message) {
|
|
console.log('🖨️ Sending PDF to Windows print service:', message);
|
|
|
|
try {
|
|
const { pdfUrl, orderId, prodOrder, quantity, printerName } = message;
|
|
|
|
if (!pdfUrl) {
|
|
throw new Error('PDF URL is required');
|
|
}
|
|
|
|
// First, test if service is available
|
|
const serviceAvailable = await testServiceConnection();
|
|
if (!serviceAvailable) {
|
|
throw new Error('Windows Print Service is not running. Please ensure the service is installed and started.');
|
|
}
|
|
|
|
// Prepare print request
|
|
const printRequest = {
|
|
pdf_url: pdfUrl,
|
|
printer_name: printerName || 'default',
|
|
order_id: orderId,
|
|
prod_order: prodOrder,
|
|
quantity: quantity,
|
|
timestamp: new Date().toISOString()
|
|
};
|
|
|
|
console.log('📤 Sending print request to service:', printRequest);
|
|
|
|
// Send PDF to Windows service for printing
|
|
const response = await fetch(`${PRINT_SERVICE_URL}/print_pdf`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(printRequest)
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
throw new Error(`Print service error (${response.status}): ${errorText}`);
|
|
}
|
|
|
|
const result = await response.json();
|
|
|
|
if (result.success) {
|
|
console.log('✅ Print job sent successfully:', result);
|
|
|
|
return {
|
|
success: true,
|
|
message: `PDF sent to ${result.printer || printerName || 'default printer'} successfully`,
|
|
method: result.method || 'Windows Print Service',
|
|
printer: result.printer || printerName,
|
|
orderId: orderId,
|
|
instruction: 'PDF has been sent to the printer queue'
|
|
};
|
|
} else {
|
|
throw new Error(result.error || 'Unknown print service error');
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ Windows service print failed:', error);
|
|
|
|
// Fallback: Return instruction to print manually
|
|
return {
|
|
success: false,
|
|
error: error.message,
|
|
fallback: true,
|
|
instruction: 'Windows service unavailable. Please download and print the PDF manually.'
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fallback function for when Windows service is not available
|
|
*/
|
|
async function handleFallbackPrint(message) {
|
|
console.log('🔄 Using fallback print method:', message);
|
|
|
|
try {
|
|
const { pdfUrl, orderId, prodOrder, quantity } = message;
|
|
|
|
// Create a new tab with the PDF
|
|
const tab = await chrome.tabs.create({
|
|
url: pdfUrl,
|
|
active: false // Don't switch to the tab
|
|
});
|
|
|
|
// Wait a moment for PDF to load
|
|
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
|
|
// Get the created tab
|
|
const updatedTab = await chrome.tabs.get(tab.id);
|
|
|
|
return {
|
|
success: true,
|
|
message: `PDF opened in new tab for manual printing`,
|
|
method: 'Manual Print Fallback',
|
|
tabId: tab.id,
|
|
instruction: 'PDF opened in new tab. Use Ctrl+P to print or close the tab if not needed.'
|
|
};
|
|
|
|
} catch (error) {
|
|
console.error('❌ Fallback print failed:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Utility functions
|
|
function delay(ms) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
// Extension startup
|
|
console.log('🖨️ Quality Label Printing Extension loaded - Windows Service Mode');
|
|
console.log(`🔗 Service URL: ${PRINT_SERVICE_URL}`);
|
|
|
|
// Test service on startup
|
|
testServiceConnection().then(connected => {
|
|
if (connected) {
|
|
console.log('✅ Windows Print Service is available');
|
|
} else {
|
|
console.log('⚠️ Windows Print Service is not available - fallback mode active');
|
|
}
|
|
});
|
|
|
|
console.log('✅ Background script loaded successfully - Platform safe mode enabled'); |