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