identities = db.identity().getIdentities();
for (EntityIdentity identity : identities)
if (replyto == null) {
if (from != null && from.equals(identity.email)) {
Address[] tmp = ref.to;
ref.to = ref.from;
ref.reply = null;
ref.from = tmp;
break;
}
} else if (replyto.equals(identity.email)) {
ref.reply = ref.to;
break;
}
}
EntityFolder drafts;
drafts = db.folder().getFolderByType(account, EntityFolder.DRAFTS);
if (drafts == null)
drafts = db.folder().getPrimaryDrafts();
if (drafts == null)
throw new IllegalArgumentException("no drafts folder");
String body = "";
draft = new EntityMessage();
draft.account = account;
draft.folder = drafts.id;
draft.msgid = EntityMessage.generateMessageId(); // for multiple appends
if (ref == null) {
try {
String to = args.getString("to");
draft.to = (TextUtils.isEmpty(to) ? null : InternetAddress.parse(to));
} catch (AddressException ex) {
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
try {
String cc = args.getString("cc");
draft.cc = (TextUtils.isEmpty(cc) ? null : InternetAddress.parse(cc));
} catch (AddressException ex) {
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
try {
String bcc = args.getString("bcc");
draft.bcc = (TextUtils.isEmpty(bcc) ? null : InternetAddress.parse(bcc));
} catch (AddressException ex) {
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
draft.subject = args.getString("subject");
body = args.getString("body");
if (!TextUtils.isEmpty(body))
body = "" + body.replaceAll("\\r?\\n", "
") + "";
} else {
draft.thread = ref.thread;
if ("reply".equals(action) || "reply_all".equals(action)) {
draft.replying = ref.id;
draft.to = (ref.reply == null || ref.reply.length == 0 ? ref.from : ref.reply);
draft.from = ref.to;
if ("reply_all".equals(action))
draft.cc = ref.cc;
} else if ("forward".equals(action)) {
//msg.replying = ref.id;
draft.from = ref.to;
}
if ("reply".equals(action) || "reply_all".equals(action)) {
String text = "";
if (answer > 0)
text = db.answer().getAnswer(answer).text;
draft.subject = context.getString(R.string.title_subject_reply, ref.subject);
body = String.format("%s
%s %s:
%s",
text.replaceAll("\\r?\\n", "
"),
Html.escapeHtml(new Date().toString()),
Html.escapeHtml(MessageHelper.getFormattedAddresses(draft.to, true)),
HtmlHelper.sanitize(context, ref.read(context), true));
} else if ("forward".equals(action)) {
draft.subject = context.getString(R.string.title_subject_forward, ref.subject);
body = String.format("
%s %s:
%s",
Html.escapeHtml(new Date().toString()),
Html.escapeHtml(MessageHelper.getFormattedAddresses(ref.from, true)),
HtmlHelper.sanitize(context, ref.read(context), true));
}
}
draft.received = new Date().getTime();
draft.seen = false;
draft.ui_seen = false;
draft.ui_hide = false;
draft.ui_found = false;
draft.id = db.message().insertMessage(draft);
draft.write(context, body == null ? "" : body);
ArrayList uris = args.getParcelableArrayList("attachments");
if (uris != null)
for (Uri uri : uris)
addAttachment(context, draft.id, uri);
EntityOperation.queue(db, draft, EntityOperation.ADD);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
EntityOperation.process(context);
return draft;
}
@Override
protected void onLoaded(Bundle args, final EntityMessage draft) {
working = draft.id;
final String action = getArguments().getString("action");
Log.i(Helper.TAG, "Loaded draft id=" + draft.id + " action=" + action);
etTo.setText(MessageHelper.getFormattedAddresses(draft.to, true));
etCc.setText(MessageHelper.getFormattedAddresses(draft.cc, true));
etBcc.setText(MessageHelper.getFormattedAddresses(draft.bcc, true));
etSubject.setText(draft.subject);
etBody.setText(null);
Bundle a = new Bundle();
a.putLong("id", draft.id);
new SimpleTask() {
@Override
protected Spanned onLoad(Context context, Bundle args) throws Throwable {
String body = EntityMessage.read(context, args.getLong("id"));
return Html.fromHtml(body);
}
@Override
protected void onLoaded(Bundle args, Spanned body) {
getActivity().invalidateOptionsMenu();
etBody.setText(body);
etBody.setSelection(0);
}
}.load(FragmentCompose.this, a);
getActivity().invalidateOptionsMenu();
Helper.setViewsEnabled(view, true);
pbWait.setVisibility(View.GONE);
grpHeader.setVisibility(View.VISIBLE);
grpAddresses.setVisibility("reply_all".equals(action) ? View.VISIBLE : View.GONE);
grpMessage.setVisibility(View.VISIBLE);
DB db = DB.getInstance(getContext());
db.identity().liveIdentities(true).removeObservers(getViewLifecycleOwner());
db.identity().liveIdentities(true).observe(getViewLifecycleOwner(), new Observer>() {
@Override
public void onChanged(@Nullable List identities) {
if (identities == null)
identities = new ArrayList<>();
Log.i(Helper.TAG, "Set identities=" + identities.size());
// Sort identities
Collections.sort(identities, new Comparator() {
@Override
public int compare(EntityIdentity i1, EntityIdentity i2) {
return i1.name.compareTo(i2.name);
}
});
// Show identities
IdentityAdapter adapter = new IdentityAdapter(getContext(), identities);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spFrom.setAdapter(adapter);
boolean found = false;
// Select earlier selected identity
if (draft.identity != null)
for (int pos = 0; pos < identities.size(); pos++) {
if (identities.get(pos).id.equals(draft.identity)) {
spFrom.setSelection(pos);
found = true;
break;
}
}
// Select identity matching from address
if (!found && draft.from != null && draft.from.length > 0) {
String from = Helper.canonicalAddress(((InternetAddress) draft.from[0]).getAddress());
for (int pos = 0; pos < identities.size(); pos++) {
if (Helper.canonicalAddress(identities.get(pos).email).equals(from)) {
spFrom.setSelection(pos);
found = true;
break;
}
}
}
// Select primary identity
if (!found)
for (int pos = 0; pos < identities.size(); pos++)
if (identities.get(pos).primary) {
spFrom.setSelection(pos);
break;
}
spFrom.setEnabled(true);
}
});
db.attachment().liveAttachments(draft.id).observe(getViewLifecycleOwner(),
new Observer>() {
@Override
public void onChanged(@Nullable List attachments) {
if (attachments == null)
attachments = new ArrayList<>();
adapter.set(attachments);
if (!free)
grpAttachments.setVisibility(attachments.size() > 0 ? View.VISIBLE : View.GONE);
}
});
db.message().liveMessage(draft.id).observe(getViewLifecycleOwner(), new Observer() {
@Override
public void onChanged(final EntityMessage draft) {
// Draft was deleted
if (draft == null || draft.ui_hide) {
finish();
return;
}
}
});
}
@Override
protected void onException(Bundle args, Throwable ex) {
Toast.makeText(getContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
};
private SimpleTask actionLoader = new SimpleTask() {
@Override
protected EntityMessage onLoad(Context context, Bundle args) throws Throwable {
// Get data
long id = args.getLong("id");
int action = args.getInt("action");
long iid = args.getLong("identity");
String to = args.getString("to");
String cc = args.getString("cc");
String bcc = args.getString("bcc");
String subject = args.getString("subject");
String body = args.getString("body");
EntityMessage draft;
DB db = DB.getInstance(context);
try {
db.beginTransaction();
// Get draft & selected identity
draft = db.message().getMessage(id);
EntityIdentity identity = db.identity().getIdentity(iid);
// Draft deleted by server
if (draft == null)
throw new MessageRemovedException("Draft for action was deleted");
Log.i(Helper.TAG, "Load action id=" + draft.id + " action=" + action);
// Convert data
InternetAddress afrom[] = (identity == null ? null : new InternetAddress[]{new InternetAddress(identity.email, identity.name)});
InternetAddress ato[] = (TextUtils.isEmpty(to) ? null : InternetAddress.parse(to));
InternetAddress acc[] = (TextUtils.isEmpty(cc) ? null : InternetAddress.parse(cc));
InternetAddress abcc[] = (TextUtils.isEmpty(bcc) ? null : InternetAddress.parse(bcc));
// Update draft
draft.identity = (identity == null ? null : identity.id);
draft.from = afrom;
draft.to = ato;
draft.cc = acc;
draft.bcc = abcc;
draft.subject = subject;
draft.received = new Date().getTime();
String pbody = "" + body.replaceAll("\\r?\\n", "
") + "";
// Execute action
if (action == R.id.action_trash) {
draft.ui_seen = true;
draft.ui_hide = true;
db.message().updateMessage(draft);
draft.write(context, pbody);
EntityFolder trash = db.folder().getFolderByType(draft.account, EntityFolder.TRASH);
EntityOperation.queue(db, draft, EntityOperation.MOVE, trash.id);
} else if (action == R.id.action_save) {
db.message().updateMessage(draft);
draft.write(context, pbody);
EntityOperation.queue(db, draft, EntityOperation.ADD);
} else if (action == R.id.action_send || action == R.id.action_encrypt) {
db.message().updateMessage(draft);
draft.write(context, pbody);
// Check data
if (draft.identity == null)
throw new IllegalArgumentException(context.getString(R.string.title_from_missing));
if (draft.to == null && draft.cc == null && draft.bcc == null)
throw new IllegalArgumentException(context.getString(R.string.title_to_missing));
if (action == R.id.action_encrypt) {
if (openPgpConnection == null || !openPgpConnection.isBound())
throw new IllegalArgumentException(getString(R.string.title_no_openpgp));
List tos = new ArrayList<>();
for (InternetAddress ia : ato)
tos.add(ia.getAddress());
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_ENCRYPT);
data.putExtra(OpenPgpApi.EXTRA_USER_IDS, tos.toArray(new String[0]));
data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
Multipart multipart = new MimeMultipart();
BodyPart bpMessage = new MimeBodyPart();
bpMessage.setContent(pbody, "text/html; charset=" + Charset.defaultCharset().name());
multipart.addBodyPart(bpMessage);
List attachments = db.attachment().getAttachments(id);
for (final EntityAttachment attachment : attachments)
if (attachment.available) {
BodyPart bpAttachment = new MimeBodyPart();
bpAttachment.setFileName(attachment.name);
File file = EntityAttachment.getFile(context, attachment.id);
FileDataSource dataSource = new FileDataSource(file);
dataSource.setFileTypeMap(new FileTypeMap() {
@Override
public String getContentType(File file) {
return attachment.type;
}
@Override
public String getContentType(String filename) {
return attachment.type;
}
});
bpAttachment.setDataHandler(new DataHandler(dataSource));
multipart.addBodyPart(bpAttachment);
} else
throw new IllegalArgumentException(context.getString(R.string.title_attachments_missing));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
multipart.writeTo(bos);
ByteArrayInputStream is = new ByteArrayInputStream(bos.toByteArray());
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(context, openPgpConnection.getService());
Intent result = api.executeApi(data, is, os);
int code = result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR);
switch (code) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
Log.i(Helper.TAG, "PGP encrypted");
for (EntityAttachment attachment : attachments)
db.attachment().deleteAttachment(attachment.id);
EntityAttachment attachment = new EntityAttachment();
attachment.message = id;
attachment.sequence = 1;
attachment.name = "encrypted.asc";
attachment.type = "application/octet-stream";
attachment.size = os.size();
attachment.progress = 0;
attachment.id = db.attachment().insertAttachment(attachment);
File file = attachment.getFile(context, attachment.id);
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
os.writeTo(out);
} finally {
if (out != null)
try {
out.close();
} catch (IOException e) {
Log.e(Helper.TAG, e + "\n" + Log.getStackTraceString(e));
}
}
attachment.progress = null;
attachment.available = true;
db.attachment().updateAttachment(attachment);
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
Log.i(Helper.TAG, "PGP user interaction");
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
args.putParcelable("pi", pi);
return null;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
throw new IllegalArgumentException(error.getMessage());
}
}
}
// Save message ID
String msgid = draft.msgid;
// Save attachments
List attachments = db.attachment().getAttachments(draft.id);
for (EntityAttachment attachment : attachments)
if (!attachment.available)
throw new IllegalArgumentException(context.getString(R.string.title_attachments_missing));
// Delete draft (cannot move to outbox)
draft.msgid = null;
draft.ui_hide = true;
db.message().updateMessage(draft);
EntityOperation.queue(db, draft, EntityOperation.DELETE);
// Copy message to outbox
draft.id = null;
draft.folder = db.folder().getOutbox().id;
draft.uid = null;
draft.msgid = msgid;
draft.ui_hide = false;
draft.ui_found = false;
draft.id = db.message().insertMessage(draft);
draft.write(getContext(), action == R.id.action_encrypt ? "" : pbody);
// Restore attachments
for (EntityAttachment attachment : attachments) {
File file = EntityAttachment.getFile(context, attachment.id);
attachment.id = null;
attachment.message = draft.id;
attachment.id = db.attachment().insertAttachment(attachment);
Helper.copy(file, EntityAttachment.getFile(context, attachment.id));
}
EntityOperation.queue(db, draft, EntityOperation.SEND);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
EntityOperation.process(context);
return draft;
}
@Override
protected void onLoaded(Bundle args, EntityMessage draft) {
int action = args.getInt("action");
Log.i(Helper.TAG, "Loaded action id=" + (draft == null ? null : draft.id) + " action=" + action);
Helper.setViewsEnabled(view, true);
getActivity().invalidateOptionsMenu();
if (action == R.id.action_trash) {
autosave = false;
getFragmentManager().popBackStack();
Toast.makeText(getContext(), R.string.title_draft_trashed, Toast.LENGTH_LONG).show();
} else if (action == R.id.action_save) {
if (draft != null)
Toast.makeText(getContext(), R.string.title_draft_saved, Toast.LENGTH_LONG).show();
} else if (action == R.id.action_send || action == R.id.action_encrypt) {
if (draft == null) {
PendingIntent pi = args.getParcelable("pi");
try {
startIntentSenderForResult(
pi.getIntentSender(),
ActivityCompose.REQUEST_OPENPGP,
null, 0, 0, 0,
new Bundle());
} catch (IntentSender.SendIntentException ex) {
Toast.makeText(getContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
} else {
autosave = false;
getFragmentManager().popBackStack();
Toast.makeText(getContext(), R.string.title_queued, Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onException(Bundle args, Throwable ex) {
Helper.setViewsEnabled(view, true);
getActivity().invalidateOptionsMenu();
if (ex instanceof IllegalArgumentException)
Snackbar.make(view, ex.getMessage(), Snackbar.LENGTH_LONG).show();
else
Toast.makeText(getContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
};
public class IdentityAdapter extends ArrayAdapter {
private Context context;
private List identities;
public IdentityAdapter(@NonNull Context context, List identities) {
super(context, 0, identities);
this.context = context;
this.identities = identities;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return getLayout(position, convertView, parent);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getLayout(position, convertView, parent);
}
public View getLayout(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == convertView)
view = LayoutInflater.from(context).inflate(R.layout.spinner_item2, parent, false);
EntityIdentity identity = identities.get(position);
TextView name = view.findViewById(android.R.id.text1);
name.setText(identity.name);
TextView email = view.findViewById(android.R.id.text2);
email.setText(identity.email);
return view;
}
}
}