DrmManagerClient.java revision 27b277779c89251f2aafcc7a56db95d264900c9d
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 info = 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                    info = new DrmInfoEvent(uniqueId, infoType, message);
201                    break;
202                }
203                case DrmInfoEvent.TYPE_ALREADY_REGISTERED_BY_ANOTHER_ACCOUNT:
204                case DrmInfoEvent.TYPE_RIGHTS_INSTALLED:
205                case DrmInfoEvent.TYPE_WAIT_FOR_RIGHTS:
206                case DrmInfoEvent.TYPE_ACCOUNT_ALREADY_REGISTERED:
207                case DrmInfoEvent.TYPE_RIGHTS_REMOVED: {
208                    info = new DrmInfoEvent(uniqueId, infoType, message);
209                    break;
210                }
211                default:
212                    error = new DrmErrorEvent(uniqueId, infoType, message);
213                    break;
214                }
215
216                if (null != mOnInfoListener && null != info) {
217                    mOnInfoListener.onInfo(DrmManagerClient.this, info);
218                }
219                if (null != mOnErrorListener && null != error) {
220                    mOnErrorListener.onError(DrmManagerClient.this, error);
221                }
222                return;
223            default:
224                Log.e(TAG, "Unknown message type " + msg.what);
225                return;
226            }
227        }
228    }
229
230    /**
231     * To instantiate DrmManagerClient
232     *
233     * @param context context of the caller
234     */
235    public DrmManagerClient(Context context) {
236        mContext = context;
237
238        HandlerThread infoThread = new HandlerThread("DrmManagerClient.InfoHandler");
239        infoThread.start();
240        mInfoHandler = new InfoHandler(infoThread.getLooper());
241
242        HandlerThread eventThread = new HandlerThread("DrmManagerClient.EventHandler");
243        eventThread.start();
244        mEventHandler = new EventHandler(eventThread.getLooper());
245
246        // save the unique id
247        mUniqueId = hashCode();
248
249        _initialize(mUniqueId, new WeakReference<DrmManagerClient>(this));
250    }
251
252    protected void finalize() {
253        _finalize(mUniqueId);
254    }
255
256    /**
257     * Register a callback to be invoked when the caller required to receive
258     * supplementary information.
259     *
260     * @param infoListener
261     */
262    public synchronized void setOnInfoListener(OnInfoListener infoListener) {
263        if (null != infoListener) {
264            mOnInfoListener = infoListener;
265        }
266    }
267
268    /**
269     * Register a callback to be invoked when the caller required to receive
270     * the result of asynchronous APIs.
271     *
272     * @param eventListener
273     */
274    public synchronized void setOnEventListener(OnEventListener eventListener) {
275        if (null != eventListener) {
276            mOnEventListener = eventListener;
277        }
278    }
279
280    /**
281     * Register a callback to be invoked when the caller required to receive
282     * error result of asynchronous APIs.
283     *
284     * @param errorListener
285     */
286    public synchronized void setOnErrorListener(OnErrorListener errorListener) {
287        if (null != errorListener) {
288            mOnErrorListener = errorListener;
289        }
290    }
291
292    /**
293     * Retrieves informations about all the plug-ins registered with DrmFramework.
294     *
295     * @return Array of DrmEngine plug-in strings
296     */
297    public String[] getAvailableDrmEngines() {
298        DrmSupportInfo[] supportInfos = _getAllSupportInfo(mUniqueId);
299        ArrayList<String> descriptions = new ArrayList<String>();
300
301        for (int i = 0; i < supportInfos.length; i++) {
302            descriptions.add(supportInfos[i].getDescriprition());
303        }
304
305        String[] drmEngines = new String[descriptions.size()];
306        return descriptions.toArray(drmEngines);
307    }
308
309    /**
310     * Get constraints information evaluated from DRM content
311     *
312     * @param path Content path from where DRM constraints would be retrieved.
313     * @param action Actions defined in {@link DrmStore.Action}
314     * @return ContentValues instance in which constraints key-value pairs are embedded
315     *         or null in case of failure
316     */
317    public ContentValues getConstraints(String path, int action) {
318        if (null == path || path.equals("") || !DrmStore.Action.isValid(action)) {
319            throw new IllegalArgumentException("Given usage or path is invalid/null");
320        }
321        return _getConstraints(mUniqueId, path, action);
322    }
323
324   /**
325    * Get metadata information from DRM content
326    *
327    * @param path Content path from where DRM metadata would be retrieved.
328    * @return ContentValues instance in which metadata key-value pairs are embedded
329    *         or null in case of failure
330    */
331    public ContentValues getMetadata(String path) {
332        if (null == path || path.equals("")) {
333            throw new IllegalArgumentException("Given path is invalid/null");
334        }
335        return _getMetadata(mUniqueId, path);
336    }
337
338    /**
339     * Get constraints information evaluated from DRM content
340     *
341     * @param uri Content URI from where DRM constraints would be retrieved.
342     * @param action Actions defined in {@link DrmStore.Action}
343     * @return ContentValues instance in which constraints key-value pairs are embedded
344     *         or null in case of failure
345     */
346    public ContentValues getConstraints(Uri uri, int action) {
347        if (null == uri || Uri.EMPTY == uri) {
348            throw new IllegalArgumentException("Uri should be non null");
349        }
350        return getConstraints(convertUriToPath(uri), action);
351    }
352
353   /**
354    * Get metadata information from DRM content
355    *
356    * @param uri Content URI from where DRM metadata would be retrieved.
357    * @return ContentValues instance in which metadata key-value pairs are embedded
358    *         or null in case of failure
359    */
360    public ContentValues getMetadata(Uri uri) {
361        if (null == uri || Uri.EMPTY == uri) {
362            throw new IllegalArgumentException("Uri should be non null");
363        }
364        return getMetadata(convertUriToPath(uri));
365    }
366
367    /**
368     * Save DRM rights to specified rights path
369     * and make association with content path.
370     *
371     * <p class="note">In case of OMA or WM-DRM, rightsPath and contentPath could be null.</p>
372     *
373     * @param drmRights DrmRights to be saved
374     * @param rightsPath File path where rights to be saved
375     * @param contentPath File path where content was saved
376     * @return
377     *     ERROR_NONE for success
378     *     ERROR_UNKNOWN for failure
379     * @throws IOException if failed to save rights information in the given path
380     */
381    public int saveRights(
382            DrmRights drmRights, String rightsPath, String contentPath) throws IOException {
383        if (null == drmRights || !drmRights.isValid()) {
384            throw new IllegalArgumentException("Given drmRights or contentPath is not valid");
385        }
386        if (null != rightsPath && !rightsPath.equals("")) {
387            DrmUtils.writeToFile(rightsPath, drmRights.getData());
388        }
389        return _saveRights(mUniqueId, drmRights, rightsPath, contentPath);
390    }
391
392    /**
393     * Install new DRM Engine Plug-in at the runtime
394     *
395     * @param engineFilePath Path of the plug-in file to be installed
396     * {@hide}
397     */
398    public void installDrmEngine(String engineFilePath) {
399        if (null == engineFilePath || engineFilePath.equals("")) {
400            throw new IllegalArgumentException(
401                "Given engineFilePath: "+ engineFilePath + "is not valid");
402        }
403        _installDrmEngine(mUniqueId, engineFilePath);
404    }
405
406    /**
407     * Check whether the given mimetype or path can be handled.
408     *
409     * @param path Path of the content to be handled
410     * @param mimeType Mimetype of the object to be handled
411     * @return
412     *        true - if the given mimeType or path can be handled
413     *        false - cannot be handled.
414     */
415    public boolean canHandle(String path, String mimeType) {
416        if ((null == path || path.equals("")) && (null == mimeType || mimeType.equals(""))) {
417            throw new IllegalArgumentException("Path or the mimetype should be non null");
418        }
419        return _canHandle(mUniqueId, path, mimeType);
420    }
421
422    /**
423     * Check whether the given mimetype or uri can be handled.
424     *
425     * @param uri Content URI of the data to be handled.
426     * @param mimeType Mimetype of the object to be handled
427     * @return
428     *        true - if the given mimeType or path can be handled
429     *        false - cannot be handled.
430     */
431    public boolean canHandle(Uri uri, String mimeType) {
432        if ((null == uri || Uri.EMPTY == uri) && (null == mimeType || mimeType.equals(""))) {
433            throw new IllegalArgumentException("Uri or the mimetype should be non null");
434        }
435        return canHandle(convertUriToPath(uri), mimeType);
436    }
437
438    /**
439     * Executes given drm information based on its type
440     *
441     * @param drmInfo Information needs to be processed
442     * @return
443     *     ERROR_NONE for success
444     *     ERROR_UNKNOWN for failure
445     */
446    public int processDrmInfo(DrmInfo drmInfo) {
447        if (null == drmInfo || !drmInfo.isValid()) {
448            throw new IllegalArgumentException("Given drmInfo is invalid/null");
449        }
450        int result = ERROR_UNKNOWN;
451        if (null != mEventHandler) {
452            Message msg = mEventHandler.obtainMessage(ACTION_PROCESS_DRM_INFO, drmInfo);
453            result = (mEventHandler.sendMessage(msg)) ? ERROR_NONE : result;
454        }
455        return result;
456    }
457
458    /**
459     * Retrieves necessary information for register, unregister or rights acquisition.
460     *
461     * @param drmInfoRequest Request information to retrieve drmInfo
462     * @return DrmInfo Instance as a result of processing given input
463     */
464    public DrmInfo acquireDrmInfo(DrmInfoRequest drmInfoRequest) {
465        if (null == drmInfoRequest || !drmInfoRequest.isValid()) {
466            throw new IllegalArgumentException("Given drmInfoRequest is invalid/null");
467        }
468        return _acquireDrmInfo(mUniqueId, drmInfoRequest);
469    }
470
471    /**
472     * Executes given DrmInfoRequest and returns the rights information asynchronously.
473     * This is a utility API which consists of {@link #acquireDrmInfo(DrmInfoRequest)}
474     * and {@link #processDrmInfo(DrmInfo)}.
475     * It can be used if selected DRM agent can work with this combined sequences.
476     * In case of some DRM schemes, such as OMA DRM, application needs to invoke
477     * {@link #acquireDrmInfo(DrmInfoRequest)} and {@link #processDrmInfo(DrmInfo)}, separately.
478     *
479     * @param drmInfoRequest Request information to retrieve drmInfo
480     * @return
481     *     ERROR_NONE for success
482     *     ERROR_UNKNOWN for failure
483     */
484    public int acquireRights(DrmInfoRequest drmInfoRequest) {
485        DrmInfo drmInfo = acquireDrmInfo(drmInfoRequest);
486        if (null == drmInfo) {
487            return ERROR_UNKNOWN;
488        }
489        return processDrmInfo(drmInfo);
490    }
491
492    /**
493     * Retrieves the type of the protected object (content, rights, etc..)
494     * using specified path or mimetype. At least one parameter should be non null
495     * to retrieve DRM object type
496     *
497     * @param path Path of the content or null.
498     * @param mimeType Mimetype of the content or null.
499     * @return Type of the DRM content.
500     * @see DrmStore.DrmObjectType
501     */
502    public int getDrmObjectType(String path, String mimeType) {
503        if ((null == path || path.equals("")) && (null == mimeType || mimeType.equals(""))) {
504            throw new IllegalArgumentException("Path or the mimetype should be non null");
505        }
506        return _getDrmObjectType(mUniqueId, path, mimeType);
507    }
508
509    /**
510     * Retrieves the type of the protected object (content, rights, etc..)
511     * using specified uri or mimetype. At least one parameter should be non null
512     * to retrieve DRM object type
513     *
514     * @param uri The content URI of the data
515     * @param mimeType Mimetype of the content or null.
516     * @return Type of the DRM content.
517     * @see DrmStore.DrmObjectType
518     */
519    public int getDrmObjectType(Uri uri, String mimeType) {
520        if ((null == uri || Uri.EMPTY == uri) && (null == mimeType || mimeType.equals(""))) {
521            throw new IllegalArgumentException("Uri or the mimetype should be non null");
522        }
523        String path = "";
524        try {
525            path = convertUriToPath(uri);
526        } catch (Exception e) {
527            // Even uri is invalid the mimetype shall be valid, so allow to proceed further.
528            Log.w(TAG, "Given Uri could not be found in media store");
529        }
530        return getDrmObjectType(path, mimeType);
531    }
532
533    /**
534     * Retrieves the mime type embedded inside the original content
535     *
536     * @param path Path of the protected content
537     * @return Mimetype of the original content, such as "video/mpeg"
538     */
539    public String getOriginalMimeType(String path) {
540        if (null == path || path.equals("")) {
541            throw new IllegalArgumentException("Given path should be non null");
542        }
543        return _getOriginalMimeType(mUniqueId, path);
544    }
545
546    /**
547     * Retrieves the mime type embedded inside the original content
548     *
549     * @param uri The content URI of the data
550     * @return Mimetype of the original content, such as "video/mpeg"
551     */
552    public String getOriginalMimeType(Uri uri) {
553        if (null == uri || Uri.EMPTY == uri) {
554            throw new IllegalArgumentException("Given uri is not valid");
555        }
556        return getOriginalMimeType(convertUriToPath(uri));
557    }
558
559    /**
560     * Check whether the given content has valid rights or not
561     *
562     * @param path Path of the protected content
563     * @return Status of the rights for the protected content
564     * @see DrmStore.RightsStatus
565     */
566    public int checkRightsStatus(String path) {
567        return checkRightsStatus(path, DrmStore.Action.DEFAULT);
568    }
569
570    /**
571     * Check whether the given content has valid rights or not
572     *
573     * @param uri The content URI of the data
574     * @return Status of the rights for the protected content
575     * @see DrmStore.RightsStatus
576     */
577    public int checkRightsStatus(Uri uri) {
578        if (null == uri || Uri.EMPTY == uri) {
579            throw new IllegalArgumentException("Given uri is not valid");
580        }
581        return checkRightsStatus(convertUriToPath(uri));
582    }
583
584    /**
585     * Check whether the given content has valid rights or not for specified action.
586     *
587     * @param path Path of the protected content
588     * @param action Action to perform
589     * @return Status of the rights for the protected content
590     * @see DrmStore.RightsStatus
591     */
592    public int checkRightsStatus(String path, int action) {
593        if (null == path || path.equals("") || !DrmStore.Action.isValid(action)) {
594            throw new IllegalArgumentException("Given path or action is not valid");
595        }
596        return _checkRightsStatus(mUniqueId, path, action);
597    }
598
599    /**
600     * Check whether the given content has valid rights or not for specified action.
601     *
602     * @param uri The content URI of the data
603     * @param action Action to perform
604     * @return Status of the rights for the protected content
605     * @see DrmStore.RightsStatus
606     */
607    public int checkRightsStatus(Uri uri, int action) {
608        if (null == uri || Uri.EMPTY == uri) {
609            throw new IllegalArgumentException("Given uri is not valid");
610        }
611        return checkRightsStatus(convertUriToPath(uri), action);
612    }
613
614    /**
615     * Removes the rights associated with the given protected content
616     *
617     * @param path Path of the protected content
618     * @return
619     *     ERROR_NONE for success
620     *     ERROR_UNKNOWN for failure
621     */
622    public int removeRights(String path) {
623        if (null == path || path.equals("")) {
624            throw new IllegalArgumentException("Given path should be non null");
625        }
626        return _removeRights(mUniqueId, path);
627    }
628
629    /**
630     * Removes the rights associated with the given protected content
631     *
632     * @param uri The content URI of the data
633     * @return
634     *     ERROR_NONE for success
635     *     ERROR_UNKNOWN for failure
636     */
637    public int removeRights(Uri uri) {
638        if (null == uri || Uri.EMPTY == uri) {
639            throw new IllegalArgumentException("Given uri is not valid");
640        }
641        return removeRights(convertUriToPath(uri));
642    }
643
644    /**
645     * Removes all the rights information of every plug-in associated with
646     * DRM framework. Will be used in master reset
647     *
648     * @return
649     *     ERROR_NONE for success
650     *     ERROR_UNKNOWN for failure
651     */
652    public int removeAllRights() {
653        int result = ERROR_UNKNOWN;
654        if (null != mEventHandler) {
655            Message msg = mEventHandler.obtainMessage(ACTION_REMOVE_ALL_RIGHTS);
656            result = (mEventHandler.sendMessage(msg)) ? ERROR_NONE : result;
657        }
658        return result;
659    }
660
661    /**
662     * This API is for Forward Lock based DRM scheme.
663     * Each time the application tries to download a new DRM file
664     * which needs to be converted, then the application has to
665     * begin with calling this API.
666     *
667     * @param mimeType Description/MIME type of the input data packet
668     * @return convert ID which will be used for maintaining convert session.
669     */
670    public int openConvertSession(String mimeType) {
671        if (null == mimeType || mimeType.equals("")) {
672            throw new IllegalArgumentException("Path or the mimeType should be non null");
673        }
674        return _openConvertSession(mUniqueId, mimeType);
675    }
676
677    /**
678     * Accepts and converts the input data which is part of DRM file.
679     * The resultant converted data and the status is returned in the DrmConvertedInfo
680     * object. This method will be called each time there are new block
681     * of data received by the application.
682     *
683     * @param convertId Handle for the convert session
684     * @param inputData Input Data which need to be converted
685     * @return Return object contains the status of the data conversion,
686     *         the output converted data and offset. In this case the
687     *         application will ignore the offset information.
688     */
689    public DrmConvertedStatus convertData(int convertId, byte[] inputData) {
690        if (null == inputData || 0 >= inputData.length) {
691            throw new IllegalArgumentException("Given inputData should be non null");
692        }
693        return _convertData(mUniqueId, convertId, inputData);
694    }
695
696    /**
697     * Informs the Drm Agent when there is no more data which need to be converted
698     * or when an error occurs. Upon successful conversion of the complete data,
699     * the agent will inform that where the header and body signature
700     * should be added. This signature appending is needed to integrity
701     * protect the converted file.
702     *
703     * @param convertId Handle for the convert session
704     * @return Return object contains the status of the data conversion,
705     *     the header and body signature data. It also informs
706     *     the application on which offset these signature data should be appended.
707     */
708    public DrmConvertedStatus closeConvertSession(int convertId) {
709        return _closeConvertSession(mUniqueId, convertId);
710    }
711
712    private int getEventType(int infoType) {
713        int eventType = -1;
714
715        switch (infoType) {
716        case DrmInfoRequest.TYPE_REGISTRATION_INFO:
717        case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
718        case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
719            eventType = DrmEvent.TYPE_DRM_INFO_PROCESSED;
720            break;
721        }
722        return eventType;
723    }
724
725    private int getErrorType(int infoType) {
726        int error = -1;
727
728        switch (infoType) {
729        case DrmInfoRequest.TYPE_REGISTRATION_INFO:
730        case DrmInfoRequest.TYPE_UNREGISTRATION_INFO:
731        case DrmInfoRequest.TYPE_RIGHTS_ACQUISITION_INFO:
732            error = DrmErrorEvent.TYPE_PROCESS_DRM_INFO_FAILED;
733            break;
734        }
735        return error;
736    }
737
738    /**
739     * This method expects uri in the following format
740     *     content://media/<table_name>/<row_index> (or)
741     *     file://sdcard/test.mp4
742     *     http://test.com/test.mp4
743     *
744     * Here <table_name> shall be "video" or "audio" or "images"
745     * <row_index> the index of the content in given table
746     */
747    private String convertUriToPath(Uri uri) {
748        String path = null;
749        if (null != uri) {
750            String scheme = uri.getScheme();
751            if (null == scheme || scheme.equals("") ||
752                    scheme.equals(ContentResolver.SCHEME_FILE)) {
753                path = uri.getPath();
754
755            } else if (scheme.equals("http")) {
756                path = uri.toString();
757
758            } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
759                String[] projection = new String[] {MediaStore.MediaColumns.DATA};
760                Cursor cursor = null;
761                try {
762                    cursor = mContext.getContentResolver().query(uri, projection, null,
763                            null, null);
764                    if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) {
765                        throw new IllegalArgumentException("Given Uri could not be found" +
766                                " in media store");
767                    }
768                    int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
769                    path = cursor.getString(pathIndex);
770                } catch (SQLiteException e) {
771                    throw new IllegalArgumentException("Given Uri is not formatted in a way " +
772                            "so that it can be found in media store.");
773                } finally {
774                    if (null != cursor) {
775                        cursor.close();
776                    }
777                }
778            } else {
779                throw new IllegalArgumentException("Given Uri scheme is not supported");
780            }
781        }
782        return path;
783    }
784
785    // private native interfaces
786    private native void _initialize(int uniqueId, Object weak_this);
787
788    private native void _finalize(int uniqueId);
789
790    private native void _installDrmEngine(int uniqueId, String engineFilepath);
791
792    private native ContentValues _getConstraints(int uniqueId, String path, int usage);
793
794    private native ContentValues _getMetadata(int uniqueId, String path);
795
796    private native boolean _canHandle(int uniqueId, String path, String mimeType);
797
798    private native DrmInfoStatus _processDrmInfo(int uniqueId, DrmInfo drmInfo);
799
800    private native DrmInfo _acquireDrmInfo(int uniqueId, DrmInfoRequest drmInfoRequest);
801
802    private native int _saveRights(
803            int uniqueId, DrmRights drmRights, String rightsPath, String contentPath);
804
805    private native int _getDrmObjectType(int uniqueId, String path, String mimeType);
806
807    private native String _getOriginalMimeType(int uniqueId, String path);
808
809    private native int _checkRightsStatus(int uniqueId, String path, int action);
810
811    private native int _removeRights(int uniqueId, String path);
812
813    private native int _removeAllRights(int uniqueId);
814
815    private native int _openConvertSession(int uniqueId, String mimeType);
816
817    private native DrmConvertedStatus _convertData(
818            int uniqueId, int convertId, byte[] inputData);
819
820    private native DrmConvertedStatus _closeConvertSession(int uniqueId, int convertId);
821
822    private native DrmSupportInfo[] _getAllSupportInfo(int uniqueId);
823}
824
825