Created
August 23, 2017 15:10
-
-
Save herpiko/42ba0f891d4e890c5305b3317436f7b0 to your computer and use it in GitHub Desktop.
PKITB Stream test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You need to install some modules first : | |
npm install --save string-to-stream stream-chunker ws | |
*/ | |
var WebSocket = require('ws'); | |
var str2Stream = require('string-to-stream'); | |
var chunker = require('stream-chunker'); | |
var PKITBWsHost = "ws://127.0.0.1:30001/s"; | |
var socket; | |
var encrypt = function(message, recipientEmailAddress, contentType) { | |
var self = this; | |
var session; | |
var p7m = ""; | |
if (socket) { | |
socket.close(); | |
delete(socket); | |
} | |
socket = new WebSocket(PKITBWsHost, "p"); | |
socket.onerror = function(e) { | |
console.log(e); | |
} | |
socket.onmessage = function(e) { | |
var result; | |
try { | |
result = JSON.parse(e.data.replace(/\r\n/g,'\n').replace(/\n/g,'\\n').replace(/="/g,'=\\"').replace(/";/g,'\\";').replace(/\"\\n/g,'\\"\\n')); | |
} catch(err) { | |
console.log(err); | |
try { | |
result = JSON.parse(e.data.replace(/\r\n/g,'\n').replace(/\n/g,'\\n')); | |
} catch(err) { | |
console.log(err); | |
console.log(e); | |
} | |
} | |
// First register | |
if (Object.keys(result).length == 1 && result.session) { | |
session = result.session; | |
var stream = str2Stream(message).pipe(chunker(5000, { flush : true, encoding:'utf8'})); | |
stream.on('data', function(chunk) { | |
console.log('onData'); | |
if (chunk && chunk.toString().length > 0) { | |
socket.send(JSON.stringify({ | |
action : 'smime-encrypt', | |
session : session, | |
state : 'update', | |
update : chunk.toString('utf8'), | |
})); | |
} | |
}); | |
stream.on('end', function(){ | |
console.log('onEnd'); | |
socket.send(JSON.stringify({ | |
action : 'smime-encrypt', | |
session : session, | |
state : 'done', | |
contentType : contentType, | |
})); | |
}); | |
} else if (Object.keys(result).length > 1 && result.state && result.state === 'update' && result.update && result.update.length > 0) { | |
// partial | |
console.log('partial'); | |
p7m += result.update; | |
} else if (Object.keys(result).length > 1 && result.state && result.state === 'done') { | |
// done | |
console.log('done'); | |
if (result.update) { | |
p7m += result.update; | |
} | |
console.log(p7m); | |
socket.close(); | |
} else { | |
console.log('else'); | |
} | |
} | |
socket.addEventListener('open', function(event) { | |
socket.send(JSON.stringify({ | |
action : 'smime-encrypt', | |
update : recipientEmailAddress, | |
contentType : contentType, | |
})); | |
}); | |
} | |
encrypt("yo", "sonia@tnisiberlab.xyz", "text/plain"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment