I am trying to read-in a file and calculate the SHA-256 hash.
The code works on localhost perfectly fine (Chrome and Safari).
As soon as I upload the page on a webserver I will get the following error in Google Chrome:
Uncaught TypeError: Cannot read property 'digest' of undefined
at FileReader.reader.onload (hashDocument.js:40)
However, the webpage works fine in Safari as well as on Android devices.
function convertStringToArrayBufferView(str)
{
var bytes = new Uint8Array(str.length);
for (var iii = 0; iii < str.length; iii++)
{
bytes[iii] = str.charCodeAt(iii);
}
return bytes;
}
function convertArrayBufferToHexaDecimal(buffer)
{
var data_view = new DataView(buffer);
var iii, len, hex = '', c;
for(iii = 0, len = data_view.byteLength; iii < len; iii += 1)
{
c = data_view.getUint8(iii).toString(16);
if(c.length < 2)
{
c = '0' + c;
}
hex += c;
}
return hex;
}
function hashIt() {
var nBytes = 0,
oFiles = document.getElementById("documentIn").files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
//console.log(oFiles[nFileId]);
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
var promise = crypto.subtle.digest({name: "SHA-256"}, convertStringToArrayBufferView(text));
promise.then(function(result){
var hashValue = convertArrayBufferToHexaDecimal(result);
// update input field
console.log("hashValue");
$("#documentHash").val(hashValue);
});
};
reader.readAsText(oFiles[nFileId]);
nBytes += oFiles[nFileId].size;
}
}
Related
I'm trying to create in image generator where I can create all permutations of an image given different elements on 3 layers. I have managed to get the three folders into arrays and am trying to use Jimp to layer them on top of each other to create composite images. But I am failing to find the correct syntax to call the composite command in jimp.
const { jimpEvChange } = require('#jimp/core');
const { composite } = require('jimp');
CombineImagesFrom3Folders("Scenes/","Faces/","Features/");
function CombineImagesFrom3Folders(folder1, folder2, folder3) {
var pngFiles1 = CreatePNGArrayFromFolder(folder1);
var pngFiles2 = CreatePNGArrayFromFolder(folder2);
var pngFiles3 = CreatePNGArrayFromFolder(folder3);
DrawImagesOnTopOfEachOther(pngFiles1, pngFiles2,pngFiles3, "Combined/");
}
function CreatePNGArrayFromFolder(folder) {
var pngFiles = [];
var fs = require('fs');
const newLocal = fs.readdirSync(folder);
var files = newLocal;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.split(".").pop() == "png") {
pngFiles.push(folder + "/" + file);
}
}
return pngFiles;
}
function DrawImagesOnTopOfEachOther(pngs1, pngs2, pngs3, folder) {
const jimp = require('jimp');
var fs = require('fs');
for (var i = 0; i < pngs1.length-1; i++) {
for (var j = 0; j < pngs2.length-1; j++) {
for(var k = 0; k < pngs3.length-1; k++){
// compositing the images
var image1 = jimp.read(pngs1[i]);
var image2 = jimp.read(pngs2[j]);
var image3 = jimp.read(pngs3[k]);
image.composite(image1, image2, image3, (err, image) => {
if (err) throw err;
image.write(folder + "/" + i + j + k + ".png");
}
);
}
}
}
}
I either get an error that "composite is not a function" or if I use "image.composite" then I get the error that "image is not defined", if I define the image as something I get "image.composite is not a function".
Hope someone can help.
James.
It turns out the composite function didn't actually do what I had expected. What I needed to do was do the layers in pairs.
function DrawImagesOnTopOfEachOther(pngs1, pngs2, pngs3, folder) {
var name = "";
for (var i = 0; i < pngs1.length; i++) {
for (var j = 0; j < pngs2.length; j++) {
for(var k = 0; k < pngs3.length; k++){
// loop through colors and colorize the images
for (var l = 0; l < colors.length; l++) {
var color = colors[l];
var image1 = new jimp(pngs1[i]);
var image2 = new jimp(pngs2[j]);
var image3 = new jimp(pngs3[k]);
// compositing the images
name = (folder + i + j + k + l + ".png");
Draw (pngs1, pngs2, pngs3,i,j,k, name);
console.log("Image " + name + " created");
}
}
}
}
}
function Draw (pngs1, pngs2, pngs3,i,j,k, name) {
jimp.read(pngs1[i])
.then(image1 => {
jimp.read(pngs2[j])
.then(image2 => {
jimp.read(pngs3[k])
.then(image3 => {
image1.composite(image2, 0, 0, {
mode: jimp.BLEND_SOURCE_OVER,
opacityDest: 1,
opacitySource: 1
})
image1.composite(image3, 0, 0, {
mode: jimp.BLEND_SOURCE_OVER,
opacityDest: 1,
opacitySource: 1
})
image1.write(name);
console.log("Image " + name + " created");
})
})
})
}
I'm trying to script a converter (image) that pickup the checksum inside a image (form my Server) and add it to the selected image file.
But there I got 2 problems:
First problem:
It just accept jpg files, I tried everythink, but it dont work (png, gif etc.)
The second problem is, that the valid image, need to be from my server (convert.jpg)
But if I do that, I get this error:
TypeError: Argument 1 of FileReader.readAsDataURL is not an
object.
The line:
readerValid.readAsDataURL(valid);
What did I do wrong? (And sry for my bad english)
My Code:
function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
function bytesToHex(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes.charCodeAt(i) >>> 4).toString(16));
hex.push((bytes.charCodeAt(i) & 0xF).toString(16));
}
return hex.join("");
}
function UpdateChecksum(pic, data) {
var string = ""
for (var i = 0; i < data.length; ++i) {
string += String.fromCharCode(data[i])
}
pic = atob(pic.replace(/^data:image\/jpeg;base64,/, ""))
for (var i = 0; i + 1 < pic.length; ++i) {
if (pic.charCodeAt(i) == 0xFF && pic.charCodeAt(i + 1) == 0xDB) {
pic = pic.slice(i, pic.length)
break
}
}
var regexp = new RegExp("(<checksum2>[0-9a-f]{32}</checksum2>)")
var match = regexp.exec(string)
string = string.replace(match[1], "<checksum2>" + bytesToHex(rc4("bns_gamepic", hexToBytes(md5(pic)))) + "</checksum2>")
for (var i = 0; i < data.length; ++i) {
data[i] = string.charCodeAt(i)
}
return data
}
function process() {
if(document.getElementById("custom").value == ""){
document.getElementById('error').innerHTML="Chose Image!";
}
else{
var valid = "convert.jpg";
var custom = document.getElementById('custom').files[0]
var readerValid = new FileReader()
readerValid.onloadend = function(e) {
var exif = piexif.load(e.target.result)
var readerCustom = new FileReader()
readerCustom.onloadend = function(e) {
var image = new Image()
image.onload = function() {
var result
try {
result = piexif.remove(e.target.result)
} catch (err) {
result = e.target.result
}
exif["Exif"][700] = UpdateChecksum(result, exif["Exif"][700])
result = piexif.insert(piexif.dump(exif), result)
download(result, "Converted_Image.jpg", "image/jpeg");
}
image.src = e.target.result
}
readerCustom.readAsDataURL(custom);
};
readerValid.readAsDataURL(valid);
}
}
I hope you can help me
Someone said:
The code var valid = "convert.jpg"; defines valid as a string, but the function readAsDataURL expect an object of type blob as a parameter, not a string.
But:
var valid = new Blob(["convert.jpg"], { type: 'image/jpeg'});
dont work :/
with this code I use to save attachment to a shared google drive folder and got notified when a change happen to it by a mail. All is fine as long as I search for pdf attachments. As I set file:xls the messages returned are far more than expected. Not only, the threads returned by the debug are correct, as well as insert the query in the search filed in Gmail, but the getmessages() returned in this case 38 messages (and attachements! And not only xls but also a pdf) of the query parameters. The conversation view is disabled in Gmail, the only match with this attachments is the from: field.
I tried to change the reference data (by adding newer_than), and nothing changed; I changed the for cycle, and nothing changed. Am I missing something really stupid or is this a kind of bug with xls?
function salvataggioTavoloTecnico(){
var folderName = 'tavoloTecnico';
var p = 0;
var f1s= DriveApp.getFoldersByName(folderName).next().getFiles();
while (f1s.hasNext()) {
var f1 = f1s.next();
p++
} Logger.log(p);
var d = new Date();
d.setDate(d.getDate()-1);
var n = d.getFullYear() + "/" + addZero(d.getMonth()+1) + "/" + addZero(d.getDate());
var query = 'in:anywhere has:attachment filename:XLS newer_than:5d (from:mariano.casillo#mit.gov.it OR from:donato.castigliego#mit.gov.it OR from:luciano.aloia#mit.gov.it)';
//var query = 'in:anywhere has:attachment filename:xls '+ 'after:'+n+' (from:mariano.casillo#mit.gov.it OR from:donato.castigliego#mit.gov.it OR from:luciano.aloia#mit.gov.it)';
var elenco = GmailApp.search(query);
var quanteMail = elenco.length; Logger.log(quanteMail);
labelName = GmailApp.createLabel('Movimenti - Tavolo tecnico');
for (var i = 0 ; i < quanteMail; i++) {
//for ( var i in elenco) {
elenco[i].addLabel(labelName);
var thr = elenco[i];
var nn = thr.getMessageCount();
Logger.log(nn);
var mesgs = thr.getMessages();
var www = mesgs.length;
for(var j = 0 ; j < www ; j ++){
var attachments = mesgs[j].getAttachments();
var rrr = attachments.length;
for(var k = 0 ; k < rrr ; k ++) {
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
DriveApp.getFoldersByName(folderName).next().addFile(file);
}
}
}
var c = 0;
var f2s = DriveApp.getFoldersByName(folderName).next().getFiles();
while (f2s.hasNext()) {
var f2 = f2s.next();
c++
}
if ( c > p) { GmailApp.sendEmail("me#me.com", " avviso "+folderName, "Un nuovo file รจ stato aggiunto")};
}
I still don't know why the search by code return more messages out of the parameters, but I workaround it by search in the "wrong" messages only those I need by parse the date, like this, and now it works:
......
var threads = GmailApp.search(query);
for ( var i in threads) {
threads[i].addLabel(labelName);
var mesgs = threads[i].getMessages();
var www = mesgs.length;
for(var j = 0 ; j < www ; j ++){
if ( mesgs[j].getDate() < d ){} else {
var attachments = mesgs[j].getAttachments();
var rrr = attachments.length;
for(var k = 0 ; k < rrr ; k ++) {
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
DriveApp.getFoldersByName(folderName).next().addFile(file);
}
}
}
}
.......
I'm attempting to build a poker game. The method in question is very simple, and it works when it runs the first time.
This part isn't perfect convention because I'm just using it to test my methods:
var $ = function (id) { return document.getElementById(id); };
var test = function() {
var deck = new POKER.Deck();
var hand = new POKER.Hand();
for (var i = 0; i < 7; i++){
hand.addCard(deck.dealCard());
}
hand.sortByRank();
for (var j = 0; j < 7; j++){
var img = document.createElement("img");
var card = hand.getCardAtIndex(j); //** <------- WORKS HERE**
img.src = card.getImage();
$("images").appendChild(img);
}
var testHand = new POKER.Hand();
testHand = hand.removePairs();
for (var k = 0; k < testHand.length; k++) {
var img2 = document.createElement("img");
var card2 = testHand.getCardAtIndex(k); // **<------FAILS HERE**
img2.src = card2.getImage();
$("handImg").appendChild(img2);
}
};
window.onload = function() {
test();
};
The first and second loop work, and the hand is displayed and everything. When it gets to the last loop, the debugger tells me "TypeError: testHand.getCardAtIndex is not a function"
I was attempting to test the removePairs method (to test for straights more easily), and when watching the variables in the debugger, testHand clearly gets populated correctly. The method seems to work just fine.
getCardAtIndex:
POKER.Hand.prototype.getCardAtIndex = function(index) {
return this.cards[index];
};
removePairs:
POKER.Hand.prototype.removePairs = function(){
var allCards = this.cards;
var tempCards = [];
var uniqueRanks = [];
var unique;
for(var i = 0; i < allCards.length; i++){
unique = true;
for(var j = 0; j < uniqueRanks.length; j++){
if(allCards[i].getRank() == uniqueRanks[j]){
unique = false;
break;
}
}
if(unique){
uniqueRanks.push(allCards[i].getRank());
tempCards.push(allCards[i]);
}
}
return tempCards;
};
I'm completely perplexed.
var testHand = new POKER.Hand();
testHand = hand.removePairs();
hand.removePairs() returns an Array, not a Hand object.
That's why you don't have access to the getCardAtIndex method.
If cards is a public property you could do:
testHand.cards = hand.removePairs();
Or you can have a setter method:
testHand.setCards(hand.removePairs);
Im getting the following error while exporting an html table to excel;
SCRIPT429: Automation server can't create object...
This function was working fine but when i restarted my pc and the the application it stopped working not sure whats going on.
function write_to_excel() {
str = "";
var myTable = document.getElementById('myTable');
var rows = myTable.getElementsByTagName('tr');
var rowCount = myTable.rows.length;
var colCount = myTable.getElementsByTagName("tr")[0]
.getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application"); //Debug shows error at this line
var ExcelWorkbook = ExcelApp.Workbooks.Add();
var ExcelSheet = ExcelWorkbook.ActiveSheet;
ExcelApp.Visible = true;
ExcelSheet.Range("A1", "Z1").Font.Bold = true;
ExcelSheet.Range("A1", "Z1").Font.ColorIndex = 23;
// Format table headers
for ( var i = 0; i < 1; i++) {
for ( var j = 0; j < colCount - 1; j++) {
str = myTable.getElementsByTagName("tr")[i]
.getElementsByTagName("th")[j].innerHTML;
ExcelSheet.Cells(i + 1, j + 1).Value = str;
}
ExcelSheet.Range("A1", "Z1").EntireColumn.AutoFit();
}
for ( var i = 1; i < rowCount; i++) {
for ( var k = 0; k < colCount - 1; k++) {
str = rows[i].getElementsByTagName('td')[k].innerHTML;
ExcelSheet.Cells(i + 1, k + 1).Value = myTable.rows[i].cells[k].innerText;
}
ExcelSheet.Range("A" + i, "Z" + i).WrapText = true;
ExcelSheet.Range("A" + 1, "Z" + i).EntireColumn.AutoFit();
}
return;
}
Automation server can't create object.
Means your ActiveX settings are too high so the code will not run.