• 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 #define MLOG_TAG "DfxManager"
16 
17 #include <sstream>
18 #include "dfx_manager.h"
19 
20 #include "dfx_cloud_manager.h"
21 #include "dfx_utils.h"
22 #include "media_file_utils.h"
23 #include "media_file_uri.h"
24 #include "media_log.h"
25 #include "userfile_manager_types.h"
26 #include "medialibrary_bundle_manager.h"
27 #ifdef META_RECOVERY_SUPPORT
28 #include "medialibrary_meta_recovery.h"
29 #endif
30 #include "dfx_database_utils.h"
31 #include "dfx_deprecated_perm_usage.h"
32 #include "vision_aesthetics_score_column.h"
33 #include "parameters.h"
34 #include "photo_storage_operation.h"
35 #include "preferences.h"
36 #include "preferences_helper.h"
37 #include "hi_audit.h"
38 #include "medialibrary_errno.h"
39 #include "medialibrary_unistore_manager.h"
40 
41 using namespace std;
42 
43 namespace OHOS {
44 namespace Media {
45 
46 shared_ptr<DfxManager> DfxManager::dfxManagerInstance_{nullptr};
47 mutex DfxManager::instanceLock_;
48 
49 struct QueryParams {
50     MediaType mediaType;
51     PhotoPositionType positionType;
52 };
53 
GetInstance()54 shared_ptr<DfxManager> DfxManager::GetInstance()
55 {
56     lock_guard<mutex> lockGuard(instanceLock_);
57     if (dfxManagerInstance_ == nullptr) {
58         dfxManagerInstance_ = make_shared<DfxManager>();
59         if (dfxManagerInstance_ != nullptr) {
60             dfxManagerInstance_->Init();
61         }
62     }
63     return dfxManagerInstance_;
64 }
65 
DfxManager()66 DfxManager::DfxManager() : isInitSuccess_(false),
67     downloadMeta_(DOWNLOAD_META_LEN),
68     uploadMeta_(UPLOAD_META_LEN),
69     downloadThumb_(DOWNLOAD_THUMB_LEN),
70     downloadLcd_(DOWNLOAD_LCD_LEN),
71     uploadAlbum_(UPLOAD_ALBUM_LEN),
72     downloadAlbum_(DOWNLOAD_ALBUM_LEN),
73     updateDetails_(UPDATE_DETAILS_LEN),
74     uploadMetaErr_(UPLOAD_META_ERR_LEN)
75 {
76 }
77 
~DfxManager()78 DfxManager::~DfxManager()
79 {
80 }
81 
Init()82 void DfxManager::Init()
83 {
84     MEDIA_INFO_LOG("Init DfxManager");
85     dfxCollector_ = make_shared<DfxCollector>();
86     dfxAnalyzer_ = make_shared<DfxAnalyzer>();
87     dfxReporter_ = make_shared<DfxReporter>();
88     dfxWorker_ = DfxWorker::GetInstance();
89     dfxWorker_->Init();
90     isInitSuccess_ = true;
91 }
92 
HandleTimeOutOperation(std::string & bundleName,int32_t type,int32_t object,int32_t time)93 void DfxManager::HandleTimeOutOperation(std::string &bundleName, int32_t type, int32_t object, int32_t time)
94 {
95     if (!isInitSuccess_) {
96         MEDIA_WARN_LOG("DfxManager not init");
97         return;
98     }
99     dfxReporter_->ReportTimeOutOperation(bundleName, type, object, time);
100 }
101 
HandleControllerServiceError(uint32_t operationCode,int32_t errorCode)102 void DfxManager::HandleControllerServiceError(uint32_t operationCode, int32_t errorCode)
103 {
104     if (!isInitSuccess_) {
105         MEDIA_WARN_LOG("DfxManager not init");
106         return;
107     }
108     dfxReporter_->ReportControllerService(operationCode, errorCode);
109 }
110 
HandleHighMemoryThumbnail(std::string & path,int32_t mediaType,int32_t width,int32_t height)111 int32_t DfxManager::HandleHighMemoryThumbnail(std::string &path, int32_t mediaType, int32_t width,
112     int32_t height)
113 {
114     if (!isInitSuccess_) {
115         MEDIA_WARN_LOG("DfxManager not init");
116         return NOT_INIT;
117     }
118     string suffix = MediaFileUtils::GetExtensionFromPath(path);
119     if (mediaType == MEDIA_TYPE_IMAGE) {
120         return dfxReporter_->ReportHighMemoryImageThumbnail(path, suffix, width, height);
121     } else {
122         return dfxReporter_->ReportHighMemoryVideoThumbnail(path, suffix, width, height);
123     }
124 }
125 
HandleThumbnailError(const std::string & path,int32_t method,int32_t errorCode)126 void DfxManager::HandleThumbnailError(const std::string &path, int32_t method, int32_t errorCode)
127 {
128     string safePath = DfxUtils::GetSafePath(path);
129     MEDIA_ERR_LOG("Failed to %{public}d, path: %{public}s, err: %{public}d", method, safePath.c_str(), errorCode);
130     if (!isInitSuccess_) {
131         MEDIA_WARN_LOG("DfxManager not init");
132         return;
133     }
134     dfxCollector_->CollectThumbnailError(safePath, method, errorCode);
135 }
136 
HandleThumbnailGeneration(const ThumbnailData::GenerateStats & stats)137 void DfxManager::HandleThumbnailGeneration(const ThumbnailData::GenerateStats &stats)
138 {
139     if (!isInitSuccess_) {
140         MEDIA_WARN_LOG("DfxManager not init");
141         return;
142     }
143     dfxReporter_->ReportThumbnailGeneration(stats);
144 }
145 
HandleCommonBehavior(string bundleName,int32_t type)146 void DfxManager::HandleCommonBehavior(string bundleName, int32_t type)
147 {
148     if (!isInitSuccess_) {
149         MEDIA_WARN_LOG("DfxManager not init");
150         return;
151     }
152     dfxCollector_->AddCommonBahavior(bundleName, type);
153 }
154 
GetDisplayName(const string & coverId,const std::map<std::string,std::string> & displayNames)155 static string GetDisplayName(const string &coverId, const std::map<std::string, std::string> &displayNames)
156 {
157     auto it = std::find_if(displayNames.begin(), displayNames.end(),
158         [&](const std::pair<std::string, std::string> &name) {
159         return name.first == coverId;
160     });
161     string displayName = it == displayNames.end() ? "" : it->second;
162     return DfxUtils::GetSafeDiaplayNameWhenChinese(displayName);
163 }
164 
GetAlbumName(const string & coverId,const DeleteBehaviorData & deleteBehaviorData)165 static string GetAlbumName(const string &coverId, const DeleteBehaviorData &deleteBehaviorData)
166 {
167     auto itIds = std::find_if(deleteBehaviorData.ownerAlbumIds.begin(), deleteBehaviorData.ownerAlbumIds.end(),
168         [&](const std::pair<std::string, std::string> &ownerAlbumId) {
169             return ownerAlbumId.first == coverId;
170         });
171     if (itIds == deleteBehaviorData.ownerAlbumIds.end()) {
172         return "";
173     }
174     string albumId = itIds->second;
175     auto it = std::find_if(deleteBehaviorData.albumNames.begin(), deleteBehaviorData.albumNames.end(),
176         [&](const std::pair<std::string, std::string> &albumName) {
177             return albumName.first == albumId;
178         });
179     string albumName = it == deleteBehaviorData.albumNames.end() ? "" : it->second;
180     return DfxUtils::GetSafeAlbumNameWhenChinese(albumName);
181 }
182 
LogDelete(DfxData * data)183 static void LogDelete(DfxData *data)
184 {
185     if (data == nullptr) {
186         return;
187     }
188     auto *taskData = static_cast<DeleteBehaviorTask *>(data);
189     string id = taskData->id_;
190     int32_t type = taskData->type_;
191     int32_t size = taskData->size_;
192     std::shared_ptr<DfxReporter> dfxReporter = taskData->dfxReporter_;
193     MEDIA_INFO_LOG("id: %{public}s, type: %{public}d, size: %{public}d", id.c_str(), type, size);
194 
195     std::vector<std::string> uris = taskData->uris_;
196     if (!uris.empty()) {
197         for (auto& uri: uris) {
198             string::size_type pos = uri.find_last_of('/');
199             if (pos == string::npos) {
200                 continue;
201             }
202             string halfUri = uri.substr(0, pos);
203             string::size_type pathPos = halfUri.find_last_of('/');
204             if (pathPos == string::npos) {
205                 continue;
206             }
207             string coverId = MediaFileUri::GetPhotoId(uri);
208             string displayName = GetDisplayName(coverId, taskData->deleteBehaviorData_.displayNames);
209             string albumName = GetAlbumName(coverId, taskData->deleteBehaviorData_);
210             AuditLog auditLog = { true, "USER BEHAVIOR", "DELETE", "io", 1, "running", "ok",
211                 id, type, size, (halfUri.substr(pathPos + 1)).c_str(), displayName, albumName };
212             HiAudit::GetInstance().Write(auditLog);
213             dfxReporter->ReportDeleteBehavior(id, type, halfUri.substr(pathPos + 1));
214         }
215     }
216 }
217 
HandleNoPermmison(int32_t type,int32_t object,int32_t error)218 void DfxManager::HandleNoPermmison(int32_t type, int32_t object, int32_t error)
219 {
220     MEDIA_INFO_LOG("permission deny: {%{public}d, %{public}d, %{public}d}", type, object, error);
221 }
222 
HandleDeleteBehavior(int32_t type,int32_t size,std::vector<std::string> & uris,string bundleName,const DeleteBehaviorData & deleteBehaviorData)223 void DfxManager::HandleDeleteBehavior(int32_t type, int32_t size, std::vector<std::string> &uris, string bundleName,
224     const DeleteBehaviorData &deleteBehaviorData)
225 {
226     if (bundleName == "") {
227         bundleName = MediaLibraryBundleManager::GetInstance()->GetClientBundleName();
228     }
229     dfxCollector_->CollectDeleteBehavior(bundleName, type, size);
230     if (dfxWorker_ == nullptr) {
231         MEDIA_ERR_LOG("Can not get dfxWork_");
232         return;
233     }
234     string id = bundleName == "" ? to_string(IPCSkeleton::GetCallingUid()) : bundleName;
235     auto *taskData = new (nothrow) DeleteBehaviorTask(id, type, size, uris, dfxReporter_, deleteBehaviorData);
236     if (taskData == nullptr) {
237         MEDIA_ERR_LOG("Failed to new taskData");
238         return;
239     }
240     auto deleteBehaviorTask = make_shared<DfxTask>(LogDelete, taskData);
241     if (deleteBehaviorTask == nullptr) {
242         MEDIA_ERR_LOG("Failed to create async task for deleteBehaviorTask.");
243         return;
244     }
245     dfxWorker_->AddTask(deleteBehaviorTask);
246 }
247 
HandlePhotoInfo(std::shared_ptr<DfxReporter> & dfxReporter)248 static void HandlePhotoInfo(std::shared_ptr<DfxReporter>& dfxReporter)
249 {
250     const std::vector<QueryParams> queryParamsList = {
251         {MediaType::MEDIA_TYPE_IMAGE, PhotoPositionType::LOCAL},
252         {MediaType::MEDIA_TYPE_VIDEO, PhotoPositionType::LOCAL},
253         {MediaType::MEDIA_TYPE_IMAGE, PhotoPositionType::CLOUD},
254         {MediaType::MEDIA_TYPE_VIDEO, PhotoPositionType::CLOUD},
255         {MediaType::MEDIA_TYPE_IMAGE, PhotoPositionType::LOCAL_AND_CLOUD},
256         {MediaType::MEDIA_TYPE_VIDEO, PhotoPositionType::LOCAL_AND_CLOUD}
257     };
258 
259     PhotoStatistics stats = {};
260     int32_t* countPtrs[] = {
261         &stats.localImageCount,
262         &stats.localVideoCount,
263         &stats.cloudImageCount,
264         &stats.cloudVideoCount,
265         &stats.sharedImageCount,
266         &stats.sharedVideoCount
267     };
268 
269     for (size_t i = 0; i < queryParamsList.size(); i++) {
270         const auto& params = queryParamsList[i];
271         *countPtrs[i] = DfxDatabaseUtils::QueryFromPhotos(params.mediaType, static_cast<int32_t>(params.positionType));
272     }
273 
274     MEDIA_INFO_LOG("localImageCount: %{public}d, localVideoCount: %{public}d, "
275                    "cloudImageCount: %{public}d, cloudVideoCount: %{public}d, "
276                    "sharedImageCount: %{public}d, sharedVideoCount: %{public}d",
277                    stats.localImageCount, stats.localVideoCount,
278                    stats.cloudImageCount, stats.cloudVideoCount,
279                    stats.sharedImageCount, stats.sharedVideoCount);
280 
281     dfxReporter->ReportPhotoInfo(stats);
282 }
283 
HandleAlbumInfoBySubtype(std::shared_ptr<DfxReporter> & dfxReporter,int32_t albumSubType)284 static void HandleAlbumInfoBySubtype(std::shared_ptr<DfxReporter> &dfxReporter, int32_t albumSubType)
285 {
286     AlbumInfo albumInfo = DfxDatabaseUtils::QueryAlbumInfoBySubtype(albumSubType);
287     string albumName = ALBUM_MAP.at(albumSubType);
288     MEDIA_INFO_LOG("album %{public}s: {count:%{public}d, imageCount:%{public}d, videoCount:%{public}d, \
289         isLocal:%{public}d}", albumName.c_str(), albumInfo.count, albumInfo.imageCount, albumInfo.videoCount,
290         albumInfo.isLocal);
291     dfxReporter->ReportAlbumInfo(albumName.c_str(), albumInfo.imageCount, albumInfo.videoCount, albumInfo.isLocal);
292 }
293 
HandleAlbumInfo(std::shared_ptr<DfxReporter> & dfxReporter)294 static void HandleAlbumInfo(std::shared_ptr<DfxReporter> &dfxReporter)
295 {
296     HandleAlbumInfoBySubtype(dfxReporter, static_cast<int32_t>(PhotoAlbumSubType::IMAGE));
297     HandleAlbumInfoBySubtype(dfxReporter, static_cast<int32_t>(PhotoAlbumSubType::VIDEO));
298     HandleAlbumInfoBySubtype(dfxReporter, static_cast<int32_t>(PhotoAlbumSubType::FAVORITE));
299     HandleAlbumInfoBySubtype(dfxReporter, static_cast<int32_t>(PhotoAlbumSubType::HIDDEN));
300     HandleAlbumInfoBySubtype(dfxReporter, static_cast<int32_t>(PhotoAlbumSubType::TRASH));
301 }
302 
HandleDirtyCloudPhoto(std::shared_ptr<DfxReporter> & dfxReporter)303 static void HandleDirtyCloudPhoto(std::shared_ptr<DfxReporter> &dfxReporter)
304 {
305     vector<PhotoInfo> photoInfoList = DfxDatabaseUtils::QueryDirtyCloudPhoto();
306     if (photoInfoList.empty()) {
307         return;
308     }
309     for (auto& photoInfo: photoInfoList) {
310         dfxReporter->ReportDirtyCloudPhoto(photoInfo.data, photoInfo.dirty, photoInfo.cloudVersion);
311     }
312 }
313 
HandleLocalVersion(std::shared_ptr<DfxReporter> & dfxReporter)314 static void HandleLocalVersion(std::shared_ptr<DfxReporter> &dfxReporter)
315 {
316     int32_t dbVersion = DfxDatabaseUtils::QueryDbVersion();
317     dfxReporter->ReportCommonVersion(dbVersion);
318     int32_t aestheticsVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_aesthetics_score",
319         "aesthetics_version");
320     dfxReporter->ReportAnalysisVersion("aesthetics_score", aestheticsVersion);
321     int32_t compositionVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_composition",
322         "composition_version");
323     dfxReporter->ReportAnalysisVersion("composition", compositionVersion);
324     int32_t headVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_head", "head_version");
325     dfxReporter->ReportAnalysisVersion("head", headVersion);
326     int32_t imageFaceVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_image_face", "features_version");
327     dfxReporter->ReportAnalysisVersion("image_face", imageFaceVersion);
328     int32_t labelVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_label", "label_version");
329     dfxReporter->ReportAnalysisVersion("label", labelVersion);
330     int32_t objectVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_object", "object_version");
331     dfxReporter->ReportAnalysisVersion("object", objectVersion);
332     int32_t ocrVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_ocr", "ocr_version");
333     dfxReporter->ReportAnalysisVersion("ocr", ocrVersion);
334     int32_t poseVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_pose", "pose_version");
335     dfxReporter->ReportAnalysisVersion("pose", poseVersion);
336     int32_t recommendationVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_recommendation",
337         "recommendation_version");
338     dfxReporter->ReportAnalysisVersion("recommendation", recommendationVersion);
339     int32_t saliencyDetectVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_saliency_detect",
340         "saliency_version");
341     dfxReporter->ReportAnalysisVersion("saliency_detect", saliencyDetectVersion);
342     int32_t segmentationVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_segmentation",
343         "segmentation_version");
344     dfxReporter->ReportAnalysisVersion("segmentation", segmentationVersion);
345     int32_t videoLabelVersion = DfxDatabaseUtils::QueryAnalysisVersion("tab_analysis_video_label", "algo_version");
346     dfxReporter->ReportAnalysisVersion("video_label", videoLabelVersion);
347 }
348 
HandleAstcInfo(std::shared_ptr<DfxReporter> & dfxReporter)349 void HandleAstcInfo(std::shared_ptr<DfxReporter>& dfxReporter)
350 {
351     LcdAndAstcCount count = {};
352     count.localAstcCount = DfxDatabaseUtils::QueryASTCThumb(true);
353     count.cloudAstcCount = DfxDatabaseUtils::QueryASTCThumb(false);
354     count.localLcdCount = DfxDatabaseUtils::QueryLCDThumb(true);
355     count.cloudLcdCount = DfxDatabaseUtils::QueryLCDThumb(false);
356 
357     MEDIA_INFO_LOG("localLcdCount: %{public}d, localAstcCount: %{public}d, "
358                    "cloudLcdCount: %{public}d, cloudAstcCount: %{public}d",
359                    count.localLcdCount, count.localAstcCount,
360                    count.cloudLcdCount, count.cloudAstcCount);
361 
362     dfxReporter->ReportAstcInfo(count);
363 }
364 
HandleStatistic(DfxData * data)365 static void HandleStatistic(DfxData *data)
366 {
367     if (data == nullptr) {
368         return;
369     }
370     auto *taskData = static_cast<StatisticData *>(data);
371     std::shared_ptr<DfxReporter> dfxReporter = taskData->dfxReporter_;
372     HandlePhotoInfo(dfxReporter);
373     HandleAlbumInfo(dfxReporter);
374     HandleDirtyCloudPhoto(dfxReporter);
375     HandleLocalVersion(dfxReporter);
376     HandleAstcInfo(dfxReporter);
377 #ifdef META_RECOVERY_SUPPORT
378     MediaLibraryMetaRecovery::GetInstance().RecoveryStatistic();
379 #endif
380     DfxDeprecatedPermUsage::Statistics();
381 }
382 
CheckPhotoError(std::shared_ptr<DfxReporter> & dfxReporter)383 static void CheckPhotoError(std::shared_ptr<DfxReporter>& dfxReporter)
384 {
385     CHECK_AND_RETURN_INFO_LOG(dfxReporter != nullptr, "E_OK");
386     auto photoCount = DfxDatabaseUtils::QueryPhotoErrorCount();
387     CHECK_AND_RETURN_INFO_LOG(photoCount, "E_OK");
388     MEDIA_ERR_LOG("DFX ReportPhotoError count is %{public}d", photoCount);
389     PhotoErrorCount photoError = { {PhotoErrorType::PHOTO_MISS_TYPE}, {photoCount} };
390     dfxReporter->ReportPhotoError(photoError);
391 }
392 
HandleCheckTwoDayTask(DfxData * data)393 static void HandleCheckTwoDayTask(DfxData *data)
394 {
395     CHECK_AND_RETURN_LOG(data != nullptr, "Failed to get data for Handle Check Two Day Task!");
396     auto *taskData = static_cast<StatisticData *>(data);
397     std::shared_ptr<DfxReporter> dfxReporter = taskData->dfxReporter_;
398     CHECK_AND_RETURN_LOG(dfxReporter != nullptr, "Failed to get dfxReporter for Handle Check Two Day Task!");
399     CheckPhotoError(dfxReporter);
400 }
401 
HandleHalfDayMissions()402 void DfxManager::HandleHalfDayMissions()
403 {
404     if (!isInitSuccess_) {
405         MEDIA_WARN_LOG("DfxManager not init");
406         return;
407     }
408     int32_t errCode;
409     shared_ptr<NativePreferences::Preferences> prefs =
410         NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
411     if (!prefs) {
412         MEDIA_ERR_LOG("get preferences error: %{public}d", errCode);
413         return;
414     }
415     int64_t lastReportTime = prefs->GetLong(LAST_HALF_DAY_REPORT_TIME, 0);
416     if (MediaFileUtils::UTCTimeSeconds() - lastReportTime > HALF_DAY && dfxWorker_ != nullptr) {
417         MEDIA_INFO_LOG("start handle statistic behavior");
418         auto *taskData = new (nothrow) StatisticData(dfxReporter_);
419         if (taskData == nullptr) {
420             MEDIA_ERR_LOG("Failed to alloc async data for Handle Half Day Missions!");
421             return;
422         }
423         auto statisticTask = make_shared<DfxTask>(HandleStatistic, taskData);
424         if (statisticTask == nullptr) {
425             MEDIA_ERR_LOG("Failed to create statistic task.");
426             return;
427         }
428         dfxWorker_->AddTask(statisticTask);
429         int64_t time = MediaFileUtils::UTCTimeSeconds();
430         prefs->PutLong(LAST_HALF_DAY_REPORT_TIME, time);
431         prefs->FlushSync();
432     }
433 }
434 
HandleTwoDayMissions()435 void DfxManager::HandleTwoDayMissions()
436 {
437     CHECK_AND_RETURN_LOG(isInitSuccess_, "DfxManager not init");
438     int32_t errCode;
439     shared_ptr<NativePreferences::Preferences> prefs =
440         NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
441     if (!prefs) {
442         MEDIA_ERR_LOG("get preferences error: %{public}d", errCode);
443         return;
444     }
445     int64_t lastReportTime = prefs->GetLong(LAST_TWO_DAY_REPORT_TIME, 0);
446     if (MediaFileUtils::UTCTimeSeconds() - lastReportTime > TWO_DAY && dfxWorker_ != nullptr) {
447         MEDIA_INFO_LOG("start handle statistic behavior");
448         auto *taskData = new (nothrow) StatisticData(dfxReporter_);
449         CHECK_AND_RETURN_LOG(taskData != nullptr, "Failed to alloc async data for Handle Two Day Missions!");
450         auto twoDayTask = make_shared<DfxTask>(HandleCheckTwoDayTask, taskData);
451         CHECK_AND_RETURN_LOG(twoDayTask != nullptr, "Failed to create dfx task.");
452         dfxWorker_->AddTask(twoDayTask);
453         int64_t time = MediaFileUtils::UTCTimeSeconds();
454         prefs->PutLong(LAST_TWO_DAY_REPORT_TIME, time);
455         prefs->FlushSync();
456     }
457 }
458 
IsDirectoryExist(const string & dirName)459 void DfxManager::IsDirectoryExist(const string& dirName)
460 {
461     struct stat statInfo {};
462     if (stat(dirName.c_str(), &statInfo) == E_SUCCESS) {
463         if (statInfo.st_mode & S_IFDIR) {
464             return;
465         }
466         MEDIA_ERR_LOG("Not Is DIR, errno is %{public}d", errno);
467         return;
468     }
469     MEDIA_ERR_LOG("Directory Not Exist, errno is %{public}d", errno);
470     return;
471 }
472 
CheckStatus()473 void DfxManager::CheckStatus()
474 {
475     const std::string CLOUD_FILE_PATH = "/storage/cloud/files";
476     IsDirectoryExist(CLOUD_FILE_PATH);
477 }
478 
HandleFiveMinuteTask()479 void DfxManager::HandleFiveMinuteTask()
480 {
481     if (!isInitSuccess_) {
482         MEDIA_WARN_LOG("DfxManager not init");
483         return;
484     }
485     std::unordered_map<string, CommonBehavior> commonBehavior = dfxCollector_->GetCommonBehavior();
486     dfxAnalyzer_->FlushCommonBehavior(commonBehavior);
487     HandleDeleteBehaviors();
488     std::unordered_map<std::string, ThumbnailErrorInfo> result = dfxCollector_->GetThumbnailError();
489     dfxAnalyzer_->FlushThumbnail(result);
490     AdaptationToMovingPhotoInfo adaptationInfo = dfxCollector_->GetAdaptationToMovingPhotoInfo();
491     dfxAnalyzer_->FlushAdaptationToMovingPhoto(adaptationInfo);
492     CheckStatus();
493 }
494 
HandleDeleteBehaviors()495 void DfxManager::HandleDeleteBehaviors()
496 {
497     std::unordered_map<string, int32_t> deleteAssetToTrash =
498         dfxCollector_->GetDeleteBehavior(DfxType::TRASH_PHOTO);
499     dfxAnalyzer_->FlushDeleteBehavior(deleteAssetToTrash, DfxType::TRASH_PHOTO);
500     std::unordered_map<string, int32_t> deleteAssetFromDisk =
501         dfxCollector_->GetDeleteBehavior(DfxType::ALBUM_DELETE_ASSETS);
502     dfxAnalyzer_->FlushDeleteBehavior(deleteAssetToTrash, DfxType::ALBUM_DELETE_ASSETS);
503     std::unordered_map<string, int32_t> removeAssets =
504         dfxCollector_->GetDeleteBehavior(DfxType::ALBUM_REMOVE_PHOTOS);
505     dfxAnalyzer_->FlushDeleteBehavior(removeAssets, DfxType::ALBUM_REMOVE_PHOTOS);
506 }
507 
HandleMiddleReport()508 int64_t DfxManager::HandleMiddleReport()
509 {
510     if (!isInitSuccess_) {
511         MEDIA_WARN_LOG("DfxManager not init");
512         return MediaFileUtils::UTCTimeSeconds();
513     }
514     dfxReporter_->ReportCommonBehavior();
515     dfxReporter_->ReportDeleteStatistic();
516     return MediaFileUtils::UTCTimeSeconds();
517 }
518 
HandleOneDayReport()519 int64_t DfxManager::HandleOneDayReport()
520 {
521     if (!isInitSuccess_) {
522         MEDIA_WARN_LOG("DfxManager not init");
523         return MediaFileUtils::UTCTimeSeconds();
524     }
525     dfxReporter_->ReportThumbnailError();
526     dfxReporter_->ReportAdaptationToMovingPhoto();
527     dfxReporter_->ReportPhotoRecordInfo();
528     dfxReporter_->ReportOperationRecordInfo();
529     return MediaFileUtils::UTCTimeSeconds();
530 }
531 
HandleAdaptationToMovingPhoto(const string & appName,bool adapted)532 void DfxManager::HandleAdaptationToMovingPhoto(const string &appName, bool adapted)
533 {
534     if (!isInitSuccess_) {
535         MEDIA_WARN_LOG("DfxManager not init");
536         return;
537     }
538     dfxCollector_->CollectAdaptationToMovingPhotoInfo(appName, adapted);
539 }
540 
GetPhotoAndPhotoExtSizes(QuerySizeAndResolution & queryInfo)541 static void GetPhotoAndPhotoExtSizes(QuerySizeAndResolution &queryInfo)
542 {
543     auto rdbStore = MediaLibraryUnistoreManager::GetInstance().GetRdbStore();
544     CHECK_AND_RETURN_LOG(rdbStore != nullptr, "RdbStore is null");
545 
546     PhotoStorageOperation photoStorageOperation;
547     int64_t cacheSize = photoStorageOperation.GetCacheSize();
548     int64_t highlightSize = photoStorageOperation.GetHighlightSizeFromPreferences();
549 
550     TotalThumbnailSizeResult totalThumbnailSizeResult = {};
551     photoStorageOperation.GetTotalThumbnailSize(rdbStore, totalThumbnailSizeResult);
552 
553     TotalEditdataSizeResult totalEditdataSizeRusult = {};
554     photoStorageOperation.GetTotalEditdataSize(rdbStore, totalEditdataSizeRusult);
555 
556     int64_t totalExtSize = cacheSize + highlightSize + totalThumbnailSizeResult.totalThumbnailSize +
557         totalEditdataSizeRusult.totalEditdataSize;
558     LocalPhotoSizeResult localPhotoSizeResult = {};
559     photoStorageOperation.GetLocalPhotoSize(rdbStore, localPhotoSizeResult, totalExtSize);
560 
561     int64_t totalSize = localPhotoSizeResult.localImageSize + localPhotoSizeResult.localVideoSize + totalExtSize;
562 
563     queryInfo.cacheRomSize = std::to_string(cacheSize);
564     queryInfo.highlightRomSize = std::to_string(highlightSize);
565     queryInfo.ThumbnailRomSize = std::to_string(totalThumbnailSizeResult.totalThumbnailSize);
566     queryInfo.EditdataRomSize = std::to_string(totalEditdataSizeRusult.totalEditdataSize);
567     queryInfo.localImageRomSize = std::to_string(localPhotoSizeResult.localImageSize);
568     queryInfo.localVideoRomSize = std::to_string(localPhotoSizeResult.localVideoSize);
569     queryInfo.totalSize = std::to_string(totalSize);
570     MEDIA_INFO_LOG("localImageRomSize: %{public}s, localVideoRomSize: %{public}s, totalThumbnailSize: %{public}s, "
571                    "totalEditdataSize: %{public}s, cacheSize: %{public}s, highlightSize: %{public}s, "
572                    "totalSize: %{public}s",
573                    queryInfo.localImageRomSize.c_str(), queryInfo.localVideoRomSize.c_str(),
574                    queryInfo.ThumbnailRomSize.c_str(), queryInfo.EditdataRomSize.c_str(),
575                    queryInfo.cacheRomSize.c_str(), queryInfo.highlightRomSize.c_str(),
576                    queryInfo.totalSize.c_str());
577 }
578 
HandleGetSizeAndResolutionInfo(std::shared_ptr<DfxReporter> & dfxReporter)579 static void HandleGetSizeAndResolutionInfo(std::shared_ptr<DfxReporter>& dfxReporter)
580 {
581     MEDIA_INFO_LOG("HandleGetSizeAndResolutionInfo start");
582     CHECK_AND_RETURN_LOG(dfxReporter != nullptr, "Failed to get dfxReporter for HandleGetSizeAndResolutionInfo!");
583     QuerySizeAndResolution queryInfo = {};
584     bool bQueryInfo = DfxDatabaseUtils::GetSizeAndResolutionInfo(queryInfo);
585     CHECK_AND_RETURN_LOG(bQueryInfo, "E_OK");
586     std::string photoMimeType;
587     DfxDatabaseUtils::GetPhotoMimeType(photoMimeType);
588     GetPhotoAndPhotoExtSizes(queryInfo);
589     dfxReporter->ReportPhotoSizeAndResolutionInfo(queryInfo, photoMimeType);
590 }
591 
HandleCheckOneWeekDayTask(DfxData * data)592 static void HandleCheckOneWeekDayTask(DfxData *data)
593 {
594     CHECK_AND_RETURN_LOG(data != nullptr, "Failed to get data for Handle Check One Week Day Task!");
595     auto *taskData = static_cast<StatisticData *>(data);
596     std::shared_ptr<DfxReporter> dfxReporter = taskData->dfxReporter_;
597     CHECK_AND_RETURN_LOG(dfxReporter != nullptr, "Failed to get dfxReporter for Handle Check One Week Day Task!");
598     HandleGetSizeAndResolutionInfo(dfxReporter);
599 }
600 
HandleOneWeekMissions()601 void DfxManager::HandleOneWeekMissions()
602 {
603     MEDIA_INFO_LOG("HandlePhotoInfo start");
604     CHECK_AND_RETURN_LOG(isInitSuccess_, "DfxManager not init");
605     int32_t errCode;
606     shared_ptr<NativePreferences::Preferences> prefs =
607     NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
608     if (!prefs) {
609         MEDIA_ERR_LOG("get preferences error: %{public}d", errCode);
610         return;
611     }
612     int64_t lastReportTime = prefs->GetLong(LAST_WEEK_REPORT_TIME, 0);
613     if (MediaFileUtils::UTCTimeSeconds() - lastReportTime > ONE_WEEK && dfxWorker_ != nullptr) {
614         MEDIA_INFO_LOG("start handle statistic behavior");
615         auto *taskData = new (nothrow) StatisticData(dfxReporter_);
616         CHECK_AND_RETURN_LOG(taskData != nullptr, "Failed to alloc async data for Handle Week Day Missions!");
617         auto oneWeekTask = make_shared<DfxTask>(HandleCheckOneWeekDayTask, taskData);
618         CHECK_AND_RETURN_LOG(oneWeekTask != nullptr, "Failed to create dfx task.");
619         dfxWorker_->AddTask(oneWeekTask);
620         int64_t time = MediaFileUtils::UTCTimeSeconds();
621         prefs->PutLong(LAST_WEEK_REPORT_TIME, time);
622         prefs->FlushSync();
623     }
624 }
625 
IsReported()626 bool IsReported()
627 {
628     int32_t errCode;
629     shared_ptr<NativePreferences::Preferences> prefs =
630         NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
631     if (!prefs) {
632         MEDIA_ERR_LOG("get dfx common preferences error: %{public}d", errCode);
633         return false;
634     }
635     return prefs->GetBool(IS_REPORTED, false);
636 }
637 
SetReported(bool isReported)638 void SetReported(bool isReported)
639 {
640     int32_t errCode;
641     shared_ptr<NativePreferences::Preferences> prefs =
642         NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
643     if (!prefs) {
644         MEDIA_ERR_LOG("get dfx common preferences error: %{public}d", errCode);
645         return;
646     }
647     prefs->PutBool(IS_REPORTED, isReported);
648 }
649 
~CloudSyncDfxManager()650 CloudSyncDfxManager::~CloudSyncDfxManager()
651 {
652     ShutDownTimer();
653 }
654 
GetInstance()655 CloudSyncDfxManager& CloudSyncDfxManager::GetInstance()
656 {
657     static CloudSyncDfxManager cloudSyncDfxManager;
658     return cloudSyncDfxManager;
659 }
660 
GetCloudSyncStatus()661 CloudSyncStatus GetCloudSyncStatus()
662 {
663     return static_cast<CloudSyncStatus>(system::GetParameter(CLOUDSYNC_STATUS_KEY, "0").at(0) - '0');
664 }
665 
CloudSyncDfxManager()666 CloudSyncDfxManager::CloudSyncDfxManager()
667 {
668     InitSyncState();
669     uint16_t newState = static_cast<uint16_t>(syncState_);
670     stateProcessFuncs_[newState].Process(*this);
671 }
672 
InitSyncState()673 void CloudSyncDfxManager::InitSyncState()
674 {
675     CloudSyncStatus cloudSyncStatus = GetCloudSyncStatus();
676     switch (cloudSyncStatus) {
677         case CloudSyncStatus::BEGIN:
678         case CloudSyncStatus::SYNC_SWITCHED_OFF:
679             syncState_ = SyncState::INIT_STATE;
680             return;
681         case CloudSyncStatus::FIRST_FIVE_HUNDRED:
682         case CloudSyncStatus::TOTAL_DOWNLOAD:
683             syncState_ = SyncState::START_STATE;
684             return;
685         case CloudSyncStatus::TOTAL_DOWNLOAD_FINISH:
686             syncState_ = SyncState::END_STATE;
687             return;
688         default:
689             return;
690     }
691 }
692 
StateSwitch(CloudSyncDfxManager & manager)693 bool InitState::StateSwitch(CloudSyncDfxManager& manager)
694 {
695     CloudSyncStatus cloudSyncStatus = GetCloudSyncStatus();
696     switch (cloudSyncStatus) {
697         case CloudSyncStatus::FIRST_FIVE_HUNDRED:
698         case CloudSyncStatus::TOTAL_DOWNLOAD:
699             manager.syncState_ = SyncState::START_STATE;
700             return true;
701         case CloudSyncStatus::TOTAL_DOWNLOAD_FINISH:
702             manager.syncState_ = SyncState::END_STATE;
703             MEDIA_INFO_LOG("CloudSyncDfxManager new status:%{public}hu", manager.syncState_);
704             return true;
705         default:
706             return false;
707     }
708 }
709 
Process(CloudSyncDfxManager & manager)710 void InitState::Process(CloudSyncDfxManager& manager)
711 {
712     MEDIA_INFO_LOG("CloudSyncDfxManager new status:%{public}hu", manager.syncState_);
713     manager.ResetStartTime();
714     manager.ShutDownTimer();
715     SetReported(false);
716 }
717 
RunDfx()718 void CloudSyncDfxManager::RunDfx()
719 {
720     uint16_t oldState = static_cast<uint16_t>(syncState_);
721     if (stateProcessFuncs_[oldState].StateSwitch(*this)) {
722         uint16_t newState = static_cast<uint16_t>(syncState_);
723         stateProcessFuncs_[newState].Process(*this);
724     }
725 }
726 
StateSwitch(CloudSyncDfxManager & manager)727 bool StartState::StateSwitch(CloudSyncDfxManager& manager)
728 {
729     CloudSyncStatus cloudSyncStatus = GetCloudSyncStatus();
730     switch (cloudSyncStatus) {
731         case CloudSyncStatus::BEGIN:
732         case CloudSyncStatus::SYNC_SWITCHED_OFF:
733             manager.syncState_ = SyncState::INIT_STATE;
734             return true;
735         case CloudSyncStatus::TOTAL_DOWNLOAD_FINISH:
736             manager.syncState_ = SyncState::END_STATE;
737             MEDIA_INFO_LOG("CloudSyncDfxManager new status:%{public}hu", manager.syncState_);
738             return true;
739         default:
740             return false;
741     }
742 }
743 
Process(CloudSyncDfxManager & manager)744 void StartState::Process(CloudSyncDfxManager& manager)
745 {
746     MEDIA_INFO_LOG("CloudSyncDfxManager new status:%{public}hu", manager.syncState_);
747     manager.SetStartTime();
748     manager.StartTimer();
749     SetReported(false);
750 }
751 
StateSwitch(CloudSyncDfxManager & manager)752 bool EndState::StateSwitch(CloudSyncDfxManager& manager)
753 {
754     CloudSyncStatus cloudSyncStatus = GetCloudSyncStatus();
755     switch (cloudSyncStatus) {
756         case CloudSyncStatus::BEGIN:
757         case CloudSyncStatus::SYNC_SWITCHED_OFF:
758             manager.syncState_ = SyncState::INIT_STATE;
759             return true;
760         case CloudSyncStatus::TOTAL_DOWNLOAD_FINISH:
761             return true;
762         default:
763             return false;
764     }
765 }
766 
Process(CloudSyncDfxManager & manager)767 void EndState::Process(CloudSyncDfxManager& manager)
768 {
769     std::unique_lock<std::mutex> lock(manager.endStateMutex_);
770     if (IsReported()) {
771         manager.ShutDownTimer();
772         return;
773     }
774     manager.SetStartTime();
775     manager.StartTimer();
776     int32_t downloadedThumb = 0;
777     int32_t generatedThumb = 0;
778     if (!DfxDatabaseUtils::QueryDownloadedAndGeneratedThumb(downloadedThumb, generatedThumb)) {
779         if (downloadedThumb != generatedThumb) {
780             return;
781         }
782         int32_t totalDownload = 0;
783         DfxDatabaseUtils::QueryTotalCloudThumb(totalDownload);
784         if (totalDownload != downloadedThumb) {
785             return;
786         }
787         SetReported(true);
788         manager.ShutDownTimer();
789         DfxReporter::ReportCloudSyncThumbGenerationStatus(downloadedThumb, generatedThumb, totalDownload);
790     }
791 }
792 
StartTimer()793 void CloudSyncDfxManager::StartTimer()
794 {
795     std::unique_lock<std::mutex> lock(timerMutex_);
796     if (timerId_ != 0) {
797         return;
798     }
799     if (timer_.Setup() != ERR_OK) {
800         MEDIA_INFO_LOG("CloudSync Dfx Set Timer Failed");
801         return;
802     }
803     Utils::Timer::TimerCallback timerCallback = [this]() {
804         (void)this;
805         if (IsReported()) {
806             return;
807         }
808         int32_t generatedThumb = 0;
809         int32_t downloadedThumb = 0;
810         if (!DfxDatabaseUtils::QueryDownloadedAndGeneratedThumb(downloadedThumb, generatedThumb)) {
811             int32_t totalDownload = 0;
812             DfxDatabaseUtils::QueryTotalCloudThumb(totalDownload);
813             if (downloadedThumb == generatedThumb && totalDownload == generatedThumb) {
814                 MEDIA_INFO_LOG("CloudSyncDfxManager Dfx report Thumb generation status, "
815                     "download: %{public}d, generate: %{public}d", downloadedThumb, generatedThumb);
816                 SetReported(true);
817             }
818             DfxReporter::ReportCloudSyncThumbGenerationStatus(downloadedThumb, generatedThumb, totalDownload);
819         }
820     };
821     timerId_ = timer_.Register(timerCallback, SIX_HOUR * TO_MILLION, false);
822     MEDIA_INFO_LOG("CloudSyncDfxManager StartTimer id:%{public}d", timerId_);
823 }
824 
ShutDownTimer()825 void CloudSyncDfxManager::ShutDownTimer()
826 {
827     std::unique_lock<std::mutex> lock(timerMutex_);
828     if (timerId_ == 0) {
829         return;
830     }
831     MEDIA_INFO_LOG("CloudSyncDfxManager ShutDownTimer id:%{public}d", timerId_);
832     timer_.Unregister(timerId_);
833     timerId_ = 0;
834     timer_.Shutdown();
835 }
836 
ResetStartTime()837 void CloudSyncDfxManager::ResetStartTime()
838 {
839     int32_t errCode;
840     shared_ptr<NativePreferences::Preferences> prefs =
841         NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
842     if (!prefs) {
843         MEDIA_ERR_LOG("get dfx common preferences error: %{public}d", errCode);
844         return;
845     }
846     prefs->PutLong(CLOUD_SYNC_START_TIME, 0);
847     prefs->FlushSync();
848 }
849 
SetStartTime()850 void CloudSyncDfxManager::SetStartTime()
851 {
852     int32_t errCode;
853     shared_ptr<NativePreferences::Preferences> prefs =
854         NativePreferences::PreferencesHelper::GetPreferences(DFX_COMMON_XML, errCode);
855     if (!prefs) {
856         MEDIA_ERR_LOG("get dfx common preferences error: %{public}d", errCode);
857         return;
858     }
859     int64_t time = prefs->GetLong(CLOUD_SYNC_START_TIME, 0);
860     // if startTime exists, no need to reset startTime
861     if (time != 0) {
862         return;
863     }
864     time = MediaFileUtils::UTCTimeSeconds();
865     prefs->PutLong(CLOUD_SYNC_START_TIME, time);
866     prefs->FlushSync();
867 }
868 
ResetStatistic()869 void DfxManager::ResetStatistic()
870 {
871     for (auto &value : downloadMeta_) {
872         value.store(0);
873     }
874     for (auto &value : uploadMeta_) {
875         value.store(0);
876     }
877     for (auto &value : downloadThumb_) {
878         value.store(0);
879     }
880     for (auto &value : downloadLcd_) {
881         value.store(0);
882     }
883     for (auto &value : uploadAlbum_) {
884         value.store(0);
885     }
886     for (auto &value : downloadAlbum_) {
887         value.store(0);
888     }
889     for (auto &value : updateDetails_) {
890         value.store(0);
891     }
892     for (auto &value : uploadMetaErr_) {
893         value.store(0);
894     }
895 }
896 
CopyStatistic(CloudSyncStat & stat)897 void DfxManager::CopyStatistic(CloudSyncStat& stat)
898 {
899     stat.downloadMeta.reserve(downloadMeta_.size());
900     for (auto &value : downloadMeta_) {
901         stat.downloadMeta.push_back(value.load());
902     }
903     stat.uploadMeta.reserve(uploadMeta_.size());
904     for (auto &value : uploadMeta_) {
905         stat.uploadMeta.push_back(value.load());
906     }
907     stat.downloadThumb.reserve(downloadThumb_.size());
908     for (auto &value : downloadThumb_) {
909         stat.downloadThumb.push_back(value.load());
910     }
911     stat.downloadLcd.reserve(downloadLcd_.size());
912     for (auto &value : downloadLcd_) {
913         stat.downloadLcd.push_back(value.load());
914     }
915 
916     stat.uploadAlbum.reserve(uploadAlbum_.size());
917     for (auto &value : uploadAlbum_) {
918         stat.uploadAlbum.push_back(value.load());
919     }
920     stat.downloadAlbum.reserve(downloadAlbum_.size());
921     for (auto &value : downloadAlbum_) {
922         stat.downloadAlbum.push_back(value.load());
923     }
924 
925     stat.updateDetails.reserve(updateDetails_.size());
926     for (auto &value : updateDetails_) {
927         stat.updateDetails.push_back(value.load());
928     }
929     stat.uploadMetaErr.reserve(uploadMetaErr_.size());
930     for (auto &value : uploadMetaErr_) {
931         stat.uploadMetaErr.push_back(value.load());
932     }
933 }
934 
HandleSyncStart(const std::string & taskId,const int32_t syncReason)935 void DfxManager::HandleSyncStart(const std::string& taskId, const int32_t syncReason)
936 {
937     ResetStatistic();
938     syncInfo_.startTime = static_cast<uint64_t>(MediaFileUtils::UTCTimeSeconds());
939     syncInfo_.syncReason = syncReason;
940     taskId_ = taskId;
941 }
942 
HandleUpdateMetaStat(uint32_t index,uint64_t diff,uint32_t syncType)943 void DfxManager::HandleUpdateMetaStat(uint32_t index, uint64_t diff, uint32_t syncType)
944 {
945     if (index < DOWNLOAD_META_LEN) {
946         downloadMeta_[index].fetch_add(diff);
947     } else if (index - INDEX_UL_META_SUCCESS < UPLOAD_META_LEN) {
948         uploadMeta_[index - INDEX_UL_META_SUCCESS].fetch_add(diff);
949     } else {
950         MEDIA_DEBUG_LOG("HandleUpdateMetaStat get a invalid index");
951     }
952 
953     if (syncType > 0 && syncType < UPDATE_DETAILS_LEN &&
954         (index == INDEX_UL_META_SUCCESS || index == INDEX_DL_META_SUCCESS)) {
955         updateDetails_[syncType].fetch_add(diff);
956     }
957 }
958 
HandleUpdateAttachmentStat(uint32_t index,uint64_t diff)959 void DfxManager::HandleUpdateAttachmentStat(uint32_t index, uint64_t diff)
960 {
961     if (index < DOWNLOAD_THUMB_LEN) {
962         downloadThumb_[index].fetch_add(diff);
963     } else if (index - INDEX_LCD_SUCCESS < DOWNLOAD_LCD_LEN) {
964         downloadLcd_[index - INDEX_LCD_SUCCESS].fetch_add(diff);
965     } else {
966         MEDIA_DEBUG_LOG("HandleUpdateAttachmentStat get a invalid index");
967     }
968 }
969 
HandleUpdateAlbumStat(uint32_t index,uint64_t diff)970 void DfxManager::HandleUpdateAlbumStat(uint32_t index, uint64_t diff)
971 {
972     if (index < DOWNLOAD_ALBUM_LEN) {
973         downloadAlbum_[index].fetch_add(diff);
974     } else if (index - INDEX_UL_ALBUM_SUCCESS < UPLOAD_ALBUM_LEN) {
975         uploadAlbum_[index - INDEX_UL_ALBUM_SUCCESS].fetch_add(diff);
976     } else {
977         MEDIA_DEBUG_LOG("HandleUpdateAlbumStat get a invalid index");
978     }
979 }
980 
HandleUpdateUploadMetaStat(uint32_t index,uint64_t diff)981 void DfxManager::HandleUpdateUploadMetaStat(uint32_t index, uint64_t diff)
982 {
983     if (index < UPLOAD_META_ERR_LEN) {
984         uploadMetaErr_[index].fetch_add(diff);
985     }
986 }
987 
HandleUpdateUploadDetailError(int32_t error)988 void DfxManager::HandleUpdateUploadDetailError(int32_t error)
989 {
990     if (error == E_CLOUD_STORAGE_FULL) {
991         uploadMetaErr_[INDEX_UL_META_ERR_STORAGE].fetch_add(1);
992     }
993 }
994 
VectorToString(const std::vector<uint64_t> & vec)995 static std::string VectorToString(const std::vector<uint64_t>& vec)
996 {
997     std::ostringstream oss;
998     for (size_t i = 0; i < vec.size(); ++i) {
999         if (0 != i) {
1000             oss << " ";
1001         }
1002         oss << vec[i];
1003     }
1004     return oss.str();
1005 }
1006 
HandleSyncEnd(const int32_t stopReason)1007 void DfxManager::HandleSyncEnd(const int32_t stopReason)
1008 {
1009     int64_t endTime = MediaFileUtils::UTCTimeSeconds();
1010     if (static_cast<uint64_t>(endTime) >= syncInfo_.startTime) {
1011         syncInfo_.duration = static_cast<uint64_t>(endTime) - syncInfo_.startTime;
1012     } else {
1013         syncInfo_.duration = 0;
1014     }
1015     syncInfo_.stopReason = stopReason;
1016     CloudSyncStat stat;
1017     CopyStatistic(stat);
1018 
1019     std::string syncInfo;
1020     for (auto &detail : stat.updateDetails) {
1021         if (detail > 0) {
1022             stat.updateDetails[0] = static_cast<uint64_t>(MediaFileUtils::UTCTimeSeconds());
1023             syncInfo = "[" + taskId_ + " " + std::to_string(syncInfo_.startTime) + " " +
1024             VectorToString(stat.updateDetails) + "]";
1025             break;
1026         }
1027     }
1028 
1029     DfxReporter::ReportSyncStat(taskId_, syncInfo_, stat, syncInfo);
1030 }
1031 
HandleReportSyncFault(const std::string & position,const SyncFaultEvent & event)1032 void DfxManager::HandleReportSyncFault(const std::string& position, const SyncFaultEvent& event)
1033 {
1034     DfxReporter::ReportSyncFault(taskId_, position, event);
1035 }
1036 
HandleAccurateRefreshTimeOut(const AccurateRefreshDfxDataPoint & reportData)1037 void DfxManager::HandleAccurateRefreshTimeOut(const AccurateRefreshDfxDataPoint& reportData)
1038 {
1039     if (!isInitSuccess_) {
1040         MEDIA_WARN_LOG("DfxManager not init");
1041         return;
1042     }
1043     MEDIA_INFO_LOG("enter HandleAccurateRefreshTimeOut");
1044     dfxReporter_->ReportAccurateRefreshResult(reportData);
1045 }
1046 } // namespace Media
1047 } // namespace OHOS
1048