• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 <fcntl.h>
17 #include <unistd.h>
18 #include <iostream>
19 #include <fstream>
20 #include <streambuf>
21 #include <filesystem>
22 #include "print_system_data.h"
23 #include "print_log.h"
24 #include "print_util.h"
25 #include "print_constant.h"
26 #include "print_service_ability.h"
27 
28 namespace OHOS {
29 namespace Print {
30 
ParsePrinterListJsonV1(Json::Value & jsonObject)31 bool PrintSystemData::ParsePrinterListJsonV1(Json::Value &jsonObject)
32 {
33     if (!PrintJsonUtil::IsMember(jsonObject, "printer_list") || !jsonObject["printer_list"].isArray()) {
34         PRINT_HILOGW("can not find printer_list");
35         return false;
36     }
37     uint32_t jsonSize = jsonObject["printer_list"].size();
38     if (jsonSize > MAX_PRINTER_SIZE) {
39         PRINT_HILOGE("printerlist size is illegal");
40         return false;
41     }
42     for (uint32_t i = 0; i < jsonSize; i++) {
43         Json::Value object = jsonObject["printer_list"][i];
44         if (!ConvertJsonToPrinterInfo(object)) {
45             PRINT_HILOGW("can not find necessary param");
46             continue;
47         }
48     }
49     return true;
50 }
51 
ConvertJsonToPrinterInfo(Json::Value & object)52 bool PrintSystemData::ConvertJsonToPrinterInfo(Json::Value &object)
53 {
54     if (!PrintJsonUtil::IsMember(object, "id") || !object["id"].isString()) {
55         PRINT_HILOGW("can not find id");
56         return false;
57     }
58     std::string id = object["id"].asString();
59     if (!PrintJsonUtil::IsMember(object, "name") || !object["name"].isString()) {
60         PRINT_HILOGW("can not find name");
61         return false;
62     }
63     std::string name = object["name"].asString();
64     if (!PrintJsonUtil::IsMember(object, "uri") || !object["uri"].isString()) {
65         PRINT_HILOGW("can not find uri");
66         return false;
67     }
68     std::string uri = object["uri"].asString();
69     if (!PrintJsonUtil::IsMember(object, "maker") || !object["maker"].isString()) {
70         PRINT_HILOGW("can not find maker");
71         return false;
72     }
73     std::string maker = object["maker"].asString();
74     if (!PrintJsonUtil::IsMember(object, "capability") || !object["capability"].isObject()) {
75         PRINT_HILOGW("can not find capability");
76         return false;
77     }
78     PrinterCapability printerCapability;
79     Json::Value capsJson = object["capability"];
80     if (!ConvertJsonToPrinterCapability(capsJson, printerCapability)) {
81         PRINT_HILOGW("convert json to printer capability failed");
82         return false;
83     }
84     printerCapability.Dump();
85     PrinterInfo info;
86     info.SetPrinterId(id);
87     info.SetPrinterName(name);
88     info.SetUri(uri);
89     info.SetPrinterMake(maker);
90     info.SetCapability(printerCapability);
91     if (PrintJsonUtil::IsMember(object, "ppdHashCode") && object["ppdHashCode"].isString()) {
92         std::string ppdHashCode = object["ppdHashCode"].asString();
93         info.SetPpdHashCode(ppdHashCode);
94     }
95     ConvertInnerJsonToPrinterInfo(object, info);
96     InsertAddedPrinter(id, info);
97     return true;
98 }
99 
ConvertInnerJsonToPrinterInfo(Json::Value & object,PrinterInfo & info)100 void PrintSystemData::ConvertInnerJsonToPrinterInfo(Json::Value &object, PrinterInfo &info)
101 {
102     if (PrintJsonUtil::IsMember(object, "alias") && object["alias"].isString()) {
103         info.SetAlias(object["alias"].asString());
104     }
105     if (PrintJsonUtil::IsMember(object, "printerStatus") && object["printerStatus"].isInt()) {
106         info.SetPrinterStatus(static_cast<PrinterStatus>(object["printerStatus"].asInt()));
107     }
108     if (PrintJsonUtil::IsMember(object, "preferences") && object["preferences"].isObject()) {
109         PrinterPreferences preference;
110         preference.ConvertJsonToPrinterPreferences(object["preferences"]);
111         info.SetPreferences(preference);
112         PRINT_HILOGI("convert json to printer preferences success");
113     }
114 }
115 
Init()116 bool PrintSystemData::Init()
117 {
118     GetAddedPrinterMap().Clear();
119     PRINT_HILOGI("load new printer list file");
120     std::filesystem::path printersDir(GetPrintersPath());
121     for (const auto& entry : std::filesystem::directory_iterator(printersDir)) {
122         if (!entry.is_directory()) {
123             ReadJsonFile(entry.path());
124         }
125     }
126 
127     Json::Value printerListJson;
128     std::string printerListFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINTER_LIST_FILE;
129     if (GetJsonObjectFromFile(printerListJson, printerListFilePath) && ParsePrinterListJsonV1(printerListJson)) {
130         PRINT_HILOGW("previous printer list file exist");
131         Json::Value preferencesJson;
132         std::string preferencesFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINTER_PREFERENCE_FILE;
133         if (GetJsonObjectFromFile(preferencesJson, preferencesFilePath) &&
134             ParsePrinterPreferencesJson(preferencesJson)) {
135             PRINT_HILOGI("parse previous preferences file success");
136         }
137         std::vector<std::string> addedPrinterList = QueryAddedPrinterIdList();
138         for (auto printerId : addedPrinterList) {
139             SavePrinterFile(printerId);
140         }
141         DeleteFile(preferencesFilePath);
142         DeleteFile(printerListFilePath);
143     }
144     return true;
145 }
146 
ReadJsonFile(const std::filesystem::path & path)147 bool PrintSystemData::ReadJsonFile(const std::filesystem::path &path)
148 {
149     std::ifstream file(path);
150     if (!file.is_open()) {
151         PRINT_HILOGW("open printer list file fail");
152         return false;
153     }
154     Json::Value fileJson;
155     if (!PrintJsonUtil::ParseFromStream(file, fileJson)) {
156         PRINT_HILOGW("json accept fail");
157         return false;
158     }
159     file.close();
160 
161     if (!ConvertJsonToPrinterInfo(fileJson)) {
162         PRINT_HILOGW("can not find necessary param");
163         return false;
164     }
165     return true;
166 }
167 
GetJsonObjectFromFile(Json::Value & jsonObject,const std::string & fileName)168 bool PrintSystemData::GetJsonObjectFromFile(Json::Value &jsonObject, const std::string &fileName)
169 {
170     std::ifstream ifs(fileName.c_str(), std::ios::in | std::ios::binary);
171     if (!ifs.is_open()) {
172         PRINT_HILOGW("open printer list file fail");
173         return false;
174     }
175     if (!PrintJsonUtil::ParseFromStream(ifs, jsonObject)) {
176         PRINT_HILOGW("json accept fail");
177         return false;
178     }
179     ifs.close();
180     if (fileName.find(PRINTER_PREFERENCE_FILE) != std::string::npos) {
181         return true;
182     }
183     if (!PrintJsonUtil::IsMember(jsonObject, "version") || !jsonObject["version"].isString()) {
184         PRINT_HILOGW("can not find version");
185         return false;
186     }
187     std::string version = jsonObject["version"].asString();
188     PRINT_HILOGI("json version: %{public}s", version.c_str());
189     std::string fileVersion = "";
190     std::string printerListFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINTER_LIST_FILE;
191     if (strcmp(fileName.c_str(), printerListFilePath.c_str())) {
192         fileVersion = PRINTER_LIST_VERSION_V1;
193     } else {
194         fileVersion = PRINT_USER_DATA_VERSION;
195     }
196     if (strcmp(version.c_str(), PRINTER_LIST_VERSION_V1.c_str())) {
197         PRINT_HILOGW("printer list version is error.");
198         return false;
199     }
200     return true;
201 }
202 
ParsePrinterPreferencesJson(Json::Value & jsonObject)203 bool PrintSystemData::ParsePrinterPreferencesJson(Json::Value &jsonObject)
204 {
205     if (!PrintJsonUtil::IsMember(jsonObject, "printer_list") || !jsonObject["printer_list"].isArray()) {
206         PRINT_HILOGW("can not find printer_list");
207         return false;
208     }
209     uint32_t jsonSize = jsonObject["printer_list"].size();
210     if (jsonSize > MAX_PRINTER_SIZE) {
211         PRINT_HILOGE("printerlist size is illegal");
212         return false;
213     }
214     for (uint32_t i = 0; i < jsonSize; i++) {
215         Json::Value object = jsonObject["printer_list"][i];
216         Json::Value::Members keys = object.getMemberNames();
217         for (auto it = keys.begin(); it != keys.end(); it++) {
218             std::string printerId = *it;
219             auto info = GetAddedPrinterMap().Find(printerId);
220             if (info == nullptr) {
221                 continue;
222             }
223             PrinterCapability capability;
224             PrinterPreferences preferences;
225             info->GetCapability(capability);
226             info->GetPreferences(preferences);
227             BuildPrinterPreference(capability, preferences);
228             UpdatePrinterPreferences(printerId, preferences);
229             Json::Value printPreferenceJson = object[printerId];
230             if (!PrintJsonUtil::IsMember(jsonObject, "setting") || !printPreferenceJson["setting"].isObject()) {
231                 PRINT_HILOGW("can not find setting");
232                 continue;
233             }
234             Json::Value settingJson = printPreferenceJson["setting"];
235             PRINT_HILOGD("ParsePrinterPreferencesJson settingJson: %{public}s",
236                 (PrintJsonUtil::WriteString(settingJson)).c_str());
237             PrinterPreferences newPreferences;
238             if (ParsePreviousPreferencesSetting(settingJson, newPreferences)) {
239                 PRINT_HILOGI("need update preferences by previous settings");
240                 newPreferences.Dump();
241                 UpdatePrinterPreferences(printerId, newPreferences);
242             }
243         }
244     }
245     return true;
246 }
247 
ParsePreviousPreferencesSetting(Json::Value & settingJson,PrinterPreferences & preferences)248 bool PrintSystemData::ParsePreviousPreferencesSetting(Json::Value &settingJson, PrinterPreferences &preferences)
249 {
250     bool updatePreferences = false;
251     if (PrintJsonUtil::IsMember(settingJson, "pagesizeId") && settingJson["pagesizeId"].isString() &&
252         !settingJson["pagesizeId"].asString().empty()) {
253         updatePreferences = true;
254         preferences.SetDefaultPageSizeId(settingJson["pagesizeId"].asString());
255     }
256     if (PrintJsonUtil::IsMember(settingJson, "orientation") && settingJson["orientation"].isString() &&
257         !settingJson["orientation"].asString().empty()) {
258         updatePreferences = true;
259         int32_t defaultOrientation = 0;
260         PrintUtil::ConvertToInt(settingJson["orientation"].asString(), defaultOrientation);
261         preferences.SetDefaultOrientation(defaultOrientation);
262     }
263     if (PrintJsonUtil::IsMember(settingJson, "duplex") && settingJson["duplex"].isString() &&
264         !settingJson["duplex"].asString().empty()) {
265         updatePreferences = true;
266         int32_t defaultDuplexMode = DUPLEX_MODE_NONE;
267         PrintUtil::ConvertToInt(settingJson["duplex"].asString(), defaultDuplexMode);
268         preferences.SetDefaultDuplexMode(defaultDuplexMode);
269     }
270     if (PrintJsonUtil::IsMember(settingJson, "quality") && settingJson["quality"].isString() &&
271         !settingJson["quality"].asString().empty()) {
272         updatePreferences = true;
273         int32_t defaultPrintQuality = PRINT_QUALITY_NORMAL;
274         PrintUtil::ConvertToInt(settingJson["quality"].asString(), defaultPrintQuality);
275         preferences.SetDefaultPrintQuality(defaultPrintQuality);
276     }
277     if (PrintJsonUtil::IsMember(settingJson, "mediaType") && settingJson["mediaType"].isString() &&
278         !settingJson["mediaType"].asString().empty()) {
279         updatePreferences = true;
280         preferences.SetDefaultMediaType(settingJson["mediaType"].asString());
281     }
282     if (PrintJsonUtil::IsMember(settingJson, "hasMargin") && settingJson["hasMargin"].isBool() &&
283         settingJson["hasMargin"].asBool() == false) {
284         updatePreferences = true;
285         preferences.SetBorderless(true);
286     }
287     return updatePreferences;
288 }
289 
InsertAddedPrinter(const std::string & printerId,const PrinterInfo & printerInfo)290 void PrintSystemData::InsertAddedPrinter(const std::string &printerId, const PrinterInfo &printerInfo)
291 {
292     auto info = GetAddedPrinterMap().Find(printerId);
293     if (info == nullptr) {
294         PRINT_HILOGI("insert new printer");
295         GetAddedPrinterMap().Insert(printerId, printerInfo);
296     } else {
297         PRINT_HILOGI("update exist printer");
298         *info = printerInfo;
299     }
300 }
301 
DeleteAddedPrinter(const std::string & printerId,const std::string & printerName)302 void PrintSystemData::DeleteAddedPrinter(const std::string &printerId, const std::string &printerName)
303 {
304     if (!printerId.empty()) {
305         PRINT_HILOGI("DeleteAddedPrinter printerName: %{private}s", printerName.c_str());
306         GetAddedPrinterMap().Remove(printerId);
307         std::filesystem::path filePath =
308             GetPrintersPath() + "/" + PrintUtil::StandardizePrinterName(printerName) + ".json";
309         DeleteFile(filePath);
310     }
311 }
312 
DeleteFile(const std::filesystem::path & path)313 void PrintSystemData::DeleteFile(const std::filesystem::path &path)
314 {
315     if (std::filesystem::remove(path)) {
316         PRINT_HILOGI("file deleted successfully");
317     } else {
318         PRINT_HILOGE("failed to delete file");
319     }
320 }
321 
SavePrinterFile(const std::string & printerId)322 void PrintSystemData::SavePrinterFile(const std::string &printerId)
323 {
324     auto info = GetAddedPrinterMap().Find(printerId);
325     if (info == nullptr) {
326         return;
327     }
328     std::string printerListFilePath =
329         GetPrintersPath() + "/" + PrintUtil::StandardizePrinterName(info->GetPrinterName()) + ".json";
330     char realPidFile[PATH_MAX] = {};
331     if (realpath(PRINTER_SERVICE_FILE_PATH.c_str(), realPidFile) == nullptr) {
332         PRINT_HILOGE("The realPidFile is null, errno:%{public}s", std::to_string(errno).c_str());
333         return;
334     }
335     FILE *file = fopen(printerListFilePath.c_str(), "w+");
336     if (file == nullptr) {
337         PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str());
338         return;
339     }
340     Json::Value printerJson;
341     printerJson["id"] = printerId;
342     printerJson["name"] = info->GetPrinterName();
343     printerJson["uri"] = info->GetUri();
344     printerJson["maker"] = info->GetPrinterMake();
345     printerJson["alias"] = info->GetAlias();
346     printerJson["ppdHashCode"] = info->GetPpdHashCode();
347     if (QueryIpPrinterInfoById(printerId) != nullptr) {
348         printerJson["printerStatus"] = info->GetPrinterStatus();
349     }
350     Json::Value capsJson;
351     PrinterCapability capability;
352     info->GetCapability(capability);
353     PrinterPreferences preference;
354     info->GetPreferences(preference);
355     ConvertPrinterCapabilityToJson(capability, capsJson);
356     printerJson["capability"] = capsJson;
357     printerJson["preferences"] = preference.ConvertToJson();
358     std::string jsonString = PrintJsonUtil::WriteString(printerJson);
359     size_t jsonLength = jsonString.length();
360     size_t writeLength = fwrite(jsonString.c_str(), strlen(jsonString.c_str()), 1, file);
361     int fcloseResult = fclose(file);
362     if (fcloseResult != 0) {
363         PRINT_HILOGE("Close File Failure.");
364         return;
365     }
366     PRINT_HILOGI("SavePrinterFile finished");
367     if (writeLength < 0 || (size_t)writeLength != jsonLength) {
368         PRINT_HILOGE("SavePrinterFile error");
369     }
370 }
371 
QueryPrinterIdByStandardizeName(const std::string & printerName)372 std::string PrintSystemData::QueryPrinterIdByStandardizeName(const std::string &printerName)
373 {
374     std::string stardardizeName = PrintUtil::StandardizePrinterName(printerName);
375     return GetAddedPrinterMap().FindKey([this, stardardizeName](const PrinterInfo &printer) -> bool {
376         return PrintUtil::StandardizePrinterName(printer.GetPrinterName()) == stardardizeName;
377     });
378 }
379 
QueryAddedPrinterInfoByPrinterId(const std::string & printerId,PrinterInfo & printer)380 bool PrintSystemData::QueryAddedPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &printer)
381 {
382     auto info = GetAddedPrinterMap().Find(printerId);
383     if (info == nullptr) {
384         return false;
385     }
386     printer = *info;
387     return true;
388 }
389 
QueryPrinterInfoById(const std::string & printerId,PrinterInfo & printerInfo)390 void PrintSystemData::QueryPrinterInfoById(const std::string &printerId, PrinterInfo &printerInfo)
391 {
392     if (QueryAddedPrinterInfoByPrinterId(printerId, printerInfo)) {
393         Json::Value option;
394         option["printerName"] = printerInfo.GetPrinterName();
395         option["printerUri"] = printerInfo.GetUri();
396         option["make"] = printerInfo.GetPrinterMake();
397         option["alias"] = printerInfo.GetAlias();
398         printerInfo.SetOption(PrintJsonUtil::WriteString(option));
399         printerInfo.Dump();
400     } else {
401         PRINT_HILOGE("query printer info failed.");
402     }
403 }
404 
QueryPpdHashCodeByPrinterName(const std::string & standardPrinterName,std::string & ppdHashCode)405 bool PrintSystemData::QueryPpdHashCodeByPrinterName(const std::string &standardPrinterName,
406     std::string &ppdHashCode)
407 {
408     auto printerId = GetAddedPrinterMap().FindKey([this, standardPrinterName](const PrinterInfo &printer) -> bool {
409         return PrintUtil::StandardizePrinterName(printer.GetPrinterName()) == standardPrinterName;
410     });
411     auto info = GetAddedPrinterMap().Find(printerId);
412     if (info != nullptr) {
413         ppdHashCode = info->GetPpdHashCode();
414         return true;
415     } else {
416         PRINT_HILOGE("query ppd hash code failed.");
417         return false;
418     }
419 }
420 
UpdatePrinterStatus(const std::string & printerId,PrinterStatus printerStatus)421 void PrintSystemData::UpdatePrinterStatus(const std::string& printerId, PrinterStatus printerStatus)
422 {
423     auto info = GetAddedPrinterMap().Find(printerId);
424     if (info != nullptr) {
425         info->SetPrinterStatus(printerStatus);
426         PRINT_HILOGI("UpdatePrinterStatus success, status: %{public}d", info->GetPrinterStatus());
427     }
428 }
429 
UpdatePrinterAlias(const std::string & printerId,const std::string & printerAlias)430 bool PrintSystemData::UpdatePrinterAlias(const std::string& printerId, const std::string& printerAlias)
431 {
432     auto info = GetAddedPrinterMap().Find(printerId);
433     if (info != nullptr) {
434         if (info->GetAlias() != printerAlias) {
435             info->SetAlias(printerAlias);
436             PRINT_HILOGI("UpdatePrinterAlias success, alias: %{private}s", (info->GetAlias()).c_str());
437             return true;
438         }
439         PRINT_HILOGW("Alias is the same, no update needed.");
440         return false;
441     }
442     PRINT_HILOGE("Unable to find the corresponding printId.");
443     return false;
444 }
445 
UpdatePrinterUri(const std::shared_ptr<PrinterInfo> & printerInfo)446 void PrintSystemData::UpdatePrinterUri(const std::shared_ptr<PrinterInfo> &printerInfo)
447 {
448     auto info = GetAddedPrinterMap().Find(printerInfo->GetPrinterId());
449     if (info != nullptr) {
450         info->SetUri(printerInfo->GetUri());
451         PRINT_HILOGI("UpdatePrinterUri success");
452     }
453 }
454 
455 
UpdatePrinterPreferences(const std::string & printerId,const PrinterPreferences & preferences)456 void PrintSystemData::UpdatePrinterPreferences(const std::string &printerId, const PrinterPreferences &preferences)
457 {
458     auto info = GetAddedPrinterMap().Find(printerId);
459     if (info != nullptr) {
460         info->SetPreferences(preferences);
461         PRINT_HILOGI("UpdatePrinterPreferences success");
462         preferences.Dump();
463     }
464 }
465 
GetAddedPrinterListFromSystemData(std::vector<std::string> & printerNameList)466 void PrintSystemData::GetAddedPrinterListFromSystemData(std::vector<std::string> &printerNameList)
467 {
468     std::vector<std::string> addedPrinterList = QueryAddedPrinterIdList();
469     for (auto printerId : addedPrinterList) {
470         auto info = GetAddedPrinterMap().Find(printerId);
471         if (info == nullptr) {
472             continue;
473         }
474         PRINT_HILOGD("GetAddedPrinterListFromSystemData info->name: %{public}s", (info->GetPrinterName()).c_str());
475         printerNameList.push_back(info->GetPrinterName());
476     }
477 }
478 
IsPrinterAdded(const std::string & printerId)479 bool PrintSystemData::IsPrinterAdded(const std::string &printerId)
480 {
481     auto info = GetAddedPrinterMap().Find(printerId);
482     if (info == nullptr) {
483         return false;
484     }
485     return true;
486 }
487 
ConvertPrinterCapabilityToJson(PrinterCapability & printerCapability,Json::Value & capsJson)488 void PrintSystemData::ConvertPrinterCapabilityToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
489 {
490     capsJson["colorMode"] = printerCapability.GetColorMode();
491     capsJson["duplexMode"] = printerCapability.GetDuplexMode();
492     ConvertPageSizeToJson(printerCapability, capsJson);
493 
494     if (printerCapability.HasMargin()) {
495         ConvertPrintMarginToJson(printerCapability, capsJson);
496     }
497 
498     if (printerCapability.HasResolution()) {
499         ConvertPrintResolutionToJson(printerCapability, capsJson);
500     }
501 
502     if (printerCapability.HasSupportedColorMode()) {
503         ConvertSupportedColorModeToJson(printerCapability, capsJson);
504     }
505 
506     if (printerCapability.HasSupportedDuplexMode()) {
507         ConvertSupportedDuplexModeToJson(printerCapability, capsJson);
508     }
509 
510     if (printerCapability.HasSupportedMediaType()) {
511         ConvertSupportedMediaTypeToJson(printerCapability, capsJson);
512     }
513 
514     if (printerCapability.HasSupportedQuality()) {
515         ConvertSupportedQualityToJson(printerCapability, capsJson);
516     }
517 
518     if (printerCapability.HasOption()) {
519         std::string options = printerCapability.GetOption();
520         if (!PrintJsonUtil::Parse(options, capsJson["options"])) {
521             PRINT_HILOGE("json accept capability options fail");
522             return;
523         }
524     }
525 }
526 
ConvertPrintResolutionToJson(PrinterCapability & printerCapability,Json::Value & capsJson)527 void PrintSystemData::ConvertPrintResolutionToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
528 {
529     Json::Value resolutionListJson;
530     std::vector<PrintResolution> resolutionList;
531     printerCapability.GetResolution(resolutionList);
532     for (auto iter : resolutionList) {
533         Json::Value resolutionJson;
534         resolutionJson["id"] = iter.GetId();
535         resolutionJson["horizontalDpi"] = iter.GetHorizontalDpi();
536         resolutionJson["verticalDpi"] = iter.GetVerticalDpi();
537         resolutionListJson.append(resolutionJson);
538     }
539     capsJson["resolution"] = resolutionListJson;
540 }
541 
ConvertSupportedColorModeToJson(PrinterCapability & printerCapability,Json::Value & capsJson)542 void PrintSystemData::ConvertSupportedColorModeToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
543 {
544     Json::Value SupportedColorModeListJson;
545     std::vector<uint32_t> SupportedColorModeList;
546     printerCapability.GetSupportedColorMode(SupportedColorModeList);
547     for (auto iter : SupportedColorModeList) {
548         SupportedColorModeListJson.append(iter);
549     }
550     capsJson["supportedColorMode"] = SupportedColorModeListJson;
551 }
552 
ConvertSupportedDuplexModeToJson(PrinterCapability & printerCapability,Json::Value & capsJson)553 void PrintSystemData::ConvertSupportedDuplexModeToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
554 {
555     Json::Value supportedDuplexModeListJson;
556     std::vector<uint32_t> supportedDuplexModeList;
557     printerCapability.GetSupportedDuplexMode(supportedDuplexModeList);
558     for (auto iter : supportedDuplexModeList) {
559         supportedDuplexModeListJson.append(iter);
560     }
561     capsJson["supportedDuplexMode"] = supportedDuplexModeListJson;
562 }
563 
ConvertSupportedMediaTypeToJson(PrinterCapability & printerCapability,Json::Value & capsJson)564 void PrintSystemData::ConvertSupportedMediaTypeToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
565 {
566     Json::Value supportedMediaTypeListJson;
567     std::vector<std::string> supportedMediaTypeList;
568     printerCapability.GetSupportedMediaType(supportedMediaTypeList);
569     for (auto iter : supportedMediaTypeList) {
570         supportedMediaTypeListJson.append(iter);
571     }
572     capsJson["supportedMediaType"] = supportedMediaTypeListJson;
573 }
574 
ConvertSupportedQualityToJson(PrinterCapability & printerCapability,Json::Value & capsJson)575 void PrintSystemData::ConvertSupportedQualityToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
576 {
577     Json::Value supportedQualityListJson;
578     std::vector<uint32_t> supportedQualityList;
579     printerCapability.GetSupportedQuality(supportedQualityList);
580     for (auto iter : supportedQualityList) {
581         supportedQualityListJson.append(iter);
582     }
583     capsJson["supportedQuality"] = supportedQualityListJson;
584 }
585 
ConvertPageSizeToJson(PrinterCapability & printerCapability,Json::Value & capsJson)586 void PrintSystemData::ConvertPageSizeToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
587 {
588     Json::Value pageSizeListJson;
589     std::vector<PrintPageSize> pageSizeList;
590     printerCapability.GetSupportedPageSize(pageSizeList);
591     for (auto iter : pageSizeList) {
592         Json::Value pageSizeJson;
593         pageSizeJson["id"] = iter.GetId();
594         pageSizeJson["name"] = iter.GetName();
595         pageSizeJson["width"] = iter.GetWidth();
596         pageSizeJson["height"] = iter.GetHeight();
597         pageSizeListJson.append(pageSizeJson);
598     }
599     capsJson["pageSize"] = pageSizeListJson;
600 }
601 
ConvertPrintMarginToJson(PrinterCapability & printerCapability,Json::Value & capsJson)602 void PrintSystemData::ConvertPrintMarginToJson(PrinterCapability &printerCapability, Json::Value &capsJson)
603 {
604     Json::Value marginJson;
605     PrintMargin minMargin;
606     printerCapability.GetMinMargin(minMargin);
607     if (minMargin.HasTop()) {
608         marginJson["top"] = minMargin.GetTop();
609     }
610     if (minMargin.HasBottom()) {
611         marginJson["bottom"] = minMargin.GetBottom();
612     }
613     if (minMargin.HasLeft()) {
614         marginJson["left"] = minMargin.GetLeft();
615     }
616     if (minMargin.HasRight()) {
617         marginJson["right"] = minMargin.GetRight();
618     }
619     capsJson["minMargin"] = marginJson;
620 }
621 
ConvertJsonToPrinterCapability(Json::Value & capsJson,PrinterCapability & printerCapability)622 bool PrintSystemData::ConvertJsonToPrinterCapability(Json::Value &capsJson, PrinterCapability &printerCapability)
623 {
624     if (!PrintJsonUtil::IsMember(capsJson, "colorMode") || !capsJson["colorMode"].isInt()) {
625         PRINT_HILOGW("can not find colorMode");
626         return false;
627     }
628     if (!PrintJsonUtil::IsMember(capsJson, "duplexMode") || !capsJson["duplexMode"].isInt()) {
629         PRINT_HILOGW("can not find duplexMode");
630         return false;
631     }
632 
633     printerCapability.SetColorMode(capsJson["colorMode"].asInt());
634 
635     printerCapability.SetDuplexMode(capsJson["duplexMode"].asInt());
636 
637     if (PrintJsonUtil::IsMember(capsJson, "minMargin") && capsJson["minMargin"].isObject()) {
638         PRINT_HILOGD("find minMargin");
639         ConvertJsonToPrintMargin(capsJson, printerCapability);
640     }
641 
642     if (!ConvertJsonToPrintResolution(capsJson, printerCapability)) {
643         PRINT_HILOGW("convert json to print resolution failed");
644         return false;
645     }
646 
647     if (!ConvertJsonToPageSize(capsJson, printerCapability)) {
648         PRINT_HILOGW("convert json to pageSize failed");
649         return false;
650     }
651 
652     if (!ConvertJsonToSupportedColorMode(capsJson, printerCapability)) {
653         PRINT_HILOGW("convert json to supportedColorMode failed.");
654         return false;
655     }
656 
657     if (!ConvertJsonToSupportedDuplexMode(capsJson, printerCapability)) {
658         PRINT_HILOGW("convert json to supportedDuplexMode failed.");
659         return false;
660     }
661 
662     if (!ConvertJsonToSupportedMediaType(capsJson, printerCapability)) {
663         PRINT_HILOGW("convert json to supportedMediaType failed.");
664         return false;
665     }
666 
667     if (!ConvertJsonToSupportedQuality(capsJson, printerCapability)) {
668         PRINT_HILOGW("convert json to supportedQuality failed.");
669         return false;
670     }
671 
672     if (!ConvertJsonToSupportedOrientation(capsJson, printerCapability)) {
673         PRINT_HILOGW("convert json to supportedOrientation failed.");
674         return false;
675     }
676 
677     if (PrintJsonUtil::IsMember(capsJson, "options") && capsJson["options"].isObject()) {
678         PRINT_HILOGD("find options");
679         printerCapability.SetOption(PrintJsonUtil::WriteString(capsJson["options"]));
680     }
681     return true;
682 }
683 
ConvertJsonToPageSize(Json::Value & capsJson,PrinterCapability & printerCapability)684 bool PrintSystemData::ConvertJsonToPageSize(Json::Value &capsJson, PrinterCapability &printerCapability)
685 {
686     return ProcessJsonToCapabilityList<PrintPageSize>(
687         capsJson, "pageSize", printerCapability, &PrinterCapability::SetSupportedPageSize,
688         [](const Json::Value &item, PrintPageSize &pageSize) -> bool {
689             if (!item.isObject() ||
690                 !PrintJsonUtil::IsMember(item, "id") ||!PrintUtils::CheckJsonType<std::string>(item["id"]) ||
691                 !PrintJsonUtil::IsMember(item, "name") ||!PrintUtils::CheckJsonType<std::string>(item["name"]) ||
692                 !PrintJsonUtil::IsMember(item, "width") ||!PrintUtils::CheckJsonType<uint32_t>(item["width"]) ||
693                 !PrintJsonUtil::IsMember(item, "height") ||!PrintUtils::CheckJsonType<uint32_t>(item["height"])) {
694                 return false;
695             }
696             pageSize.SetId(item["id"].asString());
697             pageSize.SetName(item["name"].asString());
698             pageSize.SetWidth(item["width"].asInt());
699             pageSize.SetHeight(item["height"].asInt());
700             return true;
701         }
702     );
703 }
704 
ConvertJsonToPrintResolution(Json::Value & capsJson,PrinterCapability & printerCapability)705 bool PrintSystemData::ConvertJsonToPrintResolution(Json::Value &capsJson, PrinterCapability &printerCapability)
706 {
707     return ProcessJsonToCapabilityList<PrintResolution>(capsJson, "resolution", printerCapability,
708         &PrinterCapability::SetResolution,
709         [](const Json::Value &item, PrintResolution &resolution) -> bool {
710             if (!item.isObject() ||
711                 !PrintJsonUtil::IsMember(item, "id") || !PrintUtils::CheckJsonType<std::string>(item["id"]) ||
712                 !PrintJsonUtil::IsMember(item, "horizontalDpi") ||
713                 !PrintUtils::CheckJsonType<uint32_t>(item["horizontalDpi"]) ||
714                 !PrintJsonUtil::IsMember(item, "verticalDpi") ||
715                 !PrintUtils::CheckJsonType<uint32_t>(item["verticalDpi"])) {
716                 return false;
717             }
718             resolution.SetId(item["id"].asString());
719             resolution.SetHorizontalDpi(item["horizontalDpi"].asInt());
720             resolution.SetVerticalDpi(item["verticalDpi"].asInt());
721             return true;
722         }
723     );
724 }
725 
ConvertJsonToSupportedColorMode(Json::Value & capsJson,PrinterCapability & printerCapability)726 bool PrintSystemData::ConvertJsonToSupportedColorMode(Json::Value &capsJson, PrinterCapability &printerCapability)
727 {
728     return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedColorMode", printerCapability,
729         &PrinterCapability::SetSupportedColorMode,
730         [](const Json::Value &item, uint32_t &colorMode) -> bool {
731             colorMode = item.asInt();
732             return true;
733         });
734 }
735 
ConvertJsonToSupportedDuplexMode(Json::Value & capsJson,PrinterCapability & printerCapability)736 bool PrintSystemData::ConvertJsonToSupportedDuplexMode(Json::Value &capsJson, PrinterCapability &printerCapability)
737 {
738     return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedDuplexMode", printerCapability,
739         &PrinterCapability::SetSupportedDuplexMode,
740         [](const Json::Value &item, uint32_t &duplexMode) -> bool {
741             duplexMode = item.asInt();
742             return true;
743         });
744 }
745 
ConvertJsonToSupportedMediaType(Json::Value & capsJson,PrinterCapability & printerCapability)746 bool PrintSystemData::ConvertJsonToSupportedMediaType(Json::Value &capsJson, PrinterCapability &printerCapability)
747 {
748     return ProcessJsonToCapabilityList<std::string>(capsJson, "supportedMediaType", printerCapability,
749         &PrinterCapability::SetSupportedMediaType,
750         [](const Json::Value &item, std::string &mediaType) -> bool {
751             mediaType = item.asString();
752             return true;
753         });
754 }
755 
ConvertJsonToSupportedQuality(Json::Value & capsJson,PrinterCapability & printerCapability)756 bool PrintSystemData::ConvertJsonToSupportedQuality(Json::Value &capsJson, PrinterCapability &printerCapability)
757 {
758     return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedQuality", printerCapability,
759         &PrinterCapability::SetSupportedQuality,
760         [](const Json::Value &item, uint32_t &quality) -> bool {
761             quality = item.asInt();
762             return true;
763         });
764 }
765 
ConvertJsonToSupportedOrientation(Json::Value & capsJson,PrinterCapability & printerCapability)766 bool PrintSystemData::ConvertJsonToSupportedOrientation(Json::Value &capsJson, PrinterCapability &printerCapability)
767 {
768     return ProcessJsonToCapabilityList<uint32_t>(capsJson, "supportedOrientation", printerCapability,
769         &PrinterCapability::SetSupportedOrientation,
770         [](const Json::Value &item, uint32_t &orientation) -> bool {
771             orientation = item.asInt();
772             return true;
773         });
774 }
775 
ConvertJsonToPrintMargin(Json::Value & capsJson,PrinterCapability & printerCapability)776 bool PrintSystemData::ConvertJsonToPrintMargin(Json::Value &capsJson, PrinterCapability &printerCapability)
777 {
778     Json::Value marginJson = capsJson["minMargin"];
779     PrintMargin minMargin;
780     if (!marginJson.isObject() ||
781         !PrintJsonUtil::IsMember(marginJson, "top") || !PrintUtils::CheckJsonType<uint32_t>(marginJson["top"]) ||
782         !PrintJsonUtil::IsMember(marginJson, "bottom") || !PrintUtils::CheckJsonType<uint32_t>(marginJson["bottom"]) ||
783         !PrintJsonUtil::IsMember(marginJson, "left") || !PrintUtils::CheckJsonType<uint32_t>(marginJson["left"]) ||
784         !PrintJsonUtil::IsMember(marginJson, "right") || !PrintUtils::CheckJsonType<uint32_t>(marginJson["right"])) {
785         PRINT_HILOGE("Invalid format,key is minMargin");
786         return false;
787     }
788     minMargin.SetTop(marginJson["top"].asInt());
789     minMargin.SetBottom(marginJson["bottom"].asInt());
790     minMargin.SetLeft(marginJson["left"].asInt());
791     minMargin.SetRight(marginJson["right"].asInt());
792     printerCapability.SetMinMargin(minMargin);
793     PRINT_HILOGD("ProcessJsonToCapabilityList success, key is minMargin");
794     return true;
795 }
796 
GetPrinterCapabilityFromSystemData(PrinterInfo & printer,std::string printerId,PrinterCapability & printerCapability)797 bool PrintSystemData::GetPrinterCapabilityFromSystemData(PrinterInfo &printer,
798     std::string printerId, PrinterCapability &printerCapability)
799 {
800     printer.GetCapability(printerCapability);
801     std::vector<PrintPageSize> pageSizeList;
802     printerCapability.GetPageSize(pageSizeList);
803     if (!pageSizeList.empty()) {
804         PRINT_HILOGI("find printer capability in system data");
805         return true;
806     } else if (GetPrinterCapabilityFromFile(printerId, printerCapability)) {
807         return true;
808     }
809     return false;
810 }
811 
GetPrinterCapabilityFromFile(std::string printerId,PrinterCapability & printerCapability)812 bool PrintSystemData::GetPrinterCapabilityFromFile(std::string printerId, PrinterCapability &printerCapability)
813 {
814     PRINT_HILOGI("GetPrinterCapabilityFromFile printerId: %{private}s", printerId.c_str());
815     Json::Value jsonObject;
816     std::string printerListFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINTER_LIST_FILE;
817     if (!GetJsonObjectFromFile(jsonObject, printerListFilePath)) {
818         PRINT_HILOGW("get json from file fail");
819         return false;
820     }
821 
822     if (!GetPrinterCapabilityFromJson(printerId, jsonObject, printerCapability)) {
823         PRINT_HILOGW("get caps from file json fail");
824         return false;
825     }
826     return true;
827 }
828 
GetPrinterCapabilityFromJson(std::string printerId,Json::Value & jsonObject,PrinterCapability & printerCapability)829 bool PrintSystemData::GetPrinterCapabilityFromJson(
830     std::string printerId, Json::Value &jsonObject, PrinterCapability &printerCapability)
831 {
832     if (!PrintJsonUtil::IsMember(jsonObject, "printer_list") || !jsonObject["printer_list"].isArray()) {
833         PRINT_HILOGW("can not find printer_list");
834         return false;
835     }
836     Json::Value printerMapJson = jsonObject["printer_list"];
837     if (printerMapJson.empty()) {
838         PRINT_HILOGW("printer map is empty");
839         return false;
840     }
841     uint32_t jsonSize = jsonObject["printer_list"].size();
842     if (jsonSize > MAX_PRINTER_SIZE) {
843         PRINT_HILOGE("printerlist size is illegal");
844         return false;
845     }
846     for (uint32_t i = 0; i < jsonSize; i++) {
847         Json::Value object = jsonObject["printer_list"][i];
848         if (!CheckPrinterInfoJson(object, printerId)) {
849             continue;
850         }
851         if (!PrintJsonUtil::IsMember(object, "capability")) {
852             PRINT_HILOGE("json does not contain the key as capability");
853             continue;
854         }
855         Json::Value capsJson = object["capability"];
856         PrinterCapability caps;
857         if (!ConvertJsonToPrinterCapability(capsJson, caps)) {
858             PRINT_HILOGW("convert json to printer capability failed");
859             continue;
860         }
861         std::vector<PrintPageSize> pageSizeList;
862         caps.GetPageSize(pageSizeList);
863         if (pageSizeList.size() != 0) {
864             PRINT_HILOGI("find printer capability in file");
865             caps.Dump();
866             printerCapability = caps;
867             return true;
868         }
869     }
870     return false;
871 }
872 
CheckPrinterInfoJson(Json::Value & object,std::string & printerId)873 bool PrintSystemData::CheckPrinterInfoJson(Json::Value &object, std::string &printerId)
874 {
875     if (!PrintJsonUtil::IsMember(object, "id") || !object["id"].isString()) {
876         PRINT_HILOGW("can not find id");
877         return false;
878     }
879     std::string id = object["id"].asString();
880     if (id != printerId) {
881         return false;
882     }
883     if (!PrintJsonUtil::IsMember(object, "name") || !object["name"].isString()) {
884         PRINT_HILOGW("can not find name");
885         return false;
886     }
887     if (!PrintJsonUtil::IsMember(object, "uri") || !object["uri"].isString()) {
888         PRINT_HILOGW("can not find uri");
889         return false;
890     }
891     if (!PrintJsonUtil::IsMember(object, "maker") || !object["maker"].isString()) {
892         PRINT_HILOGW("can not find maker");
893         return false;
894     }
895     if (!PrintJsonUtil::IsMember(object, "capability") || !object["capability"].isObject()) {
896         PRINT_HILOGW("can not find capability");
897         return false;
898     }
899     return true;
900 }
901 
CheckPrinterBusy(const std::string & printerId)902 bool PrintSystemData::CheckPrinterBusy(const std::string &printerId)
903 {
904     PrinterInfo printer;
905     QueryAddedPrinterInfoByPrinterId(printerId, printer);
906     if (printer.GetPrinterStatus() == PRINTER_STATUS_BUSY) {
907         PRINT_HILOGI("printer is busy");
908         return true;
909     }
910     return false;
911 }
912 
GetAllPrintUser(std::vector<int32_t> & allPrintUserList)913 bool PrintSystemData::GetAllPrintUser(std::vector<int32_t> &allPrintUserList)
914 {
915     Json::Value jsonObject;
916     std::string userDataFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINT_USER_DATA_FILE;
917     if (!GetJsonObjectFromFile(jsonObject, userDataFilePath)) {
918         PRINT_HILOGW("get json from file fail");
919         return false;
920     }
921     return ParseUserListJsonV1(jsonObject, allPrintUserList);
922 }
923 
ParseUserListJsonV1(Json::Value & jsonObject,std::vector<int32_t> & allPrintUserList)924 bool PrintSystemData::ParseUserListJsonV1(Json::Value &jsonObject, std::vector<int32_t> &allPrintUserList)
925 {
926     if (!PrintJsonUtil::IsMember(jsonObject, "print_user_data") || !jsonObject["print_user_data"].isObject()) {
927         PRINT_HILOGE("can not find print_user_data");
928         return false;
929     }
930     Json::Value::Members keys = jsonObject["print_user_data"].getMemberNames();
931     for (auto key = keys.begin(); key != keys.end(); key++) {
932         std::string userIdStr = *key;
933         if (userIdStr.empty()) {
934             continue;
935         }
936         int32_t userId = 0;
937         if (!PrintUtil::ConvertToInt(userIdStr, userId)) {
938             PRINT_HILOGE("userIdStr [%{private}s] can not parse to number.", userIdStr.c_str());
939             return false;
940         }
941         PRINT_HILOGI("ParseUserListJsonV1 userId: %{private}d", userId);
942         allPrintUserList.push_back(userId);
943     }
944     if (!allPrintUserList.size()) {
945         PRINT_HILOGE("allPrintUserList is empty.");
946         return false;
947     }
948     return true;
949 }
950 
QueryAddedPrinterIdList()951 std::vector<std::string> PrintSystemData::QueryAddedPrinterIdList()
952 {
953     return GetAddedPrinterMap().GetKeyList();
954 }
955 
QueryAddedPrintersByIp(const std::string & printerIp)956 std::vector<std::string> PrintSystemData::QueryAddedPrintersByIp(const std::string &printerIp)
957 {
958     return GetAddedPrinterMap().GetKeyList([this, printerIp](const PrinterInfo &printer) -> bool {
959         return PrintUtils::ExtractHostFromUri(printer.GetUri()) == printerIp;
960     });
961 }
962 
QueryDiscoveredPrinterInfoById(const std::string & printerId)963 std::shared_ptr<PrinterInfo> PrintSystemData::QueryDiscoveredPrinterInfoById(const std::string &printerId)
964 {
965     std::lock_guard<std::mutex> lock(discoveredListMutex);
966     auto printerIt = discoveredPrinterInfoList_.find(printerId);
967     if (printerIt != discoveredPrinterInfoList_.end()) {
968         return printerIt ->second;
969     }
970     return nullptr;
971 }
QueryDiscoveredPrinterInfoByName(const std::string & printerName)972 std::shared_ptr<PrinterInfo> PrintSystemData::QueryDiscoveredPrinterInfoByName(const std::string &printerName)
973 {
974     std::lock_guard<std::mutex> lock(discoveredListMutex);
975     std::string name = PrintUtil::StandardizePrinterName(printerName);
976     for (auto iter = discoveredPrinterInfoList_.begin(); iter != discoveredPrinterInfoList_.end(); ++iter) {
977         auto printerInfoPtr = iter->second;
978         if (printerInfoPtr == nullptr) {
979             continue;
980         }
981         if (PrintUtil::StandardizePrinterName(printerInfoPtr->GetPrinterName()) != name) {
982             continue;
983         }
984         return printerInfoPtr;
985     }
986     return nullptr;
987 }
988 
AddPrinterToDiscovery(std::shared_ptr<PrinterInfo> printerInfo)989 void PrintSystemData::AddPrinterToDiscovery(std::shared_ptr<PrinterInfo> printerInfo)
990 {
991     std::lock_guard<std::mutex> lock(discoveredListMutex);
992     if (printerInfo != nullptr) {
993         discoveredPrinterInfoList_[printerInfo->GetPrinterId()] = printerInfo;
994     }
995 }
996 
RemovePrinterFromDiscovery(const std::string & printerId)997 void PrintSystemData::RemovePrinterFromDiscovery(const std::string &printerId)
998 {
999     std::lock_guard<std::mutex> lock(discoveredListMutex);
1000     discoveredPrinterInfoList_.erase(printerId);
1001 }
1002 
GetDiscoveredPrinterCount()1003 size_t PrintSystemData::GetDiscoveredPrinterCount()
1004 {
1005     std::lock_guard<std::mutex> lock(discoveredListMutex);
1006     return discoveredPrinterInfoList_.size();
1007 }
1008 
ClearDiscoveredPrinterList()1009 void PrintSystemData::ClearDiscoveredPrinterList()
1010 {
1011     std::lock_guard<std::mutex> lock(discoveredListMutex);
1012     discoveredPrinterInfoList_.clear();
1013 }
1014 
GetDiscoveredPrinterInfo()1015 std::map<std::string, std::shared_ptr<PrinterInfo>> PrintSystemData::GetDiscoveredPrinterInfo()
1016 {
1017     std::lock_guard<std::mutex> lock(discoveredListMutex);
1018     return discoveredPrinterInfoList_;
1019 }
1020 
AddIpPrinterToList(std::shared_ptr<PrinterInfo> printerInfo)1021 void PrintSystemData::AddIpPrinterToList(std::shared_ptr<PrinterInfo> printerInfo)
1022 {
1023     std::lock_guard<std::mutex> lock(connectingIpPrinterListMutex);
1024     if (printerInfo != nullptr) {
1025         connectingIpPrinterInfoList_[printerInfo->GetPrinterId()] = printerInfo;
1026     }
1027 }
1028 
RemoveIpPrinterFromList(const std::string & printerId)1029 void PrintSystemData::RemoveIpPrinterFromList(const std::string &printerId)
1030 {
1031     std::lock_guard<std::mutex> lock(connectingIpPrinterListMutex);
1032     connectingIpPrinterInfoList_.erase(printerId);
1033 }
1034 
QueryIpPrinterInfoById(const std::string & printerId)1035 std::shared_ptr<PrinterInfo> PrintSystemData::QueryIpPrinterInfoById(const std::string &printerId)
1036 {
1037     std::lock_guard<std::mutex> lock(connectingIpPrinterListMutex);
1038     auto printerIt = connectingIpPrinterInfoList_.find(printerId);
1039     if (printerIt != connectingIpPrinterInfoList_.end()) {
1040         return printerIt ->second;
1041     }
1042     return nullptr;
1043 }
1044 
GetCupsOptionsJson(const PrinterCapability & cap)1045 Json::Value PrintSystemData::GetCupsOptionsJson(const PrinterCapability &cap)
1046 {
1047     if (!cap.HasOption()) {
1048         PRINT_HILOGE("capability does not have a cupsOptions attribute");
1049         return Json::nullValue;
1050     }
1051     std::string capOption = cap.GetOption();
1052     PRINT_HILOGD("printer capOption %{private}s", capOption.c_str());
1053     Json::Value capJson;
1054     std::istringstream iss(capOption);
1055     if (!PrintJsonUtil::ParseFromStream(iss, capJson)) {
1056         PRINT_HILOGW("capOption can not parse to json object");
1057         return Json::nullValue;
1058     }
1059     if (!capJson.isMember("cupsOptions")) {
1060         PRINT_HILOGW("The capJson does not have a cupsOptions attribute.");
1061         return Json::nullValue;
1062     }
1063     Json::Value capOpt = capJson["cupsOptions"];
1064     return capOpt;
1065 }
1066 
BuildPrinterPreference(const PrinterCapability & cap,PrinterPreferences & printPreferences)1067 int32_t PrintSystemData::BuildPrinterPreference(const PrinterCapability &cap, PrinterPreferences &printPreferences)
1068 {
1069     PRINT_HILOGI("BuildPrinterPreference enter");
1070     Json::Value capOpt = GetCupsOptionsJson(cap);
1071     if (!capOpt.isNull()) {
1072         BuildPrinterPreferenceByDefault(capOpt, printPreferences);
1073     }
1074 
1075     BuildPrinterPreferenceBySupport(cap, printPreferences);
1076     printPreferences.Dump();
1077     return E_PRINT_NONE;
1078 }
1079 
BuildPrinterPreferenceByDefault(Json::Value & capOpt,PrinterPreferences & printPreferences)1080 void PrintSystemData::BuildPrinterPreferenceByDefault(Json::Value &capOpt, PrinterPreferences &printPreferences)
1081 {
1082     PRINT_HILOGI("BuildPrinterPreferenceByDefault enter");
1083     if (printPreferences.GetDefaultPageSizeId().empty() &&
1084         PrintJsonUtil::IsMember(capOpt, "defaultPageSizeId") && capOpt["defaultPageSizeId"].isString()) {
1085         printPreferences.SetDefaultPageSizeId(capOpt["defaultPageSizeId"].asString());
1086     }
1087 
1088     int32_t defaultOrientation = PRINT_ORIENTATION_MODE_NONE;
1089     if (printPreferences.GetDefaultOrientation() != PRINT_ORIENTATION_MODE_NONE &&
1090         PrintJsonUtil::IsMember(capOpt, "orientation-requested-default") &&
1091         capOpt["orientation-requested-default"].isString()) {
1092         PrintUtil::ConvertToInt(capOpt["orientation-requested-default"].asString(), defaultOrientation);
1093     }
1094     printPreferences.SetDefaultOrientation(defaultOrientation);
1095 
1096     if (printPreferences.GetDefaultDuplexMode() != DUPLEX_MODE_NONE &&
1097         PrintJsonUtil::IsMember(capOpt, "sides-default") && capOpt["sides-default"].isString()) {
1098         int32_t defaultDuplexMode = DUPLEX_MODE_NONE;
1099         PrintUtil::ConvertToInt(capOpt["sides-default"].asString(), defaultDuplexMode);
1100         printPreferences.SetDefaultDuplexMode(defaultDuplexMode);
1101     }
1102 
1103     if (printPreferences.GetDefaultPrintQuality() != PRINT_QUALITY_NORMAL &&
1104         PrintJsonUtil::IsMember(capOpt, "print-quality-default") && capOpt["print-quality-default"].isString()) {
1105         int32_t defaultPrintQuality = PRINT_QUALITY_NORMAL;
1106         PrintUtil::ConvertToInt(capOpt["print-quality-default"].asString(), defaultPrintQuality);
1107         printPreferences.SetDefaultPrintQuality(defaultPrintQuality);
1108     }
1109 
1110     if (printPreferences.GetDefaultMediaType().empty() &&
1111         PrintJsonUtil::IsMember(capOpt, "media-type-default") && capOpt["media-type-default"].isString()) {
1112         printPreferences.SetDefaultMediaType(capOpt["media-type-default"].asString());
1113     }
1114 
1115     if (PrintJsonUtil::IsMember(capOpt, "defaultColorMode") && capOpt["defaultColorMode"].isString()) {
1116         int32_t defaultColorMode = PRINT_COLOR_MODE_MONOCHROME;
1117         PrintUtil::ConvertToInt(capOpt["defaultColorMode"].asString(), defaultColorMode);
1118         printPreferences.SetDefaultColorMode(defaultColorMode);
1119     }
1120 
1121     if (PrintJsonUtil::IsMember(capOpt, "advanceDefault") && capOpt["advanceDefault"].isString()) {
1122         printPreferences.SetOption(capOpt["advanceDefault"].asString());
1123     }
1124 }
1125 
BuildPrinterPreferenceBySupport(const PrinterCapability & cap,PrinterPreferences & printPreferences)1126 void PrintSystemData::BuildPrinterPreferenceBySupport(
1127     const PrinterCapability &cap, PrinterPreferences &printPreferences)
1128 {
1129     if (!printPreferences.HasDefaultPageSizeId()) {
1130         printPreferences.SetDefaultPageSizeId(ParseDefaultPageSizeId(cap));
1131     }
1132 
1133     if (!printPreferences.HasDefaultDuplexMode()) {
1134         std::vector<uint32_t> supportedDuplexModeList;
1135         cap.GetSupportedDuplexMode(supportedDuplexModeList);
1136         std::optional<uint32_t> defaultDuplexMode =
1137             GetPreferencesFromSupport<uint32_t>(supportedDuplexModeList, DUPLEX_MODE_NONE);
1138         if (defaultDuplexMode != std::nullopt) {
1139             printPreferences.SetDefaultDuplexMode(*defaultDuplexMode);
1140         }
1141     }
1142 
1143     if (!printPreferences.HasDefaultPrintQuality()) {
1144         std::vector<uint32_t> supportedQualityList;
1145         cap.GetSupportedQuality(supportedQualityList);
1146         std::optional<uint32_t> defaultPrintQuality =
1147             GetPreferencesFromSupport<uint32_t>(supportedQualityList, PRINT_QUALITY_NORMAL);
1148         if (defaultPrintQuality != std::nullopt) {
1149             printPreferences.SetDefaultPrintQuality(*defaultPrintQuality);
1150         }
1151     }
1152 
1153     if (!printPreferences.HasDefaultColorMode()) {
1154         std::vector<uint32_t> supportedColorModeList;
1155         cap.GetSupportedColorMode(supportedColorModeList);
1156         std::optional<uint32_t> defaultColorMode =
1157             GetPreferencesFromSupport<uint32_t>(supportedColorModeList, PRINT_COLOR_MODE_COLOR);
1158         if (defaultColorMode != std::nullopt) {
1159             printPreferences.SetDefaultColorMode(*defaultColorMode);
1160         }
1161     }
1162 
1163     if (!printPreferences.HasDefaultMediaType()) {
1164         std::vector<std::string> supportedMediaTypeList;
1165         cap.GetSupportedMediaType(supportedMediaTypeList);
1166         std::optional<std::string> defaultMediaType =
1167             GetPreferencesFromSupport<std::string>(supportedMediaTypeList, DEFAULT_MEDIA_TYPE);
1168         if (defaultMediaType != std::nullopt) {
1169             printPreferences.SetDefaultMediaType(*defaultMediaType);
1170         }
1171     }
1172 
1173     printPreferences.SetDefaultOrientation(PRINT_ORIENTATION_MODE_NONE);
1174 
1175     printPreferences.SetBorderless(false);
1176 
1177     printPreferences.SetDefaultCollate(true);
1178 
1179     printPreferences.SetDefaultReverse(false);
1180 }
1181 
ParseDefaultPageSizeId(const PrinterCapability & cap)1182 std::string PrintSystemData::ParseDefaultPageSizeId(const PrinterCapability &cap)
1183 {
1184     std::vector<PrintPageSize> supportedPageSize;
1185     cap.GetSupportedPageSize(supportedPageSize);
1186     if (supportedPageSize.size() == 0) {
1187         return "";
1188     }
1189     for (auto pageSize : supportedPageSize) {
1190         if (pageSize.GetId() == DEFAULT_PAGESIZE_ID) {
1191             return DEFAULT_PAGESIZE_ID;
1192         }
1193     }
1194     return supportedPageSize[0].GetId();
1195 }
1196 
CheckPrinterVersionFile()1197 bool PrintSystemData::CheckPrinterVersionFile()
1198 {
1199     std::string fileName = GetPrintersPath() + "/" + PRINTER_LIST_VERSION_FILE;
1200     std::filesystem::path filePath(fileName);
1201     if (std::filesystem::exists(filePath)) {
1202         PRINT_HILOGI("version file exists.");
1203         return true;
1204     }
1205     std::ofstream file(filePath);
1206     if (!file) {
1207         PRINT_HILOGE("File creation failed.");
1208         return false;
1209     }
1210 
1211     PRINT_HILOGI("File created successfully.");
1212     Json::Value versionJson;
1213     versionJson["version"] = PRINTER_LIST_VERSION_V3;
1214     std::string jsonString = PrintJsonUtil::WriteString(versionJson);
1215     SaveJsonFile(fileName, jsonString);
1216     return false;
1217 }
1218 
SaveJsonFile(const std::string & fileName,const std::string & jsonString)1219 void PrintSystemData::SaveJsonFile(const std::string &fileName, const std::string &jsonString)
1220 {
1221     FILE *file = fopen(fileName.c_str(), "w+");
1222     if (file == nullptr) {
1223         PRINT_HILOGW("Failed to open file, errno: %{public}s", std::to_string(errno).c_str());
1224         return;
1225     }
1226     size_t jsonLength = jsonString.length();
1227     size_t writeLength = fwrite(jsonString.c_str(), 1, strlen(jsonString.c_str()), file);
1228     int fcloseResult = fclose(file);
1229     if (fcloseResult != 0) {
1230         PRINT_HILOGE("Close file failure.");
1231         return;
1232     }
1233     if (writeLength < 0 || (size_t)writeLength != jsonLength) {
1234         PRINT_HILOGE("SaveJsonFile error.");
1235         return;
1236     }
1237     PRINT_HILOGI("SaveJsonFile end.");
1238 }
1239 
GetAddedPrinterMap()1240 PrintMapSafe<PrinterInfo>& PrintSystemData::GetAddedPrinterMap()
1241 {
1242 #ifdef ENTERPRISE_ENABLE
1243     if (PrintServiceAbility::GetInstance()->IsEnterpriseEnable() &&
1244         PrintServiceAbility::GetInstance()->IsEnterprise()) {
1245         return addedPrinterEnterpriseMap_;
1246     }
1247 #endif // ENTERPRISE_ENABLE
1248     return addedPrinterMap_;
1249 }
1250 
GetPrintersPath()1251 const std::string& PrintSystemData::GetPrintersPath()
1252 {
1253 #ifdef ENTERPRISE_ENABLE
1254     if (PrintServiceAbility::GetInstance()->IsEnterpriseEnable() &&
1255         PrintServiceAbility::GetInstance()->IsEnterprise()) {
1256         return PRINTER_SERVICE_PRINTERS_ENTERPRISE_PATH;
1257     }
1258 #endif // ENTERPRISE_ENABLE
1259     return PRINTER_SERVICE_PRINTERS_PATH;
1260 }
1261 
1262 }  // namespace Print
1263 }  // namespace OHOS