· 8 years ago · Nov 26, 2017, 03:54 PM
1const debug = require('debug')('hub:etl')
2const path = require('path')
3const Sqlite3 = require('sqlite3').verbose()
4const exiftool = require('node-exiftool')
5const watch4jpegs = require('./lib/watch.js')
6
7require('dotenv').config()
8
9const STORAGE_PATH = process.env.STORAGE_PATH
10if (!STORAGE_PATH) {
11 console.error(new Error('no STORAGE_PATH'))
12 process.exit(1)
13}
14const EXIFTOOL_PATH = process.env.EXIFTOOL_PATH
15if (!EXIFTOOL_PATH) {
16 console.error(new Error('no EXIFTOOL_PATH'))
17 process.exit(1)
18}
19
20const ep = new exiftool.ExiftoolProcess(EXIFTOOL_PATH)
21
22const createImages = `CREATE TABLE image (
23 id INTEGER PRIMARY KEY,
24 file_name NOT NULL DEFAULT '',
25 date_time_created datetime NOT NULL,
26 full_path NOT NULL DEFAULT '',
27 thumbnail TEXT
28);`
29
30const db = new Sqlite3.Database(path.join(__dirname, 'cam.db'), (err, result) => {
31 if (err) {
32 return debug('db open error', err)
33 }
34 debug('db open')
35 return db.run(createImages, (err, result) => {
36 if (err && err.message.match(/table image already exists/)) {
37 debug('image table exists')
38 } else if (err) {
39 return debug('db create iamge table error', err)
40 }
41 })
42})
43
44function exifDateTimeToSQLite3Time (time) {
45 return [time.split(' ')[0].split(':').join('-'), time.split(' ')[1]].join(' ')
46}
47
48function addImageToDatabase ({ fileName, dateTimeOriginal, fullPath, thumbnail }) {
49 db.run(
50 `INSERT INTO image (
51 'file_name',
52 'date_time_created',
53 'full_path',
54 'thumbnail'
55 ) values (
56 '${fileName}',
57 '${dateTimeOriginal}',
58 '${fullPath}',
59 '${thumbnail}'
60 );`
61 )
62}
63
64function getImgData (path) {
65 ep
66 .open()
67 .then(pid => debug('Started exiftool process %s', pid))
68 .then(() => ep.readMetadata(path, ['b', 'FileName', 'ThumbnailImage', 'DateTimeOriginal']))
69 .then(result => {
70 // create db entry
71 debug(result.data)
72 const model = {
73 fileName: result.data[0].FileName,
74 dateTimeOriginal: exifDateTimeToSQLite3Time(result.data[0].DateTimeOriginal),
75 fullPath: path,
76 thumbnail: result.data[0].ThumbnailImage
77 }
78 debug('model to add', model)
79 return addImageToDatabase(model)
80 })
81 .then(() => ep.close())
82 .catch(debug)
83}
84
85if (require.main === module) {
86 watch4jpegs(STORAGE_PATH, getImgData)
87}
88
89exports.addImageToDatabase = addImageToDatabase