Home | History | Annotate | Download | only in transcribe
      1 /*
      2  * Copyright (C) 2017 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 package com.android.voicemail.impl.transcribe;
     17 
     18 import android.annotation.TargetApi;
     19 import android.content.Context;
     20 import android.net.Uri;
     21 import android.os.Build.VERSION_CODES;
     22 import android.support.annotation.Nullable;
     23 import android.util.Base64;
     24 import com.android.dialer.common.Assert;
     25 import com.google.internal.communications.voicemailtranscription.v1.AudioFormat;
     26 import com.google.protobuf.ByteString;
     27 import java.io.IOException;
     28 import java.io.InputStream;
     29 import java.security.MessageDigest;
     30 import java.security.NoSuchAlgorithmException;
     31 
     32 /** Utility methods used by this transcription package. */
     33 public class TranscriptionUtils {
     34   static final String AMR_PREFIX = "#!AMR\n";
     35 
     36   // Uses try-with-resource
     37   @TargetApi(android.os.Build.VERSION_CODES.M)
     38   static ByteString getAudioData(Context context, Uri voicemailUri) {
     39     try (InputStream in = context.getContentResolver().openInputStream(voicemailUri)) {
     40       return ByteString.readFrom(in);
     41     } catch (IOException e) {
     42       return null;
     43     }
     44   }
     45 
     46   static AudioFormat getAudioFormat(ByteString audioData) {
     47     return audioData != null && audioData.startsWith(ByteString.copyFromUtf8(AMR_PREFIX))
     48         ? AudioFormat.AMR_NB_8KHZ
     49         : AudioFormat.AUDIO_FORMAT_UNSPECIFIED;
     50   }
     51 
     52   @TargetApi(VERSION_CODES.O)
     53   static String getFingerprintFor(ByteString data, @Nullable String salt) {
     54     Assert.checkArgument(data != null);
     55     try {
     56       MessageDigest md = MessageDigest.getInstance("MD5");
     57       if (salt != null) {
     58         md.update(salt.getBytes());
     59       }
     60       byte[] md5Bytes = md.digest(data.toByteArray());
     61       return Base64.encodeToString(md5Bytes, Base64.DEFAULT);
     62     } catch (NoSuchAlgorithmException e) {
     63       Assert.fail(e.toString());
     64     }
     65     return null;
     66   }
     67 }
     68