121808dbbadd3f76bd5a49031b15bb6f6de84e3e
[platform/core/csapi/tizenfx.git] / src / Tizen.Context / Tizen.Context.AppHistory / UsageStatistics.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
20 namespace Tizen.Context.AppHistory
21 {
22     /// <summary>
23     /// This class provides APIs to query application launch history.
24     /// </summary>
25     /// <since_tizen> 4 </since_tizen>
26     public class UsageStatistics : AppStatistics
27     {
28         private const string AppStatsDuration = "TotalDuration";
29         private const string AppStatsLaunchCount = "TotalCount";
30         private const string AppStatsLastLaunchTime = "LastTime";
31
32         /// <summary>
33         /// The default constructor of UsageStatistics class.
34         /// </summary>
35         /// <since_tizen> 4 </since_tizen>
36         /// <feature>http://tizen.org/feature/app_history</feature>
37         /// <exception cref="InvalidOperationException">Thrown when method fail due to internal error.</exception>
38         /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception>
39         public UsageStatistics()
40         {
41             SortOrder = SortOrderType.LastLaunchTimeNewest;
42             Uri = ConvertSortOrderToString((int)SortOrder);
43
44             bool isSupported = false;
45             int error = Interop.CtxHistory.IsSupported(Uri, out isSupported);
46             if ((AppHistoryError)error != AppHistoryError.None)
47             {
48                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, Uri);
49             }
50
51             if (!isSupported)
52             {
53                 throw AppHistoryErrorFactory.CheckAndThrowException(AppHistoryError.OperationFailed, Uri);
54             }
55         }
56
57         /// <summary>
58         /// The constructor of UsageStatistics class.
59         /// </summary>
60         /// <since_tizen> 4 </since_tizen>
61         /// <param name="order">The criteria of the usage statistics sorted by.</param>
62         /// <feature>http://tizen.org/feature/app_history</feature>
63         /// <exception cref="ArgumentException">Thrown when an invalid argument is used.</exception>
64         /// <exception cref="InvalidOperationException">Thrown when method fail due to internal error.</exception>
65         /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception>
66         public UsageStatistics(SortOrderType order)
67         {
68             SortOrder = order;
69             Uri = ConvertSortOrderToString((int)SortOrder);
70
71             if (Uri== null)
72             {
73                 throw AppHistoryErrorFactory.CheckAndThrowException(AppHistoryError.InvalidParameter, "Invalid SortOrderType");
74             }
75
76             bool isSupported = false;
77             int error = Interop.CtxHistory.IsSupported(Uri, out isSupported);
78             if ((AppHistoryError)error != AppHistoryError.None)
79             {
80                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, Uri);
81             }
82
83             if (!isSupported)
84             {
85                 throw AppHistoryErrorFactory.CheckAndThrowException(AppHistoryError.OperationFailed, Uri);
86             }
87         }
88
89         /// <summary>
90         /// Retrieves a given type of usage statistics.
91         /// </summary>
92         /// <since_tizen> 4 </since_tizen>
93         /// <param name="startTime">The start time of the data to be aggregated.</param>
94         /// <param name="endTime">The end time of the data to be aggregated.</param>
95         /// <returns>Usage statistics data retrieved.</returns>
96         /// <privilege>http://tizen.org/privilege/apphistory.read</privilege>
97         /// <feature>http://tizen.org/feature/app_history</feature>
98         /// <exception cref="ArgumentException">Thrown when an invalid argument is used.</exception>
99         /// <exception cref="InvalidOperationException">Thrown when invalid operation occurs.</exception>
100         /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception>
101         /// <exception cref="UnauthorizedAccessException">Thrown when the app has no privilege to retrieve app history.</exception>
102         public IReadOnlyList<UsageStatisticsData> Query(DateTime startTime, DateTime endTime)
103         {
104             CheckTimeSpan(startTime, endTime);
105
106             return Query(startTime, endTime, DefaultResultSize);
107         }
108
109         /// <summary>
110         /// Retrieves a given type of usage statistics.
111         /// </summary>
112         /// <since_tizen> 4 </since_tizen>
113         /// <param name="startTime">The start time of the data to be aggregated.</param>
114         /// <param name="endTime">The end time of the data to be aggregated.</param>
115         /// <param name="resultSize">The number of data records to be retrieved.</param>
116         /// <returns>Usage statistics data retrieved.</returns>
117         /// <privilege>http://tizen.org/privilege/apphistory.read</privilege>
118         /// <feature>http://tizen.org/feature/app_history</feature>
119         /// <exception cref="ArgumentException">Thrown when an invalid argument is used.</exception>
120         /// <exception cref="InvalidOperationException">Thrown when invalid operation occurs.</exception>
121         /// <exception cref="NotSupportedException">Thrown when the feature is not supported.</exception>
122         /// <exception cref="UnauthorizedAccessException">Thrown when the app has no privilege to retrieve app history.</exception>
123         public IReadOnlyList<UsageStatisticsData> Query(DateTime startTime, DateTime endTime, uint resultSize)
124         {
125             CheckTimeSpan(startTime, endTime);
126             CheckResultSize(resultSize);
127
128             List<UsageStatisticsData> result = new List<UsageStatisticsData>();
129
130             IntPtr cursor = IntPtr.Zero;
131             int error = Interop.CtxHistory.Query(Uri, ConvertDateTimeToUnixTimestamp(startTime), ConvertDateTimeToUnixTimestamp(endTime), resultSize, out cursor);
132             if ((AppHistoryError)error == AppHistoryError.NoData)
133             {
134                 return result.AsReadOnly();
135             } else if ((AppHistoryError)error != AppHistoryError.None)
136             {
137                 Log.Error(AppHistoryErrorFactory.LogTag, "Failed to request query usage statistics");
138                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, "Failed to request query usage statistics");
139             }
140
141             int size;
142             error = Interop.CtxHistoryCursor.GetCount(cursor, out size);
143             Interop.CtxHistoryCursor.First(cursor);
144
145             for (int i = 0; i < size; i++)
146             {
147                 result.Add(ConvertOutputToStatsData(cursor));
148                 Interop.CtxHistoryCursor.Next(cursor);
149             }
150             Interop.CtxHistoryCursor.Destroy(cursor);
151
152             return result.AsReadOnly();
153         }
154
155         internal override string ConvertSortOrderToString(int order)
156         {
157             switch ((SortOrderType)order)
158             {
159                 case SortOrderType.LastLaunchTimeNewest:
160                     return "stats/app/recently";
161                 case SortOrderType.LaunchCountMost:
162                     return "stats/app/often";
163                 default:
164                     return null;
165             }
166         }
167
168         private static UsageStatisticsData ConvertOutputToStatsData(IntPtr cursor)
169         {
170             string appId;
171             Int64 duration = 1;
172             Int64 launchCount = 1;
173             Int64 lastLaunchTime;
174
175             Interop.CtxHistoryCursor.GetString(cursor, AppStatsAppId, out appId);
176             Interop.CtxHistoryCursor.GetInt64(cursor, AppStatsDuration, out duration);
177             Interop.CtxHistoryCursor.GetInt64(cursor, AppStatsLaunchCount, out launchCount);
178             Interop.CtxHistoryCursor.GetInt64(cursor, AppStatsLastLaunchTime, out lastLaunchTime);
179
180             return new UsageStatisticsData(appId, (int)duration, (int)launchCount, ConvertUnixTimestampToDateTime(lastLaunchTime));
181         }
182
183         /// <summary>
184         /// Gets the criteria of usage statistics sorted by.
185         /// </summary>
186         /// <since_tizen> 4 </since_tizen>
187         /// <value>The criteria of usage statistics sorted by.</value>
188         public SortOrderType SortOrder { get; private set; }
189
190         /// <summary>
191         /// Sort order type of usage statistics
192         /// </summary>
193         /// <since_tizen> 4 </since_tizen>
194         public enum SortOrderType
195         {
196             /// <summary>
197             /// Sorts apps by the last launch time, the most recently launched apps appear first. (Default)
198             /// </summary>
199             LastLaunchTimeNewest = 0,
200             /// <summary>
201             /// Sorts apps by the launch count of being launched, the most frequently launched apps appear first.
202             /// </summary>
203             LaunchCountMost
204         }
205     }
206 }