Downloading multiple files and zip - Chrome extension - javascript

Is it possible to download multiple images into the sandbox file system (without the "save as" dialog box, or at-max one saveas dialog) ?
after downloading them, i'd like to ZIP them into one.. is there any javascript archive library?
Thanks in advance..

You can use zip.js for this.
It does already have API for fetching contents to be zipped from HTTP (cf. zip.HttpReader constructor) and for writing generated zip on HTML5 filesystem (cf. zip.FileWriter constructor).
Here is an example using the filesystem API:
index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zip JSON data from the BBC into HTML5 FileSystem</title>
</head>
<body>
<script src="zip.js"></script>
<script src="zip-fs.js"></script>
<script src="zip-ext.js"></script>
<script src="example.js"></script>
</body>
</html>
example.js file:
// create a zip virtual filesystem
var fs = new zip.fs.FS();
// add some files into the zip filesystem
// add the "bbc-music.json" file in the root directory
fs.root.addHttpContent("bbc-music.json",
"http://www.bbc.co.uk/programmes/genres/music.json");
// add the "bbc-learning.json" file in the root directory
fs.root.addHttpContent("bbc-learning.json",
"http://www.bbc.co.uk/programmes/genres/learning.json");
// create a file named "test.zip" in the root directory of the HTML5 filesystem
createFile("test.zip", function(fileEntry) {
// export the zip content into "test.zip" file
fs.root.exportFileEntry(fileEntry, function() {
console.log("done");
});
});
// function to create a file in the HTML5 temporary filesystem
function createFile(filename, callback) {
webkitRequestFileSystem(TEMPORARY, 4 * 1024 * 1024, function(fs) {
fs.root.getFile(filename, { create : true }, callback);
});
}

You can access images as regular parts of some web-pages or download them separately by means of XMLHTTPRequests. After this you can zip them in a single archive using JSZip JavaScript library. The zip can be stored as a file without a "Save As" dialog (try the example on the site). Though I'm not sure why you need the sandbox.
There exist other JavaScript libraries for zipping, for example, some are mentioned in other SO answer.

Related

Use nodejs module in external javascript from the public folder

I included a module in my js file. Now i defined a button in a ejs file, which calls a function in an external js file from the public folder. How can i use the module in this function?
I tried to pass the module as a parameter, but i didn´t work. Is this even the right way to use this module in my external file?
the route js file
var express = require("express");
var router = express.Router();
var R = require("r-integration");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("Upload", { title: "Upload", para: R });
});
module.exports = router;
my ejs file with the button which calls the function loadScript()
Here i also tried to pass the paramter para to the const rModule
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<button onClick="loadScript()">Test Skript</button>
</body>
<script>
const rModule = para;
</script>
<script src="/javascripts/rScriptTest.js"></script>
</html>
the external js file from the public folder.
But here it says, that rModule is not defined.
function loadScript() {
let result = rModule.executeRScript("./RScripts/test.r");
console.log(result);
}
You can't pass a function though an EJS template. It won't serialize cleanly.
You need:
A JS script/module that will run on a browser
A URL for that file (usually provided with express.static)
You fail at the first hurdle. The module you are trying to use describes itself thus:
This is the R-integration API which allows you to execute arbitrary R commands or scripts directly from the node JS environment. This integration works on Windows and GNU/Linux based systems and uses system calls to access the R binary.
There is no way that it is going to achieve that without using Node.js-specific APIs that are not available in the browser.
You could write a web service in Node.js and interact with it using Ajax instead.

How to handle assets like font in a Firebase function

I'm working on a Firebase function for drawing text on image.
First i download locally the image from Cloud Storage and then i use graphics magick to draw text on it and finally upload this new image to Cloud Storage.
Here the Promise to draw text on image:
return new Promise((resolve, reject) => {
gm(tempFilePath)
.font(Roboto)
.drawText(10, 10, "My text here")
.write(newTempFilePath, (err, stdout) => {
if (err) {
console.error('Failed to blur image.', err);
reject(err);
} else {
console.log(stdout);
resolve(stdout);
}
});
});
The problem: How to use custom font here ?
.font(Roboto)
Is it possible to handle an asset file as a font file (Roboto-BoldItalic.ttf) in Firebase function ?
Thx
Can you try the following:
Get the the Roboto-BoldItalic.ttf font file from here: https://github.com/google/fonts/tree/master/apache/roboto.
Under the functions directory, create a fonts folder and paste the Roboto-BoldItalic.ttf file there.
In your code do as follows:
gm(tempFilePath)
.font("./fonts/Roboto-BoldItalic.ttf")
....
Deploy your Cloud Function(s)
Since I write my firebase functions in typescript, my code is compiled to a 'lib' folder. I manually created another subfolder in the 'lib' folder called 'assets'. Then I was able to refer to anything in that folder with the path 'src/assets/...'. (The confusion results from the fact that my firebase functions were compiling to a 'lib' folder but I needed to refer to the file path with 'src' instead of 'lib').
My specific use case was to create a pdf document using pdfkit and I wanted to embed a font file. So with the file now in my 'lib/assets' folder, I could write the following:
doc
.font('src/assets/OpenSans-Regular.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
I'm not sure if this is a best practice, or if there is a way to set up my config to automatically copy files in my source code, but it worked for me!

Loading local HTML with local Javascript Sources in a WKWebView (iOS, Swift)

I am trying to load a local html file in a WKWebView for a iOS app (Swift 4.2). Unfortunately, this local file contains javascript code that does not seem to be executed.
Below is this html file (taken from https://www.verovio.org/tutorial.xhtml?id=topic00):
<html>
<head>
<title>Verovio Hello World! example</title>
<script src="verovio-toolkit.js" type="text/javascript" ></script>
<script src="jquery-3.1.1.min.js" type="text/javascript" ></script>
</head>
<body>
Hello World!
<div id="svg_output"/>
<script type="text/javascript">
var vrvToolkit = new verovio.toolkit();
$.ajax({
url: "Beethoven_StringQuartet_op.18_no.2.mei"
, dataType: "text"
, success: function(data) {
var svg = vrvToolkit.renderData(data);
$("#svg_output").html(svg);
}
});
</script>
</body>
</html>
And below the view controller file written in swift:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
}
}
Files are local under "Build Phases/Copy Bundle Resources" in the project properties. I also tried to put them in a directory but without any success. Below the file organization inside the project.
EDIT: When I change the url in the html file from Beethoven.mei to https://www.verovio.org/gh-tutorial/mei/Beethoven_StringQuartet_op.18_no.2.mei (same file but on Verovio's website), anything works good!!
So:
Local .js resources work fine
The issue comes from jquery not able to load local text file
Any idea on how to make jquery able to load the local file?
Thank you!
M.
According to the docs, loadFileURL does this:
If readAccessURL references a single file, only that file may be loaded by WebKit. If readAccessURL references a directory, files inside that file may be loaded by WebKit.
The url you got is a url of a file, namely the HTML file. You need the url of the directory. You can do this by calling deletingLastPathComponent:
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
First check your index.html file has scr path for js. if like below, that means js files contain in js folder. so you need to add reference to that folder while add to project.
<script src="js/jquery.js"></script>
then get the main resource path like below
let path = Bundle.main.resourcePath! + "/\(folderName)/\(fileName)"
print("path:=",path )
after that load that file to webView
do {
let contents = try String(contentsOfFile: path, encoding: .utf8)
let baseUrl = URL(fileURLWithPath: path)
webView.loadHTMLString(contents as String, baseURL: baseUrl)
} catch {
print ("File HTML error")
}
You can use the loadHTMLString method to load the HTML, as below:
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "html")!
do {
let html = try String(contentsOf: url)
webView.loadHTMLString(html, baseURL: url.deletingLastPathComponent())
} catch ....
The baseURL point to your app directory in file system. You can write in the src property of the script tag relative location that is interpreted as relative to baseURL.

How to mange file system of android mobile using Cordova

For reading the mobile file system, I have used following Cordova code. Its working fine
window.resolveLocalFileSystemURL(path,
function (fileSystem) {
var reader = fileSystem.createReader();
reader.readEntries(
function (entries) {
..
Additionally, I want to provide following functionalities using Cordova
• Creating new folder
• Delete file/ files
• Rename
• Get details
• Remove files/ folders
• Cut, copy and paste – single file and folder / multiple files and folders
• Search function(in depth search like windows explorer)
Could you please provide any suggestion to implement these functionalities/ code blocks?
There are two entry in cordova file API
FileEntry
DirectoryEntry
To perform operation on file e.g-Delete file,Get details of file you have to go to the file FileEntry. Similarly, to perform operation on folder e.g-Delete folder you have to go to the DirectoryEntry. And after going to that entry there are specific methods that you can perform.I just giving example of creating a folder as follows:
fileSystem.root.getDirectory("FolderName", {create: true});
For other operation i refer you to this Documentation:
Phonegap Documentation
As you mentioned window.resolveLocalFileSystemURL,So you are familiar with file plugin of cordova.
These are the things you can achieve using file plugin:-
To create a folder :-
var root = cordova.file.externalDataDirectory;
window.resolveLocalFileSystemURL(root,
function(directoryEntry) {
directoryEntry.getDirectory('your_dir_name',{create:true},successCallBack,errorCallBack);
},function(e){});
To Remove file:-
var root = cordova.file.externalDataDirectory/file.txt;
window.resolveLocalFileSystemURL(root,
function(file) {
file.remove(successCallBack,errorCallBack);
},function(e){});
To Copy/move :-
window.resolveLocalFileSystemURL('YOUR_FILE_PATH/1.txt', function(fs) {
var pathToCopy = cordova.file.externalRootDirectory+"/";
var newName = "NEW_FILE_NAME"; //After copy/Move
window.resolveLocalFileSystemURL(pathToCopy,function(directoryEntry) {
fs.copyTo(directoryEntry, newName, function() {
console.log("File Copied To:"+pathToCopy);
}, failFiles);
});
}, failFiles);
To rename to file you can use both paths same and change the file name.
Hope this helps

How to use webtorrent in browser?

I have some trouble with the the example showed in https://github.com/feross/webtorrent#usage
I'm trying to use the code in browser. So I first create a file called app.js
app.js
var WebTorrent = require('webtorrent')
var concat = require('concat-stream')
var client = new WebTorrent()
console.log('Hi there');
client.download('magnet:?xt=urn:btih:XXXXXXXX', function (torrent) {
// Got torrent metadata!
console.log('Torrent info hash:', torrent.infoHash)
torrent.files.forEach(function (file) {
// Get the file data as a Buffer (Uint8Array typed array)
file.createReadStream().pipe(concat(function (buf) {
// Append a link to download the file
var a = document.createElement('a')
a.download = file.name
a.href = URL.createObjectURL(new Blob([ buf ]))
a.textContent = 'download ' + file.name
document.body.appendChild(a)
}))
})
})
Then I type command browserify app.js > bundle.js so that can make code work for browser. I create another file called index.html:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="bundle.js"></script>
</head>
<body id="home">
<h1>test</h1>
</body>
</html>
From the console I can only see "Hi there". It seems that the client.download() function didn't work. Why this happened? I'm new to browserify, is there anything wrong with the command which I use?
WebTorrent can only download torrents that are explicitly seeded to the WebTorrent network. Torrent clients need to support WebRTC to peer with web browsers. Currently, no clients support it but you can use http://instant.io to start seeding a new torrent and try downloading it using the WebTorrent library in your application. Enable debug logs on http://instant.io by setting `localStorage.debug = '*' to get the info-hash of the torrent.
You can also learn more here:
How does WebTorrent work? (https://github.com/feross/webtorrent/issues/39)
WebRTC BEP (https://github.com/feross/webtorrent/issues/175)

Categories