chaining promises to find exif data before renaming

This commit is contained in:
Tykayn 2023-06-29 23:21:16 +02:00 committed by tykayn
parent 30c1189393
commit aaf00bd4ba
3 changed files with 147 additions and 95 deletions

6
.idea/jsLibraryMappings.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<includedPredefinedLibrary name="Node.js Core" />
</component>
</project>

View File

@ -4,6 +4,7 @@
import { tagSectionSeparator, tagSeparator } from './configs.mjs' import { tagSectionSeparator, tagSeparator } from './configs.mjs'
import exifr from 'exifr' import exifr from 'exifr'
import moment from 'moment' import moment from 'moment'
import path from 'path'
/** /**
* finds patterns for file name * finds patterns for file name
@ -11,7 +12,7 @@ import moment from 'moment'
export default class finder { export default class finder {
static statistics = { static statistics = {
filesModified : 0, filesModified: 0,
} }
static patternsFiles = { static patternsFiles = {
'downloaded_pic': /^\-\w{15}\.jpg/, // FyB8cZnWIAc21rw.jpg 'downloaded_pic': /^\-\w{15}\.jpg/, // FyB8cZnWIAc21rw.jpg
@ -19,10 +20,12 @@ export default class finder {
'open_camera': /^IMG_OC_\d{8}/i, // IMG_OC_20230617_092120_3.jpg 'open_camera': /^IMG_OC_\d{8}/i, // IMG_OC_20230617_092120_3.jpg
'screenshot': /^Screenshot/i, // Screenshot 2023-06-15 at 15-26-04 Instance Panoramax OSM-FR.png 'screenshot': /^Screenshot/i, // Screenshot 2023-06-15 at 15-26-04 Instance Panoramax OSM-FR.png
} }
static reportStatistics(){
static reportStatistics () {
console.log('statistics', console.log('statistics',
this.statistics) this.statistics)
} }
static findScreenshot (inputString) { static findScreenshot (inputString) {
return inputString.match(/screenshot/i) || inputString.match(/capture d'écran/i) return inputString.match(/screenshot/i) || inputString.match(/capture d'écran/i)
} }
@ -39,11 +42,6 @@ export default class finder {
static findFileExtension (inputString) { static findFileExtension (inputString) {
let result = inputString.match(/\.\w{3,4}$/i) let result = inputString.match(/\.\w{3,4}$/i)
// console.log('match findFileExtension', match)
// let result = ''
// if (match && match[0]) {
// result = match[0]
// }
return result return result
} }
@ -143,33 +141,31 @@ export default class finder {
/** /**
* convertit un nom de fichier en une structure décrivant plusieurs parties correspondant au pattern d'archivage * convertit un nom de fichier en une structure décrivant plusieurs parties correspondant au pattern d'archivage
* @param fileName * @param fullPath
* @returns {{extension: *, dateStamp: string, freeText: (*|string), tags: *[]}} * @returns {{extension: *, dateStamp: string, freeText: (*|string), tags: *[]}}
*/ */
static destructurateFileName (fileName) { static destructurateFileName (fullPath) {
let [folderPath, fileNameOriginal] = this.findFolderPath(fullPath)
let dateStampInFileNameOriginal = this.findFormattedDate(fileNameOriginal)
return { return {
dateStamp: this.findFormattedDate(fileName), fullPath,
freeText: this.findFileNameFreeTextPart(fileName), folderPath,
tags: this.findTagSectionInString(fileName), fileNameOriginal,
extension: this.findFileExtension(fileName), dateStampInFileNameOriginal,
dateStampExif: '',
freeText: this.findFileNameFreeTextPart(fileNameOriginal),
tags: this.findTagSectionInString(fileNameOriginal),
extension: this.findFileExtension(fileNameOriginal),
} }
} }
/** /**
* examine plusieurs propriétés exif de date et retourne la plus ancienne * finds the earliest part in several exif date info
* @param filepath * @param exifData
* @returns {string}
*/ */
static async findExifCreationDate (filepath) { static findEarliestDateInExifData (exifData) {
console.log('filepath', filepath)
let dateAlreadyInFileName = finder.findFormattedDate(filepath)
if(dateAlreadyInFileName){
console.log('------ dateAlreadyInFileName', dateAlreadyInFileName)
}
await exifr.parse(filepath).then(exifData => {
if (exifData) { if (exifData) {
let moments = [] let moments = []
@ -216,10 +212,33 @@ export default class finder {
console.log('pas de exif data') console.log('pas de exif data')
return '' return ''
} }
}).catch(error => {
console.log('/////////// Error in reading exif of file: ' + error.message)
return ''
})
} }
/**
* examine plusieurs propriétés exif de date et retourne la plus ancienne
* @param filepath
*/
static async findExifCreationDate (filepath) {
console.log('filepath', filepath)
let dateAlreadyInFileName = finder.findFormattedDate(filepath)
if (dateAlreadyInFileName) {
console.log('------ dateAlreadyInFileName', dateAlreadyInFileName)
}
return await exifr.parse(filepath)
}
static findFolderPath (filePath) {
let folders = filePath.split('/')
let fileName = folders.pop()
folders = filePath.replace(fileName, '')
console.log('\n - folders', folders)
console.log(' - fileName', fileName, '\n')
return [folders, fileName]
}
} }

View File

@ -11,7 +11,7 @@ import minimist from 'minimist'
/** --------------------- /** ---------------------
custom utilities and configuration custom utilities and configuration
--------------------- */ --------------------- */
import { enableTestsLocally, reportStatistics, tagSectionSeparator, tagSeparator } from './configs.mjs' import { enableTestsLocally, reportStatistics,tagSectionSeparator, tagSeparator } from './configs.mjs'
import { import {
TestFindFormattedDate, TestFindFormattedDate,
TestScreenShotIsFoundAndRenamed, TestScreenShotIsFoundAndRenamed,
@ -35,15 +35,6 @@ function renameFile (originalFileName, fileMixedNewName) {
}) })
} }
function makeFileNameFromProperties (fileProperties) {
let tagPlace = ''
if (fileProperties.tags.length) {
tagPlace = ' ' + tagSectionSeparator + ' '
}
return finder.cleanSpaces(fileProperties.dateStamp + ' ' + fileProperties.freeText + tagPlace + fileProperties.tags.join(tagSeparator) + fileProperties.extension).replace(+' ' + tagSectionSeparator + ' ' + '.', '.')
}
function appendFileName (fileProperties, newText) { function appendFileName (fileProperties, newText) {
fileProperties.freeText = finder.cleanSpaces(fileProperties.freeText + ' ' + newText) fileProperties.freeText = finder.cleanSpaces(fileProperties.freeText + ' ' + newText)
return fileProperties return fileProperties
@ -54,6 +45,31 @@ function prependFileName (fileProperties, newText) {
return fileProperties return fileProperties
} }
function makeFileNameFromProperties(fileProperties) {
let tagPlace = ''
if (fileProperties.tags.length) {
tagPlace = ' ' + tagSectionSeparator + ' '
}
// return finder.cleanSpaces(fileProperties.dateStamp + ' ' + fileProperties.freeText + tagPlace + fileProperties.tags.join(tagSeparator) + fileProperties.extension).replace(+' ' + tagSectionSeparator + ' ' + '.', '.')
return ''+fileProperties.dateStampExif + ' ' + fileProperties.freeText + tagPlace + fileProperties.tags.join(tagSeparator) + fileProperties.extension
}
function shouldWeChangeName (structureForFile) {
console.log(' ______ allez hop fini la recherche on fait un nouveau nom')
console.log('structureForFile', structureForFile)
let newName = makeFileNameFromProperties(structureForFile)
if (structureForFile.fileNameOriginal !== newName) {
console.log('\n ancien nom :', structureForFile.fileNameOriginal)
// console.log(' nouveau nom:', foundDate +structureForFile.freeText + structureForFile.tags.join(tagSeparator) + structureForFile.extension )
console.log(' nouveau nom:', newName)
} else {
console.log(' rien à changer')
}
}
async function guessFileNameOnAllFilesFromArguments () { async function guessFileNameOnAllFilesFromArguments () {
// parcourir les dossiers // parcourir les dossiers
@ -62,30 +78,41 @@ async function guessFileNameOnAllFilesFromArguments () {
console.log('liste des fichiers', mini_arguments._) console.log('liste des fichiers', mini_arguments._)
let fileList = mini_arguments._ let fileList = mini_arguments._
fileList.forEach(fileName => { fileList.forEach(fullPath => {
let structureForFile = finder.destructurateFileName(fullPath)
let structureForFile = finder.destructurateFileName(fileName)
// examiner les infos exif de chaque fichier pour proposer un nouveau nom // examiner les infos exif de chaque fichier pour proposer un nouveau nom
if (!structureForFile.dateStamp) { if (!structureForFile.dateStampInFileNameOriginal) {
let foundDate = finder.findExifCreationDate(fileName).then((data) => { console.log(' le nom de fichier ne contient pas de date formatée au début')
finder.findExifCreationDate(structureForFile.fullPath)
.then(data => {
console.log(' ... chercher la date de création')
let foundDate = finder.findEarliestDateInExifData(data)
console.log(' =>>>>>>> foundDate : ', foundDate) console.log(' =>>>>>>> foundDate : ', foundDate)
if (foundDate) { if (foundDate) {
structureForFile.dateStamp = finder.findExifCreationDate(fileName)
// finder.findEarliestDateInExifData(fullPath).then(response => {
// console.log(' ... trouvée')
// if (response) {
structureForFile.dateStampExif = foundDate
shouldWeChangeName(structureForFile)
// }
// })
} else { } else {
console.log(' pas de date trouvée dans le nom') console.log('pas de date trouvée dans le nom')
}
let newname = makeFileNameFromProperties(structureForFile)
if (fileName !== newname) {
console.log(' nouveau nom:', newname)
} else {
console.log(' rien à changer')
} }
}, (err) => { }
console.error(err) ,
(error) => {
console.log('/////////// Error in reading exif of file: ' + error.message)
return ''
}) })
} }
} }