MaterialXWeb 1.39.5
Utilities for using MaterialX Packages with Web clients
Loading...
Searching...
No Matches
materialServer.cjs
1// @file: materialServer.cjs
2// @brief: Initialize express server to serve static files and proxy requests
3// to download materials
4//
5const express = require('express');
6const cors = require('cors');
7// Loaders return an instance of the loader class
8const gpuopen_loader = require('./JsGPUOpenMaterialLoader');
9const ambientcg_loader = require('./JsAmbientCGLoader');
10
11// @btief: Initialize the express server
12function initializeServer() {
13
14 const app = express();
15
16 // Enable CORS for all routes
17 app.use(cors());
18
19 // Serve static files from the 'public' directory
20 app.use(express.static('public'));
21
22 app.get('/api/previews', async (req, res) => {
23 try {
24 const { source } = req.query
25 console.log('- Server: Fetch material previews from:', source)
26 if (source == 'GPUOpen') {
27 const previews = await gpuopen_loader.getPreviews();
28 res.json(previews);
29 }
30 } catch (error) {
31 console.error('- Server: Error fetching material previews:', error);
32 res.status(500).json({ error: '- Server: Failed to fetch material previews' });
33 }
34 });
35
36 // Proxy endpoint to fetch materials
37 app.get('/api/materials', async (req, res) => {
38 try {
39 const { source } = req.query
40 console.log('- Server: Download materials from:', source)
41 if (source == 'GPUOpen') {
42 const materials = await gpuopen_loader.getMaterials();
43 res.json(materials);
44 }
45 else if (source == 'AmbientCG') {
46 //console.log(ambientcg_loader)
47 const materials = await ambientcg_loader.downloadMaterialsList();
48
49 //console.log('- Server: Read database...');
50 //const database = await ambientcg_loader.downloadAssetDatabase();
51 //ambientcg_loader.writeDatabaseToFile('ambientcg_database.json');
52 //ambientcg_loader.readDatabaseFromFile('ambientcg_database.json');
53
54 res.json(materials);
55 }
56 } catch (error) {
57 console.error('- Server: Error fetching materials:', error);
58 res.status(500).json({ error: '- Server: Failed to fetch materials' });
59 }
60 });
61
62 // Proxy endpoint to download a material package from AmbientCG
63 app.get('/api/downloadAmbientCGPackage', async (req, res) => {
64 try {
65 const { assetId, imageFormat, imageResolution } = req.query;
66 console.log('- Server: Download Package: ', assetId, imageFormat, imageResolution);
67 const materialName = await ambientcg_loader.downloadMaterialAsset(assetId, imageFormat, imageResolution);
68 console.log('- Server: Downloaded:"', materialName);
69
70 const result = ambientcg_loader.getDownloadedMaterialInformation();
71 let filename = result.filename;
72
73 // Sanitize the filename
74 const sanitizeFilename = (filename) => {
75 return filename.replace(/[^a-z0-9_.-]/gi, '_');
76 };
77 const safeFilename = sanitizeFilename(materialName);
78
79 // Set headers for the zip file and include the title
80 res.setHeader('Content-Type', 'application/zip');
81 res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`);
82 res.setHeader('X-File-Title', safeFilename); // Custom header for the title
83
84 // Send the binary data directly
85 console.log('- Server: Sending data:', safeFilename);
86 res.send(Buffer.from(result.content));
87 }
88 catch (error) {
89 console.error('Error downloading package:', error);
90 res.status(500).json({ error: 'Failed to download package' });
91 }
92 });
93
94 // Proxy endpoint to download a material package from GPUOpen
95 app.get('/api/downloadGPUOpenPackage', async (req, res) => {
96 try {
97 const { listNumber, materialNumber, packageId } = req.query;
98 //const loader = new JsGPUOpenMaterialLoader();
99 console.log('- Server: Download Package: ', listNumber, materialNumber, packageId)
100 const [data, title] = await gpuopen_loader.downloadPackage(
101 parseInt(listNumber),
102 parseInt(materialNumber),
103 parseInt(packageId)
104 );
105
106 const sanitizeFilename = (filename) => {
107 return filename.replace(/[^a-z0-9_.-]/gi, '_'); // Replace invalid characters with underscores
108 };
109
110 if (data) {
111 console.log('- Server: Downloaded:"', title, '", Data:', data != null)
112
113 // Sanitize the filename
114 const sanitizeFilename = (filename) => {
115 return filename.replace(/[^a-z0-9_.-]/gi, '_'); // Replace invalid characters with underscores
116 };
117 const safeFilename = sanitizeFilename(title) + '.zip';
118
119 // Set headers for the zip file and include the title
120 res.setHeader('Content-Type', 'application/zip');
121 res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`);
122 res.setHeader('X-File-Title', safeFilename); // Custom header for the title
123
124 // Send the binary data directly
125 res.send(Buffer.from(data));
126 }
127
128 else {
129 res.status(404).json({ error: 'Package not found' });
130 }
131 } catch (error) {
132 console.error('Error downloading package:', error);
133 res.status(500).json({ error: 'Failed to download package' });
134 }
135 });
136
137 // Start the server
138 const PORT = process.env.PORT || 3000;
139 app.listen(PORT, () => {
140 console.log(`Server is running on http://localhost:${PORT}`);
141 });
142}
143
144initializeServer();