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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {CronJob, cronJob} from '@loopback/cron';
import {service} from '@loopback/core';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import SftpClient from 'ssh2-sftp-client';
import {ApCalendarService} from '@logchain/services/scan/ap-calendar.service';
const AP_CALENDAR_FILE_NAME = 'SAESL AP Calendar.xlsx';
@cronJob()
export class ImportApCalendarCronJob extends CronJob {
private readonly DATA_FILE_PATH = path.join(process.cwd(), 'data', AP_CALENDAR_FILE_NAME);
private readonly SFTP_HOST = process.env.PMO_SFTP_HOST ?? '';
private readonly SFTP_PORT = Number(process.env.PMO_SFTP_PORT ?? 22);
private readonly SFTP_USER = process.env.PMO_SFTP_USER ?? '';
private readonly SFTP_PASSWORD = process.env.PMO_SFTP_PASSWORD ?? '';
private readonly SFTP_ENV_DIR = process.env.PMO_SFTP_ENV_DIR ?? 'DEV';
private readonly SFTP_REMOTE_DIR = (process.env.PMO_SFTP_REMOTE_DIR ?? '/SSOT') + '/AP/' + this.SFTP_ENV_DIR;
private readonly SFTP_ARCHIVE_DIR = (process.env.PMO_SFTP_ARCHIVE_DIR ?? '/Archived') + '/AP/' + this.SFTP_ENV_DIR;
constructor(
@service(ApCalendarService)
private apCalendarService: ApCalendarService,
) {
super({
name: 'Import AP Calendar from SFTP',
onTick: async () => {
await this.performCronJob();
},
cronTime: '10 * * * *',
start: true,
});
}
private async downloadApCalendarFileFromSftp(): Promise<string> {
const sftp = new SftpClient();
let isConnected = false;
try {
await sftp.connect({
host: this.SFTP_HOST,
port: this.SFTP_PORT,
username: this.SFTP_USER,
password: this.SFTP_PASSWORD,
});
isConnected = true;
const remoteDirCandidates = [
this.SFTP_REMOTE_DIR,
this.SFTP_REMOTE_DIR.replace(/^\//, ''),
].filter((value, index, self) => value && self.indexOf(value) === index);
let remoteDir = '';
let files: SftpClient.FileInfo[] = [];
for (const candidate of remoteDirCandidates) {
try {
files = await sftp.list(candidate);
remoteDir = candidate;
break;
} catch (err) {
console.warn(`*** Cronjob: ${this.name} - failed to list remote dir ${candidate}:`, err);
}
}
if (!remoteDir) {
throw new Error(`Cannot access remote directory: ${this.SFTP_REMOTE_DIR}`);
}
const targetFile = files
.filter(
file =>
file.type === '-' &&
file.name.toLowerCase() === AP_CALENDAR_FILE_NAME.toLowerCase(),
)
.sort((a, b) => b.modifyTime - a.modifyTime)[0];
if (!targetFile) {
throw new Error(
`File "${AP_CALENDAR_FILE_NAME}" not found in remote directory: ${remoteDir}`,
);
}
const remoteFilePath = `${remoteDir}/${targetFile.name}`;
fs.mkdirSync(path.dirname(this.DATA_FILE_PATH), {recursive: true});
await sftp.get(remoteFilePath, this.DATA_FILE_PATH);
console.log(
`*** Cronjob: ${this.name} - downloaded ${remoteFilePath} to ${this.DATA_FILE_PATH}`,
);
return remoteFilePath;
} finally {
if (isConnected) {
await sftp.end();
}
}
}
private async moveImportedFileToArchive(remoteFilePath: string): Promise<string> {
const sftp = new SftpClient();
let isConnected = false;
try {
await sftp.connect({
host: this.SFTP_HOST,
port: this.SFTP_PORT,
username: this.SFTP_USER,
password: this.SFTP_PASSWORD,
});
isConnected = true;
const archiveDirExists = await sftp.exists(this.SFTP_ARCHIVE_DIR);
if (!archiveDirExists) {
await sftp.mkdir(this.SFTP_ARCHIVE_DIR, true);
}
const fileName = path.posix.basename(remoteFilePath);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const archivedFileName = `${path.parse(fileName).name}_${timestamp}${path.parse(fileName).ext}`;
const archiveFilePath = path.posix.join(this.SFTP_ARCHIVE_DIR, archivedFileName);
await sftp.rename(remoteFilePath, archiveFilePath);
console.log(`*** Cronjob: ${this.name} - moved ${remoteFilePath} to ${archiveFilePath}`);
return archiveFilePath;
} finally {
if (isConnected) {
await sftp.end();
}
}
}
private async zipArchivedFile(archiveFilePath: string): Promise<void> {
const sftp = new SftpClient();
let isConnected = false;
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ap-calendar-archive-'));
const archivedFileName = path.posix.basename(archiveFilePath);
const localArchivedFilePath = path.join(tempDir, archivedFileName);
const zipFileName = `${archivedFileName}.zip`;
const localZipFilePath = path.join(tempDir, zipFileName);
const remoteZipFilePath = path.posix.join(path.posix.dirname(archiveFilePath), zipFileName);
try {
await sftp.connect({
host: this.SFTP_HOST,
port: this.SFTP_PORT,
username: this.SFTP_USER,
password: this.SFTP_PASSWORD,
});
isConnected = true;
await sftp.get(archiveFilePath, localArchivedFilePath);
await this.createZipFromSingleFile(localArchivedFilePath, localZipFilePath, archivedFileName);
await sftp.put(localZipFilePath, remoteZipFilePath);
await sftp.delete(archiveFilePath);
console.log(`*** Cronjob: ${this.name} - zipped ${archiveFilePath} to ${remoteZipFilePath}`);
} finally {
if (isConnected) {
await sftp.end();
}
if (fs.existsSync(localArchivedFilePath)) {
fs.unlinkSync(localArchivedFilePath);
}
if (fs.existsSync(localZipFilePath)) {
fs.unlinkSync(localZipFilePath);
}
fs.rmdirSync(tempDir, {recursive: true});
}
}
private async createZipFromSingleFile(
inputFilePath: string,
outputZipPath: string,
archivedEntryName: string,
): Promise<void> {
const archiver = require('archiver');
await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputZipPath);
const archive = archiver('zip', {zlib: {level: 9}});
output.on('close', () => resolve());
output.on('error', (err: Error) => reject(err));
archive.on('error', (err: Error) => reject(err));
archive.pipe(output);
archive.file(inputFilePath, {name: archivedEntryName});
archive.finalize();
});
}
async performCronJob() {
const startAt = new Date();
console.log(`*** Cronjob: ${this.name} started at ${startAt}`);
try {
const remoteFilePath = await this.downloadApCalendarFileFromSftp();
if (!fs.existsSync(this.DATA_FILE_PATH)) {
console.warn(
`*** Cronjob: ${this.name} - data file not found at ${this.DATA_FILE_PATH}`,
);
return;
}
const result = await this.apCalendarService.importExcel();
console.log(
`*** Cronjob: ${this.name} - import complete:`,
`inserted=${result.inserted}`,
`updated=${result.updated}`,
`skipped=${result.skipped}`,
`total=${result.total}`,
);
const archivedFilePath = await this.moveImportedFileToArchive(remoteFilePath);
await this.zipArchivedFile(archivedFilePath);
} catch (err) {
console.error(`*** Cronjob: ${this.name} - error:`, err);
}
const finishedAt = new Date();
console.log(`*** Cronjob: ${this.name} finished at ${finishedAt}`);
}
} |