how to apply password on the zip file or on the csv in nodejs or javascript - passwords

var csvString = ['rest','test','age'];
var fileName_CSV = "Report_1.csv";
var fileName_ZIP = "Report_1.zip";
var blob = new Blob(dd,{type: application/zip"});
var zip = new JSZip();
zip.file(fileName_CSV,csvString),{type:"blob"};
var content = zip.generate({type:"blob"});
saveAs(content,fileName_ZIP);
I have the json data i have converted it to fit in csv format so i created the csv file with the data then saves it in memory and now zipped the csv file and now i want to apply password on it .. so when we open the zip and try to open the csv it should ask for the user defined password.. and either i want to use java script or nodejs for it... please help

The mini-zip-asm package supports creating zip archives with passwords.
https://www.npmjs.com/package/minizip-asm.js
From the docs:
npm install minizip-asm.js
Example Usage:
var Minizip = require('minizip-asm.js');
var fs = require("fs");
var csvString = new Buffer("Abc~~~");
var mz = new Minizip();
mz.append("Report_1.csv", csvString, {password: "insert-password"});
fs.writeFileSync("Report_1.zip", new Buffer(mz.zip()));

Related

AWS s3 in Rust: Get and store a file - Invalid file header when opening

What I want to do: Download an S3 file (pdf) in a lambda and extract its text, using Rust.
The Error:
ERROR PDF error: Invalid file header
I checked the pdf file in the bucket, downloaded it from the console and everything looks correct, so something is breaking in the way I store the file.
How I am doing it:
let config = aws_config::load_from_env().await;
let client = s3::Client::new(&config);
// Get uploaded object in raw bucket (serde derived the json)
let key = event.records.get(0).unwrap().s3.object.key.clone();
let key = key.replace('+', " ");
let key = percent_encoding::percent_decode_str(&key).decode_utf8().unwrap().to_string();
let content = client
.get_object()
.bucket(raw_bucket_name)
.key(&key)
// .response_content_type("application/pdf") // this did not make any difference
.send()
.await?;
let mut bytes = content.body.into_async_read();
let file = tempfile::NamedTempFile::new()?;
let path = file.into_temp_path();
let mut file = tokio::fs::File::create(&path).await?;
tokio::io::copy(&mut bytes, &mut file).await?;
let content = pdf_extract::extract_text(path)?; // this line breaks
Versions:
tokio = { version = "1", features = ["macros"] }
aws-sdk-s3 = "0.21.0"
aws-config = "0.51.0"
pdf-extract = "0.6.4"
I feel like I misunderstood something in how to store the bytestream, but e.g. https://stackoverflow.com/a/62003659/4986655 do it in the same way afaiks.
Any help or pointers on what the issue might be or how to debug this are very welcome.

how to prompt user with pop-up for where to save zip file

I am using the s3-zip npm package in order to download multiple files from an s3 bucket into a zip file. To do this, I am using the following code taken straight from the documentation https://www.npmjs.com/package/s3-zip:
const fs = require('fs')
const join = require('path').join
const s3Zip = require('s3-zip')
const region = 'bucket-region'
const bucket = 'name-of-s3-bucket'
const folder = 'name-of-bucket-folder/'
const file1 = 'Image A.png'
const file2 = 'Image B.png'
const file3 = 'Image C.png'
const file4 = 'Image D.png'
const output = fs.createWriteStream(join(__dirname, 'use-s3-zip.zip'))
s3Zip
.archive({ region: region, bucket: bucket}, folder, [file1, file2, file3, file4])
.pipe(output)
This works and I am able to download the zip file, but the zip file is automatically downloaded into the location specified by the parameters of createWriteStream. However, when the user downloads the zip file, I want them to be presented with the standard pop-up that allows them to choose where to download the zip file. Does anyone know what code I'll need to allow this?

Create PDF File with DriveApp.createFile with results of UrlFetchApp.fetch

I cannot create a PDF file in my Google Drive from content retrieved using UrlFetchApp.fetch
If I email the same file attached It arrives properly.
Here is my code:
var codigo ="1100016795766";
var url = "http://do.convertapi.com/Web2Pdf";
var headers = {"Content-Type":"multipart/form-data"
};
var payload= {"ApiKey":"xxxxxxxx",
"CUrl":"http://www.correos.cl/SitePages/seguimiento/seguimiento.aspx?envio="+codigo,
"LowQuality":true
}
var options = { "method":"POST",
"headers": headers,
"payload":payload,
"muteHttpExceptions":false
};
var pdf0=UrlFetchApp.fetch(url,options);
//trying several ways
var pdf=pdf0.getContent();
var pdf1=pdf0.getAs('application/pdf');
var pdf2=pdf0.getAs("application/pdf");
var pdf3=pdf0.getContentText();
//Trying several ways, none of them get a valid PDF file
DriveApp.createFile("8track_correos.pdf", pdf, 'application/pdf');
DriveApp.createFile("9track_correos.pdf", pdf0,'application/pdf');
DriveApp.createFile("1track_correos.pdf", pdf1, MimeType.PDF);
DriveApp.createFile("2track_correos.pdf", pdf1, MimeType.PDF);
DriveApp.createFile("4track_correos.pdf", pdf3);
DriveApp.createFile("7track_correos.pdf", pdf2);
DriveApp.createFile("6track_correos.pdf", pdf1);
//The attached file arrives as a good PDF file
MailApp.sendEmail("user#gmail.com", "prueba de enviar PDF", "k", {attachments:[{fileName:prefijo+p_nombre+p_apellido+"track_correos.pdf", content:pdf, mimeType:"application//pdf"}]});
The only createFile() configuration that allows a blob as the file source is:
DriveApp.createFile(blob);
So, you need to use:
var pdf0 = UrlFetchApp.fetch(url,options);
var pdf1 = pdf0.getAs('application/pdf');
var myNewFile = DriveApp.createFile(pdf1);
myNewFile.setName("track_correos.pdf");

How to move generated PDF to a specific folder in Google Drive

Here is the jist of what I want this script to do.
User submits a form using Google Forms
Form Records to Google Sheet
Sheet replaces text and generate Google Document from Template
Template is copied
PDF is created from this template
PDF is emailed
PDF is moved to a specific folder in Google Drive.
I have all of those things to work except the last step. Can someone help us out here? We are using this for a school, and nobody in our (IT) department knows anything about scripts. Through Googling and searching I have come this far. The last step is to get the PDF to move to a specific folder.
Here is the current code:
// MacArthur High School
// Generic PLC Agenda Script
// Created 18 Jul 2014
// Author: Josh Patrick
// Decatur Public Schools #61
// Document Creation - replace docTemplate links with each template link on the PLC Drive.
var docTemplate = "1DSFCE6mFZib0ZTVOgVqPbLYaRwjS-XNsnsZn5RZewsE";
var docName = "PLC Agenda";
// Form Functions (labeled identifiers for Form)
function onFormSubmit(e) {
var TimeStamp = e.values [0]
var MeetingDate = e.values [1];
var MeetingTime = e.values [2];
var MeetingLocation = e.values [3];
var PLCFocus = e.values [4];
var PlannedActions = e.values [5];
var ResourcesNeeded = e.values [6];
var AssignedEmail = "jwpatrick#dps61.org";
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+ MeetingDate)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replacing Text with Form Information
copyBody.replaceText('keyMeetingDate', MeetingDate);
copyBody.replaceText('keyMeetingTime', MeetingTime);
copyBody.replaceText('keyMeetingLocation', MeetingLocation);
copyBody.replaceText('keyPLCFocus' , PLCFocus);
copyBody.replaceText('keyPlannedActions' , PlannedActions);
copyBody.replaceText('keyResourcesNeeded' ResourcesNeeded);
// Copy Document and Save
copyDoc.saveAndClose();
// Generate PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Email
var subject = "ELA PLC Agenda for " + MeetingDate ;
var body = "Attached is the PDF copy of the ELA PLC Agenda for " + MeetingDate;
MailApp.sendEmail(AssignedEmail, subject, body, {htmlBody: body, attachments: pdf});
// Delete Temporary Document
DocsList.getFileById(copyId).setTrashed(true);
}
**** Instead of deleting the temporary document, I want to move it to a specific file in Google Drive. I have looked up the scripts help, but I don't think I have done it correctly. I can get it to copydoc but I cannot get it to move to the right folder.
Any assistance is much appreciated.
addToFolder may fit your need.
developers.google.com/apps-script/reference/docs-list/file#addToFolder(Folder)

SharpZipLib's FastZip doesn't unzip directories on Mac

I'm using the following code on Mac using Mono to unzip a zip file. The zip file contains entries under directories (for example foo/bar.txt). However, in the unzipped directory, instead of creating a directory foo with a file bar.txt, FastZip creates a file foo\bar.txt. How do I get around this?
FastZip fz = new FastZip();
string filePath = #"path\to\myfile.zip";
fz.ExtractZip(filePath, #"path\to\unzip\to", null);
This creates a file foo\bar.txt in path\to\unzip\to.
Apparently cannot use FastZip for this case so I ended up writing my own unzipping mechanism:
string filePath = #"path\to\myfile.zip";
string unzipDir = #"path\to\unzip\to";
using (var zipFile = new ZipFile(filePath))
{
foreach (var zipEntry in zipFile.OfType<ZipEntry>())
{
var unzipPath = Path.Combine(unzipDir, zipEntry.Name);
var directoryPath = Path.GetDirectoryName(unzipPath);
// create directory if needed
if (directoryPath.Length > 0)
{
Directory.CreateDirectory(directoryPath);
}
// unzip the file
var zipStream = zipFile.GetInputStream(zipEntry);
var buffer = new byte[4096];
using (var unzippedFileStream = File.Create(unzipPath))
{
StreamUtils.Copy(zipStream, unzippedFileStream, buffer);
}
}
}
use a forward slash to separate folders when creating the zip