Skip to content

Commit

Permalink
Update:Added string localization for tasks #3303 #3352
Browse files Browse the repository at this point in the history
  • Loading branch information
advplyr committed Sep 21, 2024
1 parent 8512d5e commit 1dec8ae
Show file tree
Hide file tree
Showing 13 changed files with 213 additions and 83 deletions.
39 changes: 35 additions & 4 deletions client/components/cards/ItemTaskRunningCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<p class="truncate text-sm">{{ title }}</p>

<p class="truncate text-xs text-gray-300">{{ description }}</p>
<p v-if="specialMessage" class="truncate text-xs text-gray-300">{{ specialMessage }}</p>

<p v-if="isFailed && failedMessage" class="text-xs truncate text-red-500">{{ failedMessage }}</p>
<p v-else-if="!isFinished && cancelingScan" class="text-xs truncate">Canceling...</p>
Expand All @@ -26,22 +27,34 @@ export default {
},
data() {
return {
cancelingScan: false
cancelingScan: false,
specialMessage: ''
}
},
watch: {
task: {
immediate: true,
handler() {
this.initTask()
}
}
},
computed: {
userIsAdminOrUp() {
return this.$store.getters['user/getIsAdminOrUp']
},
title() {
if (this.task.titleKey && this.$strings[this.task.titleKey]) {
return this.$getString(this.task.titleKey, this.task.titleSubs)
}
return this.task.title || 'No Title'
},
description() {
if (this.task.descriptionKey && this.$strings[this.task.descriptionKey]) {
return this.$getString(this.task.descriptionKey, this.task.descriptionSubs)
}
return this.task.description || ''
},
details() {
return this.task.details || 'Unknown'
},
isFinished() {
return !!this.task.isFinished
},
Expand All @@ -52,6 +65,9 @@ export default {
return this.isFinished && !this.isFailed
},
failedMessage() {
if (this.task.errorKey && this.$strings[this.task.errorKey]) {
return this.$getString(this.task.errorKey, this.task.errorSubs)
}
return this.task.error || ''
},
action() {
Expand Down Expand Up @@ -87,6 +103,21 @@ export default {
}
},
methods: {
initTask() {
// special message for library scan tasks
if (this.task?.data?.scanResults) {
const scanResults = this.task.data.scanResults
const strs = []
if (scanResults.added) strs.push(this.$getString('MessageTaskScanItemsAdded', [scanResults.added]))
if (scanResults.updated) strs.push(this.$getString('MessageTaskScanItemsUpdated', [scanResults.updated]))
if (scanResults.missing) strs.push(this.$getString('MessageTaskScanItemsMissing', [scanResults.missing]))
const changesDetected = strs.length > 0 ? strs.join(', ') : this.$strings.MessageTaskScanNoChangesNeeded
const timeElapsed = scanResults.elapsed ? ` (${this.$elapsedPretty(scanResults.elapsed / 1000, false, true)})` : ''
this.specialMessage = `${changesDetected}${timeElapsed}`
} else {
this.specialMessage = ''
}
},
cancelScan() {
const libraryId = this.task?.data?.libraryId
if (!libraryId) {
Expand Down
4 changes: 2 additions & 2 deletions client/plugins/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ Vue.prototype.$strings = { ...enUsStrings }
* Get string and substitute
*
* @param {string} key
* @param {string[]} subs
* @param {string[]} [subs=[]]
* @returns {string}
*/
Vue.prototype.$getString = (key, subs) => {
Vue.prototype.$getString = (key, subs = []) => {
if (!Vue.prototype.$strings[key]) return ''
if (subs?.length && Array.isArray(subs)) {
return supplant(Vue.prototype.$strings[key], subs)
Expand Down
5 changes: 4 additions & 1 deletion client/plugins/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ Vue.prototype.$bytesPretty = (bytes, decimals = 2) => {
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

Vue.prototype.$elapsedPretty = (seconds, useFullNames = false) => {
Vue.prototype.$elapsedPretty = (seconds, useFullNames = false, useMilliseconds = false) => {
if (useMilliseconds && seconds > 0 && seconds < 1) {
return `${Math.floor(seconds * 1000)} ms`
}
if (seconds < 60) {
return `${Math.floor(seconds)} sec${useFullNames ? 'onds' : ''}`
}
Expand Down
32 changes: 32 additions & 0 deletions client/strings/en-us.json
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,38 @@
"MessageShareExpiresIn": "Expires in {0}",
"MessageShareURLWillBe": "Share URL will be <strong>{0}</strong>",
"MessageStartPlaybackAtTime": "Start playback for \"{0}\" at {1}?",
"MessageTaskAudioFileNotWritable": "Audio file \"{0}\" is not writable",
"MessageTaskCanceledByUser": "Task canceled by user",
"MessageTaskDownloadingEpisodeDescription": "Downloading episode \"{0}\"",
"MessageTaskEmbeddingMetadata": "Embedding metadata",
"MessageTaskEmbeddingMetadataDescription": "Embedding metadata in audiobook \"{0}\"",
"MessageTaskEncodingM4b": "Encoding M4B",
"MessageTaskEncodingM4bDescription": "Encoding audiobook \"{0}\" into a single m4b file",
"MessageTaskFailed": "Failed",
"MessageTaskFailedToBackupAudioFile": "Failed to backup audio file \"{0}\"",
"MessageTaskFailedToCreateCacheDirectory": "Failed to create cache directory",
"MessageTaskFailedToEmbedMetadataInFile": "Failed to embed metadata in file \"{0}\"",
"MessageTaskFailedToMergeAudioFiles": "Failed to merge audio files",
"MessageTaskFailedToMoveM4bFile": "Failed to move m4b file",
"MessageTaskFailedToWriteMetadataFile": "Failed to write metadata file",
"MessageTaskMatchingBooksInLibrary": "Matching books in library \"{0}\"",
"MessageTaskNoFilesToScan": "No files to scan",
"MessageTaskOpmlImport": "OPML import",
"MessageTaskOpmlImportDescription": "Creating podcasts from {0} RSS feeds",
"MessageTaskOpmlImportFeed": "OPML import feed",
"MessageTaskOpmlImportFeedDescription": "Importing RSS feed \"{0}\"",
"MessageTaskOpmlImportFeedFailed": "Failed to get podcast feed",
"MessageTaskOpmlImportFeedPodcastDescription": "Creating podcast \"{0}\"",
"MessageTaskOpmlImportFeedPodcastExists": "Podcast already exists at path",
"MessageTaskOpmlImportFeedPodcastFailed": "Failed to create podcast",
"MessageTaskOpmlImportFinished": "Added {0} podcasts",
"MessageTaskScanItemsAdded": "{0} added",
"MessageTaskScanItemsMissing": "{0} missing",
"MessageTaskScanItemsUpdated": "{0} updated",
"MessageTaskScanNoChangesNeeded": "No changes needed",
"MessageTaskScanningFileChanges": "Scanning file changes in \"{0}\"",
"MessageTaskScanningLibrary": "Scanning \"{0}\" library",
"MessageTaskTargetDirectoryNotWritable": "Target directory is not writable",
"MessageThinking": "Thinking...",
"MessageUploaderItemFailed": "Failed to upload",
"MessageUploaderItemSuccess": "Successfully Uploaded!",
Expand Down
6 changes: 5 additions & 1 deletion server/Watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,11 @@ class FolderWatcher extends EventEmitter {
if (this.pendingFileUpdates.length) {
LibraryScanner.scanFilesChanged(this.pendingFileUpdates, this.pendingTask)
} else {
this.pendingTask.setFinished('Scan abandoned. No files to scan.')
const taskFinishedString = {
text: 'No files to scan',
key: 'MessageTaskNoFilesToScan'
}
this.pendingTask.setFinished(taskFinishedString)
TaskManager.taskFinished(this.pendingTask)
}
this.pendingTask = null
Expand Down
7 changes: 4 additions & 3 deletions server/managers/AbMergeManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,11 @@ class AbMergeManager {
if (error.message === 'FFMPEG_CANCELED') {
Logger.info(`[AbMergeManager] Task cancelled ${task.id}`)
} else {
Logger.error(`[AbMergeManager] Failed to write metadata to file "${task.data.tempFilepath}"`)
Logger.error(`[AbMergeManager] Failed to embed metadata in file "${task.data.tempFilepath}"`)
const taskFailedString = {
text: 'Failed to write metadata to m4b file',
key: 'MessageTaskFailedToWriteMetadataToM4bFile'
text: `Failed to embed metadata in file ${Path.basename(task.data.tempFilepath)}`,
key: 'MessageTaskFailedToEmbedMetadataInFile',
subs: [Path.basename(task.data.tempFilepath)]
}
task.setFailed(taskFailedString)
this.removeTask(task, true)
Expand Down
43 changes: 37 additions & 6 deletions server/managers/AudioMetadataManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ class AudioMetadataMangaer {
}
}

/**
*
* @param {import('../objects/Task')} task
*/
async runMetadataEmbed(task) {
this.tasksRunning.push(task)
TaskManager.addTask(task)
Expand All @@ -132,7 +136,11 @@ class AudioMetadataMangaer {
Logger.debug(`[AudioMetadataManager] Target directory ${task.data.libraryItemDir} writable: ${targetDirWritable}`)
if (!targetDirWritable) {
Logger.error(`[AudioMetadataManager] Target directory is not writable: ${task.data.libraryItemDir}`)
task.setFailedText('Target directory is not writable')
const taskFailedString = {
text: 'Target directory is not writable',
key: 'MessageTaskTargetDirectoryNotWritable'
}
task.setFailed(taskFailedString)
this.handleTaskFinished(task)
return
}
Expand All @@ -143,7 +151,12 @@ class AudioMetadataMangaer {
await fs.access(af.path, fs.constants.W_OK)
} catch (err) {
Logger.error(`[AudioMetadataManager] Audio file is not writable: ${af.path}`)
task.setFailedText(`Audio file "${Path.basename(af.path)}" is not writable`)
const taskFailedString = {
text: `Audio file "${Path.basename(af.path)}" is not writable`,
key: 'MessageTaskAudioFileNotWritable',
subs: [Path.basename(af.path)]
}
task.setFailed(taskFailedString)
this.handleTaskFinished(task)
return
}
Expand All @@ -157,7 +170,11 @@ class AudioMetadataMangaer {
cacheDirCreated = true
} catch (err) {
Logger.error(`[AudioMetadataManager] Failed to create cache directory ${task.data.itemCachePath}`, err)
task.setFailedText('Failed to create cache directory')
const taskFailedString = {
text: 'Failed to create cache directory',
key: 'MessageTaskFailedToCreateCacheDirectory'
}
task.setFailed(taskFailedString)
this.handleTaskFinished(task)
return
}
Expand All @@ -168,7 +185,11 @@ class AudioMetadataMangaer {
const success = await ffmpegHelpers.writeFFMetadataFile(task.data.metadataObject, task.data.chapters, ffmetadataPath)
if (!success) {
Logger.error(`[AudioMetadataManager] Failed to write ffmetadata file for audiobook "${task.data.libraryItemId}"`)
task.setFailedText('Failed to write metadata file.')
const taskFailedString = {
text: 'Failed to write metadata file',
key: 'MessageTaskFailedToWriteMetadataFile'
}
task.setFailed(taskFailedString)
this.handleTaskFinished(task)
return
}
Expand All @@ -190,7 +211,12 @@ class AudioMetadataMangaer {
Logger.debug(`[AudioMetadataManager] Backed up audio file at "${backupFilePath}"`)
} catch (err) {
Logger.error(`[AudioMetadataManager] Failed to backup audio file "${af.path}"`, err)
task.setFailedText(`Failed to backup audio file "${Path.basename(af.path)}"`)
const taskFailedString = {
text: `Failed to backup audio file "${Path.basename(af.path)}"`,
key: 'MessageTaskFailedToBackupAudioFile',
subs: [Path.basename(af.path)]
}
task.setFailed(taskFailedString)
this.handleTaskFinished(task)
return
}
Expand All @@ -204,7 +230,12 @@ class AudioMetadataMangaer {
Logger.info(`[AudioMetadataManager] Successfully tagged audio file "${af.path}"`)
} catch (err) {
Logger.error(`[AudioMetadataManager] Failed to tag audio file "${af.path}"`, err)
task.setFailedText(`Failed to tag audio file "${Path.basename(af.path)}"`)
const taskFailedString = {
text: `Failed to embed metadata in file "${Path.basename(af.path)}"`,
key: 'MessageTaskFailedToEmbedMetadataInFile',
subs: [Path.basename(af.path)]
}
task.setFailed(taskFailedString)
this.handleTaskFinished(task)
return
}
Expand Down
19 changes: 16 additions & 3 deletions server/managers/PodcastManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,22 @@ class PodcastManager {
if (!success) {
await fs.remove(this.currentDownload.targetPath)
this.currentDownload.setFinished(false)
task.setFailedText('Failed to download episode')
const taskFailedString = {
text: 'Failed',
key: 'MessageTaskFailed'
}
task.setFailed(taskFailedString)
} else {
Logger.info(`[PodcastManager] Successfully downloaded podcast episode "${this.currentDownload.podcastEpisode.title}"`)
this.currentDownload.setFinished(true)
task.setFinished()
}
} else {
task.setFailedText('Failed to download episode')
const taskFailedString = {
text: 'Failed',
key: 'MessageTaskFailed'
}
task.setFailed(taskFailedString)
this.currentDownload.setFinished(false)
}

Expand Down Expand Up @@ -560,7 +568,12 @@ class PodcastManager {

numPodcastsAdded++
}
task.setFinished(`Added ${numPodcastsAdded} podcasts`)
const taskFinishedString = {
text: `Added ${numPodcastsAdded} podcasts`,
key: 'MessageTaskOpmlImportFinished',
subs: [numPodcastsAdded]
}
task.setFinished(taskFinishedString)
TaskManager.taskFinished(task)
Logger.info(`[PodcastManager] createPodcastsFromFeedUrls: Finished OPML import. Created ${numPodcastsAdded} podcasts out of ${rssFeedUrls.length} RSS feed URLs`)
}
Expand Down
2 changes: 1 addition & 1 deletion server/managers/TaskManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class TaskManager {
createAndEmitFailedTask(action, titleString, descriptionString, errorMessageString) {
const task = new Task()
task.setData(action, titleString, descriptionString, false)
task.setFailedText(errorMessageString)
task.setFailed(errorMessageString)
SocketAuthority.emitter('task_started', task.toJSON())
return task
}
Expand Down
35 changes: 15 additions & 20 deletions server/objects/Task.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,14 @@ class Task {
action: this.action,
data: this.data ? { ...this.data } : {},
title: this.title,
titleKey: this.titleKey,
titleSubs: this.titleSubs,
description: this.description,
descriptionKey: this.descriptionKey,
descriptionSubs: this.descriptionSubs,
error: this.error,
errorKey: this.errorKey,
errorSubs: this.errorSubs,
showSuccess: this.showSuccess,
isFailed: this.isFailed,
isFinished: this.isFinished,
Expand Down Expand Up @@ -104,30 +110,19 @@ class Task {
this.setFinished()
}

/**
* Set task as failed without translation key
* TODO: Remove this method after all tasks are using translation keys
*
* @param {string} message
*/
setFailedText(message) {
this.error = message
this.errorKey = null
this.errorSubs = null
this.isFailed = true
this.failedAt = Date.now()
this.setFinished()
}

/**
* Set task as finished
* TODO: Update to use translation keys
*
* @param {string} [newDescription] update description
* @param {TaskString} [newDescriptionString] update description
* @param {boolean} [clearDescription] clear description
*/
setFinished(newDescription = null) {
if (newDescription) {
this.description = newDescription
setFinished(newDescriptionString = null, clearDescription = false) {
if (newDescriptionString) {
this.description = newDescriptionString.text
this.descriptionKey = newDescriptionString.key || null
this.descriptionSubs = newDescriptionString.subs || null
} else if (clearDescription) {
this.description = null
this.descriptionKey = null
this.descriptionSubs = null
}
Expand Down
Loading

0 comments on commit 1dec8ae

Please sign in to comment.