Save status and set up sync adapter.

There are two parts to this CL:
1. Set up the sync adapter - this involves relevant xml files and
additions to the manifest and subclassing the general VvmSyncAdapter.
2. Processing the status sms that activates the voicemail source -
saving it to the voicemail status database and registering a sync
account.
These were done together because in order to have a fully-functioning
sync adapter, at least one sync account must be registered for it.

Also moved the code from VvmSyncService to OmtpVvmSyncService because
there's no need to have a super class yet. Note that most of the syncing
logic was removed for now so it  can be added incrementally.

Bug: 19236241
Change-Id: If2baf43de4bd70761feadd2d2bd5c4f58c25d19b
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 14a283a..dcdae0c 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -98,6 +98,10 @@
     <uses-permission android:name="android.permission.REGISTER_CALL_PROVIDER" />
     <uses-permission android:name="android.permission.REGISTER_SIM_SUBSCRIPTION" />
     <uses-permission android:name="android.permission.BIND_CARRIER_MESSAGING_SERVICE" />
+    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
+    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
+    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
+    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
 
     <!-- This tells the activity manager to not delay any of our activity
          start requests, even if they happen immediately after the user
@@ -583,7 +587,6 @@
                 <action android:name="android.content.action.SEARCH_INDEXABLES_PROVIDER" />
             </intent-filter>
         </provider>
-
         <receiver android:name="com.android.phone.vvm.omtp.sms.OmtpMessageReceiver"
             android:exported="true">
             <intent-filter>
@@ -591,5 +594,24 @@
                 <data android:scheme="sms" />
             </intent-filter>
         </receiver>
+        <service
+                android:name="com.android.phone.vvm.omtp.OmtpVvmSyncService"
+                android:exported="true"
+                android:process=":sync">
+            <intent-filter>
+                <action android:name="android.content.SyncAdapter"/>
+            </intent-filter>
+            <meta-data android:name="android.content.SyncAdapter"
+                    android:resource="@xml/syncadapter" />
+        </service>
+        <service
+            android:name="android.telecom.AuthenticatorService">
+        <intent-filter>
+            <action android:name="android.accounts.AccountAuthenticator"/>
+        </intent-filter>
+        <meta-data
+            android:name="android.accounts.AccountAuthenticator"
+            android:resource="@xml/authenticator" />
+       </service>
     </application>
 </manifest>
diff --git a/res/xml/authenticator.xml b/res/xml/authenticator.xml
new file mode 100644
index 0000000..f035d3a
--- /dev/null
+++ b/res/xml/authenticator.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<account-authenticator
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:accountType="com.android.phone.vvm.omtp" />
\ No newline at end of file
diff --git a/res/xml/syncadapter.xml b/res/xml/syncadapter.xml
new file mode 100644
index 0000000..b0484b1
--- /dev/null
+++ b/res/xml/syncadapter.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<sync-adapter
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:contentAuthority="com.android.voicemail"
+        android:accountType="com.android.phone.vvm.omtp"
+        android:userVisible="false"
+        android:supportsUploading="true"
+        android:allowParallelSyncs="false"
+        android:isAlwaysSyncable="true"/>
\ No newline at end of file
diff --git a/src/com/android/phone/PhoneUtils.java b/src/com/android/phone/PhoneUtils.java
index 615f777..f7c5939 100644
--- a/src/com/android/phone/PhoneUtils.java
+++ b/src/com/android/phone/PhoneUtils.java
@@ -2449,6 +2449,10 @@
                 == Configuration.ORIENTATION_LANDSCAPE;
     }
 
+    public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
+        return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
+    }
+
     public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
         return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
     }
diff --git a/src/com/android/phone/vvm/omtp/OmtpVvmSyncAccountManager.java b/src/com/android/phone/vvm/omtp/OmtpVvmSyncAccountManager.java
new file mode 100644
index 0000000..de39745
--- /dev/null
+++ b/src/com/android/phone/vvm/omtp/OmtpVvmSyncAccountManager.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package com.android.phone.vvm.omtp;
+
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.util.Log;
+
+/**
+ * A singleton class designed to assist in OMTP visual voicemail sync behavior.
+ */
+public class OmtpVvmSyncAccountManager {
+    public static final String TAG = "OmtpVvmSyncAccountManager";
+    // Constants
+    // The authority for the sync adapter's content provider
+    public static final String AUTHORITY = "com.android.voicemail";
+    // An account type, in the form of a domain name
+    public static final String ACCOUNT_TYPE = "com.android.phone.vvm.omtp";
+
+    private static OmtpVvmSyncAccountManager sInstance = new OmtpVvmSyncAccountManager();
+
+    private AccountManager mAccountManager;
+
+    /**
+     * Private constructor. Instance should only be acquired through getInstance().
+     */
+    private OmtpVvmSyncAccountManager() {}
+
+    public static OmtpVvmSyncAccountManager getInstance(Context context) {
+        sInstance.setAccountManager(context);
+        return sInstance;
+    }
+
+    /**
+     * Set the account manager so it does not need to be retrieved every time.
+     * @param context The context to get the account manager for.
+     */
+    private void setAccountManager(Context context) {
+        if (mAccountManager == null) {
+            mAccountManager = AccountManager.get(context);
+        }
+    }
+
+    /**
+     * Register a sync account. There should be a one to one mapping of sync account to voicemail
+     * source. These sync accounts primarily service the purpose of keeping track of how many OMTP
+     * voicemail sources are active and which phone accounts they correspond to.
+     *
+     * @param account The account to register
+     */
+    public void createSyncAccount(Account account) {
+        // Add the account and account type, no password or user data
+        if (mAccountManager.addAccountExplicitly(account, null, null)) {
+             ContentResolver.setIsSyncable(account, AUTHORITY, 1);
+             ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
+        } else {
+            Log.w(TAG, "Attempted to re-register existing account.");
+        }
+    }
+
+    /**
+     * Check if a certain account is registered.
+     *
+     * @param account The account to look for.
+     * @return {@code true} if the account is in the list of registered OMTP voicemail sync
+     * accounts. {@code false} otherwise.
+     */
+    public boolean isAccountRegistered(Account account) {
+        Account[] accounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE);
+        for (int i = 0; i < accounts.length; i++) {
+            if (account.equals(accounts[i])) {
+                return true;
+            }
+        }
+        return false;
+    }
+}
diff --git a/src/com/android/phone/vvm/omtp/OmtpVvmSyncService.java b/src/com/android/phone/vvm/omtp/OmtpVvmSyncService.java
new file mode 100644
index 0000000..811e7e6
--- /dev/null
+++ b/src/com/android/phone/vvm/omtp/OmtpVvmSyncService.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+/**
+ * A {@link Service} which runs the internal implementation of {@link AbstractThreadedSyncAdapter},
+ * syncing voicemails to and from a visual voicemail server.
+ */
+
+package com.android.phone.vvm.omtp;
+
+import android.accounts.Account;
+import android.app.Service;
+import android.content.AbstractThreadedSyncAdapter;
+import android.content.ContentProviderClient;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SyncResult;
+import android.os.Bundle;
+import android.os.IBinder;
+
+/**
+ * A service to run the VvmSyncAdapter.
+ */
+public class OmtpVvmSyncService extends Service {
+    // Storage for an instance of the sync adapter
+    private static OmtpVvmSyncAdapter sSyncAdapter = null;
+    // Object to use as a thread-safe lock
+    private static final Object sSyncAdapterLock = new Object();
+
+    @Override
+    public void onCreate() {
+        synchronized (sSyncAdapterLock) {
+            if (sSyncAdapter == null) {
+                sSyncAdapter = new OmtpVvmSyncAdapter(getApplicationContext(), true);
+            }
+        }
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return sSyncAdapter.getSyncAdapterBinder();
+    }
+
+    public class OmtpVvmSyncAdapter extends AbstractThreadedSyncAdapter {
+        public OmtpVvmSyncAdapter(Context context, boolean autoInitialize) {
+            super(context, autoInitialize);
+        }
+
+        @Override
+        public void onPerformSync(Account account, Bundle extras, String authority,
+                ContentProviderClient provider, SyncResult syncResult) {
+            // TODO: Write code necessary for syncing.
+        }
+    }
+}
diff --git a/src/com/android/phone/vvm/omtp/sms/OmtpMessageReceiver.java b/src/com/android/phone/vvm/omtp/sms/OmtpMessageReceiver.java
index bb9b28f..932fb1a 100644
--- a/src/com/android/phone/vvm/omtp/sms/OmtpMessageReceiver.java
+++ b/src/com/android/phone/vvm/omtp/sms/OmtpMessageReceiver.java
@@ -15,14 +15,22 @@
  */
 package com.android.phone.vvm.omtp.sms;
 
+import android.accounts.Account;
 import android.content.BroadcastReceiver;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Bundle;
 import android.provider.Telephony;
+import android.provider.VoicemailContract;
+import android.telecom.PhoneAccountHandle;
 import android.telephony.SmsMessage;
 import android.util.Log;
 
+import com.android.internal.telephony.PhoneConstants;
+import com.android.phone.PhoneUtils;
 import com.android.phone.vvm.omtp.OmtpConstants;
+import com.android.phone.vvm.omtp.OmtpVvmSyncAccountManager;
 
 import java.io.UnsupportedEncodingException;
 
@@ -32,8 +40,15 @@
 public class OmtpMessageReceiver extends BroadcastReceiver {
     private static final String TAG = "OmtpMessageReceiver";
 
+    private Context mContext;
+    private PhoneAccountHandle mPhoneAccount;
+
     @Override
     public void onReceive(Context context, Intent intent) {
+        mContext = context;
+        mPhoneAccount = PhoneUtils.makePstnPhoneAccountHandle(
+                intent.getExtras().getInt(PhoneConstants.PHONE_KEY));
+
         SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
         StringBuilder userData = new StringBuilder();
         StringBuilder messageBody = new StringBuilder();
@@ -50,7 +65,7 @@
                 //TODO: handle message
             } else if (messageData.getPrefix() == OmtpConstants.STATUS_SMS_PREFIX) {
                 StatusMessage message = new StatusMessage(messageData);
-                //TODO: handle message
+                handleStatusMessage(message);
             } else {
                 Log.e(TAG, "This should never have happened");
             }
@@ -67,4 +82,24 @@
             throw new IllegalStateException("This should have never happened", e);
         }
     }
+
+    private void handleStatusMessage(StatusMessage message) {
+        OmtpVvmSyncAccountManager vvmSyncManager = OmtpVvmSyncAccountManager.getInstance(mContext);
+        Account account = new Account(mPhoneAccount.getId(),
+                OmtpVvmSyncAccountManager.ACCOUNT_TYPE);
+
+        if (!vvmSyncManager.isAccountRegistered(account)) {
+            // If the account has not been previously registered, it means that this STATUS sms
+            // is a result of the ACTIVATE sms, so register the voicemail source.
+            vvmSyncManager.createSyncAccount(account);
+            VoicemailContract.Status.setStatus(mContext, mPhoneAccount,
+                    VoicemailContract.Status.CONFIGURATION_STATE_OK,
+                    VoicemailContract.Status.DATA_CHANNEL_STATE_OK,
+                    VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_OK);
+        }
+
+        //TODO: figure out how to pass IMAP credentials to sync adapter
+
+        ContentResolver.requestSync(account, VoicemailContract.AUTHORITY, new Bundle());
+    }
 }