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