projectb/savexml.js
2023-10-20 16:03:55 +05:30

198 lines
5.1 KiB
JavaScript

const fs = require('fs');
const cheerio = require('cheerio');
const Swal = require('sweetalert2')
const encode = require('./encode')
const path = require('path')
require('dotenv').config();
//Get the value from .env
const isEncrypted = process.env.ENCRYPTED;
// start the Autosave filename take the names in xml folder
////////
function getFilesInFolder(folderName) {
const xmlFilePath = path.join(__dirname, folderName);
try {
const fileNames = fs.readdirSync(xmlFilePath);
const xmlFiles = fileNames.filter((file) => file.endsWith('.xml'));
return xmlFiles;
} catch (error) {
console.error('Error reading folder:', error);
return [];
}
}
//XmlPath get from .env
const xmlPath_ = process.env.XML_FILE_PATH;
const folderName = `/${xmlPath_}`;
const filePaths = [];
const files = getFilesInFolder(folderName);
files.forEach((file) => {
const filePath = file;
filePaths.push(filePath);
});
////////
//end the autosave
function saveXmlToFile(xmlData, filePath,reorder=false) {
console.log(filePath);
// console.log(filePath);
// Check if the file path is provided
if (!filePath) {
console.error('File path is required.');
return;
}
// Write the XML data to the specified file path
fs.writeFileSync(filePath, xmlData, 'utf8', (err) => {
console.log("fs write inside ");
alert("fs write inside")
if (err) {
console.error('Error writing XML file:', err);
} else {
console.log('XML file saved successfully.');
// Clear all data in local storage
localStorage.clear();
}
});
localStorage.clear();
if(reorder){
window.location.reload();
}else{
window.location.href = 'dashboard.html';
}
}
function savexml(UserFilename,reorder=false) {
console.log("reorder",reorder);
// Get the XML string from localStorage
var xmlString = localStorage.getItem("xml");
//check Encrypted or not
var enc = "";
if (isEncrypted === 'YES') {
// Encrypt
enc = encode(xmlString);
} else {
enc = xmlString;
}
//XmlPath get from .env
const xmlPathenv=process.env.XML_FILE_PATH;
const xmlPath = path.join(__dirname, xmlPathenv)
// Get the json string from localStorage for set fileName
var jsonData = localStorage.getItem("json");
// Create a filename using on the subtitle
var xmlfilename = `${UserFilename}.xml`;
// var jsonfilename = `${UserFilename}.json`;
// file path where you want to save the XML file
// const xmlfilePath = process.cwd() + `/${xmlPath}` + xmlfilename;
const xmlfilePath = `${xmlPath}` + xmlfilename;
// const jsonfilePath = process.cwd() + '/xml/' + jsonfilename;
if(reorder){
saveXmlToFile(enc, xmlfilePath,reorder=true);
}else{
// Call the function to save the XML file
saveXmlToFile(enc, xmlfilePath);
}
}
function promptBox() {
var jsonData = localStorage.getItem("json");
var jsonString = JSON.parse(jsonData);
var getTitle = jsonString.question_paper_title;
var RawFileNam = removeHtmlTags(getTitle);
var RawFileName;
if (RawFileNam === "" || RawFileNam === null) {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
let hours = currentDate.getHours();
let ampm = 'AM';
if (hours > 12) {
hours -= 12;
ampm = 'PM';
}
hours = String(hours).padStart(2, '0');
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
// Create a formatted date-time string
const formattedDateTime = `${year}${month}${day}(${hours};${minutes}${ampm})`;
RawFileName = "untitled" +formattedDateTime;
} else {
RawFileName = RawFileNam
}
Swal.fire({
title: 'Enter Filename',
input: 'text',
inputValue: RawFileName,
showCancelButton: true,
showDenyButton: false,
denyButtonText: 'Overwrite',
confirmButtonText: 'Submit',
cancelButtonText: 'Cancel',
inputValidator: (value) => {
// console.log(value);
const entervalue =value+'.xml'
if (!value) {
return 'You need to enter Filename!'
}
else if (value){
const fileexist =fileexists(entervalue);
if(fileexist){
Swal.update({ showDenyButton: true });
return 'This file Name already exists'
}else {
Swal.update({ showDenyButton: false });
}
}
}
}).then((result) => {
// console.log(result);
if (result.isConfirmed) {
const inputValue = result.value
savexml(inputValue)
}else if(result.isDenied){
savexml(RawFileName)
}
})
}
// function using for REMOVE HTML ELEMENT in the String
function removeHtmlTags(inputString) {
const $ = cheerio.load(inputString);
const text = $.text();
return text;
}
//check filename is already exists or not
function fileexists(enteredfilename) {
var nextFilename
for (const files of filePaths) {
nextFilename = files;
if (nextFilename === enteredfilename) {
return true;
}
}
}