Merge "[MediaContent] Fixed errors in the doc-comments."
[platform/core/csapi/tizenfx.git] / src / Tizen.Security.PrivacyPrivilegeManager / Tizen.Security / PrivacyPrivilegeManager.cs
1 /*
2  * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
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
17 using System;
18 using System.Collections.Generic;
19 using Tizen.Internals.Errors;
20
21 namespace Tizen.Security
22 {
23     /// <summary>
24     /// The PrivacyPrivilegeManager provides the properties or methods to check and request a permission for privacy privilege.
25     /// </summary>
26     public static class PrivacyPrivilegeManager
27     {
28         private const string LogTag = "Tizen.Privilege";
29         private static Interop.PrivacyPrivilegeManager.RequestResponseCallback s_requestResponseCb;
30         private static IDictionary<string, ResponseContext> s_responseMap = new Dictionary<string, ResponseContext>();
31
32         static PrivacyPrivilegeManager()
33         {
34             s_requestResponseCb = (Interop.PrivacyPrivilegeManager.CallCause cause, Interop.PrivacyPrivilegeManager.RequestResult result, string privilege, IntPtr userData) =>
35             {
36                 try
37                 {
38                     s_responseMap[privilege].FireEvent((CallCause)cause, (RequestResult) result);
39                 }
40                 catch (Exception e)
41                 {
42                     Log.Error(LogTag, "Exception in callback : " + e.Message);
43                 }
44             };
45         }
46
47         /// <summary>
48         /// Gets the status of a privacy privilege permission.
49         /// </summary>
50         /// <param name="privilege">The privacy privilege to be checked.</param>
51         /// <returns>The permission setting for a respective privilege.</returns>
52         /// <exception cref="ArgumentException">Thrown when an invalid parameter is passed.</exception>
53         /// <exception cref="OutOfMemoryException">Thrown when a memory error occurred.</exception>
54         /// <exception cref="System.IO.IOException">Thrown when the method failed due to an internal I/O error.</exception>
55         /// <example>
56         /// <code>
57         ///     CheckResult result = PrivacyPrivilegeManager.CheckPermission("http://tizen.org/privilege/account.read");
58         ///     switch (result)
59         ///     {
60         ///         case Allow:
61         ///             // Privilege can be used
62         ///             break;
63         ///         case Deny:
64         ///             // Privilege can't be used
65         ///             break;
66         ///         case Ask:
67         ///             // User permission request required
68         ///             PrivacyPrivilegeManager.RequestPermission("http://tizen.org/privilege/account.read");
69         ///             break;
70         ///     }
71         /// </code>
72         /// </example>
73         public static CheckResult CheckPermission(string privilege)
74         {
75             Interop.PrivacyPrivilegeManager.CheckResult result;
76             int ret = (int)Interop.PrivacyPrivilegeManager.CheckPermission(privilege, out result);
77             if (ret != (int)Interop.PrivacyPrivilegeManager.ErrorCode.None)
78             {
79                 Log.Error(LogTag, "Failed to check permission");
80                 throw PrivacyPrivilegeManagerErrorFactory.GetException(ret);
81             }
82             return (CheckResult)result;
83         }
84
85         /// <summary>
86         /// Triggers the permission request for a user.
87         /// </summary>
88         /// <param name="privilege">The privacy privilege to be requested.</param>
89         /// <exception cref="ArgumentException">Thrown when an invalid parameter is passed.</exception>
90         /// <exception cref="OutOfMemoryException">Thrown when a memory error occurred.</exception>
91         /// <exception cref="System.IO.IOException">Thrown when the method failed due to an internal I/O error.</exception>
92         /// <example>
93         /// <code>
94         ///     CheckResult result = PrivacyPrivilegeManager.CheckPermission("http://tizen.org/privilege/account.read");
95         ///     switch (result)
96         ///     {
97         ///         case Allow:
98         ///             // Privilege can be used
99         ///             break;
100         ///         case Deny:
101         ///             // Privilege can't be used
102         ///             break;
103         ///         case Ask:
104         ///             // User permission request required
105         ///             PrivacyPrivilegeManager.RequestPermission("http://tizen.org/privilege/account.read");
106         ///             break;
107         ///     }
108         /// </code>
109         /// </example>
110         public static void RequestPermission(string privilege)
111         {
112             int ret = (int)Interop.PrivacyPrivilegeManager.RequestPermission(privilege, s_requestResponseCb, IntPtr.Zero);
113             if (ret != (int)Interop.PrivacyPrivilegeManager.ErrorCode.None)
114             {
115                 Log.Error(LogTag, "Failed to request permission");
116                 throw PrivacyPrivilegeManagerErrorFactory.GetException(ret);
117             }
118         }
119
120         /// <summary>
121         /// Gets the response context for a given privilege.
122         /// </summary>
123         /// <seealso cref="ResponseContext"/>
124         /// <param name="privilege">The privilege.</param>
125         /// <returns>The response context of a respective privilege.</returns>
126         /// <exception cref="ArgumentException">Thrown if the key is an invalid parameter.</exception>
127         /// <example>
128         /// <code>
129         /// private static void PPM_RequestResponse(object sender, RequestResponseEventArgs e)
130         /// {
131         ///     if (e.cause == CallCause.Answer)
132         ///     {
133         ///        switch(e.result)
134         ///
135         ///        {
136         ///
137         ///         case RequestResult.AllowForever:
138         ///             Console.WriteLine("User allowed usage of privilege {0} definitely", e.privilege);
139         ///             break;
140         ///         case RequestResult.DenyForever:
141         ///             Console.WriteLine("User denied usage of privilege {0} definitely", e.privilege);
142         ///             break;
143         ///         case RequestResult.DenyOnce:
144         ///             Console.WriteLine("User denied usage of privilege {0} this time", e.privilege);
145         ///             break;
146         ///         };
147         ///     }
148         ///     else
149         ///     {
150         ///         Console.WriteLine("Error occured during requesting permission for {0}", e.privilege);
151         ///     }
152         ///}
153         ///
154         ///     PrivacyPrivilegeManager.ResponseContext context = null;
155         ///     PrivacyPrivilegeManager.GetResponseContext("http://tizen.org/privilege/account.read").TryGetTarget(out context);
156         ///     if(context != null)
157         ///     {
158         ///         context.ResponseFetched += PPM_RequestResponse;
159         ///     }
160         ///
161         ///     PrivacyPrivilegeManager.RequestPermission("http://tizen.org/privilege/account.read");
162         ///
163         ///     PrivacyPrivilegeManager.GetResponseContext("http://tizen.org/privilege/account.read").TryGetTarget(out context);
164         ///     if(context != null)
165         ///     {
166         ///         context.ResponseFetched -= PPM_RequestResponse;
167         ///     }
168         /// </code>
169         /// </example>
170         public static WeakReference<ResponseContext> GetResponseContext(string privilege)
171         {
172             if (!s_responseMap.ContainsKey(privilege))
173             {
174                 s_responseMap[privilege] = new ResponseContext(privilege);
175             }
176             return new WeakReference<ResponseContext>(s_responseMap[privilege]);
177         }
178
179         /// <summary>
180         /// This class manages event handlers of the privilege permission requests.
181         /// This class enables having event handlers for an individual privilege.
182         /// </summary>
183         public class ResponseContext
184         {
185             private string _privilege;
186
187             internal ResponseContext(string privilege)
188             {
189                 _privilege = privilege;
190             }
191             /// <summary>
192             /// Occurs when the response for a permission request is fetched.
193             /// </summary>
194             /// <exception cref="System.InvalidOperationException">Thrown when the bundle instance has been disposed.</exception>
195             public event EventHandler<RequestResponseEventArgs> ResponseFetched
196             {
197                 add
198                 {
199                     _ResponseFetched += value;
200                 }
201
202                 remove
203                 {
204                     _ResponseFetched -= value;
205                     if (_ResponseFetched == null)
206                     {
207                         s_responseMap.Remove(_privilege);
208                     }
209                 }
210             }
211
212             private event EventHandler<RequestResponseEventArgs> _ResponseFetched;
213
214             internal void FireEvent(CallCause _cause, RequestResult _result)
215             {
216                 _ResponseFetched?.Invoke(null, new RequestResponseEventArgs() { cause = _cause, result = _result, privilege = _privilege });
217             }
218         }
219     }
220
221     internal static class PrivacyPrivilegeManagerErrorFactory
222     {
223         static internal Exception GetException(int error)
224         {
225             Interop.PrivacyPrivilegeManager.ErrorCode errCode = (Interop.PrivacyPrivilegeManager.ErrorCode)error;
226             switch(errCode)
227             {
228                 case Interop.PrivacyPrivilegeManager.ErrorCode.InvalidParameter:
229                     return new ArgumentException("Invalid parameter");
230                 case Interop.PrivacyPrivilegeManager.ErrorCode.IoError:
231                     return new System.IO.IOException("I/O Error");
232                 case Interop.PrivacyPrivilegeManager.ErrorCode.OutOfMemory:
233                     return new OutOfMemoryException("Out of memory");
234                 case Interop.PrivacyPrivilegeManager.ErrorCode.Unknown:
235                 default:
236                     return new ArgumentException("Unknown error");
237             }
238         }
239     }
240 }