DrmManagerClient.java revision f05913aaa0cc96eab32be3431de1a80d405527a1
1/*
2 * Copyright (C) 2010 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
17package android.drm;
18
19import android.content.ContentResolver;
20import android.content.ContentValues;
21import android.content.Context;
22import android.database.Cursor;
23import android.database.sqlite.SQLiteException;
24import android.net.Uri;
25import android.os.Handler;
26import android.os.HandlerThread;
27import android.os.Looper;
28import android.os.Message;
29import android.provider.MediaStore;
30import android.util.Log;
31
32import java.io.IOException;
33import java.lang.ref.WeakReference;
34import java.util.ArrayList;
35import java.util.HashMap;
36
37/**
38 * Interface of DRM Framework.
39 * Java application will instantiate this class
40 * to access DRM agent through DRM Framework.
41 *
42 */
43public class DrmManagerClient {
44    /**
45     * Constant field signifies the success or no error occurred
46     */
47    public static final int ERROR_NONE = 0;
48    /**
49     * Constant field signifies that error occurred and the reason is not known
50     */
51    public static final int ERROR_UNKNOWN = -2000;
52
53    private static final String TAG = "DrmManagerClient";
54
55    static {
56        // Load the respective library
57        System.loadLibrary("drmframework_jni");
58    }
59
60    /**
61     * Interface definition of a callback to be invoked to communicate
62     * some info and/or warning about DrmManagerClient.
63     */
64    public interface OnInfoListener {
65        /**
66         * Called to indicate an info or a warning.
67         *
68         * @param client DrmManagerClient instance
69         * @param event instance which wraps reason and necessary information
70         */
71        public void onInfo(DrmManagerClient client, DrmInfoEvent event);
72    }
73
74    /**
75     * Interface definition of a callback to be invoked to communicate
76     * the result of time consuming APIs asynchronously
77     */
78    public interface OnEventListener {
79        /**
80         * Called to indicate the result of asynchronous APIs.
81         *
82         * @param client DrmManagerClient instance
83         * @param event instance which wraps type and message
84         * @param attributes resultant values in key and value pair.
85         */
86        public void onEvent(DrmManagerClient client, DrmEvent event,
87                HashMap<String, Object> attributes);
88    }
89
90    /**
91     * Interface definition of a callback to be invoked to communicate
92     * the error occurred
93     */
94    public interface OnErrorListener {
95        /**
96         * Called to indicate the error occurred.
97         *
98         * @param client DrmManagerClient instance
99         * @param event instance which wraps error type and message
100         */
101        public void onError(DrmManagerClient client, DrmErrorEvent event);
102    }
103
104    private static final int ACTION_REMOVE_ALL_RIGHTS = 1001;
105    private static final int ACTION_PROCESS_DRM_INFO = 1002;
106
107    private int mUniqueId;
108    private int mNativeContext;
109    private Context mContext;
110    private InfoHandler mInfoHandler;
111    private EventHandler mEventHandler;
112    private OnInfoListener mOnInfoListener;
113    private OnEventListener mOnEventListener;
114    private OnErrorListener mOnErrorListener;
115
116    private class EventHandler extends Handler {
117
118        public EventHandler(Looper looper) {
119            super(looper);
120        }
121
122        public void handleMessage(Message msg) {
123            DrmEvent event = null;
124            DrmErrorEvent error = null;
125            HashMap<String, Object> attributes = new HashMap<String, Object>();
126
127            switch(msg.what) {
128            case ACTION_PROCESS_DRM_INFO: {
129                final DrmInfo drmInfo = (DrmInfo) msg.obj;
130                DrmInfoStatus status = _processDrmInfo(mUniqueId, drmInfo);
131                if (null != status && DrmInfoStatus.STATUS_OK == status.statusCode) {
132                    attributes.put(DrmEvent.DRM_INFO_STATUS_OBJECT, status);
133                    event = new DrmEvent(mUniqueId, getEventType(status.infoType), null);
134                } else {
135                    int infoType = (null != status) ? status.infoType : drmInfo.getInfoType();
136                    error = new DrmErrorEvent(mUniqueId, getErrorType(infoType), null);
137                }
138                break;
139            }
140            case ACTION_REMOVE_ALL_RIGHTS: {
141                if (ERROR_NONE == _removeAllRights(mUniqueId)) {
142                    event = new DrmEvent(mUniqueId, DrmEvent.TYPE_ALL_RIGHTS_REMOVED, null);
143                } else {
144                    error = new DrmErrorEvent(mUniqueId,
145                            DrmErrorEvent.TYPE_REMOVE_ALL_RIGHTS_FAILED, null);
146                }
147                break;
148            }
149            default:
150                Log.e(TAG, "Unknown message type " + msg.what);
151                return;
152            }
153            if (null != mOnEventListener && null != event) {
154                mOnEventListener.onEvent(DrmManagerClient.this, event, attributes);
155            }
156            if (null != mOnErrorListener && null != error) {
157                mOnErrorListener.onError(DrmManagerClient.this, error);
158            }
159        }
160    }
161
162    /**
163     * {@hide}
164     */
165    public static void notify(
166            Object thisReference, int uniqueId, int infoType, String message) {
167        DrmManagerClient instance = (DrmManagerClient)((WeakReference)thisReference).get();
168
169        if (null != instance && null != instance.mInfoHandler) {
170            Message m = instance.mInfoHandler.obtainMessage(
171                InfoHandler.INFO_EVENT_TYPE, uniqueId, infoType, message);
172            instance.mInfoHandler.sendMessage(m);
173        }
174    }
175
176    private class InfoHandler extends Handler {
177        public static final int INFO_EVENT_TYPE = 1;
178
179        public InfoHandler(Looper looper) {
180            super(looper);
181        }
182
183        public void handleMessage(Message msg) {
184            DrmInfoEvent event = null;
185            DrmErrorEvent error = null;
186
187            switch (msg.what) {
188            case InfoHandler.INFO_EVENT_TYPE:
189                int uniqueId = msg.arg1;
190                int infoType = msg.arg2;
191                String message = msg.obj.toString();
192
193                switch (infoType) {
194                case DrmInfoEvent.TYPE_REMOVE_RIGHTS: {
195                    try {
196                        DrmUtils.removeFile(message);
197                    } catch (IOException e) {
198                        e.printStackTrace();
199                    }
200                    event = new DrmInfoEvent(uniqueId, infoType, message);
201                    break;
202                }
203                case DrmInfoEvent.TYPE_ALREADY_REGISTERED_BY_ANOTHER_ACCOUNT: {
204                    event = new DrmInfoEvent(uniqueId, infoType, message);
205                    break;
206                }
207                default:
208                    error = new DrmErrorEvent(uniqueId, infoType, message);
209                    break;
210                }
211
212                if (null != mOnInfoListener && null != event) {
213                    mOnInfoListener.onInfo(DrmManagerClient.this, event);
214                }
215                if (null != mOnErrorListener && null != error) {
216                    mOnErrorListener.onError(DrmManagerClient.this, error);
217                }
218                return;
219            default:
220                Log.e(TAG, "Unknown message type " + msg.what);
221                return;
222            }
223        }
224    }
225
226    /**
227     * To instantiate DrmManagerClient
228     *
229     * @param context context of the caller
230     */
231    public DrmManagerClient(Context context) {
232        mContext = context;
233
234        HandlerThread infoThread = new HandlerThread("DrmManagerClient.InfoHandler");
235        infoThread.start();
236        mInfoHandler = new InfoHandler(infoThread.getLooper());
237
238        HandlerThread eventThread = new HandlerThread("DrmManagerClient.EventHandler");
239        eventThread.start();
240        mEventHandler = new EventHandler(eventThread.getLooper());
241
242        // save the unique id
243        mUniqueId = hashCode();
244
245        _initialize(mUniqueId, new WeakReference<DrmManagerClient>(this));
246    }
247
248    protected void finalize() {
249        _finalize(mUniqueId);
250    }
251
252    /**
253     * Register a callback to be invoked when the caller required to receive
254     * supplementary information.
255     *
256     * @param infoListener
257     */
258    public synchronized void setOnInfoListener(OnInfoListener infoListener) {
259        if (null != infoListener) {
260            mOnInfoListener = infoListener;
261        }
262    }
263
264    /**
265     * Register a callback to be invoked when the caller required to receive
266     * the result of asynchronous APIs.
267     *
268     * @param eventListener
269     */
270    public synchronized void setOnEventListener(OnEventListener eventListener) {
271        if (null != eventListener) {
272            mOnEventListener = eventListener;
273        }
274    }
275
276    /**
277     * Register a callback to be invoked when the caller required to receive
278     * error result of asynchronous APIs.
279     *
280     * @param errorListener
281     */
282    public synchronized void setOnErrorListener(OnErrorListener errorListener) {
283        if (null != errorListener) {
284            mOnErrorListener = errorListener;
285        }
286    }
287
288    /**
289     * Retrieves informations about all the plug-ins registered with DrmFramework.
290     *
291     * @return Array of DrmEngine plug-in strings
292     */
293    public String[] getAvailableDrmEngines() {
294        DrmSupportInfo[] supportInfos = _getAllSupportInfo(mUniqueId);
295        ArrayList<String> descriptions = new ArrayList<String>();
296
297        for (int i = 0; i < supportInfos.length; i++) {
298            descriptions.add(supportInfos[i].getDescriprition());
299        }
300
301        String[] drmEngines = new String[descriptions.size()];
302        return descriptions.toArray(drmEngines);
303    }
304
305    /**
306     * Get constraints information evaluated from DRM content
307     *
308     * @param path Content path from where DRM constraints would be retrieved.
309     * @param action Actions defined in {@link DrmStore.Action}
310     * @return ContentValues instance in which constraints key-value pairs are embedded
311     *         or null in case of failure
312     */
313    public ContentValues getConstraints(String path, int action) {
314        if (null == path || path.equals("") || !DrmStore.Action.isValid(action)) {
315            throw new IllegalArgumentException("Given usage or path is invalid/null");
316        }
317        return _getConstraints(mUniqueId, path, action);
318    }
319
320   /**
321    * Get metadata information from DRM content
322    *
323    * @param path Content path from where DRM metadata would be retrieved.
324    * @return ContentValues instance in which metadata key-value pairs are embedded
325    *         or null in case of failure
326    */
327    public ContentValues getMetadata(String path) {
328        if (null == path || path.equals("")) {
329            throw new IllegalArgumentException("Given path is invalid/null");
330        }
331        return _getMetadata(mUniqueId, path);
332    }
333
334    /**
335     * Get constraints information evaluated from DRM content
336     *
337     * @param uri Content URI from where DRM constraints would be retrieved.
338     * @param action Actions defined in {@link DrmStore.Action}
339     * @return ContentValues instance in which constraints key-value pairs are embedded
340     *         or null in case of failure
341     */
342    public ContentValues getConstraints(Uri uri, int action) {
343        if (null == uri || Uri.EMPTY == uri) {
344            throw new IllegalArgumentException("Uri should be non null");
345        }
346        return getConstraints(convertUriToPath(uri), action);
347    }
348
349   /**
350    * Get metadata information from DRM content
351    *
352    * @param uri Content URI from where DRM metadata would be retrieved.
353    * @return ContentValues instance in which metadata key-value pairs are embedded
354    *         or null in case of failure
355    */
356    public ContentValues getMetadata(Uri uri) {
357        if (null == uri || Uri.EMPTY == uri) {
358            throw new IllegalArgumentException("Uri should be non null");
359        }
360        return getMetadata(convertUriToPath(uri));
361    }
362
363    /**
364     * Save DRM rights to specified rights path
365     * and make association with content path.
366     *
367     * <p class="note">In case of OMA or WM-DRM, rightsPath and contentPath could be null.</p>
368     *
369     * @param drmRights DrmRights to be saved
370     * @param rightsPath File path where rights to be saved
371     * @param contentPath File path where content was saved
372     * @return
373     *     ERROR_NONE for success
374     *     ERROR_UNKNOWN for failure
375     * @throws IOException if failed to save rights information in the given path
376     */
377    public int saveRights(
378            DrmRights drmRights, String rightsPath, String contentPath) throws IOException {
379        if (null == drmRights || !drmRights.isValid()) {
380            throw new IllegalArgumentException("Given drmRights or contentPath is not valid");
381        }
382        if (null != rightsPath && !rightsPath.equals("")) {
383            DrmUtils.writeToFile(rightsPath, drmRights.getData());
384        }
385        return _saveRights(mUniqueId, drmRights, rightsPath, contentPath);
386    }
387
388    /**
389     * Install new DRM Engine Plug-in at the runtime
390     *
391     * @param engineFilePath Path of the plug-in file to be installed
392     * {@hide}
393     */
394    public void installDrmEngine(String engineFilePath) {
395        if (null == engineFilePath || engineFilePath.equals("")) {
396            throw new IllegalArgumentException(
397                "Given engineFilePath: "+ engineFilePath + "is not valid");
398        }
399        _installDrmEngine(mUniqueId, engineFilePath);
400    }
401
402    /**
403     * Check whether the given mimetype or path can be handled.
404     *
405     * @param path Path of the content to be handled
406     * @param mimeType Mimetype of the object to be handled
407     * @return
408     *        true - if the given mimeType or path can be handled
409     *        false - cannot be handled.
410     */
411    public boolean canHandle(String path, String mimeType) {
412        if ((null == path || path.equals("")) && (null == mimeType || mimeType.equals(""))) {
413            throw new IllegalArgumentException("Path or the mimetype should be non null");
414        }
415        return _canHandle(mUniqueId, path, mimeType);
416    }
417
418    /**
419     * Check whether the given mimetype or uri can be handled.
420     *
421     * @param uri Content URI of the data to be handled.
422     * @param mimeType Mimetype of the object to be handled
423     * @return
424     *        true - if the given mimeType or path can be handled
425     *        false - cannot be handled.
426     */
427    public boolean canHandle(Uri uri, String mimeType) {
428        if ((null == uri || Uri.EMPTY == uri) && (null == mimeType || mimeType.equals(""))) {
429            throw new IllegalArgumentException("Uri or the mimetype should be non null");
430        }
431        return canHandle(convertUriToPath(uri), mimeType);
432    }
433
434    /**
435     * Executes given drm information based on its type
436     *
437     * @param drmInfo Information needs to be processed
438     * @return
439     *     ERROR_NONE for success
440     *     ERROR_UNKNOWN for failure
441     */
442    public int processDrmInfo(DrmInfo drmInfo) {
443        if (null == drmInfo || !drmInfo.isValid()) {
444            throw new IllegalArgumentException("Given drmInfo is invalid/null");
445        }
446        int result = ERROR_UNKNOWN;
447        if (null != mEventHandler) {
448            Message msg = mEventHandler.obtainMessage(ACTION_PROCESS_DRM_INFO, drmInfo);
449            result = (mEventHandler.sendMessage(msg)) ? ERROR_NONE : result;
450        }
451        return result;
452    }
453
454    /**
455     * Retrieves necessary information for register, unregister or rights acquisition.
456     *
457     * @param drmInfoRequest Request information to retrieve drmInfo
458     * @return DrmInfo Instance as a result of processing given input
459     */
460    public DrmInfo acquireDrmInfo(DrmInfoRequest drmInfoRequest) {
461        if (null == drmInfoRequest || !drmInfoRequest.isValid()) {
462            throw new IllegalArgumentException("Given drmInfoRequest is invalid/null");
463        }
464        return _acquireDrmInfo(mUniqueId, drmInfoRequest);
465    }
466
467    /**
468     * Executes given DrmInfoRequest and returns the rights information asynchronously.
469     * This is a utility API which consists of {@link #acquireDrmInfo(DrmInfoRequest)}
470     * and {@link #processDrmInfo(DrmInfo)}.
471     * It can be used if selected DRM agent can work with this combined sequences.
472     * In case of some DRM schemes, such as OMA DRM, application needs to invoke
473     * {@link #acquireDrmInfo(DrmInfoRequest)} and {@link #processDrmInfo(DrmInfo)}, separately.
474     *
475     * @param drmInfoRequest Request information to retrieve drmInfo
476     * @return
477     *     ERROR_NONE for success
478     *     ERROR_UNKNOWN for failure
479     */
480    public int acquireRights(DrmInfoRequest drmInfoRequest) {
481        DrmInfo drmInfo = acquireDrmInfo(drmInfoRequest);
482        return processDrmInfo(drmInfo);
483    }
484
485    /**
486     * Retrieves the type of the protected object (content, rights, etc..)
487     * using specified path or mimetype. At least one parameter should be non null
488     * to retrieve DRM object type
489     *
490     * @param path Path of the content or null.
491     * @param mimeType Mimetype of the content or null.
492     * @return Type of the DRM content.
493     * @see DrmStore.DrmObjectType
494     */
495    public int getDrmObjectType(String path, String mimeType) {
496        if ((null == path || path.equals("")) && (null == mimeType || mimeType.equals(""))) {
497            throw new IllegalArgumentException("Path or the mimetype should be non null");
498        }
499        return _getDrmObjectType(mUniqueId, path, mimeType);
500    }
501
502    /**
503     * Retrieves the type of the protected object (content, rights, etc..)
504     * using specified uri or mimetype. At least one parameter should be non null
505     * to retrieve DRM object type
506     *
507     * @param uri The content URI of the data
508     * @param mimeType Mimetype of the content or null.
509     * @return Type of the DRM content.
510     * @see DrmStore.DrmObjectType
511     */
512    public int getDrmObjectType(Uri uri, String mimeType) {
513        if ((null == uri || Uri.EMPTY == uri) && (null == mimeType || mimeType.equals(""))) {
514            throw new IllegalArgumentException("Uri or the mimetype should be non null");
515        }
516        String path = "";
517        try {
518            path = convertUriToPath(uri);
519        } catch (Exception e) {
520            // Even uri is invalid the mimetype shall be valid, so allow to proceed further.
521            Log.w(TAG, "Given Uri could not be found in media store");
522        }
523        return getDrmObjectType(path, mimeType);
524    }
525
526    /**
527     * Retrieves the mime type embedded inside the original content
528     *
529     * @param path Path of the protected content
530     * @return Mimetype of the original content, such as "video/mpeg"
531     */
532    public String getOriginalMimeType(String path) {
533        if (null == path || path.equals("")) {
534            throw new IllegalArgumentException("Given path should be non null");
535        }
536        return _getOriginalMimeType(mUniqueId, path);
537    }
538
539    /**
540     * Retrieves the mime type embedded inside the original content
541     *
542     * @param uri The content URI of the data
543     * @return Mimetype of the original content, such as "video/mpeg"
544     */
545    public String getOriginalMimeType(Uri uri) {
546        if (null == uri || Uri.EMPTY == uri) {
547            throw new IllegalArgumentException("Given uri is not valid");
548        }
549        return getOriginalMimeType(convertUriToPath(uri));
550    }
551
552    /**
553     * Check whether the given content has valid rights or not
554     *
555     * @param path Path of the protected content
556     * @return Status of the rights for the protected content
557     * @see DrmStore.RightsStatus
558     */
559    public int checkRightsStatus(String path) {
560        return checkRightsStatus(path, DrmStore.Action.DEFAULT);
561    }
562
563    /**
564     * Check whether the given content has valid rights or not
565     *
566     * @param uri The content URI of the data
567     * @return Status of the rights for the protected content
568     * @see DrmStore.RightsStatus
569     */
570    public int checkRightsStatus(Uri uri) {
571        if (null == uri || Uri.EMPTY == uri) {
572            throw new IllegalArgumentException("Given uri is not valid");
573        }
574        return checkRightsStatus(convertUriToPath(uri));
575    }
576
577    /**
578     * Check whether the given content has valid rights or not for specified action.
579     *
580     * @param path Path of the protected content
581     * @param action Action to perform
582     * @return Status of the rights for the protected content
583     * @see DrmStore.RightsStatus
584     */
585    public int checkRightsStatus(String path, int action) {
586        if (null == path || path.equals("") || !DrmStore.Action.isValid(action)) {
587            throw new IllegalArgumentException("Given path or action is not valid");
588        }
589        return _checkRightsStatus(mUniqueId, path, action);
590    }
591
592    /**
593     * Check whether the given content has valid rights or not for specified action.
594     *
595     * @param uri The content URI of the data
596     * @param action Action to perform
597     * @return Status of the rights for the protected content
598     * @see DrmStore.RightsStatus
599     */
600    public int checkRightsStatus(Uri uri, int action) {
601        if (null == uri || Uri.EMPTY == uri) {
602            throw new IllegalArgumentException("Given uri is not valid");
603        }
604        return checkRightsStatus(convertUriToPath(uri), action);
605    }
606
607    /**
608     * Removes the rights associated with the given protected content
609     *
610     * @param path Path of the protected content
611     * @return
612     *     ERROR_NONE for success
613     *     ERROR_UNKNOWN for failure
614     */
615    public int removeRights(String path) {
616        if (null == path || path.equals("")) {
617            throw new IllegalArgumentException("Given path should be non null");
618        }
619        return _removeRights(mUniqueId, path);
620    }
621
622    /**
623     * Removes the rights associated with the given protected content
624     *
625     * @param uri The content URI of the data
626     * @return
627     *     ERROR_NONE for success
628     *     ERROR_UNKNOWN for failure
629     */
630    public int removeRights(Uri uri) {
631        if (null == uri || Uri.EMPTY == uri) {
632            throw new IllegalArgumentException("Given uri is not valid");
633        }
634        return removeRights(convertUriToPath(uri));
635    }
636
637    /**
638     * Removes all the rights information of every plug-in associated with
639     * DRM framework. Will be used in master reset
640     *
641     * @return
642     *     ERROR_NONE for success
643     *     ERROR_UNKNOWN for failure
644     */
645    public int removeAllRights() {
646        int result = ERROR_UNKNOWN;
647        if (null != mEventHandler) {
648            Message msg = mEventHandler.obtainMessage(ACTION_REMOVE_ALL_RIGHTS);
649            result = (mEventHandler.sendMessage(msg)) ? ERROR_NONE : result;
650        }
651        return result;
652    }
653
654    /**
655     * This API is for Forward Lock based DRM scheme.
656     * Each time the application tries to download a new DRM file
657     * which needs to be converted, then the application has to
658     * begin with calling this API.
659     *
660     * @param mimeType Description/MIME type of the input data packet
661     * @return convert ID which will be used for maintaining convert session.
662     */
663    public int openConvertSession(String mimeType) {
664        if (null == mimeType || mimeType.equals("")) {
665            throw new IllegalArgumentException("Path or the mimeType should be non null");
666        }
667        return _openConvertSession(mUniqueId, mimeType);
668    }
669
670    /**
671     * Accepts and converts the input data which is part of DRM file.
672     * The resultant converted data and the status is returned in the DrmConvertedInfo
673     * object. This method will be called each time there are new block
674     * of data received by the application.
675     *
676     * @param convertId Handle for the convert session
677     * @param inputData Input Data which need to be converted
678     * @return Return object contains the status of the data conversion,
679     *         the output converted data and offset. In this case the
680     *         application will ignore the offset information.
681     */
682    public DrmConvertedStatus convertData(int convertId, byte[] inputData) {
683        if (null == inputData || 0 >= inputData.length) {
684            throw new IllegalArgumentException("Given inputData should be non null");
685        }
686        return _convertData(mUniqueId, convertId, inputData);
687    }
688
689    /**
690     * Informs the Drm Agent when there is no more data which need to be converted
691     * or when an error occurs. Upon successful conversion of the complete data,
692     * the agent will inform that where the header and body signature
693     * should be added. This signature appending is needed to integrity
694     * protect the converted file.
695     *
696     * @param convertId Handle for the convert session
697     * @return Return object contains the status of the data conversion,
698     *     the header and body signature data. It also informs
699     *     the application on which offset these signature data should be appended.
700     */
701    public DrmConvertedStatus closeConvertSession(int convertId) {
702        return _closeConvertSession(mUniqueId, convertId);
703    }
704
705    private int getEventType(int infoType) {
706        int eventType = -1;
707
708        switch (infoType) {
709        case DrmInfoRequest.TYPE_REGISTRATION_INFO:
710        case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
711        case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
712            eventType = DrmEvent.TYPE_DRM_INFO_PROCESSED;
713            break;
714        }
715        return eventType;
716    }
717
718    private int getErrorType(int infoType) {
719        int error = -1;
720
721        switch (infoType) {
722        case DrmInfoRequest.TYPE_REGISTRATION_INFO:
723        case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
724        case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
725            error = DrmErrorEvent.TYPE_PROCESS_DRM_INFO_FAILED;
726            break;
727        }
728        return error;
729    }
730
731    /**
732     * This method expects uri in the following format
733     *     content://media/<table_name>/<row_index> (or)
734     *     file://sdcard/test.mp4
735     *
736     * Here <table_name> shall be "video" or "audio" or "images"
737     * <row_index> the index of the content in given table
738     */
739    private String convertUriToPath(Uri uri) {
740        String path = null;
741        if (null != uri) {
742            String scheme = uri.getScheme();
743            if (null == scheme || scheme.equals("") ||
744                    scheme.equals(ContentResolver.SCHEME_FILE)) {
745                path = uri.getPath();
746            } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
747                String[] projection = new String[] {MediaStore.MediaColumns.DATA};
748                Cursor cursor = null;
749                try {
750                    cursor = mContext.getContentResolver().query(uri, projection, null,
751                            null, null);
752                    if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
753                        throw new IllegalArgumentException("Given Uri could not be found" +
754                                " in media store");
755                    }
756                    int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
757                    path = cursor.getString(pathIndex);
758                } catch (SQLiteException e) {
759                    throw new IllegalArgumentException("Given Uri is not formatted in a way " +
760                            "so that it can be found in media store.");
761                } finally {
762                    if (null != cursor) {
763                        cursor.close();
764                    }
765                }
766            } else {
767                throw new IllegalArgumentException("Given Uri scheme is not supported");
768            }
769        }
770        return path;
771    }
772
773    // private native interfaces
774    private native void _initialize(int uniqueId, Object weak_this);
775
776    private native void _finalize(int uniqueId);
777
778    private native void _installDrmEngine(int uniqueId, String engineFilepath);
779
780    private native ContentValues _getConstraints(int uniqueId, String path, int usage);
781
782    private native ContentValues _getMetadata(int uniqueId, String path);
783
784    private native boolean _canHandle(int uniqueId, String path, String mimeType);
785
786    private native DrmInfoStatus _processDrmInfo(int uniqueId, DrmInfo drmInfo);
787
788    private native DrmInfo _acquireDrmInfo(int uniqueId, DrmInfoRequest drmInfoRequest);
789
790    private native int _saveRights(
791            int uniqueId, DrmRights drmRights, String rightsPath, String contentPath);
792
793    private native int _getDrmObjectType(int uniqueId, String path, String mimeType);
794
795    private native String _getOriginalMimeType(int uniqueId, String path);
796
797    private native int _checkRightsStatus(int uniqueId, String path, int action);
798
799    private native int _removeRights(int uniqueId, String path);
800
801    private native int _removeAllRights(int uniqueId);
802
803    private native int _openConvertSession(int uniqueId, String mimeType);
804
805    private native DrmConvertedStatus _convertData(
806            int uniqueId, int convertId, byte[] inputData);
807
808    private native DrmConvertedStatus _closeConvertSession(int uniqueId, int convertId);
809
810    private native DrmSupportInfo[] _getAllSupportInfo(int uniqueId);
811}
812
813