Skip to content

Commit

Permalink
Validate images before uploading and retry if invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
matijse committed Apr 21, 2021
1 parent 1de5b33 commit 40fb754
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 1 deletion.
24 changes: 23 additions & 1 deletion mqtt/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const MQTT = require('async-mqtt')
const get = require('get-value')
const fetch = require('node-fetch')
const winston = require('winston')
const { validateBufferMIMEType } = require('validate-image-type')
const { sleep } = require('eufy-node-client')
const DB = require('../db')
const config = require('../config')
Expand Down Expand Up @@ -112,6 +113,7 @@ class MqttClient {
}

if (attributes.thumbnail && attributes.thumbnail.length > 0) {
await sleep(100)
await this.uploadThumbnail(deviceSN, attributes.thumbnail)
}
}
Expand All @@ -125,7 +127,27 @@ class MqttClient {
async uploadThumbnail(deviceSN, thumbnailUrl) {
winston.debug(`Uploading new thumbnail for ${deviceSN} from ${thumbnailUrl}`)
const response = await fetch(thumbnailUrl)
const image = await response.buffer()
let image = await response.buffer()

const result = validateBufferMIMEType(image, {
allowMimeTypes: ['image/jpeg', 'image/gif', 'image/png', 'image/svg+xml']
})

winston.debug(`Image validation result: `, result)

if (!result.ok) {
winston.error(`Image seems to be invalid. URL: ${thumbnailUrl}`, result)
await sleep(1000)
winston.info(`Retrying image ${thumbnailUrl} after waiting 1 second...`)
const response = await fetch(thumbnailUrl)
image = await response.buffer()

const result = validateBufferMIMEType(image, {
allowMimeTypes: ['image/jpeg', 'image/gif', 'image/png', 'image/svg+xml']
})

winston.info(`Retry - Image validation result: `, result)
}

const topic = HaDiscovery.baseTopicForCapability(NotificationType.THUMBNAIL, deviceSN)

Expand Down
70 changes: 70 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"js-yaml": "^3.14.1",
"node-fetch": "^2.6.1",
"sqlite3": "^5.0.1",
"validate-image-type": "^1.1.1",
"winston": "^3.3.3"
}
}

0 comments on commit 40fb754

Please sign in to comment.