Last active
September 3, 2022 16:02
-
-
Save MrOrz/773667a3b0c982ea1db808d18192d21b to your computer and use it in GitHub Desktop.
Cofacts collected image scripts
This file contains hidden or 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
const fs = require('fs/promises'); | |
const { hashes } = require('@cofacts/media-manager'); | |
const sharp = require('sharp'); | |
async function main() { | |
const path = process.argv[2]; | |
const fd = await fs.open(path); | |
const [{ size }, { format }] = await Promise.all([ | |
fd.stat(), | |
sharp(path).metadata(), | |
]); | |
const result = await hashes.getImageSearchHashes( | |
fd.createReadStream(), | |
size, | |
`image/${format}` | |
); | |
console.log(result.join('.')); | |
} | |
main(); |
This file contains hidden or 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
const fs = require('fs'); | |
const { MediaManager, variants } = require('@cofacts/media-manager'); | |
const sharp = require('sharp'); | |
const mediaManager = new MediaManager({ | |
bucketName: process.env.GCS_BUCKET_NAME, | |
credentialsJSON: fs.readFileSync(`./${process.env.GCS_CREDENTIAL_NAME}`, { encoding: 'utf-8'}), | |
prefix: process.env.GCS_MEDIA_FOLDER, | |
getVariantSettings({contentType}) { | |
return [ | |
variants.original(contentType), | |
{ | |
name: 'jpg240h', | |
contentType: 'image/jpeg', | |
transform: sharp() | |
.resize({ height: 240, withoutEnlargement: true }) | |
.jpeg({ quality: 60 }), | |
}, | |
{ | |
name: 'webp600w', | |
contentType: 'image/webp', | |
transform: sharp() | |
.resize({ width: 600, withoutEnlargement: true }) | |
.webp({ quality: 30 }), | |
}, | |
]; | |
} | |
}); | |
const METADATA = { | |
cacheControl: 'public, max-age=31536000, immutable', | |
}; | |
async function main() { | |
const url = process.argv[2]; | |
let mediaEntry; | |
const uploadError = await new Promise((resolve, reject) => { | |
mediaManager.insert({ | |
url, | |
onUploadStop: resolve | |
}).then(result => {mediaEntry = result}, reject); | |
}); | |
// After upload stops, | |
if (uploadError) { | |
console.log(JSON.stringify({ error: uploadError.toString() })); | |
return; | |
} | |
// Return only when all metadata is set | |
// otherwise they may cancel as the script terminates | |
await Promise.all(mediaEntry.variants.map(variant => | |
mediaEntry.getFile(variant).setMetadata(METADATA) | |
)); | |
console.log(JSON.stringify({mediaEntry})); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment