All files / src/queues/jobs autoImport.ts

76.31% Statements 29/38
76.92% Branches 10/13
50% Functions 1/2
76.31% Lines 29/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                      7x   7x     7x   7x                                 6x 1x 1x     5x 1x   1x 1x   4x     5x 5x 5x   5x 5x 5x 5x     5x   5x 5x 2x 2x 2x   1x       5x 5x 5x      
import { AboutService } from "@billos/firefly-iii-sdk"
import pino from "pino"
 
import { client } from "../../client"
import { env } from "../../config"
import { notifier } from "../../modules/notifiers"
import { redis } from "../../redis"
import { renderTemplate } from "../../utils/renderTemplate"
import { getQueue } from "../queue"
import { SimpleJob } from "./BaseJob"
 
const logger = pino()
 
const AUTOIMPORT_NOTIFICATION_KEY = "sparkleft:notification:autoimport:id"
 
export class AutoImportJob extends SimpleJob {
  readonly id = "auto-import"
 
  override readonly retryable = false // auto-import is triggered externally and should not be retried on failure
 
  override async init(): Promise<void> {
    if (!env.autoImportCron) {
      logger.info("AUTO_IMPORT_CRON is not set, skipping auto-import scheduler setup")
      return
    }
    const queue = await getQueue()
    logger.info("Setting up auto-import scheduler with cron '%s'", env.autoImportCron)
    try {
      await queue.upsertJobScheduler("auto-import-repeat", { pattern: env.autoImportCron }, { name: this.id, data: { job: this.id } })
    } catch (err) {
      logger.error({ err }, "Failed to set up auto-import scheduler; auto-import will not run automatically")
    }
  }
 
  async run(): Promise<void> {
    if (!env.importerUrl || !env.importDirectory || !env.autoImportSecret) {
      logger.warn("Missing required configuration for auto-import job (importerUrl, importDirectory, autoImportSecret), skipping")
      return
    }
 
    if (env.fireflyCliToken) {
      logger.info("Triggering Firefly III cron job before auto-import")
      // await AboutService.getCron(env.fireflyCliToken)
      await AboutService.getCron({ client, path: { cliToken: env.fireflyCliToken } })
      logger.info("Firefly III cron job triggered successfully")
    } else {
      logger.warn("FIREFLY_III_CLI_TOKEN is not set, skipping Firefly III cron job trigger")
    }
 
    const params = new URLSearchParams()
    params.set("directory", env.importDirectory)
    params.set("secret", env.autoImportSecret)
 
    const url = `${env.importerUrl}/autoimport?${params.toString()}`
    logger.info("Triggering auto-import at %s/autoimport with directory: %s", env.importerUrl, env.importDirectory)
    const result = await fetch(url, { method: "POST" })
    Iif (!result.ok) {
      throw new Error(`Auto-import request failed with status ${result.status}: ${await result.text()}`)
    }
    logger.info("Auto-import triggered successfully")
 
    const previousNotificationId = await redis.get(AUTOIMPORT_NOTIFICATION_KEY)
    if (previousNotificationId) {
      logger.info("Deleting previous auto-import notification with ID %s", previousNotificationId)
      try {
        await notifier.deleteMessage(previousNotificationId)
      } catch (err) {
        logger.error({ err }, "Failed to delete previous auto-import notification with ID %s", previousNotificationId)
      }
    }
 
    const msg = renderTemplate("auto-import.njk", { importDirectory: env.importDirectory })
    const notificationId = await notifier.sendMessage("Auto Import", msg)
    await redis.set(AUTOIMPORT_NOTIFICATION_KEY, notificationId)
  }
}