2019-05-29 05:21:06 -04:00
|
|
|
/* eslint-disable
|
2020-12-15 05:23:54 -05:00
|
|
|
node/handle-callback-err,
|
2019-05-29 05:21:06 -04:00
|
|
|
max-len,
|
|
|
|
no-unused-vars,
|
|
|
|
*/
|
|
|
|
// TODO: This file was created by bulk-decaffeinate.
|
|
|
|
// Fix any style issues and re-enable lint.
|
|
|
|
/*
|
|
|
|
* decaffeinate suggestions:
|
|
|
|
* DS102: Remove unnecessary code created because of implicit returns
|
|
|
|
* DS207: Consider shorter variations of null checks
|
|
|
|
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
|
|
|
*/
|
|
|
|
let FileHashManager
|
|
|
|
const crypto = require('crypto')
|
2021-11-01 11:05:16 -04:00
|
|
|
const logger = require('@overleaf/logger')
|
2019-05-29 05:21:06 -04:00
|
|
|
const fs = require('fs')
|
|
|
|
const _ = require('underscore')
|
|
|
|
|
|
|
|
module.exports = FileHashManager = {
|
|
|
|
computeHash(filePath, callback) {
|
|
|
|
if (callback == null) {
|
2021-10-27 05:49:18 -04:00
|
|
|
callback = function () {}
|
2019-05-29 05:21:06 -04:00
|
|
|
}
|
|
|
|
callback = _.once(callback) // avoid double callbacks
|
|
|
|
|
|
|
|
// taken from v1/history/storage/lib/blob_hash.js
|
|
|
|
const getGitBlobHeader = byteLength => `blob ${byteLength}` + '\x00'
|
|
|
|
|
|
|
|
const getByteLengthOfFile = cb =>
|
2021-04-14 09:17:21 -04:00
|
|
|
fs.stat(filePath, function (err, stats) {
|
2019-05-29 05:21:06 -04:00
|
|
|
if (err != null) {
|
|
|
|
return cb(err)
|
|
|
|
}
|
|
|
|
return cb(null, stats.size)
|
|
|
|
})
|
|
|
|
|
2021-04-14 09:17:21 -04:00
|
|
|
return getByteLengthOfFile(function (err, byteLength) {
|
2019-05-29 05:21:06 -04:00
|
|
|
if (err != null) {
|
|
|
|
return callback(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
const input = fs.createReadStream(filePath)
|
2021-04-14 09:17:21 -04:00
|
|
|
input.on('error', function (err) {
|
2019-07-01 09:48:09 -04:00
|
|
|
logger.warn({ filePath, err }, 'error opening file in computeHash')
|
2019-05-29 05:21:06 -04:00
|
|
|
return callback(err)
|
|
|
|
})
|
|
|
|
|
|
|
|
const hash = crypto.createHash('sha1')
|
|
|
|
hash.setEncoding('hex')
|
|
|
|
hash.update(getGitBlobHeader(byteLength))
|
2021-04-14 09:17:21 -04:00
|
|
|
hash.on('readable', function () {
|
2019-05-29 05:21:06 -04:00
|
|
|
const result = hash.read()
|
|
|
|
if (result != null) {
|
|
|
|
return callback(null, result.toString('hex'))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
return input.pipe(hash)
|
|
|
|
})
|
2021-04-27 03:52:58 -04:00
|
|
|
},
|
2019-05-29 05:21:06 -04:00
|
|
|
}
|