DrmManagerClient.java revision 4ef690a38b1dfdff3ae34e260435edcec37e520f
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        if (null == drmInfo) {
483            return ERROR_UNKNOWN;
484        }
485        return processDrmInfo(drmInfo);
486    }
487
488    /**
489     * Retrieves the type of the protected object (content, rights, etc..)
490     * using specified path or mimetype. At least one parameter should be non null
491     * to retrieve DRM object type
492     *
493     * @param path Path of the content or null.
494     * @param mimeType Mimetype of the content or null.
495     * @return Type of the DRM content.
496     * @see DrmStore.DrmObjectType
497     */
498    public int getDrmObjectType(String path, String mimeType) {
499        if ((null == path || path.equals("")) && (null == mimeType || mimeType.equals(""))) {
500            throw new IllegalArgumentException("Path or the mimetype should be non null");
501        }
502        return _getDrmObjectType(mUniqueId, path, mimeType);
503    }
504
505    /**
506     * Retrieves the type of the protected object (content, rights, etc..)
507     * using specified uri or mimetype. At least one parameter should be non null
508     * to retrieve DRM object type
509     *
510     * @param uri The content URI of the data
511     * @param mimeType Mimetype of the content or null.
512     * @return Type of the DRM content.
513     * @see DrmStore.DrmObjectType
514     */
515    public int getDrmObjectType(Uri uri, String mimeType) {
516        if ((null == uri || Uri.EMPTY == uri) && (null == mimeType || mimeType.equals(""))) {
517            throw new IllegalArgumentException("Uri or the mimetype should be non null");
518        }
519        String path = "";
520        try {
521            path = convertUriToPath(uri);
522        } catch (Exception e) {
523            // Even uri is invalid the mimetype shall be valid, so allow to proceed further.
524            Log.w(TAG, "Given Uri could not be found in media store");
525        }
526        return getDrmObjectType(path, mimeType);
527    }
528
529    /**
530     * Retrieves the mime type embedded inside the original content
531     *
532     * @param path Path of the protected content
533     * @return Mimetype of the original content, such as "video/mpeg"
534     */
535    public String getOriginalMimeType(String path) {
536        if (null == path || path.equals("")) {
537            throw new IllegalArgumentException("Given path should be non null");
538        }
539        return _getOriginalMimeType(mUniqueId, path);
540    }
541
542    /**
543     * Retrieves the mime type embedded inside the original content
544     *
545     * @param uri The content URI of the data
546     * @return Mimetype of the original content, such as "video/mpeg"
547     */
548    public String getOriginalMimeType(Uri uri) {
549        if (null == uri || Uri.EMPTY == uri) {
550            throw new IllegalArgumentException("Given uri is not valid");
551        }
552        return getOriginalMimeType(convertUriToPath(uri));
553    }
554
555    /**
556     * Check whether the given content has valid rights or not
557     *
558     * @param path Path of the protected content
559     * @return Status of the rights for the protected content
560     * @see DrmStore.RightsStatus
561     */
562    public int checkRightsStatus(String path) {
563        return checkRightsStatus(path, DrmStore.Action.DEFAULT);
564    }
565
566    /**
567     * Check whether the given content has valid rights or not
568     *
569     * @param uri The content URI of the data
570     * @return Status of the rights for the protected content
571     * @see DrmStore.RightsStatus
572     */
573    public int checkRightsStatus(Uri uri) {
574        if (null == uri || Uri.EMPTY == uri) {
575            throw new IllegalArgumentException("Given uri is not valid");
576        }
577        return checkRightsStatus(convertUriToPath(uri));
578    }
579
580    /**
581     * Check whether the given content has valid rights or not for specified action.
582     *
583     * @param path Path of the protected content
584     * @param action Action to perform
585     * @return Status of the rights for the protected content
586     * @see DrmStore.RightsStatus
587     */
588    public int checkRightsStatus(String path, int action) {
589        if (null == path || path.equals("") || !DrmStore.Action.isValid(action)) {
590            throw new IllegalArgumentException("Given path or action is not valid");
591        }
592        return _checkRightsStatus(mUniqueId, path, action);
593    }
594
595    /**
596     * Check whether the given content has valid rights or not for specified action.
597     *
598     * @param uri The content URI of the data
599     * @param action Action to perform
600     * @return Status of the rights for the protected content
601     * @see DrmStore.RightsStatus
602     */
603    public int checkRightsStatus(Uri uri, int action) {
604        if (null == uri || Uri.EMPTY == uri) {
605            throw new IllegalArgumentException("Given uri is not valid");
606        }
607        return checkRightsStatus(convertUriToPath(uri), action);
608    }
609
610    /**
611     * Removes the rights associated with the given protected content
612     *
613     * @param path Path of the protected content
614     * @return
615     *     ERROR_NONE for success
616     *     ERROR_UNKNOWN for failure
617     */
618    public int removeRights(String path) {
619        if (null == path || path.equals("")) {
620            throw new IllegalArgumentException("Given path should be non null");
621        }
622        return _removeRights(mUniqueId, path);
623    }
624
625    /**
626     * Removes the rights associated with the given protected content
627     *
628     * @param uri The content URI of the data
629     * @return
630     *     ERROR_NONE for success
631     *     ERROR_UNKNOWN for failure
632     */
633    public int removeRights(Uri uri) {
634        if (null == uri || Uri.EMPTY == uri) {
635            throw new IllegalArgumentException("Given uri is not valid");
636        }
637        return removeRights(convertUriToPath(uri));
638    }
639
640    /**
641     * Removes all the rights information of every plug-in associated with
642     * DRM framework. Will be used in master reset
643     *
644     * @return
645     *     ERROR_NONE for success
646     *     ERROR_UNKNOWN for failure
647     */
648    public int removeAllRights() {
649        int result = ERROR_UNKNOWN;
650        if (null != mEventHandler) {
651            Message msg = mEventHandler.obtainMessage(ACTION_REMOVE_ALL_RIGHTS);
652            result = (mEventHandler.sendMessage(msg)) ? ERROR_NONE : result;
653        }
654        return result;
655    }
656
657    /**
658     * This API is for Forward Lock based DRM scheme.
659     * Each time the application tries to download a new DRM file
660     * which needs to be converted, then the application has to
661     * begin with calling this API.
662     *
663     * @param mimeType Description/MIME type of the input data packet
664     * @return convert ID which will be used for maintaining convert session.
665     */
666    public int openConvertSession(String mimeType) {
667        if (null == mimeType || mimeType.equals("")) {
668            throw new IllegalArgumentException("Path or the mimeType should be non null");
669        }
670        return _openConvertSession(mUniqueId, mimeType);
671    }
672
673    /**
674     * Accepts and converts the input data which is part of DRM file.
675     * The resultant converted data and the status is returned in the DrmConvertedInfo
676     * object. This method will be called each time there are new block
677     * of data received by the application.
678     *
679     * @param convertId Handle for the convert session
680     * @param inputData Input Data which need to be converted
681     * @return Return object contains the status of the data conversion,
682     *         the output converted data and offset. In this case the
683     *         application will ignore the offset information.
684     */
685    public DrmConvertedStatus convertData(int convertId, byte[] inputData) {
686        if (null == inputData || 0 >= inputData.length) {
687            throw new IllegalArgumentException("Given inputData should be non null");
688        }
689        return _convertData(mUniqueId, convertId, inputData);
690    }
691
692    /**
693     * Informs the Drm Agent when there is no more data which need to be converted
694     * or when an error occurs. Upon successful conversion of the complete data,
695     * the agent will inform that where the header and body signature
696     * should be added. This signature appending is needed to integrity
697     * protect the converted file.
698     *
699     * @param convertId Handle for the convert session
700     * @return Return object contains the status of the data conversion,
701     *     the header and body signature data. It also informs
702     *     the application on which offset these signature data should be appended.
703     */
704    public DrmConvertedStatus closeConvertSession(int convertId) {
705        return _closeConvertSession(mUniqueId, convertId);
706    }
707
708    private int getEventType(int infoType) {
709        int eventType = -1;
710
711        switch (infoType) {
712        case DrmInfoRequest.TYPE_REGISTRATION_INFO:
713        case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
714        case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
715            eventType = DrmEvent.TYPE_DRM_INFO_PROCESSED;
716            break;
717        }
718        return eventType;
719    }
720
721    private int getErrorType(int infoType) {
722        int error = -1;
723
724        switch (infoType) {
725        case DrmInfoRequest.TYPE_REGISTRATION_INFO:
726        case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
727        case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
728            error = DrmErrorEvent.TYPE_PROCESS_DRM_INFO_FAILED;
729            break;
730        }
731        return error;
732    }
733
734    /**
735     * This method expects uri in the following format
736     *     content://media/<table_name>/<row_index> (or)
737     *     file://sdcard/test.mp4
738     *
739     * Here <table_name> shall be "video" or "audio" or "images"
740     * <row_index> the index of the content in given table
741     */
742    private String convertUriToPath(Uri uri) {
743        String path = null;
744        if (null != uri) {
745            String scheme = uri.getScheme();
746            if (null == scheme || scheme.equals("") ||
747                    scheme.equals(ContentResolver.SCHEME_FILE)) {
748                path = uri.getPath();
749            } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
750                String[] projection = new String[] {MediaStore.MediaColumns.DATA};
751                Cursor cursor = null;
752                try {
753                    cursor = mContext.getContentResolver().query(uri, projection, null,
754                            null, null);
755                    if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
756                        throw new IllegalArgumentException("Given Uri could not be found" +
757                                " in media store");
758                    }
759                    int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
760                    path = cursor.getString(pathIndex);
761                } catch (SQLiteException e) {
762                    throw new IllegalArgumentException("Given Uri is not formatted in a way " +
763                            "so that it can be found in media store.");
764                } finally {
765                    if (null != cursor) {
766                        cursor.close();
767                    }
768                }
769            } else {
770                throw new IllegalArgumentException("Given Uri scheme is not supported");
771            }
772        }
773        return path;
774    }
775
776    // private native interfaces
777    private native void _initialize(int uniqueId, Object weak_this);
778
779    private native void _finalize(int uniqueId);
780
781    private native void _installDrmEngine(int uniqueId, String engineFilepath);
782
783    private native ContentValues _getConstraints(int uniqueId, String path, int usage);
784
785    private native ContentValues _getMetadata(int uniqueId, String path);
786
787    private native boolean _canHandle(int uniqueId, String path, String mimeType);
788
789    private native DrmInfoStatus _processDrmInfo(int uniqueId, DrmInfo drmInfo);
790
791    private native DrmInfo _acquireDrmInfo(int uniqueId, DrmInfoRequest drmInfoRequest);
792
793    private native int _saveRights(
794            int uniqueId, DrmRights drmRights, String rightsPath, String contentPath);
795
796    private native int _getDrmObjectType(int uniqueId, String path, String mimeType);
797
798    private native String _getOriginalMimeType(int uniqueId, String path);
799
800    private native int _checkRightsStatus(int uniqueId, String path, int action);
801
802    private native int _removeRights(int uniqueId, String path);
803
804    private native int _removeAllRights(int uniqueId);
805
806    private native int _openConvertSession(int uniqueId, String mimeType);
807
808    private native DrmConvertedStatus _convertData(
809            int uniqueId, int convertId, byte[] inputData);
810
811    private native DrmConvertedStatus _closeConvertSession(int uniqueId, int convertId);
812
813    private native DrmSupportInfo[] _getAllSupportInfo(int uniqueId);
814}
815
816