Browse Source

Store attachments as files

main
M66B 6 years ago
parent
commit
951bdfab67
11 changed files with 230 additions and 222 deletions
  1. +6
    -6
      app/schemas/eu.faircode.email.DB/1.json
  2. +64
    -100
      app/src/main/java/eu/faircode/email/AdapterAttachment.java
  3. +10
    -22
      app/src/main/java/eu/faircode/email/DaoAttachment.java
  4. +2
    -2
      app/src/main/java/eu/faircode/email/EntityAttachment.java
  5. +48
    -28
      app/src/main/java/eu/faircode/email/FragmentCompose.java
  6. +2
    -2
      app/src/main/java/eu/faircode/email/FragmentMessage.java
  7. +30
    -14
      app/src/main/java/eu/faircode/email/MessageHelper.java
  8. +46
    -27
      app/src/main/java/eu/faircode/email/ServiceSynchronize.java
  9. +0
    -19
      app/src/main/java/eu/faircode/email/TupleAttachment.java
  10. +21
    -1
      app/src/main/res/layout/item_attachment.xml
  11. +1
    -1
      app/src/main/res/xml/fileprovider_paths.xml

+ 6
- 6
app/schemas/eu.faircode.email.DB/1.json View File

@ -2,7 +2,7 @@
"formatVersion": 1, "formatVersion": 1,
"database": { "database": {
"version": 1, "version": 1,
"identityHash": "984985d3928b4abdec0802b65e820b2b",
"identityHash": "0b5e9888b548ea410934b7082b08a3b6",
"entities": [ "entities": [
{ {
"tableName": "identity", "tableName": "identity",
@ -569,7 +569,7 @@
}, },
{ {
"tableName": "attachment", "tableName": "attachment",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` INTEGER NOT NULL, `sequence` INTEGER NOT NULL, `name` TEXT, `type` TEXT NOT NULL, `size` INTEGER, `progress` INTEGER, `content` BLOB, FOREIGN KEY(`message`) REFERENCES `message`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` INTEGER NOT NULL, `sequence` INTEGER NOT NULL, `name` TEXT, `type` TEXT NOT NULL, `size` INTEGER, `progress` INTEGER, `filename` TEXT, FOREIGN KEY(`message`) REFERENCES `message`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [ "fields": [
{ {
"fieldPath": "id", "fieldPath": "id",
@ -614,9 +614,9 @@
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "content",
"columnName": "content",
"affinity": "BLOB",
"fieldPath": "filename",
"columnName": "filename",
"affinity": "TEXT",
"notNull": false "notNull": false
} }
], ],
@ -752,7 +752,7 @@
], ],
"setupQueries": [ "setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"984985d3928b4abdec0802b65e820b2b\")"
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"0b5e9888b548ea410934b7082b08a3b6\")"
] ]
} }
} }

+ 64
- 100
app/src/main/java/eu/faircode/email/AdapterAttachment.java View File

@ -25,7 +25,7 @@ import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.text.TextUtils;
import android.preference.PreferenceManager;
import android.util.Log; import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@ -36,7 +36,6 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
@ -52,15 +51,18 @@ import androidx.recyclerview.widget.RecyclerView;
public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.ViewHolder> { public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.ViewHolder> {
private Context context; private Context context;
private LifecycleOwner owner; private LifecycleOwner owner;
private boolean debug;
private List<TupleAttachment> all = new ArrayList<>();
private List<TupleAttachment> filtered = new ArrayList<>();
private List<EntityAttachment> all = new ArrayList<>();
private List<EntityAttachment> filtered = new ArrayList<>();
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View itemView; View itemView;
TextView tvName; TextView tvName;
TextView tvSize; TextView tvSize;
ImageView ivStatus; ImageView ivStatus;
TextView tvType;
TextView tvFile;
ProgressBar progressbar; ProgressBar progressbar;
ViewHolder(View itemView) { ViewHolder(View itemView) {
@ -70,6 +72,8 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
tvName = itemView.findViewById(R.id.tvName); tvName = itemView.findViewById(R.id.tvName);
tvSize = itemView.findViewById(R.id.tvSize); tvSize = itemView.findViewById(R.id.tvSize);
ivStatus = itemView.findViewById(R.id.ivStatus); ivStatus = itemView.findViewById(R.id.ivStatus);
tvType = itemView.findViewById(R.id.tvType);
tvFile = itemView.findViewById(R.id.tvFile);
progressbar = itemView.findViewById(R.id.progressbar); progressbar = itemView.findViewById(R.id.progressbar);
} }
@ -81,28 +85,33 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
itemView.setOnClickListener(null); itemView.setOnClickListener(null);
} }
private void bindTo(TupleAttachment attachment) {
private void bindTo(EntityAttachment attachment) {
tvName.setText(attachment.name); tvName.setText(attachment.name);
if (attachment.size != null) if (attachment.size != null)
tvSize.setText(Helper.humanReadableByteCount(attachment.size, false)); tvSize.setText(Helper.humanReadableByteCount(attachment.size, false));
tvSize.setVisibility(attachment.size == null ? View.GONE : View.VISIBLE); tvSize.setVisibility(attachment.size == null ? View.GONE : View.VISIBLE);
if (attachment.progress != null)
progressbar.setProgress(attachment.progress);
progressbar.setVisibility(
attachment.progress == null || attachment.content ? View.GONE : View.VISIBLE);
if (attachment.content) {
ivStatus.setImageResource(R.drawable.baseline_visibility_24);
ivStatus.setVisibility(View.VISIBLE);
} else {
if (attachment.filename == null) {
if (attachment.progress == null) { if (attachment.progress == null) {
ivStatus.setImageResource(R.drawable.baseline_get_app_24); ivStatus.setImageResource(R.drawable.baseline_get_app_24);
ivStatus.setVisibility(View.VISIBLE); ivStatus.setVisibility(View.VISIBLE);
} else } else
ivStatus.setVisibility(View.GONE); ivStatus.setVisibility(View.GONE);
} else {
ivStatus.setImageResource(R.drawable.baseline_visibility_24);
ivStatus.setVisibility(View.VISIBLE);
} }
if (attachment.progress != null)
progressbar.setProgress(attachment.progress);
progressbar.setVisibility(
attachment.progress == null || attachment.filename != null ? View.GONE : View.VISIBLE);
tvType.setText(attachment.type);
tvFile.setText(attachment.filename);
tvType.setVisibility(debug ? View.VISIBLE : View.GONE);
tvFile.setVisibility(debug ? View.VISIBLE : View.GONE);
} }
@Override @Override
@ -110,82 +119,9 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
int pos = getAdapterPosition(); int pos = getAdapterPosition();
if (pos == RecyclerView.NO_POSITION) if (pos == RecyclerView.NO_POSITION)
return; return;
final TupleAttachment attachment = filtered.get(pos);
final EntityAttachment attachment = filtered.get(pos);
if (attachment != null) if (attachment != null)
if (attachment.content) {
// Build file name
final File dir = new File(context.getCacheDir(), "attachments");
final File file = new File(dir, TextUtils.isEmpty(attachment.name)
? "attachment_" + attachment.id
: attachment.name.toLowerCase().replaceAll("[^a-zA-Z0-9-.]", "_"));
// https://developer.android.com/reference/android/support/v4/content/FileProvider
Uri uri = FileProvider.getUriForFile(context, "eu.faircode.email", file);
// Build intent
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
//intent.setType(attachment.type);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.i(Helper.TAG, "Sharing " + file + " type=" + attachment.type);
// Set permissions
List<ResolveInfo> targets = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : targets)
context.grantUriPermission(resolveInfo.activityInfo.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Check if viewer available
if (targets.size() == 0) {
Toast.makeText(context, R.string.title_no_viewer, Toast.LENGTH_LONG).show();
return;
}
Bundle args = new Bundle();
args.putLong("id", attachment.id);
args.putSerializable("file", file);
args.putSerializable("dir", dir);
// View
new SimpleTask<Void>() {
@Override
protected Void onLoad(Context context, Bundle args) throws Throwable {
long id = args.getLong("id");
File file = (File) args.getSerializable("file");
File dir = (File) args.getSerializable("dir");
// Create file
if (!file.exists()) {
dir.mkdir();
file.createNewFile();
// Get attachment content
byte[] content = DB.getInstance(context).attachment().getContent(id);
// Write attachment content to file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content);
} finally {
if (fos != null)
fos.close();
}
}
return null;
}
@Override
protected void onLoaded(Bundle args, Void data) {
context.startActivity(intent);
}
@Override
protected void onException(Bundle args, Throwable ex) {
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}.load(context, owner, args);
} else {
if (attachment.filename == null) {
if (attachment.progress == null) { if (attachment.progress == null) {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putLong("id", attachment.id); args.putLong("id", attachment.id);
@ -219,6 +155,33 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
} }
}.load(context, owner, args); }.load(context, owner, args);
} }
} else {
// Build file name
File dir = new File(context.getFilesDir(), "attachments");
File file = new File(dir, attachment.filename);
// https://developer.android.com/reference/android/support/v4/content/FileProvider
Uri uri = FileProvider.getUriForFile(context, "eu.faircode.email", file);
// Build intent
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType(attachment.type);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.i(Helper.TAG, "Sharing " + file + " type=" + attachment.type);
// Set permissions
List<ResolveInfo> targets = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : targets)
context.grantUriPermission(resolveInfo.activityInfo.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Check if viewer available
if (targets.size() == 0) {
Toast.makeText(context, R.string.title_no_viewer, Toast.LENGTH_LONG).show();
return;
}
context.startActivity(intent);
} }
} }
} }
@ -226,15 +189,16 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
AdapterAttachment(Context context, LifecycleOwner owner) { AdapterAttachment(Context context, LifecycleOwner owner) {
this.context = context; this.context = context;
this.owner = owner; this.owner = owner;
this.debug = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("debug", false);
setHasStableIds(true); setHasStableIds(true);
} }
public void set(@NonNull List<TupleAttachment> attachments) {
public void set(@NonNull List<EntityAttachment> attachments) {
Log.i(Helper.TAG, "Set attachments=" + attachments.size()); Log.i(Helper.TAG, "Set attachments=" + attachments.size());
Collections.sort(attachments, new Comparator<TupleAttachment>() {
Collections.sort(attachments, new Comparator<EntityAttachment>() {
@Override @Override
public int compare(TupleAttachment a1, TupleAttachment a2) {
public int compare(EntityAttachment a1, EntityAttachment a2) {
return a1.sequence.compareTo(a2.sequence); return a1.sequence.compareTo(a2.sequence);
} }
}); });
@ -272,10 +236,10 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
} }
private class MessageDiffCallback extends DiffUtil.Callback { private class MessageDiffCallback extends DiffUtil.Callback {
private List<TupleAttachment> prev;
private List<TupleAttachment> next;
private List<EntityAttachment> prev;
private List<EntityAttachment> next;
MessageDiffCallback(List<TupleAttachment> prev, List<TupleAttachment> next) {
MessageDiffCallback(List<EntityAttachment> prev, List<EntityAttachment> next) {
this.prev = prev; this.prev = prev;
this.next = next; this.next = next;
} }
@ -292,15 +256,15 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
@Override @Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
TupleAttachment a1 = prev.get(oldItemPosition);
TupleAttachment a2 = next.get(newItemPosition);
EntityAttachment a1 = prev.get(oldItemPosition);
EntityAttachment a2 = next.get(newItemPosition);
return a1.id.equals(a2.id); return a1.id.equals(a2.id);
} }
@Override @Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
TupleAttachment a1 = prev.get(oldItemPosition);
TupleAttachment a2 = next.get(newItemPosition);
EntityAttachment a1 = prev.get(oldItemPosition);
EntityAttachment a2 = next.get(newItemPosition);
return a1.equals(a2); return a1.equals(a2);
} }
} }
@ -325,7 +289,7 @@ public class AdapterAttachment extends RecyclerView.Adapter<AdapterAttachment.Vi
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.unwire(); holder.unwire();
TupleAttachment attachment = filtered.get(position);
EntityAttachment attachment = filtered.get(position);
holder.bindTo(attachment); holder.bindTo(attachment);
holder.wire(); holder.wire();


+ 10
- 22
app/src/main/java/eu/faircode/email/DaoAttachment.java View File

@ -29,48 +29,36 @@ import androidx.room.Update;
@Dao @Dao
public interface DaoAttachment { public interface DaoAttachment {
@Query("SELECT attachment.id, attachment.message, sequence, name, type, size, progress" +
", (NOT content IS NULL) as content" +
" FROM attachment" +
@Query("SELECT * FROM attachment" +
" WHERE message = :id" + " WHERE message = :id" +
" ORDER BY sequence") " ORDER BY sequence")
LiveData<List<TupleAttachment>> liveAttachments(long id);
LiveData<List<EntityAttachment>> liveAttachments(long id);
@Query("SELECT attachment.id, attachment.message, sequence, name, type, size, progress" +
", (NOT content IS NULL) as content" +
" FROM attachment" +
@Query("SELECT attachment.* FROM attachment" +
" JOIN message ON message.id = attachment.message" + " JOIN message ON message.id = attachment.message" +
" WHERE folder = :folder" + " WHERE folder = :folder" +
" AND msgid = :msgid" + " AND msgid = :msgid" +
" ORDER BY sequence") " ORDER BY sequence")
LiveData<List<TupleAttachment>> liveAttachments(long folder, String msgid);
@Query("SELECT * FROM attachment" +
" WHERE message = :message" +
" AND sequence = :sequence")
EntityAttachment getAttachment(long message, int sequence);
LiveData<List<EntityAttachment>> liveAttachments(long folder, String msgid);
@Query("SELECT COUNT(attachment.id)" + @Query("SELECT COUNT(attachment.id)" +
" FROM attachment" + " FROM attachment" +
" WHERE message = :message") " WHERE message = :message")
int getAttachmentCount(long message); int getAttachmentCount(long message);
@Query("SELECT SUM(CASE WHEN content IS NULL THEN 1 ELSE 0 END)" +
" FROM attachment" +
" WHERE message = :message")
int getAttachmentCountWithoutContent(long message);
@Query("SELECT id, message, sequence, name, type, size, progress, NULL AS content FROM attachment" +
@Query("SELECT * FROM attachment" +
" WHERE message = :message" + " WHERE message = :message" +
" ORDER BY sequence") " ORDER BY sequence")
List<EntityAttachment> getAttachments(long message); List<EntityAttachment> getAttachments(long message);
@Query("SELECT * FROM attachment" +
" WHERE message = :message" +
" AND sequence = :sequence")
EntityAttachment getAttachment(long message, int sequence);
@Query("UPDATE attachment SET progress = :progress WHERE id = :id") @Query("UPDATE attachment SET progress = :progress WHERE id = :id")
void setProgress(long id, int progress); void setProgress(long id, int progress);
@Query("SELECT content FROM attachment WHERE id = :id")
byte[] getContent(long id);
@Insert @Insert
long insertAttachment(EntityAttachment attachment); long insertAttachment(EntityAttachment attachment);


+ 2
- 2
app/src/main/java/eu/faircode/email/EntityAttachment.java View File

@ -54,7 +54,7 @@ public class EntityAttachment {
public String type; public String type;
public Integer size; public Integer size;
public Integer progress; public Integer progress;
public byte[] content;
public String filename;
@Ignore @Ignore
BodyPart part; BodyPart part;
@ -69,7 +69,7 @@ public class EntityAttachment {
this.type.equals(other.type) && this.type.equals(other.type) &&
(this.size == null ? other.size == null : this.size.equals(other.size)) && (this.size == null ? other.size == null : this.size.equals(other.size)) &&
(this.progress == null ? other.progress == null : this.progress.equals(other.progress)) && (this.progress == null ? other.progress == null : this.progress.equals(other.progress)) &&
(this.content == null ? other.content == null : other.content != null));
(this.filename == null ? other.filename == null : this.filename.equals(other.filename)));
} else } else
return false; return false;
} }


+ 48
- 28
app/src/main/java/eu/faircode/email/FragmentCompose.java View File

@ -50,9 +50,12 @@ import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import java.io.ByteArrayOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -412,37 +415,58 @@ public class FragmentCompose extends FragmentEx {
attachment.progress = 0; attachment.progress = 0;
attachment.id = db.attachment().insertAttachment(attachment); attachment.id = db.attachment().insertAttachment(attachment);
Log.i(Helper.TAG, "Created attachment seq=" + attachment.sequence + " name=" + attachment.name);
Log.i(Helper.TAG, "Created attachment seq=" + attachment.sequence +
" name=" + attachment.name + " type=" + attachment.type);
db.setTransactionSuccessful(); db.setTransactionSuccessful();
} finally { } finally {
db.endTransaction(); db.endTransaction();
} }
InputStream is = null;
try { try {
is = context.getContentResolver().openInputStream(uri);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE];
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
// Update progress
if (attachment.size != null) {
attachment.progress = os.size() * 100 / attachment.size;
db.attachment().updateAttachment(attachment);
File dir = new File(context.getFilesDir(), "attachments");
dir.mkdir();
File file = new File(dir, Long.toString(attachment.id));
InputStream is = null;
OutputStream os = null;
try {
is = context.getContentResolver().openInputStream(uri);
os = new BufferedOutputStream(new FileOutputStream(file));
int size = 0;
byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
size += len;
os.write(buffer, 0, len);
// Update progress
if (attachment.size != null) {
attachment.progress = size * 100 / attachment.size;
db.attachment().updateAttachment(attachment);
}
}
attachment.size = size;
attachment.progress = null;
attachment.filename = file.getName();
} finally {
try {
if (is != null)
is.close();
} finally {
if (os != null)
os.close();
} }
} }
attachment.size = os.size();
db.attachment().updateAttachment(attachment);
} catch (Throwable ex) {
// Reset progress on failure
attachment.progress = null; attachment.progress = null;
attachment.content = os.toByteArray();
attachment.filename = null;
db.attachment().updateAttachment(attachment); db.attachment().updateAttachment(attachment);
} finally {
if (is != null)
is.close();
throw ex;
} }
return null; return null;
@ -594,9 +618,9 @@ public class FragmentCompose extends FragmentEx {
DB db = DB.getInstance(getContext()); DB db = DB.getInstance(getContext());
db.attachment().liveAttachments(draft.folder, draft.msgid).observe(getViewLifecycleOwner(), db.attachment().liveAttachments(draft.folder, draft.msgid).observe(getViewLifecycleOwner(),
new Observer<List<TupleAttachment>>() {
new Observer<List<EntityAttachment>>() {
@Override @Override
public void onChanged(@Nullable List<TupleAttachment> attachments) {
public void onChanged(@Nullable List<EntityAttachment> attachments) {
if (attachments != null) if (attachments != null)
adapter.set(attachments); adapter.set(attachments);
grpAttachments.setVisibility(attachments != null && attachments.size() > 0 ? View.VISIBLE : View.GONE); grpAttachments.setVisibility(attachments != null && attachments.size() > 0 ? View.VISIBLE : View.GONE);
@ -794,8 +818,6 @@ public class FragmentCompose extends FragmentEx {
// Save attachments // Save attachments
List<EntityAttachment> attachments = db.attachment().getAttachments(draft.id); List<EntityAttachment> attachments = db.attachment().getAttachments(draft.id);
for (EntityAttachment attachment : attachments)
attachment.content = db.attachment().getContent(attachment.id);
// Delete previous draft // Delete previous draft
draft.msgid = null; draft.msgid = null;
@ -829,16 +851,14 @@ public class FragmentCompose extends FragmentEx {
if (draft.to == null && draft.cc == null && draft.bcc == null) if (draft.to == null && draft.cc == null && draft.bcc == null)
throw new IllegalArgumentException(context.getString(R.string.title_to_missing)); throw new IllegalArgumentException(context.getString(R.string.title_to_missing));
if (db.attachment().getAttachmentCountWithoutContent(draft.id) > 0)
throw new IllegalArgumentException(context.getString(R.string.title_attachments_missing));
// Save message ID // Save message ID
String msgid = draft.msgid; String msgid = draft.msgid;
// Save attachments // Save attachments
List<EntityAttachment> attachments = db.attachment().getAttachments(draft.id); List<EntityAttachment> attachments = db.attachment().getAttachments(draft.id);
for (EntityAttachment attachment : attachments) for (EntityAttachment attachment : attachments)
attachment.content = db.attachment().getContent(attachment.id);
if (attachment.filename == null)
throw new IllegalArgumentException(context.getString(R.string.title_attachments_missing));
// Delete draft (cannot move to outbox) // Delete draft (cannot move to outbox)
draft.msgid = null; draft.msgid = null;


+ 2
- 2
app/src/main/java/eu/faircode/email/FragmentMessage.java View File

@ -342,9 +342,9 @@ public class FragmentMessage extends FragmentEx {
// Observe attachments // Observe attachments
db.attachment().liveAttachments(id).observe(getViewLifecycleOwner(), db.attachment().liveAttachments(id).observe(getViewLifecycleOwner(),
new Observer<List<TupleAttachment>>() {
new Observer<List<EntityAttachment>>() {
@Override @Override
public void onChanged(@Nullable List<TupleAttachment> attachments) {
public void onChanged(@Nullable List<EntityAttachment> attachments) {
if (attachments != null) if (attachments != null)
adapter.set(attachments); adapter.set(attachments);
grpAttachments.setVisibility(attachments != null && attachments.size() > 0 ? View.VISIBLE : View.GONE); grpAttachments.setVisibility(attachments != null && attachments.size() > 0 ? View.VISIBLE : View.GONE);


+ 30
- 14
app/src/main/java/eu/faircode/email/MessageHelper.java View File

@ -19,12 +19,14 @@ package eu.faircode.email;
Copyright 2018 by Marcel Bokhorst (M66B) Copyright 2018 by Marcel Bokhorst (M66B)
*/ */
import android.content.Context;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Base64; import android.util.Base64;
import android.util.Log; import android.util.Log;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -34,7 +36,8 @@ import java.util.List;
import java.util.Properties; import java.util.Properties;
import javax.activation.DataHandler; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.FileTypeMap;
import javax.mail.Address; import javax.mail.Address;
import javax.mail.BodyPart; import javax.mail.BodyPart;
import javax.mail.Flags; import javax.mail.Flags;
@ -48,7 +51,6 @@ import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class MessageHelper { public class MessageHelper {
private MimeMessage imessage; private MimeMessage imessage;
@ -84,7 +86,7 @@ public class MessageHelper {
return props; return props;
} }
static MimeMessageEx from(EntityMessage message, List<EntityAttachment> attachments, Session isession) throws MessagingException {
static MimeMessageEx from(Context context, EntityMessage message, List<EntityAttachment> attachments, Session isession) throws MessagingException {
MimeMessageEx imessage = new MimeMessageEx(isession, message.msgid); MimeMessageEx imessage = new MimeMessageEx(isession, message.msgid);
imessage.setFlag(Flags.Flag.SEEN, message.seen); imessage.setFlag(Flags.Flag.SEEN, message.seen);
@ -118,15 +120,29 @@ public class MessageHelper {
bpMessage.setContent(message.body, "text/html; charset=" + Charset.defaultCharset().name()); bpMessage.setContent(message.body, "text/html; charset=" + Charset.defaultCharset().name());
multipart.addBodyPart(bpMessage); multipart.addBodyPart(bpMessage);
for (EntityAttachment attachment : attachments) {
BodyPart bpAttachment = new MimeBodyPart();
bpAttachment.setFileName(attachment.name);
DataSource dataSource = new ByteArrayDataSource(attachment.content, attachment.type);
bpAttachment.setDataHandler(new DataHandler(dataSource));
multipart.addBodyPart(bpAttachment);
}
for (final EntityAttachment attachment : attachments)
if (attachment.filename != null) {
BodyPart bpAttachment = new MimeBodyPart();
bpAttachment.setFileName(attachment.name);
File dir = new File(context.getFilesDir(), "attachments");
File file = new File(dir, attachment.filename);
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);
}
imessage.setContent(multipart); imessage.setContent(multipart);
} }
@ -136,8 +152,8 @@ public class MessageHelper {
return imessage; return imessage;
} }
static MimeMessageEx from(EntityMessage message, EntityMessage reply, List<EntityAttachment> attachments, Session isession) throws MessagingException {
MimeMessageEx imessage = from(message, attachments, isession);
static MimeMessageEx from(Context context, EntityMessage message, EntityMessage reply, List<EntityAttachment> attachments, Session isession) throws MessagingException {
MimeMessageEx imessage = from(context, message, attachments, isession);
imessage.addHeader("In-Reply-To", reply.msgid); imessage.addHeader("In-Reply-To", reply.msgid);
imessage.addHeader("References", (reply.references == null ? "" : reply.references + " ") + reply.msgid); imessage.addHeader("References", (reply.references == null ? "" : reply.references + " ") + reply.msgid);
return imessage; return imessage;


+ 46
- 27
app/src/main/java/eu/faircode/email/ServiceSynchronize.java View File

@ -49,9 +49,12 @@ import com.sun.mail.smtp.SMTPSendFailedException;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import java.io.ByteArrayOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -844,12 +847,10 @@ public class ServiceSynchronize extends LifecycleService {
// Append message // Append message
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id); List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
for (EntityAttachment attachment : attachments)
attachment.content = db.attachment().getContent(attachment.id);
Properties props = MessageHelper.getSessionProperties(); Properties props = MessageHelper.getSessionProperties();
Session isession = Session.getInstance(props, null); Session isession = Session.getInstance(props, null);
MimeMessage imessage = MessageHelper.from(message, attachments, isession);
MimeMessage imessage = MessageHelper.from(this, message, attachments, isession);
ifolder.appendMessages(new Message[]{imessage}); ifolder.appendMessages(new Message[]{imessage});
} }
@ -875,15 +876,13 @@ public class ServiceSynchronize extends LifecycleService {
Log.w(Helper.TAG, "MOVE by DELETE/APPEND"); Log.w(Helper.TAG, "MOVE by DELETE/APPEND");
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id); List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
for (EntityAttachment attachment : attachments)
attachment.content = db.attachment().getContent(attachment.id);
if (!EntityFolder.ARCHIVE.equals(folder.type)) { if (!EntityFolder.ARCHIVE.equals(folder.type)) {
imessage.setFlag(Flags.Flag.DELETED, true); imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge(); ifolder.expunge();
} }
MimeMessageEx icopy = MessageHelper.from(message, attachments, isession);
MimeMessageEx icopy = MessageHelper.from(this, message, attachments, isession);
Folder itarget = istore.getFolder(target.name); Folder itarget = istore.getFolder(target.name);
itarget.appendMessages(new Message[]{icopy}); itarget.appendMessages(new Message[]{icopy});
} }
@ -909,8 +908,6 @@ public class ServiceSynchronize extends LifecycleService {
EntityIdentity ident = db.identity().getIdentity(message.identity); EntityIdentity ident = db.identity().getIdentity(message.identity);
EntityMessage reply = (message.replying == null ? null : db.message().getMessage(message.replying)); EntityMessage reply = (message.replying == null ? null : db.message().getMessage(message.replying));
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id); List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
for (EntityAttachment attachment : attachments)
attachment.content = db.attachment().getContent(attachment.id);
if (!ident.synchronize) { if (!ident.synchronize) {
// Message will remain in outbox // Message will remain in outbox
@ -924,9 +921,9 @@ public class ServiceSynchronize extends LifecycleService {
// Create message // Create message
MimeMessage imessage; MimeMessage imessage;
if (reply == null) if (reply == null)
imessage = MessageHelper.from(message, attachments, isession);
imessage = MessageHelper.from(this, message, attachments, isession);
else else
imessage = MessageHelper.from(message, reply, attachments, isession);
imessage = MessageHelper.from(this, message, reply, attachments, isession);
if (ident.replyto != null) if (ident.replyto != null)
imessage.setReplyTo(new Address[]{new InternetAddress(ident.replyto)}); imessage.setReplyTo(new Address[]{new InternetAddress(ident.replyto)});
@ -1000,29 +997,51 @@ public class ServiceSynchronize extends LifecycleService {
MessageHelper helper = new MessageHelper((MimeMessage) imessage); MessageHelper helper = new MessageHelper((MimeMessage) imessage);
EntityAttachment a = helper.getAttachments().get(sequence - 1); EntityAttachment a = helper.getAttachments().get(sequence - 1);
// Build filename
File dir = new File(getFilesDir(), "attachments");
dir.mkdir();
File file = new File(dir, Long.toString(attachment.id));
// Download attachment // Download attachment
InputStream is = a.part.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
// Update progress
if (attachment.size != null) {
attachment.progress = os.size() * 100 / attachment.size;
db.attachment().updateAttachment(attachment);
Log.i(Helper.TAG, folder.name + " progress %=" + attachment.progress);
InputStream is = null;
OutputStream os = null;
try {
is = a.part.getInputStream();
os = new BufferedOutputStream(new FileOutputStream(file));
int size = 0;
byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
size += len;
os.write(buffer, 0, len);
// Update progress
if (attachment.size != null) {
attachment.progress = size * 100 / attachment.size;
db.attachment().updateAttachment(attachment);
Log.i(Helper.TAG, folder.name + " progress %=" + attachment.progress);
}
} }
}
// Store attachment data
attachment.progress = null;
attachment.content = os.toByteArray();
// Store attachment data
attachment.size = size;
attachment.progress = null;
attachment.filename = file.getName();
} finally {
try {
if (is != null)
is.close();
} finally {
if (os != null)
os.close();
}
}
db.attachment().updateAttachment(attachment); db.attachment().updateAttachment(attachment);
Log.i(Helper.TAG, folder.name + " downloaded bytes=" + attachment.content.length);
Log.i(Helper.TAG, folder.name + " downloaded bytes=" + attachment.size);
} catch (Throwable ex) { } catch (Throwable ex) {
// Reset progress on failure // Reset progress on failure
attachment.progress = null; attachment.progress = null;
attachment.filename = null;
db.attachment().updateAttachment(attachment); db.attachment().updateAttachment(attachment);
throw ex; throw ex;
} }


+ 0
- 19
app/src/main/java/eu/faircode/email/TupleAttachment.java View File

@ -1,19 +0,0 @@
package eu.faircode.email;
import androidx.annotation.NonNull;
public class TupleAttachment {
@NonNull
public Long id;
@NonNull
public Long message;
@NonNull
public Integer sequence;
public String name;
@NonNull
public String type;
public Integer size;
public Integer progress;
@NonNull
public boolean content;
}

+ 21
- 1
app/src/main/res/layout/item_attachment.xml View File

@ -51,6 +51,26 @@
app:layout_constraintStart_toEndOf="@id/tvSize" app:layout_constraintStart_toEndOf="@id/tvSize"
app:layout_constraintTop_toTopOf="parent" /> app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="6dp"
android:text="text/plain"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintStart_toEndOf="@id/ivAttachments"
app:layout_constraintTop_toBottomOf="@id/ivAttachments" />
<TextView
android:id="@+id/tvFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="6dp"
android:text="filename"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivAttachments" />
<ProgressBar <ProgressBar
android:id="@+id/progressbar" android:id="@+id/progressbar"
style="@style/Widget.AppCompat.ProgressBar.Horizontal" style="@style/Widget.AppCompat.ProgressBar.Horizontal"
@ -59,5 +79,5 @@
android:progress="50" android:progress="50"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ivAttachments" />
app:layout_constraintTop_toBottomOf="@id/tvType" />
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>

+ 1
- 1
app/src/main/res/xml/fileprovider_paths.xml View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<paths> <paths>
<cache-path
<files-path
name="attachments" name="attachments"
path="attachments" /> path="attachments" />
</paths> </paths>

Loading…
Cancel
Save