mail/src/js/controller/write.js

557 lines
18 KiB
JavaScript
Raw Normal View History

define(function(require) {
2013-09-11 16:11:26 -04:00
'use strict';
var angular = require('angular'),
_ = require('underscore'),
2013-09-15 11:05:37 -04:00
appController = require('js/app-controller'),
axe = require('axe'),
2014-06-05 09:26:19 -04:00
aes = require('js/crypto/aes-gcm'),
util = require('js/crypto/util'),
2014-01-15 04:57:28 -05:00
str = require('js/app-config').string,
pgp, emailDao, outbox, keychainDao, auth;
//
// Controller
//
2013-09-12 11:22:17 -04:00
var WriteCtrl = function($scope, $filter, $q) {
pgp = appController._pgp;
auth = appController._auth;
emailDao = appController._emailDao;
2014-02-24 04:14:07 -05:00
outbox = appController._outboxBo;
2014-05-23 04:52:34 -04:00
keychainDao = appController._keychain;
// set default value so that the popover height is correct on init
$scope.keyId = 'XXXXXXXX';
2013-10-12 13:39:09 -04:00
//
// Init
//
2013-11-08 15:55:08 -05:00
$scope.state.writer = {
write: function(replyTo, replyAll, forward) {
$scope.state.lightbox = 'write';
$scope.replyTo = replyTo;
2013-11-08 15:55:08 -05:00
resetFields();
// fill fields depending on replyTo
fillFields(replyTo, replyAll, forward);
$scope.updatePreview();
2014-01-14 10:11:59 -05:00
$scope.verify($scope.to[0]);
2013-11-08 15:55:08 -05:00
},
reportBug: function() {
$scope.state.lightbox = 'write';
resetFields();
reportBug();
$scope.verify($scope.to[0]);
},
2013-11-08 15:55:08 -05:00
close: function() {
$scope.state.lightbox = undefined;
2013-10-18 21:32:00 -04:00
}
2013-11-08 15:55:08 -05:00
};
2013-10-18 21:32:00 -04:00
function resetFields() {
$scope.writerTitle = 'New email';
$scope.to = [];
$scope.showCC = false;
$scope.cc = [];
$scope.showBCC = false;
$scope.bcc = [];
2013-10-21 09:02:54 -04:00
$scope.subject = '';
$scope.body = '';
$scope.ciphertextPreview = '';
$scope.attachments = [];
2013-10-18 21:32:00 -04:00
}
2013-10-12 13:39:09 -04:00
function reportBug() {
var dump = '';
var appender = {
log: function(level, date, component, log) {
// add a tag for the log level
if (level === axe.DEBUG) {
dump += '[DEBUG]';
} else if (level === axe.INFO) {
dump += '[INFO]';
} else if (level === axe.WARN) {
dump += '[WARN]';
} else if (level === axe.ERROR) {
dump += '[ERROR]';
}
dump += '[' + date.toISOString() + ']';
// component is optional
if (component) {
dump += '[' + component + ']';
}
// log may be an error or a string
dump += ' ' + (log || '').toString();
// if an error it is, a stack trace it has. print it, we should.
if (log.stack) {
dump += ' . Stack: ' + log.stack;
}
dump += '\n';
}
};
axe.dump(appender);
$scope.to = [{
address: str.supportAddress
}];
$scope.writerTitle = str.bugReportTitle;
$scope.subject = str.bugReportSubject;
$scope.body = str.bugReportBody + dump;
}
function fillFields(re, replyAll, forward) {
var replyTo, from, sentDate, body;
2013-10-13 07:49:37 -04:00
2013-10-12 13:39:09 -04:00
if (!re) {
return;
}
$scope.writerTitle = (forward) ? 'Forward' : 'Reply';
replyTo = re.replyTo && re.replyTo[0] && re.replyTo[0].address || re.from[0].address;
// fill recipient field and references
if (!forward) {
$scope.to.unshift({
address: replyTo
});
$scope.to.forEach($scope.verify);
$scope.references = (re.references || []);
if (re.id && $scope.references.indexOf(re.id) < 0) {
// references might not exist yet, so use the double concat
$scope.references = $scope.references.concat(re.id);
}
if (re.id) {
$scope.inReplyTo = re.id;
}
}
if (replyAll) {
re.to.concat(re.cc).forEach(function(recipient) {
var me = emailDao._account.emailAddress;
if (recipient.address === me && replyTo !== me) {
// don't reply to yourself
return;
}
$scope.cc.unshift({
address: recipient.address
});
});
// filter duplicates
$scope.cc = _.uniq($scope.cc, function(recipient) {
return recipient.address;
});
$scope.showCC = true;
$scope.cc.forEach($scope.verify);
}
// fill attachments and references on forward
if (forward) {
// create a new array, otherwise removing an attachment will also
// remove it from the original in the mail list as a side effect
$scope.attachments = [].concat(re.attachments);
if (re.id) {
$scope.references = [re.id];
}
}
2013-10-12 13:39:09 -04:00
// fill subject
if (forward) {
$scope.subject = 'Fwd: ' + re.subject;
} else {
$scope.subject = 'Re: ' + ((re.subject) ? re.subject.replace('Re: ', '') : '');
}
2013-10-12 13:39:09 -04:00
// fill text body
from = re.from[0].name || replyTo;
sentDate = $filter('date')(re.sentDate, 'EEEE, MMM d, yyyy h:mm a');
function createString(array) {
var str = '';
array.forEach(function(to) {
str += (str) ? ', ' : '';
str += ((to.name) ? to.name : to.address) + ' <' + to.address + '>';
});
return str;
}
if (forward) {
body = '\n\n' +
'---------- Forwarded message ----------\n' +
'From: ' + re.from[0].name + ' <' + re.from[0].address + '>\n' +
'Date: ' + sentDate + '\n' +
'Subject: ' + re.subject + '\n' +
'To: ' + createString(re.to) + '\n' +
((re.cc && re.cc.length > 0) ? 'Cc: ' + createString(re.cc) + '\n' : '') +
'\n\n';
} else {
body = '\n\n' + sentDate + ' ' + from + ' wrote:\n> ';
}
if (re.body) {
body += re.body.trim().split('\n').join('\n> ').replace(/ >/g, '>');
$scope.body = body;
}
2013-10-12 13:39:09 -04:00
}
//
// Editing headers
//
2014-01-14 10:11:59 -05:00
/**
* Verify email address and fetch its public key
2014-01-14 10:11:59 -05:00
*/
$scope.verify = function(recipient) {
if(!recipient) {
return;
}
// set display to insecure while fetching keys
2014-01-10 15:35:34 -05:00
recipient.key = undefined;
recipient.secure = false;
$scope.checkSendStatus();
2014-01-10 15:35:34 -05:00
// verify email address
if (!util.validateEmailAddress(recipient.address)) {
recipient.secure = undefined;
2014-01-14 10:11:59 -05:00
$scope.checkSendStatus();
2014-01-10 15:35:34 -05:00
return;
}
// keychainDao is undefined in local dev environment
if(keychainDao) {
// check if to address is contained in known public keys
// when we write an email, we always need to work with the latest keys available
keychainDao.refreshKeyForUserId(recipient.address, function(err, key) {
if (err) {
$scope.onError(err);
return;
}
2014-01-13 17:54:53 -05:00
if (key) {
// compare again since model could have changed during the roundtrip
var matchingUserId = _.findWhere(key.userIds, {
emailAddress: recipient.address
});
// compare either primary userId or (if available) multiple IDs
if (key.userId === recipient.address || matchingUserId) {
recipient.key = key;
recipient.secure = true;
}
}
$scope.checkSendStatus();
$scope.$digest();
});
}
};
2014-01-14 10:11:59 -05:00
/**
* Check if it is ok to send an email depending on the invitation state of the addresses
*/
$scope.checkSendStatus = function() {
2014-01-13 17:54:53 -05:00
$scope.okToSend = false;
$scope.sendBtnText = undefined;
2014-01-13 17:54:53 -05:00
$scope.sendBtnSecure = undefined;
2014-01-13 17:54:53 -05:00
var allSecure = true;
var numReceivers = 0;
// count number of receivers and check security
$scope.to.forEach(check);
$scope.cc.forEach(check);
$scope.bcc.forEach(check);
function check(recipient) {
// validate address
if (!util.validateEmailAddress(recipient.address)) {
return;
}
numReceivers++;
if (!recipient.secure) {
allSecure = false;
}
}
// only allow sending if receviers exist
if (numReceivers < 1) {
return;
}
// bcc automatically disables secure sending
if ($scope.bcc.filter(filterEmptyAddresses).length > 0) {
allSecure = false;
}
if (allSecure) {
// send encrypted if all secure
2014-01-13 17:54:53 -05:00
$scope.okToSend = true;
2014-01-15 04:57:28 -05:00
$scope.sendBtnText = str.sendBtnSecure;
2014-01-13 17:54:53 -05:00
$scope.sendBtnSecure = true;
} else {
// send plaintext
$scope.okToSend = true;
$scope.sendBtnText = str.sendBtnClear;
$scope.sendBtnSecure = false;
2014-01-13 17:54:53 -05:00
}
2014-01-14 10:11:59 -05:00
};
2014-02-05 18:41:08 -05:00
//
// Editing attachments
//
$scope.remove = function(attachment) {
$scope.attachments.splice($scope.attachments.indexOf(attachment), 1);
};
//
// Editing email body
2013-10-12 13:39:09 -04:00
//
// generate key,iv for encryption preview
var key = util.random(128),
iv = util.random(128);
$scope.updatePreview = function() {
if (!$scope.sendBtnSecure || !$scope.body.trim()) {
$scope.ciphertextPreview = undefined;
return;
}
2013-09-14 08:23:46 -04:00
// Although this does encrypt live using AES, this is just for show. The plaintext is encrypted seperately before sending the email.
$scope.ciphertextPreview = aes.encrypt($scope.body, key, iv);
};
$scope.$watch('sendBtnSecure', $scope.updatePreview);
2013-09-15 11:05:37 -04:00
$scope.sendToOutbox = function() {
var email;
2013-11-11 10:11:06 -05:00
// build email model for smtp-client
2013-09-15 11:05:37 -04:00
email = {
2014-02-24 04:14:07 -05:00
from: [{
name: emailDao._account.realname,
2014-02-24 04:14:07 -05:00
address: emailDao._account.emailAddress
}],
2014-02-25 08:10:55 -05:00
to: $scope.to.filter(filterEmptyAddresses),
cc: $scope.cc.filter(filterEmptyAddresses),
bcc: $scope.bcc.filter(filterEmptyAddresses),
2014-01-16 05:58:39 -05:00
subject: $scope.subject.trim() ? $scope.subject.trim() : str.fallbackSubject, // Subject line, or the fallback subject, if nothing valid was entered
2014-07-29 08:13:00 -04:00
body: $scope.body.trim(), // use parsed plaintext body
2014-03-06 12:02:05 -05:00
attachments: $scope.attachments,
sentDate: new Date(),
headers: {}
2013-09-15 11:05:37 -04:00
};
if ($scope.inReplyTo) {
email.headers['in-reply-to'] = '<' + $scope.inReplyTo + '>';
}
if ($scope.references && $scope.references.length) {
email.headers.references = $scope.references.map(function(reference) {
return '<' + reference + '>';
}).join(' ');
}
2014-02-25 15:05:59 -05:00
// close the writer
$scope.state.writer.close();
2014-02-24 04:14:07 -05:00
// persist the email to disk for later sending
outbox.put(email, function(err) {
2013-09-15 11:05:37 -04:00
if (err) {
$scope.onError(err);
2013-09-15 11:05:37 -04:00
return;
}
// if we need to synchronize replyTo.answered = true to imap,
// let's do that. otherwise, we're done
if (!$scope.replyTo || $scope.replyTo.answered) {
return;
}
$scope.replyTo.answered = true;
emailDao.setFlags({
folder: currentFolder(),
message: $scope.replyTo
2014-02-24 04:14:07 -05:00
}, function(err) {
if (err && err.code !== 42) {
$scope.onError(err);
2014-02-24 04:14:07 -05:00
return;
}
// offline or no error, let's apply the ui changes
$scope.$apply();
2014-02-24 04:14:07 -05:00
});
});
2014-02-25 08:10:55 -05:00
2014-02-24 04:14:07 -05:00
};
2013-09-11 16:11:26 -04:00
//
// Tag input & Autocomplete
//
2014-09-15 11:10:28 -04:00
$scope.tagStyle = function(recipient) {
var classes = ['label'];
if(recipient.secure === false) {
classes.push('label-primary');
}
return classes;
};
2014-09-15 11:10:28 -04:00
$scope.lookupAddressBook = function(/*query*/) {
var deferred = $q.defer();
deferred.resolve([
{ address: 'john@doe.com' },
{ address: 'jane@doe.com' },
{ address: 'john.doe@example.com' },
{ address: 'jane.doe@example.com' },
{ address: 'max.mustermann@example.com' },
]);
return deferred.promise;
};
//
// Helpers
//
function currentFolder() {
return $scope.state.nav.currentFolder;
}
/*
* Visitor to filter out objects without an address property, i.e. empty addresses
*/
function filterEmptyAddresses(addr) {
return !!addr.address;
}
};
//
// Directives
//
var ngModule = angular.module('write', []);
ngModule.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
// view -> model
2013-10-13 07:49:37 -04:00
elm.on('keyup keydown', function() {
// set model
ctrl.$setViewValue(elm[0].innerText);
scope.$digest();
});
// model -> view
2013-10-12 13:39:09 -04:00
ctrl.$render = function() {
2013-11-26 13:06:37 -05:00
elm[0].innerText = ctrl.$viewValue;
};
// load init value from DOM
2013-11-26 13:06:37 -05:00
ctrl.$setViewValue(elm[0].innerText);
}
};
});
2013-10-12 13:39:09 -04:00
2013-10-19 09:06:23 -04:00
ngModule.directive('focusMe', function($timeout, $parse) {
return {
2013-10-19 09:06:23 -04:00
//scope: true, // optionally create a child scope
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
if (value === true) {
$timeout(function() {
element[0].focus();
}, 100);
2013-10-19 09:06:23 -04:00
}
});
}
};
});
ngModule.directive('focusChild', function() {
return {
//scope: true, // optionally create a child scope
link: function(scope, element) {
element.on('click', function() {
element[0].children[0].focus();
});
}
};
});
ngModule.directive('focusInput', function($timeout, $parse) {
return {
//scope: true, // optionally create a child scope
link: function(scope, element, attrs) {
var model = $parse(attrs.focusInput);
scope.$watch(model, function(value) {
if(value === true) {
$timeout(function() {
element.find('input').first().focus();
}, 100);
}
});
}
};
});
ngModule.directive('focusInputOnClick', function() {
2014-01-10 15:35:34 -05:00
return {
//scope: true, // optionally create a child scope
link: function(scope, element) {
element.on('click', function() {
element.find('input').first().focus();
2014-01-10 15:35:34 -05:00
});
}
};
});
2014-02-05 18:41:08 -05:00
ngModule.directive('attachmentInput', function() {
return function(scope, elm) {
2014-02-05 18:41:08 -05:00
elm.on('change', function(e) {
for (var i = 0; i < e.target.files.length; i++) {
addAttachment(e.target.files.item(i));
}
});
function addAttachment(file) {
var reader = new FileReader();
reader.onload = function(e) {
scope.attachments.push({
2014-02-06 13:19:00 -05:00
filename: file.name,
mimeType: file.type,
content: new Uint8Array(e.target.result)
});
scope.$digest();
};
reader.readAsArrayBuffer(file);
}
};
});
2014-02-05 18:41:08 -05:00
ngModule.directive('attachmentBtn', function() {
return function(scope, elm) {
elm.on('click touchstart', function(e) {
e.preventDefault();
2014-02-05 18:41:08 -05:00
document.querySelector('#attachment-input').click();
});
};
});
2013-09-11 16:11:26 -04:00
return WriteCtrl;
2014-07-23 07:36:21 -04:00
});