Added Gmail OAuth

Closes #17
This commit is contained in:
M66B
2018-08-27 14:31:45 +00:00
parent 9ff3718561
commit bc30dee6a1
18 changed files with 1058 additions and 45 deletions

View File

@@ -37,6 +37,9 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class ActivitySetup extends ActivityBase implements FragmentManager.OnBackStackChangedListener {
boolean hasAccount;
static final int REQUEST_PERMISSION = 1;
static final int REQUEST_CHOOSE_ACCOUNT = 2;
static final String ACTION_EDIT_ACCOUNT = BuildConfig.APPLICATION_ID + ".EDIT_ACCOUNT";
static final String ACTION_EDIT_IDENTITY = BuildConfig.APPLICATION_ID + ".EDIT_IDENTITY";

View File

@@ -45,7 +45,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase;
// https://developer.android.com/topic/libraries/architecture/room.html
@Database(
version = 4,
version = 5,
entities = {
EntityIdentity.class,
EntityAccount.class,
@@ -135,6 +135,14 @@ public abstract class DB extends RoomDatabase {
db.execSQL("CREATE TABLE IF NOT EXISTS `answer` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT NOT NULL, `text` TEXT NOT NULL)");
}
})
.addMigrations(new Migration(4, 5) {
@Override
public void migrate(SupportSQLiteDatabase db) {
Log.i(Helper.TAG, "DB migration from version " + startVersion + " to " + endVersion);
db.execSQL("ALTER TABLE `account` ADD COLUMN `auth_type` INTEGER NOT NULL DEFAULT 1");
db.execSQL("ALTER TABLE `identity` ADD COLUMN `auth_type` INTEGER NOT NULL DEFAULT 1");
}
})
.build();
}

View File

@@ -43,6 +43,8 @@ public class EntityAccount {
@NonNull
public String password;
@NonNull
public Integer auth_type;
@NonNull
public Boolean primary;
@NonNull
public Boolean synchronize;

View File

@@ -59,6 +59,8 @@ public class EntityIdentity {
@NonNull
public String password;
@NonNull
public Integer auth_type;
@NonNull
public Boolean primary;
@NonNull
public Boolean synchronize;

View File

@@ -19,8 +19,17 @@ package eu.faircode.email;
Copyright 2018 by Marcel Bokhorst (M66B)
*/
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
@@ -53,6 +62,7 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.MessagingException;
@@ -62,14 +72,18 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.Group;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import static android.accounts.AccountManager.newChooseAccountIntent;
public class FragmentAccount extends FragmentEx {
private ViewGroup view;
private EditText etName;
private Spinner spProvider;
private EditText etHost;
private EditText etPort;
private Button btnAuthorize;
private EditText etUser;
private TextInputLayout tilPassword;
private TextView tvLink;
@@ -91,6 +105,18 @@ public class FragmentAccount extends FragmentEx {
private Group grpInstructions;
private Group grpFolders;
private long id = -1;
private int auth_type = Helper.AUTH_TYPE_PASSWORD;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get arguments
Bundle args = getArguments();
id = (args == null ? -1 : args.getLong("id", -1));
}
@Override
@Nullable
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -98,14 +124,11 @@ public class FragmentAccount extends FragmentEx {
view = (ViewGroup) inflater.inflate(R.layout.fragment_account, container, false);
// Get arguments
Bundle args = getArguments();
final long id = (args == null ? -1 : args.getLong("id", -1));
// Get controls
spProvider = view.findViewById(R.id.spProvider);
etName = view.findViewById(R.id.etName);
etHost = view.findViewById(R.id.etHost);
btnAuthorize = view.findViewById(R.id.btnAuthorize);
etPort = view.findViewById(R.id.etPort);
etUser = view.findViewById(R.id.etUser);
tilPassword = view.findViewById(R.id.tilPassword);
@@ -143,12 +166,23 @@ public class FragmentAccount extends FragmentEx {
tvLink.setText(Html.fromHtml("<a href=\"" + provider.link + "\">" + provider.link + "</a>"));
grpInstructions.setVisibility(provider.link == null ? View.GONE : View.VISIBLE);
if (provider.imap_port != 0) {
if (provider.imap_port > 0) {
etName.setText(provider.name);
etHost.setText(provider.imap_host);
etPort.setText(Integer.toString(provider.imap_port));
etUser.requestFocus();
if (provider.type == null)
etUser.requestFocus();
}
if (provider.type == null) {
btnAuthorize.setVisibility(View.GONE);
if (auth_type != Helper.AUTH_TYPE_PASSWORD) {
auth_type = Helper.AUTH_TYPE_PASSWORD;
etUser.setText(null);
tilPassword.getEditText().setText(null);
}
} else
btnAuthorize.setVisibility(View.VISIBLE);
}
@Override
@@ -156,6 +190,19 @@ public class FragmentAccount extends FragmentEx {
}
});
btnAuthorize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String permission = Manifest.permission.GET_ACCOUNTS;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O &&
ContextCompat.checkSelfPermission(getContext(), permission) != PackageManager.PERMISSION_GRANTED) {
Log.i(Helper.TAG, "Requesting " + permission);
requestPermissions(new String[]{permission}, ActivitySetup.REQUEST_PERMISSION);
} else
selectAccount();
}
});
cbSynchronize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
@@ -181,6 +228,7 @@ public class FragmentAccount extends FragmentEx {
args.putString("port", etPort.getText().toString());
args.putString("user", etUser.getText().toString());
args.putString("password", tilPassword.getEditText().getText().toString());
args.putInt("auth_type", auth_type);
args.putBoolean("synchronize", cbSynchronize.isChecked());
args.putBoolean("primary", cbPrimary.isChecked());
@@ -192,6 +240,7 @@ public class FragmentAccount extends FragmentEx {
String port = args.getString("port");
String user = args.getString("user");
String password = args.getString("password");
int auth_type = args.getInt("auth_type");
if (TextUtils.isEmpty(host))
throw new Throwable(getContext().getString(R.string.title_no_host));
@@ -204,7 +253,10 @@ public class FragmentAccount extends FragmentEx {
// Check IMAP server / get folders
List<EntityFolder> folders = new ArrayList<>();
Session isession = Session.getInstance(MessageHelper.getSessionProperties(), null);
Properties props = MessageHelper.getSessionProperties(auth_type);
Session isession = Session.getInstance(props, null);
isession.setDebug(true);
IMAPStore istore = null;
try {
istore = (IMAPStore) isession.getStore("imaps");
@@ -379,6 +431,7 @@ public class FragmentAccount extends FragmentEx {
args.putString("port", etPort.getText().toString());
args.putString("user", etUser.getText().toString());
args.putString("password", tilPassword.getEditText().getText().toString());
args.putInt("auth_type", auth_type);
args.putBoolean("synchronize", cbSynchronize.isChecked());
args.putBoolean("primary", cbPrimary.isChecked());
args.putString("poll_interval", etInterval.getText().toString());
@@ -396,6 +449,7 @@ public class FragmentAccount extends FragmentEx {
String port = args.getString("port");
String user = args.getString("user");
String password = args.getString("password");
int auth_type = args.getInt("auth_type");
boolean synchronize = args.getBoolean("synchronize");
boolean primary = args.getBoolean("primary");
String poll_interval = args.getString("poll_interval");
@@ -421,7 +475,7 @@ public class FragmentAccount extends FragmentEx {
// Check IMAP server
if (synchronize) {
Session isession = Session.getInstance(MessageHelper.getSessionProperties(), null);
Session isession = Session.getInstance(MessageHelper.getSessionProperties(auth_type), null);
IMAPStore istore = null;
try {
istore = (IMAPStore) isession.getStore("imaps");
@@ -451,6 +505,7 @@ public class FragmentAccount extends FragmentEx {
account.port = Integer.parseInt(port);
account.user = user;
account.password = password;
account.auth_type = auth_type;
account.synchronize = synchronize;
account.primary = (account.synchronize && primary);
account.store_sent = false;
@@ -582,6 +637,7 @@ public class FragmentAccount extends FragmentEx {
// Initialize
Helper.setViewsEnabled(view, false);
btnAuthorize.setVisibility(View.GONE);
tilPassword.setPasswordVisibilityToggleEnabled(id < 0);
tvLink.setMovementMethod(LinkMovementMethod.getInstance());
btnCheck.setEnabled(false);
@@ -599,6 +655,7 @@ public class FragmentAccount extends FragmentEx {
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("provider", spProvider.getSelectedItemPosition());
outState.putInt("auth_type", auth_type);
outState.putString("password", tilPassword.getEditText().getText().toString());
outState.putInt("instructions", grpInstructions.getVisibility());
}
@@ -607,10 +664,6 @@ public class FragmentAccount extends FragmentEx {
public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Get arguments
Bundle args = getArguments();
long id = (args == null ? -1 : args.getLong("id", -1));
// Observe
DB.getInstance(getContext()).account().liveAccount(id).observe(getViewLifecycleOwner(), new Observer<EntityAccount>() {
boolean once = false;
@@ -640,6 +693,7 @@ public class FragmentAccount extends FragmentEx {
etInterval.setText(account == null ? "9" : Integer.toString(account.poll_interval));
} else {
int provider = savedInstanceState.getInt("provider");
auth_type = savedInstanceState.getInt("auth_type");
spProvider.setTag(provider);
spProvider.setSelection(provider);
tilPassword.getEditText().setText(savedInstanceState.getString("password"));
@@ -648,6 +702,7 @@ public class FragmentAccount extends FragmentEx {
Helper.setViewsEnabled(view, true);
btnAuthorize.setVisibility(auth_type == Helper.AUTH_TYPE_PASSWORD ? View.GONE : View.VISIBLE);
cbPrimary.setEnabled(cbSynchronize.isChecked());
btnCheck.setVisibility(cbSynchronize.isChecked() ? View.VISIBLE : View.GONE);
@@ -660,4 +715,70 @@ public class FragmentAccount extends FragmentEx {
}
});
}
void selectAccount() {
Log.i(Helper.TAG, "Select account");
Provider provider = (Provider) spProvider.getSelectedItem();
if (provider.type != null)
startActivityForResult(newChooseAccountIntent(
null,
null,
new String[]{provider.type},
null,
null,
null,
null), ActivitySetup.REQUEST_CHOOSE_ACCOUNT);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == ActivitySetup.REQUEST_PERMISSION)
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
selectAccount();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(Helper.TAG, "Activity result request=" + requestCode + " result=" + resultCode + " data=" + data);
if (resultCode == Activity.RESULT_OK)
if (requestCode == ActivitySetup.REQUEST_CHOOSE_ACCOUNT) {
String name = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String type = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
String authTokenType = null;
if ("com.google".equals(type))
authTokenType = "oauth2:https://mail.google.com/";
AccountManager am = AccountManager.get(getContext());
Account[] accounts = am.getAccountsByType(type);
Log.i(Helper.TAG, "Accounts=" + accounts.length);
for (final Account account : accounts)
if (name.equals(account.name)) {
am.getAuthToken(
account,
authTokenType,
new Bundle(),
getActivity(),
new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.i(Helper.TAG, "Got token");
auth_type = Helper.AUTH_TYPE_GMAIL;
etUser.setText(account.name);
tilPassword.getEditText().setText(token);
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
Toast.makeText(getContext(), Helper.formatThrowable(ex), Toast.LENGTH_LONG).show();
}
}
},
null);
break;
}
}
}
}

View File

@@ -804,7 +804,7 @@ public class FragmentCompose extends FragmentEx {
text = db.answer().getAnswer(answer).text;
draft.subject = context.getString(R.string.title_subject_reply, ref.subject);
body = String.format("%s<br><br>%s %s:<br><br>%s",
Html.escapeHtml(text).replaceAll("\\r?\\n", "<br />"),
text.replaceAll("\\r?\\n", "<br />"),
Html.escapeHtml(new Date().toString()),
Html.escapeHtml(MessageHelper.getFormattedAddresses(draft.to, true)),
HtmlHelper.sanitize(context, ref.read(context), true));

View File

@@ -79,6 +79,17 @@ public class FragmentIdentity extends FragmentEx {
private ProgressBar pbWait;
private Group grpInstructions;
private long id = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get arguments
Bundle args = getArguments();
id = (args == null ? -1 : args.getLong("id", -1));
}
@Override
@Nullable
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -86,10 +97,6 @@ public class FragmentIdentity extends FragmentEx {
view = (ViewGroup) inflater.inflate(R.layout.fragment_identity, container, false);
// Get arguments
Bundle args = getArguments();
final long id = (args == null ? -1 : args.getLong("id", -1));
// Get controls
etName = view.findViewById(R.id.etName);
etEmail = view.findViewById(R.id.etEmail);
@@ -214,6 +221,7 @@ public class FragmentIdentity extends FragmentEx {
args.putString("email", etEmail.getText().toString());
args.putString("replyto", etReplyTo.getText().toString());
args.putLong("account", account == null ? -1 : account.id);
args.putInt("auth_type", account == null ? Helper.AUTH_TYPE_PASSWORD : account.auth_type);
args.putString("host", etHost.getText().toString());
args.putBoolean("starttls", cbStartTls.isChecked());
args.putString("port", etPort.getText().toString());
@@ -236,6 +244,7 @@ public class FragmentIdentity extends FragmentEx {
String port = args.getString("port");
String user = args.getString("user");
String password = args.getString("password");
int auth_type = args.getInt("auth_type");
boolean synchronize = args.getBoolean("synchronize");
boolean primary = args.getBoolean("primary");
boolean store_sent = args.getBoolean("store_sent");
@@ -260,7 +269,7 @@ public class FragmentIdentity extends FragmentEx {
// Check SMTP server
if (synchronize) {
Properties props = MessageHelper.getSessionProperties();
Properties props = MessageHelper.getSessionProperties(auth_type);
Session isession = Session.getInstance(props, null);
Transport itransport = isession.getTransport(starttls ? "smtp" : "smtps");
try {
@@ -287,6 +296,7 @@ public class FragmentIdentity extends FragmentEx {
identity.starttls = starttls;
identity.user = user;
identity.password = password;
identity.auth_type = auth_type;
identity.synchronize = synchronize;
identity.primary = (identity.synchronize && primary);
identity.store_sent = store_sent;
@@ -394,10 +404,6 @@ public class FragmentIdentity extends FragmentEx {
public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Get arguments
Bundle args = getArguments();
long id = (args == null ? -1 : args.getLong("id", -1));
final DB db = DB.getInstance(getContext());
// Observe identity
@@ -447,7 +453,7 @@ public class FragmentIdentity extends FragmentEx {
EntityAccount unselected = new EntityAccount();
unselected.id = -1L;
unselected.name = "";
unselected.name = getString(R.string.title_select);
unselected.primary = false;
accounts.add(0, unselected);

View File

@@ -52,6 +52,9 @@ import javax.mail.internet.InternetAddress;
public class Helper {
static final String TAG = "fairemail";
static final int AUTH_TYPE_PASSWORD = 1;
static final int AUTH_TYPE_GMAIL = 2;
static int resolveColor(Context context, int attr) {
int[] attrs = new int[]{attr};
TypedArray a = context.getTheme().obtainStyledAttributes(attrs);

View File

@@ -57,7 +57,7 @@ public class MessageHelper {
private MimeMessage imessage;
private String raw = null;
static Properties getSessionProperties() {
static Properties getSessionProperties(int auth_type) {
Properties props = new Properties();
// https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/package-summary.html#properties
@@ -97,6 +97,12 @@ public class MessageHelper {
props.put("mail.mime.address.strict", "false");
props.put("mail.mime.decodetext.strict", "false");
// https://javaee.github.io/javamail/OAuth2
if (auth_type == Helper.AUTH_TYPE_GMAIL) {
props.put("mail.imaps.auth.mechanisms", "XOAUTH2");
props.put("mail.smtps.auth.mechanisms", "XOAUTH2");
}
return props;
}

View File

@@ -35,6 +35,7 @@ import java.util.Locale;
public class Provider {
public String name;
public String link;
public String type;
public String imap_host;
public int imap_port;
public String smtp_host;
@@ -62,6 +63,7 @@ public class Provider {
provider = new Provider();
provider.name = xml.getAttributeValue(null, "name");
provider.link = xml.getAttributeValue(null, "link");
provider.type = xml.getAttributeValue(null, "type");
} else if ("imap".equals(xml.getName())) {
provider.imap_host = xml.getAttributeValue(null, "host");
provider.imap_port = xml.getAttributeIntValue(null, "port", 0);

View File

@@ -117,7 +117,7 @@ public class SearchDataSource extends PositionalDataSource<TupleMessageEx> imple
folder = db.folder().getFolder(fid);
account = db.account().getAccount(folder.account);
Properties props = MessageHelper.getSessionProperties();
Properties props = MessageHelper.getSessionProperties(account.auth_type);
Session isession = Session.getInstance(props, null);
Log.i(Helper.TAG, "SDS connecting account=" + account.name);

View File

@@ -73,6 +73,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
@@ -390,7 +391,7 @@ public class ServiceSynchronize extends LifecycleService {
if (debug)
System.setProperty("mail.socket.debug", "true");
Properties props = MessageHelper.getSessionProperties();
Properties props = MessageHelper.getSessionProperties(account.auth_type);
final Session isession = Session.getInstance(props, null);
isession.setDebug(debug);
// adb -t 1 logcat | grep "fairemail\|System.out"
@@ -455,6 +456,8 @@ public class ServiceSynchronize extends LifecycleService {
// Initiate connection
Log.i(Helper.TAG, account.name + " connect");
for (EntityFolder folder : db.folder().getFolders(account.id))
db.folder().setFolderState(folder.id, null);
db.account().setAccountState(account.id, "connecting");
istore.connect(account.host, account.port, account.user, account.password);
@@ -470,9 +473,6 @@ public class ServiceSynchronize extends LifecycleService {
throw new IllegalStateException("synchronize folders", ex);
}
for (EntityFolder folder : db.folder().getFolders(account.id))
db.folder().setFolderState(folder.id, null);
// Synchronize folders
for (final EntityFolder folder : db.folder().getFolders(account.id, true)) {
Log.i(Helper.TAG, account.name + " sync folder " + folder.name);
@@ -752,6 +752,9 @@ public class ServiceSynchronize extends LifecycleService {
reportError(account.name, null, ex);
db.account().setAccountError(account.id, Helper.formatThrowable(ex));
if (ex instanceof AuthenticationFailedException)
break;
} finally {
// Close store
Log.i(Helper.TAG, account.name + " closing");
@@ -840,7 +843,7 @@ public class ServiceSynchronize extends LifecycleService {
doDelete(folder, ifolder, message, jargs, db);
else if (EntityOperation.SEND.equals(op.name))
doSend(isession, message, db);
doSend(message, db);
else if (EntityOperation.ATTACHMENT.equals(op.name))
doAttachment(folder, op, ifolder, message, jargs, db);
@@ -960,23 +963,27 @@ public class ServiceSynchronize extends LifecycleService {
db.message().deleteMessage(message.id);
}
private void doSend(Session isession, EntityMessage message, DB db) throws MessagingException, IOException {
private void doSend(EntityMessage message, DB db) throws MessagingException, IOException {
// Send message
EntityIdentity ident = db.identity().getIdentity(message.identity);
EntityMessage reply = (message.replying == null ? null : db.message().getMessage(message.replying));
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
if (!ident.synchronize) {
// Message will remain in outbox
return;
}
// Create session
Properties props = MessageHelper.getSessionProperties(ident.auth_type);
final Session isession = Session.getInstance(props, null);
// Create message
MimeMessage imessage;
EntityMessage reply = (message.replying == null ? null : db.message().getMessage(message.replying));
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
if (reply == null)
imessage = MessageHelper.from(this, message, attachments, isession);
else
imessage = MessageHelper.from(this, message, reply, attachments, isession);
if (ident.replyto != null)
imessage.setReplyTo(new Address[]{new InternetAddress(ident.replyto)});
@@ -1564,16 +1571,12 @@ public class ServiceSynchronize extends LifecycleService {
public void onReceive(Context context, Intent intent) {
Log.v(Helper.TAG, outbox.name + " run operations");
// Create session
Properties props = MessageHelper.getSessionProperties();
final Session isession = Session.getInstance(props, null);
executor.submit(new Runnable() {
@Override
public void run() {
try {
Log.i(Helper.TAG, outbox.name + " start operations");
processOperations(outbox, isession, null, null);
processOperations(outbox, null, null, null);
} catch (Throwable ex) {
Log.e(Helper.TAG, outbox.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(null, outbox.name, ex);