save email attachments using Thunderbird source - javascript

I would like to save email attachments using thunderbird source code. I got the following code in your forums..but its not working
alert("Messages selected: " + gFolderDisplay.selectedCount);
let enumerator = gFolderDisplay.selectedMessages;
for each (let msgHdr in fixIterator(enumerator, Ci.nsIMsgDBHdr)) {
var messageID = msgHdr.messageId;
alert("MessageID: " + messageID);
var subject = msgHdr.mime2DecodedSubject;
alert("Subject: " + subject);
MsgHdrToMimeMessage(msgHdr, null, function (aMsgHdr, aMimeMsg) {
try {
alert("Size of the message: " + aMimeMsg.size);
alert("Structure of the message:\n" + aMimeMsg.prettyString(true, undefined, true));
let attachments = aMimeMsg.allUserAttachments || aMimeMsg.allAttachments;
alert("Number of attachments: " + attachments.length);
for (let [index, att] in Iterator(attachments))
{
alert ("URL: " + att.url + " Name: " + att.name);
let ioService = Cc["#mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
let neckoURL = null;
neckoURL = ioService.newURI(att.url, null, null);
neckoURL.QueryInterface(Ci.nsIMsgMessageUrl);
let uri = neckoURL.uri;
let attInfo = new AttachmentInfo(att.contentType, att.url, att.name, uri, att.isExternal);
attInfo.save();
}
} catch (err) {
alert(err);
}
}, true, { examineEncryptedParts: true, });
}
Using above code i can able to go through the selected messages.but not saving the attachments.its showing number of attachments.
And also i would like to set my own labels for the selected mails. How i can i achieve this? Please help me out... Thanks in advance

working code
var enumerator = gFolderDisplay.selectedMessages;
for each (var msgHdr in fixIterator(enumerator, Components.interfaces.nsIMsgDBHdr)) {
msgHdr.setStringProperty("docuHive","dhivelabel");
MsgHdrToMimeMessage(msgHdr, null, function (aMsgHdr, aMimeMsg) {
try {
var attachments = aMimeMsg.allUserAttachments || aMimeMsg.allAttachments;
for (var [index, att] in Iterator(attachments))
{
var ioService = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var neckoURL = null;
neckoURL = ioService.newURI(att.url, null, null);
neckoURL.QueryInterface(Components.interfaces.nsIMsgMessageUrl);
var uri = neckoURL.uri;
var attInfo = new AttachmentInfo(att.contentType, att.url, att.name, uri, att.isExternal);
// getting the chrome directory
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("AChrom", Components.interfaces.nsIFile);
var msguri = msgHdr.folder.getUriForMsg(msgHdr);
messenger = Components.classes["#mozilla.org/messenger;1"]
.createInstance(Components.interfaces.nsIMessenger);
alert(messenger);
messenger.saveAttachmentToFolder(att.contentType,att.url,"attachmentname.extension",msguri,file);
}
} catch (err) {
alert(err);
}
}, true, { examineEncryptedParts: true, });
}

Related

How to send a variable back from foreground.js to background.js

I tried to send my variable back from foreground.js to background.js by using an unchanged variable, and it works. Now I can't send some data that I use my AddEventListener syntax to store the data into the variable to call its back to background.js here are my code on foreground.js
foreground.js
console.log("foreground.js injected");
var pswdBtns = [];
let hrefLists = [];
var data = {};
var i;
function readUUID(){
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
return uid;
}
async function passwordProtected(pointerList){
const date = new Date();
const uid = readUUID();
alert("You are in dangerous on \'"+ pointerList.title + "\' row = " + pointerList.id.slice(20));
data = {
"Webtitle": pointerList.href,
"Title": pointerList.title,
"Time": date.toString(),
"UUID": uid
}
console.log("foreground = ", data);
return data;
}
console.log("Start loop")
//This function made for collect each id in passwordShowPasswordButton
for(i = 0; i<=pswdBtns.length; i++){
if(document.querySelector("#passwordShowPasswordButton_"+ i) == null){
console.log("This is your limit!!");
}
else{
hrefLists[i] = document.querySelector("#passwordWebsitelink_"+ i);
pswdBtns[i] = document.querySelector("#passwordShowPasswordButton_"+ i);;
data = pswdBtns[i].addEventListener('click', passwordProtected.bind(pswdBtns[i], hrefLists[i]));
console.log(hrefLists[i].title); /* Title VARCHAR(30) */
console.log(hrefLists[i].href); /* Website VARCHAR(50) */
}
}
console.log("End");
and these are my code on background.js
background.js
const edgePswd = "edge://settings/passwords";
const settingPage = "edge://settings/";
chrome.tabs.onActivated.addListener(async (tab) => {
await chrome.tabs.get(tab.tabId, (current_tab_info) => {
var pswdPageChecked = 1;
while(pswdPageChecked < 2) {
if (edgePswd == current_tab_info.url) {
chrome.tabs.executeScript(null, { file: "/extension/foreground.js" }, (data) => {
console.log("Coming to foreground");
console.log(data);
});
pswdPageChecked++;
}
}
});
});
It would be a pleasure if someone can figure this.

Editing PDFs with Hummus.js problem with certain pages

i am currently trying to edit a pdf with hummus.js to replace certain placeholder characters in the pdf with others.
This works perfectly fine for almost every page, but for certain pages I get the following error:
TypeError:
pageObject.getDictionary(...).toJSObject(...).Contents.getObjectID is
not a function for:
const textObjectID = pageObject.getDictionary().toJSObject().Contents.getObjectID();
Whenever that error happens and it doesnt work,
pageObject.getDictionary().toJSObject().Contents returns a PDFArray {}, while, when it works, it returns an PDFIndirectObjectReference {}
Does anybody know how I could solve this issue or any other way to edit a pdf that way (replacing certain placeholder characters with others)
UPDATE 1: I can now differentiate between IndirectObjectReferences and arrays containing IndirectObjectReferences, but for some reason it removes all text but keeps the images from pdf pages which i access through these arrays, the rest of the pdf pages still work perfectly fine
async function replacetext(filePath, callback) {
var pageCount = 0;
const modPdfWriter = hummus.createWriterToModify(filePath+'.pdf', { modifiedFilePath: `${filePath}-modified.pdf`, compress: false })
const numPages = modPdfWriter.createPDFCopyingContextForModifiedFile().getSourceDocumentParser().getPagesCount()
var log="";
for (let page = 0; page < numPages; page++) {
const copyingContext = modPdfWriter.createPDFCopyingContextForModifiedFile()
const objectsContext = modPdfWriter.getObjectsContext()
const pageObject = copyingContext.getSourceDocumentParser().parsePage(page)
pageCount = pageCount + 1;
try
{
var replaceTextRight = " " + pageCount.toString();
if(pageCount > 9 && pageCount < 100)
{
replaceTextRight = " " + pageCount.toString();
}
else if(pageCount > 99)
{
replaceTextRight = " " + pageCount.toString();
}
const textStream = copyingContext.getSourceDocumentParser().queryDictionaryObject(pageObject.getDictionary(), 'Contents')
console.log(textStream);
if(textStream.toString() == 'Array')
{
let data = []
streamArray = textStream.toJSArray();
for(var i = 0; i<streamArray.length; i++)
{
var streamo = copyingContext.getSourceDocumentParser().queryArrayObject(textStream, i);
const readStream = copyingContext.getSourceDocumentParser().startReadingFromStream(streamo)
while (readStream.notEnded()) {
const readData = readStream.read(10000)
data = data.concat(readData)
}
var redactedPdfPageAsString = new Buffer.from(data).toString();
var replacedBuffer = replace(redactedPdfPageAsString, "12345", pageCount.toString());
log = log+" \n Replaced " +page +" with " + pageCount.toString();
var replacedBuffer = replace(replacedBuffer, "67890", replaceTextRight);
log = log+" \n Replaced " +page +" with " + replaceTextRight;
var textObjectID = streamArray[i].getObjectID();
objectsContext.startModifiedIndirectObject(textObjectID)
var stream = objectsContext.startUnfilteredPDFStream();
stream.getWriteStream().write(strToByteArray(replacedBuffer));
objectsContext.endPDFStream(stream);
objectsContext.endIndirectObject();
}
}
else
{
let data = []
const readStream = copyingContext.getSourceDocumentParser().startReadingFromStream(textStream)
while (readStream.notEnded()) {
const readData = readStream.read(10000)
data = data.concat(readData)
}
var redactedPdfPageAsString = new Buffer.from(data).toString();
var replacedBuffer = replace(redactedPdfPageAsString, "12345", pageCount.toString());
log = log+" \n Replaced " +page +" with " + pageCount.toString();
var replacedBuffer = replace(replacedBuffer, "67890", replaceTextRight);
log = log+" \n Replaced " +page +" with " + replaceTextRight;
const textObjectID = pageObject.getDictionary().toJSObject().Contents.getObjectID();
var content = pageObject.getDictionary().toJSObject().Contents;
objectsContext.startModifiedIndirectObject(textObjectID)
const stream = objectsContext.startUnfilteredPDFStream();
stream.getWriteStream().write(strToByteArray(replacedBuffer));
objectsContext.endPDFStream(stream);
objectsContext.endIndirectObject();
}
}
catch(e){
console.log(e);
}
}
fs.writeFile('C:\\Users\\Administrator\\Downloads\\PDFModifyDebugging\\PDFWRITELOG.txt', log, function (err) {
if (err) return console.log(err);
console.log('written in file');
});
modPdfWriter.end()
hummus.recrypt(`${filePath}-modified.pdf`, filePath)
callback();
}

Join multiple room in kurento

I want to create an application that allows a user to join multiple video call rooms in kurento.
I wrote the following code:
function joinRooms() {
var userId = document.getElementById('expertid').value;
console.log("UserID = " + userId);
var roomIds = document.getElementById('roomids').value.split(",");//Assume that we have 2 rooms r1 & r2
var userIdAlias = [];
for (var i = 0; i < roomIds.length; i++) {
userIdAlias[i] = userId + "(" + i + ")";
console.log("User alias = " + userIdAlias[i]);
}
var wsUri = 'wss://' + location.host + '/room';
kurento = KurentoRoom(wsUri, function(error, kurento) {
if (error)
return console.log(error);
for (let i = 0; i < roomIds.length; i++) {
//console.log("Start loop Roomid = " + roomId);
rooms[i] = kurento.Room({
room : roomIds[i],
user : userIdAlias[i],
subscribeToStreams : true
});
localStreams[i] = kurento.Stream(rooms[i], {
audio : true,
video : true,
data : true
});
localStreams[i].addEventListener("access-accepted", function() {
var playVideo = function(stream) {
var participantId = stream.getParticipant().getID();
var userId = document.getElementById('expertid').value;
console.log("userId = " + userId + ", participantId = " + participantId);
if (!userIdAlias.includes(participantId)) {
var elementId = "video-" + stream.getGlobalID();
var div = document.createElement('div');
div.setAttribute("id", elementId);
document.getElementById("participants").appendChild(div);
stream.playThumbnail(elementId);
// Check color
var videoTag = document.getElementById("native-" + elementId);
var userId = stream.getGlobalID();
var canvas = document.createElement('CANVAS');
checkColor(videoTag, canvas, userId);
}
}
rooms[i].addEventListener("room-connected", function(){
var j = i;
return function(roomEvent) {
document.getElementById('room-header').innerText = 'ROOM \"'
+ roomIds[j] + '\"';
//document.getElementById('join').style.display = 'none';
document.getElementById('room').style.display = 'block';
localStreams[j].publish();
var streams = roomEvent.streams;
for (var streamsIdx = 0; streamsIdx < streams.length; streamsIdx++) {
playVideo(streams[streamsIdx]);
}
}
});
rooms[i].addEventListener("stream-added", function(streamEvent) {
playVideo(streamEvent.stream);
});
rooms[i].addEventListener("stream-removed", function(streamEvent) {
var element = document.getElementById("video-"
+ streamEvent.stream.getGlobalID());
if (element !== undefined) {
element.parentNode.removeChild(element);
}
});
playVideo(localStreams[i]);
rooms[i].connect();
});
localStreams[i].init();
}
});
}
However, the code does not work. The log in server said that there is only one user request to join room r2 but not r1.
I think the reason is Javascript works with too many asynchronous task so it worked incorrectly.
Can you give some advice about the way to joining multiple rooms in kurento?

Need Help Making Java Script Discord Music Bot

I have tried to use this code to make a discord music bot but i am getting error telling me i need ffmpeg, but how would I implement it into this code?
index.js file
const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require("./config.json");
const ytdl = require('ytdl-core');
var youtube = require('./youtube.js');
var ytAudioQueue = [];
var dispatcher = null;
bot.on('message', function(message) {
var messageParts = message.content.split(' ');
var command = messageParts[0].toLowerCase();
var parameters = messageParts.splice(1, messageParts.length);
switch (command) {
case "-join" :
message.reply("Attempting to join channel " + parameters[0]);
JoinCommand(parameters[0], message);
break;
case "-play" :
PlayCommand(parameters.join(" "), message);
break;
case "-playqueue":
PlayQueueCommand(message);
break;
}
});
function PlayCommand(searchTerm) {
if(bot.voiceConnections.array().length == 0) {
var defaultVoiceChannel = bot.channels.find(val => val.type === 'voice').name;
JoinCommand(defaultVoiceChannel);
}
youtube.search(searchTerm, QueueYtAudioStream);
}
function PlayQueueCommand(message) {
var queueString = "";
for(var x = 0; x < ytAudioQueue.length; x++) {
queueString += ytAudioQueue[x].videoName + ", ";
}
queueString = queueString.substring(0, queueString.length - 2);
message.reply(queueString);
}
function JoinCommand(ChannelName) {
var voiceChannel = GetChannelByName(ChannelName);
if (voiceChannel) {
voiceChannel.join();
console.log("Joined " + voiceChannel.name);
}
return voiceChannel;
}
/* Helper Methods */
function GetChannelByName(name) {
var channel = bot.channels.find(val => val.name === name);
return channel;
}
function QueueYtAudioStream(videoId, videoName) {
var streamUrl = youtube.watchVideoUrl + videoId;
if (!ytAudioQueue.length) {
ytAudioQueue.push(
{
'streamUrl' : streamUrl,
'videoName' : videoName
}
);
console.log('Queued audio ' + videoName);
PlayStream(ytAudioQueue[0].streamUrl);
}
else {
ytAudioQueue.push(
{
'streamUrl' : streamUrl,
'videoName' : videoName
}
);
}
console.log("Queued audio " + videoName);
}
function PlayStream(streamUrl) {
const streamOptions = {seek: 0, volume: 1};
if (streamUrl) {
const stream = ytdl(streamUrl, {filter: 'audioonly'});
if (dispatcher == null) {
var voiceConnection = bot.voiceConnections.first();
if(voiceConnection) {
console.log("Now Playing " + ytAudioQueue[0].videoname);
dispatcher = bot.voiceConnections.first().playStream(stream, streamOptions);
dispatcher.on('end', () => {
dispatcher = null;
PlayNextStreamInQueue();
});
dispatcher.on('error', (err) => {
console.log(err);
});
}
} else {
dispatcher = bot.voiceConnections.first().playStream(stream, streamOptions);
}
}
}
function PlayNextStreamInQueue() {
ytAudioQueue.splice(0, 1);
if (ytAudioQueue.length != 0) {
console.log("now Playing " + ytAudioQueue[0].videoName);
PlayStream(ytAudioQueue[0].streamUrl);
}
}
bot.login(config.token);
youtube.js file
var request = require('superagent');
const API_KEY = "My API KEY";
const WATCH_VIDEO_URL = "https://www.youtube.com/watch?v=";
exports.watchVideoUrl = WATCH_VIDEO_URL;
exports.search = function search(searchKeywords, callback) {
var requestUrl = 'https://www.googleapis.com/youtube/v3/search' + '?part=snippet&q=' + escape(searchKeywords) + '&key=' + API_KEY;
request(requestUrl, (error, response) => {
if (!error && response.statusCode == 200) {
var body = response.body;
if (body.items.length == 0) {
console.log("I Could Not Find Anything!");
return;
}
for (var item of body.items) {
if (item.id.kind == 'youtube#video') {
callback(item.id.videoId, item.snippet.title);
return;
}
}
} else {
console.log("Unexpected error!");
return;
}
});
return;
};
Error I am getting when I try to run code :
Joined General
C:\Discord Bot\node_modules\discord.js\src\client\voice\pcm\FfmpegConverterEngine.
js:80
throw new Error(
^
Error: FFMPEG was not found on your system, so audio cannot be played. Please make
sure FFMPEG is installed and in your PATH.
You need to download/extract FFMPEG and make it as your PATH/System variable[environment variable]
Make sure that you have it as your System variable like this :
The System Variable should named as 'FFMPEG' and should be directed to where the execution(.exe) file is. It should be in a folder called 'bin' in your FFMPEG folder.
You can google/search online on how to add a new System/PATH variable for your specific OS.

json response is not open in new window

I want to open the json response in to the new window, i tried a lot but didn't get ant success, if any one can helps me, it will be appreciated.
this is my app.js code
Titanium.UI.setBackgroundColor('#fff');
var tabGroup = Titanium.UI.createTabGroup();
var login = Titanium.UI.createWindow({
title:'User Authentication Demo',
tabBarHidden:true,
url:'main_windows/login.js'
});
var loginTab = Titanium.UI.createTab({
title:"Login",
window:login
});
tabGroup.addTab(loginTab);
tabGroup.open();
and this is my login.js code
var win = Titanium.UI.currentWindow;
var UserLogin = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'UserLogin',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(UserLogin);
var UserPassword = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'UserPassword',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(UserPassword);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
win.add(loginBtn);
/*
* Login Event Handling
*/
var loginReq = Titanium.Network.createHTTPClient();
var data, User, UserName, UserEmail, UserFirstName, UserLastName, UserAvatar, BioGraphyNative,BioGraphyEnglish,UserPhone,CreatedOn;
loginReq.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
var message = response.message;
var code = response.code;
if (response.data == null) {
alert("Message " + message + "code " + code);
} else {
var win1 = Titanium.UI.createWindow();
win1.open();
User = response.data.User;
UserName = User.UserLogin;
UserEmail = User.UserEmail;
UserFirstName = User.UserFirstName;
UserLastName = User.UserLastName;
UserAvatar = User.UserAvatar;
BioGraphyNative = User.BioGraphyNative;
BioGraphyEnglish = User.BioGraphyEnglish;
UserPhone = User.UserPhone;
CreatedOn = User.CreatedOn;
alert("UserName " + UserName + "UserEmail " + UserEmail);
}
};
loginReq.onerror = function() {
alert("Network error");
};
/*
* Login Button Click Event
*/
loginBtn.addEventListener('click',function(e) {
if (UserLogin.value !== '' && UserPassword.value !== '') {
var win1 = Titanium.UI.createWindow();
loginReq.open("POST", "url");
var params = {
UserLogin: UserLogin.value,
UserPassword: UserPassword.value
};
loginReq.send(params);
} else {
alert("Username/Password are required");
}
});
I am new in titanium, i f any body can helps me it will be very appreciated, and million ton thanks in advance.
Your window object is created but it's empty and has transparent background, so you don't see it on the screen.
You can change your onload to this:
loginReq.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
var message = response.message;
var code = response.code;
if (response.data == null) {
alert("Message " + message + "code " + code);
} else {
var win1 = Titanium.UI.createWindow({
backgroundColor: 'white',
layout: 'vertical',
});
var User = response.data.User;
for (var i in User) {
win1.add(Ti.UI.createLabel({ text: User[i] });
}
win1.open();
}
};
Also look out for JavaScript issues like declaring variable without var statement. Always use and try put all declaration at the beginning of function. To keep it monitored it's good have JSHint or JSLint installed and checking your code on every save.

Categories

Resources