Home | History | Annotate | Download | only in telecom
      1 /*
      2  * Copyright 2014, The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *     http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.server.telecom;
     18 
     19 import android.content.Context;
     20 import android.content.Intent;
     21 import android.Manifest.permission;
     22 import android.net.Uri;
     23 import android.os.AsyncTask;
     24 import android.provider.CallLog.Calls;
     25 import android.telecom.CallState;
     26 import android.telecom.DisconnectCause;
     27 import android.telecom.PhoneAccountHandle;
     28 import android.telecom.VideoProfile;
     29 import android.telephony.PhoneNumberUtils;
     30 
     31 // TODO: Needed for move to system service: import com.android.internal.R;
     32 import com.android.internal.telephony.CallerInfo;
     33 import com.android.internal.telephony.PhoneConstants;
     34 
     35 /**
     36  * Helper class that provides functionality to write information about calls and their associated
     37  * caller details to the call log. All logging activity will be performed asynchronously in a
     38  * background thread to avoid blocking on the main thread.
     39  */
     40 final class CallLogManager extends CallsManagerListenerBase {
     41     /**
     42      * Parameter object to hold the arguments to add a call in the call log DB.
     43      */
     44     private static class AddCallArgs {
     45         /**
     46          * @param callerInfo Caller details.
     47          * @param number The phone number to be logged.
     48          * @param presentation Number presentation of the phone number to be logged.
     49          * @param callType The type of call (e.g INCOMING_TYPE). @see
     50          *     {@link android.provider.CallLog} for the list of values.
     51          * @param features The features of the call (e.g. FEATURES_VIDEO). @see
     52          *     {@link android.provider.CallLog} for the list of values.
     53          * @param creationDate Time when the call was created (milliseconds since epoch).
     54          * @param durationInMillis Duration of the call (milliseconds).
     55          * @param dataUsage Data usage in bytes, or null if not applicable.
     56          */
     57         public AddCallArgs(Context context, CallerInfo callerInfo, String number,
     58                 int presentation, int callType, int features, PhoneAccountHandle accountHandle,
     59                 long creationDate, long durationInMillis, Long dataUsage) {
     60             this.context = context;
     61             this.callerInfo = callerInfo;
     62             this.number = number;
     63             this.presentation = presentation;
     64             this.callType = callType;
     65             this.features = features;
     66             this.accountHandle = accountHandle;
     67             this.timestamp = creationDate;
     68             this.durationInSec = (int)(durationInMillis / 1000);
     69             this.dataUsage = dataUsage;
     70         }
     71         // Since the members are accessed directly, we don't use the
     72         // mXxxx notation.
     73         public final Context context;
     74         public final CallerInfo callerInfo;
     75         public final String number;
     76         public final int presentation;
     77         public final int callType;
     78         public final int features;
     79         public final PhoneAccountHandle accountHandle;
     80         public final long timestamp;
     81         public final int durationInSec;
     82         public final Long dataUsage;
     83     }
     84 
     85     private static final String TAG = CallLogManager.class.getSimpleName();
     86 
     87     private final Context mContext;
     88     private static final String ACTION_CALLS_TABLE_ADD_ENTRY =
     89                 "com.android.server.telecom.intent.action.CALLS_ADD_ENTRY";
     90     private static final String PERMISSION_PROCESS_CALLLOG_INFO =
     91                 "android.permission.PROCESS_CALLLOG_INFO";
     92     private static final String CALL_TYPE = "callType";
     93     private static final String CALL_DURATION = "duration";
     94 
     95     public CallLogManager(Context context) {
     96         mContext = context;
     97     }
     98 
     99     @Override
    100     public void onCallStateChanged(Call call, int oldState, int newState) {
    101         boolean isNewlyDisconnected =
    102                 newState == CallState.DISCONNECTED || newState == CallState.ABORTED;
    103         boolean isCallCanceled = isNewlyDisconnected &&
    104                 call.getDisconnectCause().getCode() == DisconnectCause.CANCELED;
    105 
    106         // Log newly disconnected calls only if:
    107         // 1) It was not in the "choose account" phase when disconnected
    108         // 2) It is a conference call
    109         // 3) Call was not explicitly canceled
    110         if (isNewlyDisconnected &&
    111                 (oldState != CallState.PRE_DIAL_WAIT &&
    112                  !call.isConference() &&
    113                  !isCallCanceled)) {
    114             int type;
    115             if (!call.isIncoming()) {
    116                 type = Calls.OUTGOING_TYPE;
    117             } else if (oldState == CallState.RINGING) {
    118                 type = Calls.MISSED_TYPE;
    119             } else {
    120                 type = Calls.INCOMING_TYPE;
    121             }
    122             logCall(call, type);
    123         }
    124     }
    125 
    126     /**
    127      * Logs a call to the call log based on the {@link Call} object passed in.
    128      *
    129      * @param call The call object being logged
    130      * @param callLogType The type of call log entry to log this call as. See:
    131      *     {@link android.provider.CallLog.Calls#INCOMING_TYPE}
    132      *     {@link android.provider.CallLog.Calls#OUTGOING_TYPE}
    133      *     {@link android.provider.CallLog.Calls#MISSED_TYPE}
    134      */
    135     void logCall(Call call, int callLogType) {
    136         final long creationTime = call.getCreationTimeMillis();
    137         final long age = call.getAgeMillis();
    138 
    139         final String logNumber = getLogNumber(call);
    140 
    141         Log.d(TAG, "logNumber set to: %s", Log.pii(logNumber));
    142 
    143         final int presentation = getPresentation(call);
    144         final PhoneAccountHandle accountHandle = call.getTargetPhoneAccount();
    145 
    146         // TODO(vt): Once data usage is available, wire it up here.
    147         int callFeatures = getCallFeatures(call.getVideoStateHistory());
    148         logCall(call.getCallerInfo(), logNumber, presentation, callLogType, callFeatures,
    149                 accountHandle, creationTime, age, null);
    150     }
    151 
    152     /**
    153      * Inserts a call into the call log, based on the parameters passed in.
    154      *
    155      * @param callerInfo Caller details.
    156      * @param number The number the call was made to or from.
    157      * @param presentation
    158      * @param callType The type of call.
    159      * @param features The features of the call.
    160      * @param start The start time of the call, in milliseconds.
    161      * @param duration The duration of the call, in milliseconds.
    162      * @param dataUsage The data usage for the call, null if not applicable.
    163      */
    164     private void logCall(
    165             CallerInfo callerInfo,
    166             String number,
    167             int presentation,
    168             int callType,
    169             int features,
    170             PhoneAccountHandle accountHandle,
    171             long start,
    172             long duration,
    173             Long dataUsage) {
    174         boolean isEmergencyNumber = PhoneNumberUtils.isLocalEmergencyNumber(mContext, number);
    175 
    176         // On some devices, to avoid accidental redialing of emergency numbers, we *never* log
    177         // emergency calls to the Call Log.  (This behavior is set on a per-product basis, based
    178         // on carrier requirements.)
    179         final boolean okToLogEmergencyNumber =
    180                 mContext.getResources().getBoolean(R.bool.allow_emergency_numbers_in_call_log);
    181 
    182         // Don't log emergency numbers if the device doesn't allow it.
    183         final boolean isOkToLogThisCall = !isEmergencyNumber || okToLogEmergencyNumber;
    184 
    185         sendAddCallBroadcast(callType, duration);
    186 
    187         if (isOkToLogThisCall) {
    188             Log.d(TAG, "Logging Calllog entry: " + callerInfo + ", "
    189                     + Log.pii(number) + "," + presentation + ", " + callType
    190                     + ", " + start + ", " + duration);
    191             AddCallArgs args = new AddCallArgs(mContext, callerInfo, number, presentation,
    192                     callType, features, accountHandle, start, duration, dataUsage);
    193             logCallAsync(args);
    194         } else {
    195           Log.d(TAG, "Not adding emergency call to call log.");
    196         }
    197     }
    198 
    199     /**
    200      * Based on the video state of the call, determines the call features applicable for the call.
    201      *
    202      * @param videoState The video state.
    203      * @return The call features.
    204      */
    205     private static int getCallFeatures(int videoState) {
    206         if ((videoState & VideoProfile.VideoState.TX_ENABLED)
    207                 == VideoProfile.VideoState.TX_ENABLED) {
    208             return Calls.FEATURES_VIDEO;
    209         }
    210         return 0;
    211     }
    212 
    213     /**
    214      * Retrieve the phone number from the call, and then process it before returning the
    215      * actual number that is to be logged.
    216      *
    217      * @param call The phone connection.
    218      * @return the phone number to be logged.
    219      */
    220     private String getLogNumber(Call call) {
    221         Uri handle = call.getOriginalHandle();
    222 
    223         if (handle == null) {
    224             return null;
    225         }
    226 
    227         String handleString = handle.getSchemeSpecificPart();
    228         if (!PhoneNumberUtils.isUriNumber(handleString)) {
    229             handleString = PhoneNumberUtils.stripSeparators(handleString);
    230         }
    231         return handleString;
    232     }
    233 
    234     /**
    235      * Gets the presentation from the {@link Call}.
    236      *
    237      * TODO: There needs to be a way to pass information from
    238      * Connection.getNumberPresentation() into a {@link Call} object. Until then, always return
    239      * PhoneConstants.PRESENTATION_ALLOWED. On top of that, we might need to introduce
    240      * getNumberPresentation to the ContactInfo object as well.
    241      *
    242      * @param call The call object to retrieve caller details from.
    243      * @return The number presentation constant to insert into the call logs.
    244      */
    245     private int getPresentation(Call call) {
    246         return PhoneConstants.PRESENTATION_ALLOWED;
    247     }
    248 
    249     /**
    250      * Adds the call defined by the parameters in the provided AddCallArgs to the CallLogProvider
    251      * using an AsyncTask to avoid blocking the main thread.
    252      *
    253      * @param args Prepopulated call details.
    254      * @return A handle to the AsyncTask that will add the call to the call log asynchronously.
    255      */
    256     public AsyncTask<AddCallArgs, Void, Uri[]> logCallAsync(AddCallArgs args) {
    257         return new LogCallAsyncTask().execute(args);
    258     }
    259 
    260     /**
    261      * Helper AsyncTask to access the call logs database asynchronously since database operations
    262      * can take a long time depending on the system's load. Since it extends AsyncTask, it uses
    263      * its own thread pool.
    264      */
    265     private class LogCallAsyncTask extends AsyncTask<AddCallArgs, Void, Uri[]> {
    266         @Override
    267         protected Uri[] doInBackground(AddCallArgs... callList) {
    268             int count = callList.length;
    269             Uri[] result = new Uri[count];
    270             for (int i = 0; i < count; i++) {
    271                 AddCallArgs c = callList[i];
    272 
    273                 try {
    274                     // May block.
    275                     result[i] = Calls.addCall(c.callerInfo, c.context, c.number, c.presentation,
    276                             c.callType, c.features, c.accountHandle, c.timestamp, c.durationInSec,
    277                             c.dataUsage, true /* addForAllUsers */);
    278                 } catch (Exception e) {
    279                     // This is very rare but may happen in legitimate cases.
    280                     // E.g. If the phone is encrypted and thus write request fails, it may cause
    281                     // some kind of Exception (right now it is IllegalArgumentException, but this
    282                     // might change).
    283                     //
    284                     // We don't want to crash the whole process just because of that, so just log
    285                     // it instead.
    286                     Log.e(TAG, e, "Exception raised during adding CallLog entry.");
    287                     result[i] = null;
    288                 }
    289             }
    290             return result;
    291         }
    292 
    293         /**
    294          * Performs a simple sanity check to make sure the call was written in the database.
    295          * Typically there is only one result per call so it is easy to identify which one failed.
    296          */
    297         @Override
    298         protected void onPostExecute(Uri[] result) {
    299             for (Uri uri : result) {
    300                 if (uri == null) {
    301                     Log.w(TAG, "Failed to write call to the log.");
    302                 }
    303             }
    304         }
    305     }
    306 
    307     private void sendAddCallBroadcast(int callType, long duration) {
    308         Intent callAddIntent = new Intent(ACTION_CALLS_TABLE_ADD_ENTRY);
    309         callAddIntent.putExtra(CALL_TYPE, callType);
    310         callAddIntent.putExtra(CALL_DURATION, duration);
    311         mContext.sendBroadcast(callAddIntent, PERMISSION_PROCESS_CALLLOG_INFO);
    312     }
    313 }
    314