• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <ctime>
17 #include <limits>
18 #include "bundle_active_util.h"
19 #include "bundle_active_log.h"
20 #include <dirent.h>
21 #include <sys/stat.h>
22 #include <sys/statfs.h>
23 
24 namespace OHOS {
25 namespace DeviceUsageStats {
26 const int32_t MILLISECOND_TO_MICROSECOND = 1000;
27 const int32_t MILLISECOND_TO_SECOND = 1000;
28 const int32_t SECOND_TO_MILLISECOND = 1000;
29 const int64_t ONE_DAY_TIME = 24 * 60 * 60 *1000LL;
30 const int64_t WEEK_OFFSET = 6LL;
31 const int64_t DAYS_OF_WEEK = 7LL;
32 const int64_t HOUR_OF_MIDNIGHT = 0;
33 const int64_t MIN_OF_MIDNIGHT = 0;
34 const int64_t SECOND_TO_MIDNIGHT = 0;
35 const int64_t STATR_DAY_OF_MON = 1;
36 const int64_t STATR_MON_OF_YEAR = 0;
37 const int64_t ERROR_TIME = 0;
GetBundleUsageKey(const std::string & bundleName,const int32_t uid)38 std::string BundleActiveUtil::GetBundleUsageKey(const std::string &bundleName, const int32_t uid)
39 {
40     return bundleName + std::to_string(uid);
41 }
42 
GetFFRTDelayTime(const int64_t & delayTime)43 int64_t BundleActiveUtil::GetFFRTDelayTime(const int64_t& delayTime)
44 {
45     return delayTime * MILLISECOND_TO_MICROSECOND;
46 }
47 
GetIntervalTypeStartTime(const int64_t & timeStamp,const int32_t & intervalType)48 int64_t BundleActiveUtil::GetIntervalTypeStartTime(const int64_t& timeStamp, const int32_t& intervalType)
49 {
50     if (timeStamp <= 0) {
51         return ERROR_TIME;
52     }
53     time_t time = timeStamp / MILLISECOND_TO_SECOND;
54     std::tm* tm_time = std::localtime(&time);
55     if (tm_time == nullptr) {
56         return ERROR_TIME;
57     }
58     tm_time->tm_hour = HOUR_OF_MIDNIGHT;
59     tm_time->tm_min = MIN_OF_MIDNIGHT;
60     tm_time->tm_sec = SECOND_TO_MIDNIGHT;
61     if (intervalType == PERIOD_WEEKLY) {
62         int64_t weekday = tm_time->tm_wday;
63         time_t startOfDay = mktime(tm_time) * SECOND_TO_MILLISECOND;
64         time_t weekDayTime = (weekday + WEEK_OFFSET) % DAYS_OF_WEEK * ONE_DAY_TIME;
65         return startOfDay - weekDayTime;
66     }
67     switch (intervalType) {
68         case PERIOD_DAILY:
69             break;
70         case PERIOD_MONTHLY:
71             tm_time->tm_mday = STATR_DAY_OF_MON;
72             break;
73         case PERIOD_YEARLY:
74             tm_time->tm_mon = STATR_MON_OF_YEAR;
75             tm_time->tm_mday = STATR_DAY_OF_MON;
76             break;
77         default:
78             break;
79     }
80     return mktime(tm_time) * SECOND_TO_MILLISECOND;
81 }
82 
StringToInt32(const std::string & str)83 int32_t BundleActiveUtil::StringToInt32(const std::string& str)
84 {
85     char* pEnd = nullptr;
86     errno = 0;
87     int64_t res = std::strtol(str.c_str(), &pEnd, 10);
88     if (errno == ERANGE || pEnd == str.c_str() || *pEnd != '\0' ||
89         (res < std::numeric_limits<int32_t>::min()) ||
90         res > std::numeric_limits<int32_t>::max()) {
91         return 0;
92     }
93     return static_cast<int32_t>(res);
94 }
95 
StringToInt64(const std::string & str)96 int64_t BundleActiveUtil::StringToInt64(const std::string& str)
97 {
98     char* pEnd = nullptr;
99     errno = 0;
100     int64_t res = std::strtol(str.c_str(), &pEnd, 10);
101     if (errno == ERANGE || pEnd == str.c_str() || *pEnd != '\0') {
102         return 0;
103     }
104     return res;
105 }
106 
GetSystemTimeMs()107 int64_t BundleActiveUtil::GetSystemTimeMs()
108 {
109     time_t now;
110     (void)time(&now);  // unit is seconds.
111     if (static_cast<int64_t>(now) < 0) {
112         BUNDLE_ACTIVE_LOGE("Get now time error");
113         return 0;
114     }
115     auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now);
116     auto tarDuration = std::chrono::duration_cast<std::chrono::milliseconds>(tarEndTimePoint.time_since_epoch());
117     int64_t tarDate = tarDuration.count();
118     if (tarDate < 0) {
119         BUNDLE_ACTIVE_LOGE("tarDuration is less than 0.");
120         return -1;
121     }
122     return static_cast<int64_t>(tarDate);
123 }
124 
GetSteadyTime()125 int64_t BundleActiveUtil::GetSteadyTime()
126 {
127     std::chrono::seconds secs = std::chrono::duration_cast<std::chrono::seconds>(
128         std::chrono::steady_clock::now().time_since_epoch());
129     return static_cast<int64_t>(secs.count());
130 }
131 
GetNowMicroTime()132 int64_t BundleActiveUtil::GetNowMicroTime()
133 {
134     std::chrono::microseconds microSecs;
135     // get system time, it can change.
136     microSecs = std::chrono::duration_cast<std::chrono::microseconds>(
137     std::chrono::system_clock::now().time_since_epoch());
138     return static_cast<int64_t>(microSecs.count());
139 }
140 
GetFolderOrFileSize(const std::string & path)141 uint64_t BundleActiveUtil::GetFolderOrFileSize(const std::string& path)
142 {
143     struct stat st;
144     if (stat(path.c_str(), &st) != 0) {
145         return 0;
146     }
147     if (!S_ISDIR(st.st_mode)) {
148         return static_cast<uint64_t>(st.st_size);
149     }
150     uint64_t totalSize = 0;
151     DIR *dir = opendir(path.c_str());
152     // input invaild, open failed
153     if (dir == nullptr) {
154         return 0;
155     }
156     struct dirent *entry;
157     while ((entry = readdir(dir)) != nullptr) {
158         // current dir is path of '.' or '..'
159         std::string entryPath = path + "/" + entry->d_name;
160         if (entry->d_name[0] == '.') {
161             continue;
162         }
163 
164         struct stat entryStat;
165         if (stat(entryPath.c_str(), &entryStat) != 0) {
166             continue;
167         }
168         if (S_ISDIR(entryStat.st_mode)) {
169             uint64_t subDirSize = GetFolderOrFileSize(entryPath);
170             totalSize += subDirSize;
171         } else {
172             totalSize += static_cast<uint64_t>(entryStat.st_size);
173         }
174     }
175     closedir(dir);
176     return totalSize;
177 }
178 
GetPartitionName(const std::string & path)179 std::string BundleActiveUtil::GetPartitionName(const std::string& path)
180 {
181     std::string partition;
182     std::size_t first = path.find_first_of("/");
183     if (first == std::string::npos) {
184         partition = "/" + path;
185         return partition;
186     }
187     std::size_t second = path.find_first_of("/", first + 1);
188     if (second == std::string::npos) {
189         if (path.at(0) != '/') {
190             partition = "/" + path.substr(0, first);
191         } else {
192             partition = path;
193         }
194         return partition;
195     }
196     partition = path.substr(0, second - first);
197     return partition;
198 }
199 
GetDeviceValidSize(const std::string & path)200 double BundleActiveUtil::GetDeviceValidSize(const std::string& path)
201 {
202     std::string partitionName = GetPartitionName(path);
203     struct statfs stat;
204     if (statfs(partitionName.c_str(), &stat) != 0) {
205         return 0;
206     }
207     constexpr double units = 1024.0;
208     return (static_cast<double>(stat.f_bfree) / units) * (static_cast<double>(stat.f_bsize) / units);
209 }
210 
GetPercentOfAvailableUserSpace(const std::string & path)211 double BundleActiveUtil::GetPercentOfAvailableUserSpace(const std::string& path)
212 {
213     std::string partitionName = GetPartitionName(path);
214     struct statfs stat;
215     if (statfs(partitionName.c_str(), &stat) != 0) {
216         return 0;
217     }
218     uint64_t totalBytes = static_cast<uint64_t>(stat.f_blocks) * stat.f_bsize;
219     uint64_t availableBytes = static_cast<uint64_t>(stat.f_bfree) * stat.f_bsize;
220     if (totalBytes == 0 || availableBytes == 0) {
221         return 0;
222     }
223     return static_cast<double>(availableBytes) / static_cast<double>(totalBytes);
224 }
225 } // namespace DeviceUsageStats
226 }  // namespace OHOS
227 
228