-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
1 changed file
with
39 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,47 @@ | ||
import convert from 'fbx2gltf'; | ||
import fs from 'fs/promises'; | ||
import fs from 'fs'; | ||
import fsPromises from 'fs/promises'; | ||
import path from 'path'; | ||
import os from 'os'; | ||
import crypto from 'crypto'; | ||
|
||
const getFileHash = (filepath: string) => { | ||
const fd = fs.createReadStream(filepath); | ||
|
||
const hash = crypto.createHash('sha1'); | ||
hash.setEncoding('hex'); | ||
|
||
return new Promise((resolve) => { | ||
fd.on('end', () => { | ||
hash.end(); | ||
resolve(hash.read()); | ||
}); | ||
fd.on('error', () => resolve('')); | ||
fd.pipe(hash); | ||
}); | ||
}; | ||
|
||
const silentlyReadFile = async (filepath: string) => { | ||
try { | ||
const result = await fsPromises.readFile(filepath, 'base64'); | ||
return result; | ||
} catch (e) { | ||
return ''; | ||
} | ||
}; | ||
|
||
export const readAndConvertFbxToGltf = async (filepath: string) => { | ||
const glbDestPath = path.resolve(os.tmpdir(), `${filepath}.glb`); | ||
const fbxHash = await getFileHash(filepath); | ||
const glbDestPath = path.resolve(os.tmpdir(), `${fbxHash}.glb`); | ||
|
||
const recentlyGeneratedGlb = await silentlyReadFile(glbDestPath); | ||
if (recentlyGeneratedGlb) { | ||
return recentlyGeneratedGlb; | ||
} | ||
|
||
await convert(filepath, glbDestPath); | ||
const glbBase64 = await fs.readFile(glbDestPath, 'base64'); | ||
await fs.unlink(glbDestPath); | ||
|
||
const glbBase64 = await fsPromises.readFile(glbDestPath, 'base64'); | ||
|
||
return glbBase64; | ||
}; |