1 /*
2  * Copyright (c) 2022 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 #include "print_service_ability.h"
16 
17 #include <cerrno>
18 #include <ctime>
19 #include <string>
20 #include <sys/time.h>
21 #include <thread>
22 #include <unistd.h>
23 
24 #ifdef CUPS_ENABLE
25 #include "print_cups_client.h"
26 #endif // CUPS_ENABLE
27 #include "accesstoken_kit.h"
28 #include "array_wrapper.h"
29 #include "int_wrapper.h"
30 #include "ipc_skeleton.h"
31 #include "iservice_registry.h"
32 #include "print_bms_helper.h"
33 #include "print_constant.h"
34 #include "print_log.h"
35 #include "printer_info.h"
36 #include "print_service_converter.h"
37 #include "print_utils.h"
38 #include "string_wrapper.h"
39 #include "system_ability_definition.h"
40 #include "want_params_wrapper.h"
41 #include "common_event_data.h"
42 #include "common_event_manager.h"
43 #include "common_event_support.h"
44 #include "print_security_guard_manager.h"
45 #include "hisys_event_util.h"
46 #include "nlohmann/json.hpp"
47 #ifdef IPPOVERUSB_ENABLE
48 #include "print_ipp_over_usb_manager.h"
49 #endif // IPPOVERUSB_ENABLE
50 #include "uri.h"
51 #include <fstream>
52 #include <streambuf>
53 
54 namespace OHOS::Print {
55 using namespace OHOS::HiviewDFX;
56 using namespace Security::AccessToken;
57 using json = nlohmann::json;
58 
59 const uint32_t MAX_JOBQUEUE_NUM = 512;
60 const uint32_t ASYNC_CMD_DELAY = 10;
61 const int64_t INIT_INTERVAL = 5000L;
62 const int32_t UID_TRANSFORM_DIVISOR = 200000;
63 const std::int32_t START_USER_ID = 100;
64 const std::int32_t MAX_USER_ID = 1099;
65 const uint32_t UNLOAD_SA_INTERVAL = 90000;
66 
67 const uint32_t INDEX_ZERO = 0;
68 const uint32_t INDEX_THREE = 3;
69 const uint32_t SERIAL_LENGTH = 6;
70 
71 static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler";
72 static const std::string SPOOLER_PACKAGE_NAME = "com.ohos.spooler";
73 static const std::string PRINT_EXTENSION_BUNDLE_NAME = "com.ohos.hwprintext";
74 static const std::string EPRINTER_ID = "com.ohos.hwprintext:ePrintID";
75 static const std::string SPOOLER_ABILITY_NAME = "MainAbility";
76 static const std::string LAUNCH_PARAMETER_DOCUMENT_NAME = "documentName";
77 static const std::string LAUNCH_PARAMETER_JOB_ID = "jobId";
78 static const std::string LAUNCH_PARAMETER_FILE_LIST = "fileList";
79 static const std::string LAUNCH_PARAMETER_FD_LIST = "fdList";
80 static const std::string LAUNCH_PARAMETER_PRINT_ATTRIBUTE = "printAttributes";
81 static const std::string PRINTER_EVENT_TYPE = "printerStateChange";
82 static const std::string PRINTJOB_EVENT_TYPE = "jobStateChange";
83 static const std::string EXTINFO_EVENT_TYPE = "extInfoChange";
84 static const std::string PRINT_ADAPTER_EVENT_TYPE = "printCallback_adapter";
85 static const std::string PRINT_GET_FILE_EVENT_TYPE = "getPrintFileCallback_adapter";
86 static const std::string EVENT_BLOCK = "block";
87 static const std::string EVENT_SUCCESS = "succeed";
88 static const std::string EVENT_FAIL = "fail";
89 static const std::string EVENT_CANCEL = "cancel";
90 static const std::string CALLER_PKG_NAME = "caller.pkgName";
91 
92 static const std::string FD = "FD";
93 static const std::string TYPE_PROPERTY = "type";
94 static const std::string VALUE_PROPERTY = "value";
95 static const std::string QUEUE_JOB_LIST_CHANGED = "queuedJobListChanged";
96 static const std::string ACTION_QUEUE_JOB_LIST_CHANGED = "action.printkit.queuedJobListChanged";
97 static const std::string QUEUE_JOB_LIST_PRINTING = "printing";
98 static const std::string QUEUE_JOB_LIST_COMPLETED = "completed";
99 static const std::string QUEUE_JOB_LIST_BLOCKED = "blocked";
100 static const std::string QUEUE_JOB_LIST_CLEAR_BLOCKED = "clear_blocked";
101 static const std::string QUEUE_JOB_LIST_UNSUBSCRIBE = "unsubscribe";
102 static const std::string QUEUE_JOB_LIST_HIDE = "hide";
103 static const std::string SPOOLER_PREVIEW_ABILITY_NAME = "PrintServiceExtAbility";
104 static const std::string SPOOLER_STATUS_BAR_ABILITY_NAME = "PluginPrintIconExtAbility";
105 static const std::string TOKEN_KEY = "ohos.ability.params.token";
106 
107 static const std::string NOTIFY_INFO_SPOOLER_CLOSED_FOR_CANCELLED = "spooler_closed_for_cancelled";
108 static const std::string NOTIFY_INFO_SPOOLER_CLOSED_FOR_STARTED = "spooler_closed_for_started";
109 
110 static const std::string PRINTER_ID_DELIMITER = ":";
111 static const std::string USB_PRINTER = "usb";
112 
113 const std::string PRINTER_PREFERENCE_FILE = "printer_preference.json";
114 
115 static bool g_publishState = false;
116 
117 REGISTER_SYSTEM_ABILITY_BY_ID(PrintServiceAbility, PRINT_SERVICE_ID, true);
118 
119 std::mutex PrintServiceAbility::instanceLock_;
120 sptr<PrintServiceAbility> PrintServiceAbility::instance_;
121 std::shared_ptr<AppExecFwk::EventHandler> PrintServiceAbility::serviceHandler_;
122 std::chrono::time_point<std::chrono::high_resolution_clock> PrintServiceAbility::startPrintTime_;
123 std::string PrintServiceAbility::ingressPackage;
124 
PrintServiceAbility(int32_t systemAbilityId,bool runOnCreate)125 PrintServiceAbility::PrintServiceAbility(int32_t systemAbilityId, bool runOnCreate)
126     : SystemAbility(systemAbilityId, runOnCreate),
127       state_(ServiceRunningState::STATE_NOT_START),
128       spoolerBundleName_(SPOOLER_BUNDLE_NAME),
129       spoolerAbilityName_(SPOOLER_ABILITY_NAME),
130       currentJobOrderId_(0),
131       helper_(nullptr),
132       isJobQueueBlocked_(false),
133       currentUserId_(-1),
134       printAppCount_(0),
135       unloadCount_(0)
136 {}
137 
~PrintServiceAbility()138 PrintServiceAbility::~PrintServiceAbility()
139 {
140     PRINT_HILOGE("~PrintServiceAbility state_  is %{public}d.", static_cast<int>(state_));
141 }
142 
GetInstance()143 sptr<PrintServiceAbility> PrintServiceAbility::GetInstance()
144 {
145     if (instance_ == nullptr) {
146         std::lock_guard<std::mutex> autoLock(instanceLock_);
147         if (instance_ == nullptr) {
148             instance_ = new PrintServiceAbility(PRINT_SERVICE_ID, true);
149         }
150     }
151     return instance_;
152 }
153 
Init()154 int32_t PrintServiceAbility::Init()
155 {
156     {
157         std::lock_guard<std::recursive_mutex> lock(apiMutex_);
158         if (helper_ == nullptr) {
159             helper_ = std::make_shared<PrintServiceHelper>();
160         }
161         if (helper_ == nullptr) {
162             PRINT_HILOGE("PrintServiceHelper create failed.");
163             return E_PRINT_SERVER_FAILURE;
164         }
165         DelayedSingleton<PrintBMSHelper>::GetInstance()->SetHelper(helper_);
166         helper_->PrintSubscribeCommonEvent();
167     }
168     if (!g_publishState) {
169         bool ret = Publish(PrintServiceAbility::GetInstance());
170         if (!ret) {
171             PRINT_HILOGE("PrintServiceAbility Publish failed.");
172             return E_PRINT_SERVER_FAILURE;
173         }
174         g_publishState = true;
175     }
176     printSystemData_.Init();
177     InitPreferenceMap();
178     state_ = ServiceRunningState::STATE_RUNNING;
179     PRINT_HILOGI("state_ is %{public}d.Init PrintServiceAbility success.", static_cast<int>(state_));
180 #ifdef IPPOVERUSB_ENABLE
181     PRINT_HILOGD("before PrintIppOverUsbManager Init");
182     DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->Init();
183     PRINT_HILOGD("end PrintIppOverUsbManager Init");
184 #endif // IPPOVERUSB_ENABLE
185 #ifdef CUPS_ENABLE
186     return DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
187 #endif  // CUPS_ENABLE
188     return ERR_OK;
189 }
190 
OnStart()191 void PrintServiceAbility::OnStart()
192 {
193     PRINT_HILOGI("PrintServiceAbility::Enter OnStart.");
194     if (instance_ == nullptr) {
195         instance_ = this;
196     }
197     if (state_ == ServiceRunningState::STATE_RUNNING) {
198         PRINT_HILOGI("PrintServiceAbility is already running.");
199 #ifdef CUPS_ENABLE
200         DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
201 #endif  // CUPS_ENABLE
202         return;
203     }
204     InitServiceHandler();
205     int32_t ret = Init();
206     if (ret != ERR_OK) {
207         auto callback = [=]() { Init(); };
208         serviceHandler_->PostTask(callback, INIT_INTERVAL);
209         PRINT_HILOGE("PrintServiceAbility Init failed. Try again 5s later");
210         return;
211     }
212     vendorManager.Init(GetInstance(), true);
213     state_ = ServiceRunningState::STATE_RUNNING;
214     return;
215 }
216 
InitServiceHandler()217 void PrintServiceAbility::InitServiceHandler()
218 {
219     PRINT_HILOGI("InitServiceHandler started.");
220     if (serviceHandler_ != nullptr) {
221         PRINT_HILOGI("InitServiceHandler already init.");
222         return;
223     }
224     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("PrintServiceAbility");
225     serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
226     PRINT_HILOGI("InitServiceHandler succeeded.");
227 }
228 
ManualStart()229 void PrintServiceAbility::ManualStart()
230 {
231     if (state_ != ServiceRunningState::STATE_RUNNING) {
232         PRINT_HILOGI("PrintServiceAbility restart.");
233         OnStart();
234     } else {
235 #ifdef CUPS_ENABLE
236         DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
237 #endif  // CUPS_ENABLE
238     }
239 }
240 
GetPrintJobOrderId()241 std::string PrintServiceAbility::GetPrintJobOrderId()
242 {
243     std::lock_guard<std::mutex> autoLock(instanceLock_);
244     return std::to_string(currentJobOrderId_++);
245 }
246 
OnStop()247 void PrintServiceAbility::OnStop()
248 {
249     PRINT_HILOGI("OnStop started.");
250     if (state_ != ServiceRunningState::STATE_RUNNING) {
251         return;
252     }
253     vendorManager.UnInit();
254     serviceHandler_ = nullptr;
255     state_ = ServiceRunningState::STATE_NOT_START;
256     PRINT_HILOGI("OnStop end.");
257 }
258 
StartService()259 int32_t PrintServiceAbility::StartService()
260 {
261     ManualStart();
262     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
263         PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION);
264         return E_PRINT_NO_PERMISSION;
265     }
266     int64_t callerTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
267     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
268     auto iter = printUserDataMap_.find(callerTokenId);
269     if (iter == printUserDataMap_.end()) {
270         auto userData = std::make_shared<PrintUserData>();
271         if (userData != nullptr) {
272             printUserDataMap_.insert(std::make_pair(callerTokenId, userData));
273         }
274     }
275     printAppCount_++;
276     PRINT_HILOGI("NativePrint PrintServiceAbility StartService started. PrintAppCount_: %{public}u", printAppCount_);
277 #ifdef CUPS_ENABLE
278     return DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
279 #endif // CUPS_ENABLE
280     return E_PRINT_NONE;
281 }
282 
StartPrint(const std::vector<std::string> & fileList,const std::vector<uint32_t> & fdList,std::string & taskId)283 int32_t PrintServiceAbility::StartPrint(const std::vector<std::string> &fileList,
284     const std::vector<uint32_t> &fdList, std::string &taskId)
285 {
286     return CallSpooler(fileList, fdList, taskId);
287 }
288 
CallSpooler(const std::vector<std::string> & fileList,const std::vector<uint32_t> & fdList,std::string & taskId)289 int32_t PrintServiceAbility::CallSpooler(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
290     std::string &taskId)
291 {
292     ManualStart();
293     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
294         PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION);
295         return E_PRINT_NO_PERMISSION;
296     }
297     PRINT_HILOGD("PrintServiceAbility StartPrint started.");
298     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
299     if (taskId.empty()) {
300         PRINT_HILOGE("jobId is empty");
301         return E_PRINT_INVALID_PARAMETER;
302     }
303     PRINT_HILOGI("CallSpooler jobId: %{public}s", taskId.c_str());
304     auto printJob = std::make_shared<PrintJob>();
305     if (printJob == nullptr) {
306         PRINT_HILOGE("printJob is nullptr");
307         return E_PRINT_SERVER_FAILURE;
308     }
309     printJob->SetFdList(fdList);
310     printJob->SetJobId(taskId);
311     printJob->SetJobState(PRINT_JOB_PREPARED);
312     RegisterAdapterListener(taskId);
313     std::string callerPkg = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
314     ingressPackage = callerPkg;
315     AddToPrintJobList(taskId, printJob);
316     SendPrintJobEvent(*printJob);
317     securityGuardManager_.receiveBaseInfo(taskId, callerPkg, fileList);
318 
319     printAppCount_++;
320     PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
321     return E_PRINT_NONE;
322 }
323 
StopPrint(const std::string & taskId)324 int32_t PrintServiceAbility::StopPrint(const std::string &taskId)
325 {
326     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
327         PRINT_HILOGE("no permission to access print service");
328         return E_PRINT_NO_PERMISSION;
329     }
330 
331     PRINT_HILOGD("PrintServiceAbility StopPrint started.");
332     return E_PRINT_NONE;
333 }
334 
HandleExtensionConnectPrinter(const std::string & printerId)335 int32_t PrintServiceAbility::HandleExtensionConnectPrinter(const std::string &printerId)
336 {
337     std::string extensionId = PrintUtils::GetExtensionId(printerId);
338     std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_CONNECT_PRINTER);
339     if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
340         PRINT_HILOGW("ConnectPrinter Not Register Yet!!!");
341         return E_PRINT_SERVER_FAILURE;
342     }
343 #ifdef IPPOVERUSB_ENABLE
344     ConnectIppOverUsbPrinter(printerId);
345     auto cbFunc = extCallbackMap_[cid];
346     auto callback = [=]() {
347         if (cbFunc != nullptr) {
348             cbFunc->OnCallback(printerId);
349         }
350     };
351     if (helper_->IsSyncMode()) {
352         callback();
353     } else {
354         serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
355     }
356 #endif // IPPOVERUSB_ENABLE
357     return E_PRINT_NONE;
358 }
359 
ConnectPrinter(const std::string & printerId)360 int32_t PrintServiceAbility::ConnectPrinter(const std::string &printerId)
361 {
362     ManualStart();
363     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
364         PRINT_HILOGE("no permission to access print service");
365         return E_PRINT_NO_PERMISSION;
366     }
367     PRINT_HILOGD("ConnectPrinter started.");
368     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
369     vendorManager.ClearConnectingPrinter();
370     if (printSystemData_.QueryDiscoveredPrinterInfoById(printerId) == nullptr) {
371         PRINT_HILOGI("Invalid printer id, try connect printer by ip");
372         return TryConnectPrinterByIp(printerId);
373     }
374     vendorManager.SetConnectingPrinter(ID_AUTO, printerId);
375     std::string extensionId = PrintUtils::GetExtensionId(printerId);
376     if (!vendorManager.ExtractVendorName(extensionId).empty()) {
377         if (!vendorManager.ConnectPrinter(printerId)) {
378             PRINT_HILOGE("Vendor not found");
379             return E_PRINT_SERVER_FAILURE;
380         }
381         return E_PRINT_NONE;
382     }
383     return HandleExtensionConnectPrinter(printerId);
384 }
385 
DisconnectPrinter(const std::string & printerId)386 int32_t PrintServiceAbility::DisconnectPrinter(const std::string &printerId)
387 {
388     ManualStart();
389     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
390         PRINT_HILOGE("no permission to access print service");
391         return E_PRINT_NO_PERMISSION;
392     }
393 
394     PRINT_HILOGD("DisconnectPrinter started.");
395     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
396 
397     if (printSystemData_.QueryDiscoveredPrinterInfoById(printerId) == nullptr) {
398         PRINT_HILOGE("Invalid printer id");
399         return E_PRINT_INVALID_PRINTER;
400     }
401 
402     std::string extensionId = PrintUtils::GetExtensionId(printerId);
403     std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_DISCONNECT_PRINTER);
404     if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
405         PRINT_HILOGW("DisconnectPrinter Not Register Yet!!!");
406         return E_PRINT_SERVER_FAILURE;
407     }
408 
409     auto cbFunc = extCallbackMap_[cid];
410     auto callback = [=]() {
411         if (cbFunc != nullptr) {
412             cbFunc->OnCallback(printerId);
413         }
414     };
415     if (helper_->IsSyncMode()) {
416         callback();
417     } else {
418         serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
419     }
420     return E_PRINT_NONE;
421 }
422 
StartDiscoverPrinter(const std::vector<std::string> & extensionIds)423 int32_t PrintServiceAbility::StartDiscoverPrinter(const std::vector<std::string> &extensionIds)
424 {
425     ManualStart();
426     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
427         PRINT_HILOGE("no permission to access print service");
428         return E_PRINT_NO_PERMISSION;
429     }
430 
431     PRINT_HILOGD("StartDiscoverPrinter started.");
432     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
433     std::vector<std::string> printerIdList = printSystemData_.QueryAddedPrinterIdList();
434     for (auto &printerId : printerIdList) {
435         vendorManager.MonitorPrinterStatus(printerId, true);
436     }
437     vendorManager.StartStatusMonitor();
438     vendorManager.StartDiscovery();
439     return StartExtensionDiscovery(extensionIds);
440 }
441 
DelayStartDiscovery(const std::string & extensionId)442 bool PrintServiceAbility::DelayStartDiscovery(const std::string &extensionId)
443 {
444     PRINT_HILOGD("DelayStartDiscovery started. %{public}s", extensionId.c_str());
445     if (extensionStateList_.find(extensionId) == extensionStateList_.end()) {
446         PRINT_HILOGE("invalid extension id");
447         return false;
448     }
449 
450     if (extensionStateList_[extensionId] != PRINT_EXTENSION_LOADED) {
451         PRINT_HILOGE("invalid extension state");
452         return false;
453     }
454 
455     std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_DISCOVERY);
456     if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
457         PRINT_HILOGE("StartDiscoverPrinter Not Register, BUT State is LOADED");
458         return false;
459     }
460 
461     int32_t ret = E_PRINT_SERVER_FAILURE;
462     if (extCallbackMap_[cid]->OnCallback()) {
463         ret = E_PRINT_NONE;
464     }
465     return ret == E_PRINT_NONE;
466 }
467 
StopDiscoverPrinter()468 int32_t PrintServiceAbility::StopDiscoverPrinter()
469 {
470     ManualStart();
471     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
472         PRINT_HILOGE("no permission to access print service");
473         return E_PRINT_NO_PERMISSION;
474     }
475     PRINT_HILOGD("StopDiscoverPrinter started.");
476     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
477     vendorManager.StopDiscovery();
478     vendorManager.StopStatusMonitor();
479     for (auto extension : extensionStateList_) {
480         if (extension.second < PRINT_EXTENSION_LOADING) {
481             continue;
482         }
483         extension.second = PRINT_EXTENSION_UNLOAD;
484         std::string cid = PrintUtils::EncodeExtensionCid(extension.first, PRINT_EXTCB_STOP_DISCOVERY);
485         if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
486             PRINT_HILOGE("StopDiscoverPrinter Not Register, BUT State is LOADED");
487             continue;
488         }
489 
490         auto cbFunc = extCallbackMap_[cid];
491         auto callback = [=]() {
492             if (cbFunc != nullptr) {
493                 cbFunc->OnCallback();
494             }
495         };
496         if (helper_->IsSyncMode()) {
497             callback();
498         } else {
499             serviceHandler_->PostTask(callback, 0);
500         }
501     }
502     PRINT_HILOGW("StopDiscoverPrinter out.");
503     return E_PRINT_NONE;
504 }
505 
DestroyExtension()506 int32_t PrintServiceAbility::DestroyExtension()
507 {
508     ManualStart();
509     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
510         PRINT_HILOGE("no permission to access print service");
511         return E_PRINT_NO_PERMISSION;
512     }
513     PRINT_HILOGD("DestroyExtension started.");
514     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
515 
516     for (auto extension : extensionStateList_) {
517         if (extension.second < PRINT_EXTENSION_LOADING) {
518             continue;
519         }
520         extension.second = PRINT_EXTENSION_UNLOAD;
521         std::string cid = PrintUtils::EncodeExtensionCid(extension.first, PRINT_EXTCB_DESTROY_EXTENSION);
522         if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
523             PRINT_HILOGE("Destroy extension Not Register, BUT State is LOADED");
524             continue;
525         }
526 
527         auto cbFunc = extCallbackMap_[cid];
528         if (cbFunc != nullptr) {
529             cbFunc->OnCallback();
530         }
531     }
532     PRINT_HILOGW("DestroyExtension out.");
533     return E_PRINT_NONE;
534 }
535 
QueryAllExtension(std::vector<PrintExtensionInfo> & extensionInfos)536 int32_t PrintServiceAbility::QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos)
537 {
538     ManualStart();
539     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
540         PRINT_HILOGE("no permission to access print service");
541         return E_PRINT_NO_PERMISSION;
542     }
543     PRINT_HILOGD("QueryAllExtension started.");
544     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
545 
546     std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfo;
547     if (!DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryExtensionInfos(extensionInfo)) {
548         PRINT_HILOGE("Failed to query extension");
549         return E_PRINT_SERVER_FAILURE;
550     }
551 
552     extensionList_.clear();
553     extensionStateList_.clear();
554     for (auto extInfo : extensionInfo) {
555         PRINT_HILOGD("bundleName = %{public}s", extInfo.bundleName.c_str());
556         PRINT_HILOGD("moduleName = %{public}s", extInfo.moduleName.c_str());
557         PRINT_HILOGD("name = %{public}s", extInfo.name.c_str());
558         PrintExtensionInfo printExtInfo = ConvertToPrintExtensionInfo(extInfo);
559         extensionInfos.emplace_back(printExtInfo);
560         extensionList_.insert(std::make_pair(printExtInfo.GetExtensionId(), extInfo));
561         extensionStateList_.insert(std::make_pair(printExtInfo.GetExtensionId(), PRINT_EXTENSION_UNLOAD));
562     }
563     PRINT_HILOGI("QueryAllExtension End.");
564     return E_PRINT_NONE;
565 }
566 
QueryAllPrintJob(std::vector<PrintJob> & printJobs)567 int32_t PrintServiceAbility::QueryAllPrintJob(std::vector<PrintJob> &printJobs)
568 {
569     ManualStart();
570     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
571         PRINT_HILOGE("no permission to access print service");
572         return E_PRINT_NO_PERMISSION;
573     }
574     PRINT_HILOGD("QueryAllPrintJob started.");
575     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
576     auto userData = GetCurrentUserData();
577     if (userData == nullptr) {
578         PRINT_HILOGE("Get user data failed.");
579         return E_PRINT_INVALID_USERID;
580     }
581     int32_t ret = userData->QueryAllPrintJob(printJobs);
582     if (ret != E_PRINT_NONE) {
583         PRINT_HILOGE("QueryAllPrintJob failed.");
584         return ret;
585     }
586     return E_PRINT_NONE;
587 }
588 
QueryAddedPrinter(std::vector<std::string> & printerList)589 int32_t PrintServiceAbility::QueryAddedPrinter(std::vector<std::string> &printerList)
590 {
591     ManualStart();
592     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
593         PRINT_HILOGE("no permission to access print service");
594         return E_PRINT_NO_PERMISSION;
595     }
596     PRINT_HILOGD("QueryAddedPrinter started.");
597     std::vector<std::string> printerNameList;
598     printSystemData_.GetAddedPrinterListFromSystemData(printerNameList);
599     if (printerNameList.size() <= 0) {
600         PRINT_HILOGW("no added printerId");
601         return E_PRINT_NONE;
602     }
603     for (uint32_t i = 0; i < printerNameList.size(); i++) {
604         PRINT_HILOGD("QueryAddedPrinter in printerName %{public}s", printerNameList[i].c_str());
605         std::string printerId = printSystemData_.QueryPrinterIdByStandardizeName(printerNameList[i]);
606         PRINT_HILOGD("QueryAddedPrinter in printerId %{public}s", printerId.c_str());
607         if (printerId.empty()) {
608             continue;
609         }
610         printerList.push_back(printerId);
611     }
612     return E_PRINT_NONE;
613 }
614 
QueryPrinterInfoByPrinterId(const std::string & printerId,PrinterInfo & info)615 int32_t PrintServiceAbility::QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info)
616 {
617     ManualStart();
618     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
619         PRINT_HILOGE("no permission to access print service");
620         return E_PRINT_NO_PERMISSION;
621     }
622     PRINT_HILOGD("QueryPrinterInfoByPrinterId started %{public}s", printerId.c_str());
623     info.SetPrinterId(printerId);
624     OHOS::Print::CupsPrinterInfo cupsPrinter;
625     if (printSystemData_.QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinter)) {
626         info.SetPrinterName(PrintUtil::RemoveUnderlineFromPrinterName(cupsPrinter.name));
627         nlohmann::json option;
628         option["printerName"] = cupsPrinter.name;
629         option["printerUri"] = cupsPrinter.uri; // Deprecated, to be removed in a future version.
630         option["make"] = cupsPrinter.maker;     // Deprecated, to be removed in a future version.
631         option["alias"] = cupsPrinter.alias;
632         if (!cupsPrinter.uri.empty()) {
633             info.SetUri(cupsPrinter.uri);
634         }
635         if (!cupsPrinter.maker.empty()) {
636             info.SetPrinterMake(cupsPrinter.maker);
637         }
638         info.SetOption(option.dump());
639         info.SetCapability(cupsPrinter.printerCapability);
640         info.SetPrinterStatus(cupsPrinter.printerStatus);
641         PRINT_HILOGI("QueryPrinterInfoByPrinterId printerStatus: %{public}d", info.GetPrinterStatus());
642     } else {
643         std::string extensionId = PrintUtils::GetExtensionId(printerId);
644         if (!vendorManager.ExtractVendorName(extensionId).empty()) {
645             return QueryVendorPrinterInfo(printerId, info);
646         }
647         int32_t ret = DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPrinterInfoByPrinterId(printerId, info);
648         if (ret != 0) {
649             PRINT_HILOGE("cups QueryPrinterInfoByPrinterId fail, ret = %{public}d", ret);
650             return E_PRINT_INVALID_PRINTER;
651         }
652     }
653     if (CheckIsDefaultPrinter(printerId)) {
654         info.SetIsDefaultPrinter(true);
655     }
656     if (CheckIsLastUsedPrinter(printerId)) {
657         info.SetIsLastUsedPrinter(true);
658     }
659     return E_PRINT_NONE;
660 }
661 
QueryPrinterProperties(const std::string & printerId,const std::vector<std::string> & keyList,std::vector<std::string> & valueList)662 int32_t PrintServiceAbility::QueryPrinterProperties(const std::string &printerId,
663     const std::vector<std::string> &keyList, std::vector<std::string> &valueList)
664 {
665     ManualStart();
666     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
667         PRINT_HILOGE("no permission to access print service");
668         return E_PRINT_NO_PERMISSION;
669     }
670     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
671     PRINT_HILOGD("printerId %{public}s", printerId.c_str());
672     PrinterInfo printerInfo;
673     uint32_t ret = QueryPrinterInfoByPrinterId(printerId, printerInfo);
674     if (ret != E_PRINT_NONE) {
675         PRINT_HILOGW("no printerInfo");
676         return E_PRINT_INVALID_PRINTER;
677     }
678     PRINT_HILOGD("printerInfo %{public}s", printerInfo.GetPrinterName().c_str());
679     for (auto &key : keyList) {
680         PRINT_HILOGD("QueryPrinterProperties key %{public}s", key.c_str());
681         if (key == "printerPreference") {
682             std::string printerPreference;
683             if (GetPrinterPreference(printerId, printerPreference) == E_PRINT_NONE &&
684                 json::accept(printerPreference)) {
685                 nlohmann::json preferenceJson = json::parse(printerPreference);
686                 valueList.emplace_back(preferenceJson.at("setting").dump());
687                 PRINT_HILOGD("getPrinterPreference success");
688             }
689         }
690     }
691     return E_PRINT_NONE;
692 }
693 
QueryPrintJobById(std::string & printJobId,PrintJob & printJob)694 int32_t PrintServiceAbility::QueryPrintJobById(std::string &printJobId, PrintJob &printJob)
695 {
696     ManualStart();
697     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
698         PRINT_HILOGE("no permission to access print service");
699         return E_PRINT_NO_PERMISSION;
700     }
701     PRINT_HILOGD("QueryPrintJobById started.");
702     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
703 
704     auto userData = GetCurrentUserData();
705     if (userData == nullptr) {
706         PRINT_HILOGE("Get user data failed.");
707         return E_PRINT_INVALID_USERID;
708     }
709     int32_t ret = userData->QueryPrintJobById(printJobId, printJob);
710     if (ret != E_PRINT_NONE) {
711         PRINT_HILOGE("QueryPrintJobById failed.");
712         return ret;
713     }
714     return E_PRINT_NONE;
715 }
716 
AddPrinterToCups(const std::string & printerUri,const std::string & printerName,const std::string & printerMake)717 int32_t PrintServiceAbility::AddPrinterToCups(const std::string &printerUri, const std::string &printerName,
718     const std::string &printerMake)
719 {
720     ManualStart();
721     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
722         PRINT_HILOGE("no permission to access print service");
723         return E_PRINT_NO_PERMISSION;
724     }
725     PRINT_HILOGD("AddPrinterToCups started.");
726 #ifdef CUPS_ENABLE
727     auto ret = DelayedSingleton<PrintCupsClient>::GetInstance()->AddPrinterToCups(printerUri, printerName, printerMake);
728     if (ret != E_PRINT_NONE) {
729         PRINT_HILOGW("AddPrinterToCups error = %{public}d.", ret);
730         return ret;
731     }
732 #endif // CUPS_ENABLE
733     PRINT_HILOGD("AddPrinterToCups End.");
734     return E_PRINT_NONE;
735 }
736 
QueryPrinterCapabilityByUri(const std::string & printerUri,const std::string & printerId,PrinterCapability & printerCaps)737 int32_t PrintServiceAbility::QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId,
738     PrinterCapability &printerCaps)
739 {
740     {
741         std::lock_guard <std::recursive_mutex> lock(apiMutex_);
742         ManualStart();
743         if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
744             PRINT_HILOGE("no permission to access print service");
745             return E_PRINT_NO_PERMISSION;
746         }
747     }
748     PRINT_HILOGD("QueryPrinterCapabilityByUri started.");
749     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
750     std::string standardizeId = printerId;
751     if (standardizeId.find(extensionId) == std::string::npos && vendorManager.ExtractVendorName(printerId).empty()) {
752         standardizeId = PrintUtils::GetGlobalId(extensionId, printerId);
753     }
754     PRINT_HILOGI("extensionId = %{public}s, printerId : %{public}s", extensionId.c_str(), standardizeId.c_str());
755 #ifdef CUPS_ENABLE
756     if (printerUri.length() > SERIAL_LENGTH && printerUri.substr(INDEX_ZERO, INDEX_THREE) == USB_PRINTER) {
757         auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(standardizeId);
758         if (printerInfo == nullptr) {
759             PRINT_HILOGE("can not find the printer");
760             return E_PRINT_INVALID_PRINTER;
761         }
762         if (printerInfo->HasOption() && json::accept(printerInfo->GetOption())) {
763             PRINT_HILOGD("QueryPrinterCapabilityByUri ops : %{public}s.", printerInfo->GetOption().c_str());
764             nlohmann::json opsJson = json::parse(printerInfo->GetOption());
765             if (!opsJson.contains("printerMake") || !opsJson["printerMake"].is_string()) {
766                 PRINT_HILOGW("can not find printerMake");
767                 return E_PRINT_INVALID_PRINTER;
768             }
769             std::string make = opsJson["printerMake"];
770             auto ret = DelayedSingleton<PrintCupsClient>::GetInstance()->
771                 AddPrinterToCups(printerUri, printerInfo->GetPrinterName(), make);
772             if (ret != E_PRINT_NONE) {
773                 PRINT_HILOGE("AddPrinterToCups error = %{public}d.", ret);
774                 return ret;
775             }
776             DelayedSingleton<PrintCupsClient>::GetInstance()->
777                 QueryPrinterCapabilityFromPPD(printerInfo->GetPrinterName(), printerCaps);
778         }
779     } else {
780         DelayedSingleton<PrintCupsClient>::GetInstance()->
781             QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps);
782     }
783 #endif // CUPS_ENABLE
784     PRINT_HILOGD("QueryPrinterCapabilityByUri End.");
785     WritePrinterPreference(standardizeId, printerCaps);
786     return E_PRINT_NONE;
787 }
788 
BuildPrinterPreferenceByDefault(nlohmann::json & capOpt,PreferenceSetting & printerDefaultAttr)789 void PrintServiceAbility::BuildPrinterPreferenceByDefault(nlohmann::json& capOpt, PreferenceSetting &printerDefaultAttr)
790 {
791     if (capOpt.contains("defaultPageSizeId") && capOpt["defaultPageSizeId"].is_string()) {
792         printerDefaultAttr.pagesizeId = capOpt["defaultPageSizeId"].get<std::string>();
793     }
794     if (capOpt.contains("orientation-requested-default") && capOpt["orientation-requested-default"].is_string()) {
795         printerDefaultAttr.orientation = capOpt["orientation-requested-default"].get<std::string>();
796     }
797     if (capOpt.contains("sides-default") && capOpt["sides-default"].is_string()) {
798         printerDefaultAttr.duplex = capOpt["sides-default"].get<std::string>();
799     }
800     if (capOpt.contains("print-quality-default") && capOpt["print-quality-default"].is_string()) {
801         printerDefaultAttr.quality = capOpt["print-quality-default"].get<std::string>();
802     }
803     if (capOpt.contains("media-type-default") && capOpt["media-type-default"].is_string()) {
804         printerDefaultAttr.mediaType = capOpt["media-type-default"].get<std::string>();
805     }
806     printerDefaultAttr.hasMargin = true;
807 }
808 
BuildPrinterPreferenceByOption(std::string & key,std::string & supportedOpts,std::vector<std::string> & optAttrs)809 void PrintServiceAbility::BuildPrinterPreferenceByOption(std::string& key, std::string& supportedOpts,
810     std::vector<std::string>& optAttrs)
811 {
812     if (supportedOpts.length() <= 0) {
813         return;
814     }
815     PRINT_HILOGI("BuildPrinterPreferenceByOption %{public}s", supportedOpts.c_str());
816     if (json::accept(supportedOpts) && supportedOpts.find("{") != std::string::npos) {
817         nlohmann::json ArrJson = json::parse(supportedOpts);
818         BuildPrinterAttrComponentByJson(key, ArrJson, optAttrs);
819     } else {
820         PrintUtil::Str2VecStr(supportedOpts, optAttrs);
821     }
822 }
823 
BuildPrinterPreference(PrinterCapability & cap,PrinterPreference & printPreference)824 int32_t PrintServiceAbility::BuildPrinterPreference(PrinterCapability &cap, PrinterPreference &printPreference)
825 {
826     std::string capOption = cap.GetOption();
827     PRINT_HILOGI("printer capOption %{public}s", capOption.c_str());
828     if (!json::accept(capOption)) {
829         PRINT_HILOGW("capOption can not parse to json object");
830         return E_PRINT_INVALID_PARAMETER;
831     }
832     nlohmann::json capJson = json::parse(capOption);
833     if (!capJson.contains("cupsOptions")) {
834         PRINT_HILOGW("The capJson does not have a cupsOptions attribute.");
835         return E_PRINT_INVALID_PARAMETER;
836     }
837     nlohmann::json capOpt = capJson["cupsOptions"];
838 
839     std::string key = "id";
840     std::vector<PrintPageSize> supportedPageSizes;
841     cap.GetSupportedPageSize(supportedPageSizes);
842     if (supportedPageSizes.size() > 0) {
843         std::string supportedPageSizeOpts = ConvertListToJson<PrintPageSize>(supportedPageSizes, ConvertPageSizeToJson);
844         BuildPrinterPreferenceByOption(key, supportedPageSizeOpts, printPreference.pagesizeId);
845     }
846 
847     key = "orientation";
848     if (capOpt.contains("orientation-requested-supported") && capOpt["orientation-requested-supported"].is_string()) {
849         std::string supportedOriOpts = capOpt["orientation-requested-supported"].get<std::string>();
850         BuildPrinterPreferenceByOption(key, supportedOriOpts, printPreference.orientation);
851     }
852 
853     key = "duplex";
854     if (capOpt.contains("sides-supported") && capOpt["sides-supported"].is_string()) {
855         std::string supportedDeplexOpts = capOpt["sides-supported"].get<std::string>();
856         BuildPrinterPreferenceByOption(key, supportedDeplexOpts, printPreference.duplex);
857     }
858 
859     key = "quality";
860     if (capOpt.contains("print-quality-supported") && capOpt["print-quality-supported"].is_string()) {
861         std::string supportedQualityOpts = capOpt["print-quality-supported"].get<std::string>();
862         BuildPrinterPreferenceByOption(key, supportedQualityOpts, printPreference.quality);
863     }
864 
865     std::vector<std::string> supportedMediaTypes;
866     cap.GetSupportedMediaType(supportedMediaTypes);
867     if (supportedMediaTypes.size() > 0) {
868         printPreference.mediaType = supportedMediaTypes;
869     }
870 
871     BuildPrinterPreferenceByDefault(capOpt, printPreference.defaultSetting);
872     return E_PRINT_NONE;
873 }
874 
BuildPrinterAttrComponentByJson(std::string & key,nlohmann::json & jsonArrObject,std::vector<std::string> & printerAttrs)875 void PrintServiceAbility::BuildPrinterAttrComponentByJson(std::string &key, nlohmann::json &jsonArrObject,
876     std::vector<std::string> &printerAttrs)
877 {
878     if (!jsonArrObject.is_array()) {
879         PRINT_HILOGW("can not PrinterAttrsComponent by jsonArrObject");
880         return;
881     }
882     for (auto &element : jsonArrObject.items()) {
883         nlohmann::json object = element.value();
884         if (object.contains(key)) {
885             if (object[key].is_string()) {
886                 printerAttrs.push_back(object[key].get<std::string>());
887             } else if (object[key].is_number()) {
888                 int value = object[key];
889                 printerAttrs.push_back(std::to_string(value));
890             }
891         }
892     }
893 }
894 
GetPrinterPreference(const std::string & printerId,std::string & printerPreference)895 int32_t PrintServiceAbility::GetPrinterPreference(const std::string &printerId, std::string &printerPreference)
896 {
897     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
898     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
899         PRINT_HILOGE("no permission to access print service");
900         return E_PRINT_NO_PERMISSION;
901     }
902     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
903     int printerPreferenceNum = static_cast<int>(printerIdAndPreferenceMap_.size());
904     if (printerPreferenceNum <= 0) {
905         InitPreferenceMap();
906     }
907     if (printerIdAndPreferenceMap_.size() > 0 && ReadPreferenceFromFile(printerId, printerPreference)) {
908         PRINT_HILOGI("ReadPreferenceFromFile %{public}s", printerPreference.c_str());
909         return E_PRINT_NONE;
910     }
911     return E_PRINT_INVALID_PRINTER;
912 }
913 
SetPrinterPreference(const std::string & printerId,const std::string & printerSetting)914 int32_t PrintServiceAbility::SetPrinterPreference(const std::string &printerId, const std::string &printerSetting)
915 {
916     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
917     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
918         PRINT_HILOGE("no permission to access print service");
919         return E_PRINT_NO_PERMISSION;
920     }
921     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
922     int printerPreferenceNum = static_cast<int>(printerIdAndPreferenceMap_.size());
923     if (printerPreferenceNum <= 0) {
924         InitPreferenceMap();
925     }
926     std::string printPreference;
927     if (printerIdAndPreferenceMap_.size() > 0 && ReadPreferenceFromFile(printerId, printPreference)) {
928         if (!nlohmann::json::accept(printPreference) || !nlohmann::json::accept(printerSetting)) {
929             PRINT_HILOGW("json accept fail");
930             return E_PRINT_INVALID_PRINTER;
931         }
932         nlohmann::json objectJson = nlohmann::json::parse(printPreference);
933         PrinterPreference oldPrintPreference = PrinterPreference::BuildPrinterPreferenceFromJson(objectJson);
934 
935         PRINT_HILOGD("printerSetting %{public}s", printerSetting.c_str());
936         nlohmann::json settingJson = nlohmann::json::parse(printerSetting);
937         PreferenceSetting newSetting = PreferenceSetting::BuildPreferenceSettingFromJson(settingJson);
938         oldPrintPreference.setting = newSetting;
939 
940         nlohmann::json savePrinterPreference = oldPrintPreference.BuildPrinterPreferenceJson();
941         std::string newPrintPreference = savePrinterPreference.dump();
942         PRINT_HILOGI("WriteNewPreferenceToFile %{public}s", newPrintPreference.c_str());
943         printerIdAndPreferenceMap_[printerId] = newPrintPreference;
944         PrinterInfo info;
945         printSystemData_.QueryPrinterInfoById(printerId, info);
946         SendPrinterChangeEvent(PRINTER_EVENT_PREFERENCE_CHANGED, info);
947         if (WritePreferenceToFile() == false) {
948             PRINT_HILOGE("WritePreferenceToFile fail");
949             return E_PRINT_SERVER_FAILURE;
950         };
951         return E_PRINT_NONE;
952     }
953     return E_PRINT_INVALID_PRINTER;
954 }
955 
ReadPreferenceFromFile(const std::string & printerId,std::string & printPreference)956 bool PrintServiceAbility::ReadPreferenceFromFile(const std::string &printerId, std::string& printPreference)
957 {
958     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
959     auto iter = printerIdAndPreferenceMap_.find(printerId);
960     if (iter != printerIdAndPreferenceMap_.end()) {
961         printPreference = iter->second;
962         PRINT_HILOGE("open printer preference find %{public}s", printPreference.c_str());
963         return true;
964     }
965     return false;
966 }
967 
InitPreferenceMap()968 void PrintServiceAbility::InitPreferenceMap()
969 {
970     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
971     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
972     std::string printerPreferenceFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINTER_PREFERENCE_FILE;
973     std::ifstream ifs(printerPreferenceFilePath.c_str(), std::ios::in | std::ios::binary);
974     if (!ifs.is_open()) {
975         PRINT_HILOGW("open printer preference file fail");
976         return;
977     }
978     std::string fileData((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
979     ifs.close();
980     if (!nlohmann::json::accept(fileData)) {
981         PRINT_HILOGW("json accept fail");
982         return;
983     }
984     nlohmann::json jsonObject = nlohmann::json::parse(fileData);
985     if (!jsonObject.contains("printer_list") || !jsonObject["printer_list"].is_array()) {
986         PRINT_HILOGW("can not find printer_list");
987         return;
988     }
989     for (auto &element : jsonObject["printer_list"].items()) {
990         nlohmann::json object = element.value();
991         for (auto it = object.begin(); it != object.end(); it++) {
992             std::string printerId = it.key();
993             nlohmann::json printPreferenceJson = object[printerId];
994             printerIdAndPreferenceMap_[printerId] = printPreferenceJson.dump();
995         }
996     }
997 }
998 
WritePreferenceToFile()999 bool PrintServiceAbility::WritePreferenceToFile()
1000 {
1001     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1002     char realPidFile[PATH_MAX] = {};
1003     std::string printerPreferenceFilePath = PRINTER_SERVICE_FILE_PATH + "/" + PRINTER_PREFERENCE_FILE;
1004     if (realpath(PRINTER_SERVICE_FILE_PATH.c_str(), realPidFile) == nullptr) {
1005         PRINT_HILOGE("The realPidFile is null, errno:%{public}s", std::to_string(errno).c_str());
1006         return false;
1007     }
1008     nlohmann::json printerMapJson = nlohmann::json::array();
1009 
1010     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
1011     for (auto& printPreference : printerIdAndPreferenceMap_) {
1012         if (json::accept(printPreference.second)) {
1013             nlohmann::json printPreferenceJson = nlohmann::json::parse(printPreference.second);
1014             nlohmann::json objectJson;
1015             objectJson[printPreference.first] = printPreferenceJson;
1016             printerMapJson.push_back(objectJson);
1017         }
1018     }
1019 
1020     nlohmann::json jsonObject;
1021     jsonObject["printer_list"] = printerMapJson;
1022     std::string jsonString;
1023     try {
1024         jsonString = jsonObject.dump();
1025     }
1026     catch (const std::exception& e) {
1027         PRINT_HILOGE("jsonObject dump fail");
1028         return false;
1029     }
1030     size_t jsonLength = jsonString.length();
1031     int32_t fd = open(printerPreferenceFilePath.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0640);
1032     PRINT_HILOGD("SavePrinterPreferenceMap fd: %{public}d", fd);
1033     if (fd < 0) {
1034         PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str());
1035         return false;
1036     }
1037     auto writeLength = write(fd, jsonString.c_str(), jsonLength);
1038     close(fd);
1039     return (size_t)writeLength == jsonLength;
1040 }
1041 
WritePrinterPreference(const std::string & printerId,PrinterCapability & printerCaps)1042 bool PrintServiceAbility::WritePrinterPreference(const std::string &printerId, PrinterCapability &printerCaps)
1043 {
1044     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
1045     if (printerCaps.HasOption()) {
1046         if (printerIdAndPreferenceMap_.count(printerId)) {
1047             return false;
1048         }
1049         PrinterPreference printPreference;
1050         int32_t ret = BuildPrinterPreference(printerCaps, printPreference);
1051         if (ret != E_PRINT_NONE) {
1052             PRINT_HILOGE("printerCaps can not success to printPreference");
1053             return false;
1054         }
1055         nlohmann::json jsonObject = nlohmann::json::object();
1056         jsonObject = printPreference.BuildPrinterPreferenceJson();
1057         std::string savePrinterPreference = jsonObject.dump();
1058         printerIdAndPreferenceMap_.insert(std::make_pair(printerId, savePrinterPreference));
1059         return WritePreferenceToFile();
1060     }
1061     return false;
1062 }
1063 
WriteEprinterPreference(const std::string & printerId,PrinterCapability & printerCaps)1064 bool PrintServiceAbility::WriteEprinterPreference(const std::string &printerId, PrinterCapability &printerCaps)
1065 {
1066     std::lock_guard<std::recursive_mutex> preferenceLock(printerPreferenceMapMutex_);
1067     if (printerIdAndPreferenceMap_.count(printerId)) {
1068         return false;
1069     }
1070     json printerPreference;
1071     std::vector<PrintPageSize> supportedPageSize;
1072     printerCaps.GetSupportedPageSize(supportedPageSize);
1073     std::vector<std::string> supportedPageSizeStr;
1074     for (auto &item : supportedPageSize) {
1075         supportedPageSizeStr.push_back(item.GetId());
1076     }
1077     std::vector<uint32_t> supportedDuplexMode;
1078     printerCaps.GetSupportedDuplexMode(supportedDuplexMode);
1079     std::vector<std::string> supportedDuplexModeStr;
1080     for (auto &item : supportedDuplexMode) {
1081         supportedDuplexModeStr.push_back(std::to_string(item));
1082     }
1083     std::vector<uint32_t> supportedOrientation;
1084     printerCaps.GetSupportedOrientation(supportedOrientation);
1085     std::vector<std::string> supportedOrientationStr;
1086     for (auto &item : supportedOrientation) {
1087         supportedOrientationStr.push_back(std::to_string(item));
1088     }
1089     std::vector<uint32_t> supportedQuality;
1090     printerCaps.GetSupportedQuality(supportedQuality);
1091     std::vector<std::string> supportedQualityStr;
1092     for (auto &item : supportedQuality) {
1093         supportedQualityStr.push_back(std::to_string(item));
1094     }
1095 
1096     std::vector<std::string> supportedMediaTypeStr;
1097     printerCaps.GetSupportedMediaType(supportedMediaTypeStr);
1098 
1099     printerPreference["pagesizeId"] = supportedPageSizeStr;
1100     printerPreference["orientation"] = supportedOrientationStr;
1101     printerPreference["duplex"] = supportedDuplexModeStr;
1102     printerPreference["quality"] = supportedQualityStr;
1103     printerPreference["mediaType"] = supportedMediaTypeStr;
1104     PreferenceSetting preferenceSetting;
1105     printerPreference["defaultSetting"] = preferenceSetting.BuildPreferenceSettingJson();
1106     printerPreference["setting"] = preferenceSetting.BuildPreferenceSettingJson();
1107     std::string savePrinterPreference = printerPreference.dump();
1108     PRINT_HILOGD("savePrinterPreference = %{public}s", savePrinterPreference.c_str());
1109     printerIdAndPreferenceMap_.insert(std::make_pair(printerId, savePrinterPreference));
1110     return WritePreferenceToFile();
1111 }
1112 
UpdatePrintJobOptionByPrinterId(PrintJob & printJob)1113 bool PrintServiceAbility::UpdatePrintJobOptionByPrinterId(PrintJob &printJob)
1114 {
1115     CupsPrinterInfo printerInfo;
1116     if (!printSystemData_.QueryCupsPrinterInfoByPrinterId(printJob.GetPrinterId(), printerInfo)) {
1117         PRINT_HILOGW("cannot find printer info by printerId");
1118         return false;
1119     }
1120     std::string oldOption = printJob.GetOption();
1121     PRINT_HILOGD("Print job option: %{public}s", oldOption.c_str());
1122     if (!json::accept(oldOption)) {
1123         PRINT_HILOGW("old option not accepted");
1124         return false;
1125     }
1126     nlohmann::json infoJson = json::parse(oldOption);
1127     infoJson["printerName"] = printerInfo.name;
1128     infoJson["printerUri"] = printerInfo.uri;
1129     infoJson["alias"] = printerInfo.alias;
1130     std::string updatedOption = infoJson.dump();
1131     PRINT_HILOGD("Updated print job option: %{public}s", updatedOption.c_str());
1132     printJob.SetOption(updatedOption);
1133     return true;
1134 }
1135 
AddNativePrintJob(const std::string & jobId,PrintJob & printJob)1136 std::shared_ptr<PrintJob> PrintServiceAbility::AddNativePrintJob(const std::string &jobId, PrintJob &printJob)
1137 {
1138     PRINT_HILOGD("jobId %{public}s", jobId.c_str());
1139     printJob.SetJobId(jobId);
1140     printJob.SetJobState(PRINT_JOB_PREPARED);
1141     auto nativePrintJob = std::make_shared<PrintJob>();
1142     if (nativePrintJob == nullptr) {
1143         PRINT_HILOGW("nativePrintJob is null");
1144         return nullptr;
1145     }
1146     nativePrintJob->UpdateParams(printJob);
1147     nativePrintJob->Dump();
1148     AddToPrintJobList(jobId, nativePrintJob);
1149     return nativePrintJob;
1150 }
1151 
StartNativePrintJob(PrintJob & printJob)1152 int32_t PrintServiceAbility::StartNativePrintJob(PrintJob &printJob)
1153 {
1154     startPrintTime_ = std::chrono::high_resolution_clock::now();
1155     ManualStart();
1156     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
1157         PRINT_HILOGE("no permission to access print service");
1158         return E_PRINT_NO_PERMISSION;
1159     }
1160     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1161     if (!UpdatePrintJobOptionByPrinterId(printJob)) {
1162         PRINT_HILOGW("cannot update printer name/uri");
1163         return E_PRINT_INVALID_PRINTER;
1164     }
1165     std::string jobId = PrintUtils::GetPrintJobId();
1166     auto nativePrintJob = AddNativePrintJob(jobId, printJob);
1167     if (nativePrintJob == nullptr) {
1168         return E_PRINT_SERVER_FAILURE;
1169     }
1170     UpdateQueuedJobList(jobId, nativePrintJob);
1171     auto printerId = nativePrintJob->GetPrinterId();
1172     printerJobMap_[printerId].insert(std::make_pair(jobId, true));
1173     return StartPrintJobInternal(nativePrintJob);
1174 }
1175 
StartPrintJob(PrintJob & jobInfo)1176 int32_t PrintServiceAbility::StartPrintJob(PrintJob &jobInfo)
1177 {
1178     startPrintTime_ = std::chrono::high_resolution_clock::now();
1179     ManualStart();
1180     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1181         PRINT_HILOGE("no permission to access print service");
1182         return E_PRINT_NO_PERMISSION;
1183     }
1184     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1185     if (!CheckPrintJob(jobInfo)) {
1186         PRINT_HILOGW("check printJob unavailable");
1187         return E_PRINT_INVALID_PRINTJOB;
1188     }
1189     auto jobId = jobInfo.GetJobId();
1190     auto printerId = jobInfo.GetPrinterId();
1191     auto printJob = std::make_shared<PrintJob>();
1192     printJob->UpdateParams(jobInfo);
1193     PRINT_HILOGI("set job state to PRINT_JOB_QUEUED");
1194     printJob->SetJobState(PRINT_JOB_QUEUED);
1195     UpdateQueuedJobList(jobId, printJob);
1196     printerJobMap_[printerId].insert(std::make_pair(jobId, true));
1197     return StartPrintJobInternal(printJob);
1198 }
1199 
CheckPrintJob(PrintJob & jobInfo)1200 bool PrintServiceAbility::CheckPrintJob(PrintJob &jobInfo)
1201 {
1202     if (!UpdatePrintJobOptionByPrinterId(jobInfo)) {
1203         PRINT_HILOGW("cannot update printer name/uri");
1204         return false;
1205     }
1206     auto jobIt = printJobList_.find(jobInfo.GetJobId());
1207     if (jobIt == printJobList_.end()) {
1208         PRINT_HILOGE("invalid job id");
1209         return false;
1210     }
1211     printJobList_.erase(jobIt);
1212     return true;
1213 }
1214 
UpdateQueuedJobList(const std::string & jobId,const std::shared_ptr<PrintJob> & printJob)1215 void PrintServiceAbility::UpdateQueuedJobList(const std::string &jobId, const std::shared_ptr<PrintJob> &printJob)
1216 {
1217     PRINT_HILOGI("enter UpdateQueuedJobList, jobId: %{public}s.", jobId.c_str());
1218 #ifdef IPPOVERUSB_ENABLE
1219     ConnectIppOverUsbPrinter(printJob->GetPrinterId());
1220 #endif // IPPOVERUSB_ENABLE
1221     std::string jobOrderId = GetPrintJobOrderId();
1222     if (jobOrderId == "0") {
1223         jobOrderList_.clear();
1224     }
1225     PRINT_HILOGI("UpdateQueuedJobList jobOrderId: %{public}s.", jobOrderId.c_str());
1226     if (queuedJobList_.find(jobId) != queuedJobList_.end()) {
1227         queuedJobList_[jobId] = printJob;
1228         jobOrderList_[jobOrderId] = jobId;
1229     } else if (static_cast<uint32_t>(queuedJobList_.size()) < MAX_JOBQUEUE_NUM) {
1230         queuedJobList_.insert(std::make_pair(jobId, printJob));
1231         jobOrderList_.insert(std::make_pair(jobOrderId, jobId));
1232     } else {
1233         PRINT_HILOGE("UpdateQueuedJobList out of MAX_JOBQUEUE_NUM or jobId not found");
1234     }
1235 
1236     int32_t userId = GetCurrentUserId();
1237     if (userId == E_PRINT_INVALID_USERID) {
1238         PRINT_HILOGE("Invalid user id.");
1239         return;
1240     }
1241     auto iter = printUserMap_.find(userId);
1242     if (iter == printUserMap_.end() || iter->second == nullptr) {
1243         PRINT_HILOGE("Invalid user id");
1244         return;
1245     }
1246     iter->second->UpdateQueuedJobList(jobId, printJob, jobOrderId);
1247 
1248     std::string printerId = printJob->GetPrinterId();
1249     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
1250     if (printerInfo != nullptr) {
1251         printerInfo->SetPrinterStatus(PRINTER_STATUS_BUSY);
1252         printerInfo->SetPrinterName(PrintUtil::RemoveUnderlineFromPrinterName(printerInfo->GetPrinterName()));
1253         printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_BUSY);
1254         SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo, true);
1255         SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
1256         SendPrinterEventChangeEvent(PRINTER_EVENT_LAST_USED_PRINTER_CHANGED, *printerInfo);
1257     }
1258     SetLastUsedPrinter(printerId);
1259 }
1260 
SetLastUsedPrinter(const std::string & printerId)1261 void PrintServiceAbility::SetLastUsedPrinter(const std::string &printerId)
1262 {
1263     PRINT_HILOGD("SetLastUsedPrinter started.");
1264     if (!printSystemData_.IsPrinterAdded(printerId)) {
1265         PRINT_HILOGE("Printer is not added to cups.");
1266         return;
1267     }
1268 
1269     auto userData = GetCurrentUserData();
1270     if (userData == nullptr) {
1271         PRINT_HILOGE("Get user data failed.");
1272         return;
1273     }
1274     int32_t ret = userData->SetLastUsedPrinter(printerId);
1275     if (ret != E_PRINT_NONE) {
1276         PRINT_HILOGE("SetLastUsedPrinter failed.");
1277         return;
1278     }
1279 }
1280 
StartPrintJobCB(const std::string & jobId,const std::shared_ptr<PrintJob> & printJob)1281 void PrintServiceAbility::StartPrintJobCB(const std::string &jobId, const std::shared_ptr<PrintJob> &printJob)
1282 {
1283     PRINT_HILOGD("Start send task to Extension PrintJob %{public}s", jobId.c_str());
1284     NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1285     printJob->SetJobState(PRINT_JOB_QUEUED);
1286     UpdatePrintJobState(jobId, PRINT_JOB_QUEUED, PRINT_JOB_BLOCKED_UNKNOWN);
1287 }
1288 
CancelPrintJob(const std::string & jobId)1289 int32_t PrintServiceAbility::CancelPrintJob(const std::string &jobId)
1290 {
1291     ManualStart();
1292     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1293         PRINT_HILOGE("no permission to access print service");
1294         return E_PRINT_NO_PERMISSION;
1295     }
1296     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1297 
1298     auto userData = GetUserDataByJobId(jobId);
1299     if (userData == nullptr) {
1300         PRINT_HILOGE("Get user data failed.");
1301         return E_PRINT_INVALID_USERID;
1302     }
1303     auto jobIt = userData->queuedJobList_.find(jobId);
1304     if (jobIt == userData->queuedJobList_.end()) {
1305         PRINT_HILOGE("invalid job id");
1306         return E_PRINT_INVALID_PRINTJOB;
1307     }
1308 
1309     if (jobIt->second->GetJobState() >= PRINT_JOB_QUEUED) {
1310         std::string extensionId = PrintUtils::GetExtensionId(jobIt->second->GetPrinterId());
1311         std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_CANCEL_PRINT);
1312         if (cid.find(PRINT_EXTENSION_BUNDLE_NAME) == string::npos) {
1313 #ifdef CUPS_ENABLE
1314             DelayedSingleton<PrintCupsClient>::GetInstance()->CancelCupsJob(jobIt->second->GetJobId());
1315 #endif // CUPS_ENABLE
1316             return E_PRINT_NONE;
1317         }
1318         if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
1319             PRINT_HILOGW("CancelPrintJob Not Register Yet!!!");
1320             UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED);
1321             return E_PRINT_SERVER_FAILURE;
1322         }
1323         auto cbFunc = extCallbackMap_[cid];
1324         auto tmpPrintJob = userData->queuedJobList_[jobId];
1325         auto callback = [=]() {
1326             if (cbFunc != nullptr && cbFunc->OnCallback(*tmpPrintJob) == false) {
1327                 UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED);
1328             }
1329         };
1330         if (helper_->IsSyncMode()) {
1331             callback();
1332         } else {
1333             serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1334         }
1335     } else {
1336         SetPrintJobCanceled(*jobIt->second);
1337     }
1338     return E_PRINT_NONE;
1339 }
1340 
SetPrintJobCanceled(PrintJob & jobinfo)1341 void PrintServiceAbility::SetPrintJobCanceled(PrintJob &jobinfo)
1342 {
1343     auto printJob = std::make_shared<PrintJob>(jobinfo);
1344     if (printJob == nullptr) {
1345         PRINT_HILOGE("create printJob failed.");
1346         return;
1347     }
1348     std::string jobId = printJob->GetJobId();
1349     auto userData = GetUserDataByJobId(jobId);
1350     if (userData == nullptr) {
1351         PRINT_HILOGE("Get user data failed.");
1352         return;
1353     }
1354     printJob->SetJobState(PRINT_JOB_COMPLETED);
1355     printJob->SetSubState(PRINT_JOB_COMPLETED_CANCELLED);
1356     userData->printJobList_.insert(std::make_pair(jobId, printJob));
1357     printJobList_.insert(std::make_pair(jobId, printJob));
1358     UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED);
1359 }
1360 
CancelUserPrintJobs(const int32_t userId)1361 void PrintServiceAbility::CancelUserPrintJobs(const int32_t userId)
1362 {
1363     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1364     auto removedUser = printUserMap_.find(userId);
1365     if (removedUser == printUserMap_.end()) {
1366         PRINT_HILOGE("User dose not exist.");
1367         return;
1368     }
1369     if (removedUser->second == nullptr) {
1370         PRINT_HILOGE("PrintUserData is nullptr.");
1371         return;
1372     }
1373     for (auto jobIt: removedUser->second->queuedJobList_) {
1374         PRINT_HILOGI("CancelUserPrintJobs user jobId: %{public}s", jobIt.first.c_str());
1375         int32_t ret = CancelPrintJob(jobIt.first);
1376         PRINT_HILOGI("CancelUserPrintJobs CancelPrintJob ret: %{public}d", ret);
1377         userJobMap_.erase(jobIt.first);
1378     }
1379     printUserMap_.erase(userId);
1380     PRINT_HILOGI("remove user-%{public}d success.", userId);
1381 }
1382 
NotifyCurrentUserChanged(const int32_t userId)1383 void PrintServiceAbility::NotifyCurrentUserChanged(const int32_t userId)
1384 {
1385     PRINT_HILOGD("NotifyAppCurrentUserChanged begin");
1386     PRINT_HILOGI("currentUserId_ is: %{public}d", userId);
1387     currentUserId_ = userId;
1388     auto userData = GetUserDataByUserId(userId);
1389     if (userData == nullptr) {
1390         PRINT_HILOGE("Get user data failed.");
1391         return;
1392     }
1393     auto status = DetermineUserJobStatus(userData->queuedJobList_);
1394 
1395     switch (status) {
1396         case PRINT_JOB_BLOCKED:
1397             NotifyAppJobQueueChanged(QUEUE_JOB_LIST_BLOCKED);
1398             break;
1399         case PRINT_JOB_COMPLETED:
1400             NotifyAppJobQueueChanged(QUEUE_JOB_LIST_HIDE);
1401             break;
1402         case PRINT_JOB_RUNNING:
1403             NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1404             break;
1405         default:
1406             break;
1407     }
1408     PRINT_HILOGD("NotifyAppCurrentUserChanged end");
1409 }
1410 
SendQueuePrintJob(const std::string & printerId)1411 bool PrintServiceAbility::SendQueuePrintJob(const std::string &printerId)
1412 {
1413     if (printerJobMap_[printerId].empty()) {
1414         return false;
1415     }
1416 
1417     auto userData = GetCurrentUserData();
1418     if (userData == nullptr) {
1419         PRINT_HILOGE("Get user data failed.");
1420         return false;
1421     }
1422     auto jobId = printerJobMap_[printerId].begin()->first;
1423     auto jobIt = userData->queuedJobList_.find(jobId);
1424     if (jobIt == userData->queuedJobList_.end()) {
1425         PRINT_HILOGE("invalid print job, jobId:%{public}s", jobId.c_str());
1426         return false;
1427     }
1428 
1429     if (jobIt->second->GetJobState() != PRINT_JOB_PREPARED) {
1430         PRINT_HILOGE("job state isn't prepared, jobId:%{public}s", jobId.c_str());
1431         return false;
1432     }
1433 
1434     auto extensionId = PrintUtils::GetExtensionId(printerId);
1435     std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT);
1436 #ifdef CUPS_ENABLE
1437     if (cid.find(PRINT_EXTENSION_BUNDLE_NAME) != string::npos) {
1438     PRINT_HILOGD("not eprint extension, no need SendQueuePrintJob");
1439     return false;
1440     }
1441 #endif // CUPS_ENABLE
1442 
1443     auto cbFunc = extCallbackMap_[cid];
1444     auto printJob = jobIt->second;
1445     auto callback = [=]() {
1446         PRINT_HILOGD("Start Next Print Job %{public}s", jobId.c_str());
1447         if (cbFunc != nullptr && cbFunc->OnCallback(*printJob)) {
1448             printJob->SetJobState(PRINT_JOB_QUEUED);
1449             NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1450             UpdatePrintJobState(jobId, PRINT_JOB_QUEUED, PRINT_JOB_BLOCKED_UNKNOWN);
1451         }
1452     };
1453     if (helper_->IsSyncMode()) {
1454         callback();
1455     } else {
1456         serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1457     }
1458     return true;
1459 }
1460 
CheckPrinterUriDifferent(const std::shared_ptr<PrinterInfo> & info)1461 bool PrintServiceAbility::CheckPrinterUriDifferent(const std::shared_ptr<PrinterInfo> &info)
1462 {
1463     CupsPrinterInfo cupsPrinter;
1464     if (printSystemData_.QueryCupsPrinterInfoByPrinterId(info->GetPrinterId(), cupsPrinter)) {
1465         std::string printerUri = info->GetUri();
1466         auto exceptBackendUri = [=](std::string uri) -> std::string {
1467             auto pos = uri.find("://");
1468             if (pos == std::string::npos || uri.length() <= pos + 1) {
1469                 return "";
1470             }
1471             return uri.substr(pos + 1);
1472         };
1473         if (!printerUri.empty() && exceptBackendUri(printerUri) != exceptBackendUri(cupsPrinter.uri)) {
1474             return true;
1475         }
1476     }
1477     return false;
1478 }
1479 
AddPrinters(const std::vector<PrinterInfo> & printerInfos)1480 int32_t PrintServiceAbility::AddPrinters(const std::vector<PrinterInfo> &printerInfos)
1481 {
1482     ManualStart();
1483     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1484         PRINT_HILOGE("no permission to access print service");
1485         return E_PRINT_NO_PERMISSION;
1486     }
1487     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1488     PRINT_HILOGD("AddPrinters started. Total size is %{public}zd", printSystemData_.GetDiscoveredPrinterCount());
1489 
1490     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1491     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1492     for (auto &info : printerInfos) {
1493         AddSinglePrinterInfo(info, extensionId);
1494     }
1495     PRINT_HILOGD("AddPrinters end. Total size is %{public}zd", printSystemData_.GetDiscoveredPrinterCount());
1496     return E_PRINT_NONE;
1497 }
1498 
RemovePrinters(const std::vector<std::string> & printerIds)1499 int32_t PrintServiceAbility::RemovePrinters(const std::vector<std::string> &printerIds)
1500 {
1501     ManualStart();
1502     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1503         PRINT_HILOGE("no permission to access print service");
1504         return E_PRINT_NO_PERMISSION;
1505     }
1506     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1507     PRINT_HILOGD("RemovePrinters started. Total size is %{public}zd", printSystemData_.GetDiscoveredPrinterCount());
1508     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1509     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1510 
1511     bool anyPrinterRemoved = false;
1512     for (const auto& printerId : printerIds) {
1513         std::string globalPrinterId = PrintUtils::GetGlobalId(extensionId, printerId);
1514         PRINT_HILOGD("RemovePrinters printerId = %{public}s", globalPrinterId.c_str());
1515 
1516         if (RemoveSinglePrinterInfo(globalPrinterId)) {
1517             anyPrinterRemoved = true;
1518         }
1519     }
1520     if (!anyPrinterRemoved) {
1521         PRINT_HILOGE("Invalid printer ids");
1522         return E_PRINT_INVALID_PARAMETER;
1523     }
1524     PRINT_HILOGD("RemovePrinters end. Total size is %{public}zd", printSystemData_.GetDiscoveredPrinterCount());
1525     return E_PRINT_NONE;
1526 }
1527 
UpdatePrinters(const std::vector<PrinterInfo> & printerInfos)1528 int32_t PrintServiceAbility::UpdatePrinters(const std::vector<PrinterInfo> &printerInfos)
1529 {
1530     ManualStart();
1531     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1532         PRINT_HILOGE("no permission to access print service");
1533         return E_PRINT_NO_PERMISSION;
1534     }
1535 
1536     PRINT_HILOGD("UpdatePrinters started. Total size is %{public}zd", printSystemData_.GetDiscoveredPrinterCount());
1537     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1538 
1539     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1540     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1541 
1542     bool isAnyPrinterChanged = false;
1543     for (const auto &info : printerInfos) {
1544         bool isPrinterChanged = UpdateSinglePrinterInfo(info, extensionId);
1545         isAnyPrinterChanged |= isPrinterChanged;
1546     }
1547     if (isAnyPrinterChanged) {
1548         printSystemData_.SaveCupsPrinterMap();
1549     }
1550     PRINT_HILOGD("UpdatePrinters end. Total size is %{private}zd", printSystemData_.GetDiscoveredPrinterCount());
1551     return E_PRINT_NONE;
1552 }
1553 
UpdatePrinterSystemData(const PrinterInfo & info)1554 bool PrintServiceAbility::UpdatePrinterSystemData(const PrinterInfo &info)
1555 {
1556     std::string option = info.GetOption();
1557     if (json::accept(option)) {
1558         json optionJson = json::parse(option);
1559         if (optionJson.contains("alias") && optionJson["alias"].is_string()) {
1560             if (printSystemData_.UpdatePrinterAlias(info.GetPrinterId(), optionJson["alias"])) {
1561                 SendPrinterEventChangeEvent(PRINTER_EVENT_INFO_CHANGED, info);
1562                 return true;
1563             }
1564         }
1565     }
1566     return false;
1567 }
1568 
UpdatePrinterCapability(const std::string & printerId,const PrinterInfo & info)1569 bool PrintServiceAbility::UpdatePrinterCapability(const std::string &printerId, const PrinterInfo &info)
1570 {
1571     PRINT_HILOGI("UpdatePrinterCapability Enter");
1572     if (!PrintUtil::startsWith(printerId, SPOOLER_BUNDLE_NAME)) {
1573         PRINT_HILOGI("ePrinter Enter");
1574         PrinterCapability printerCaps;
1575         info.GetCapability(printerCaps);
1576         WriteEprinterPreference(printerId, printerCaps);
1577     }
1578 
1579     CupsPrinterInfo cupsPrinterInfo;
1580     auto output = info;
1581     cupsPrinterInfo.name = info.GetPrinterName();
1582     cupsPrinterInfo.uri = info.GetUri();
1583     cupsPrinterInfo.maker = info.GetPrinterMake();
1584     cupsPrinterInfo.printerStatus = PRINTER_STATUS_IDLE;
1585     info.GetCapability(cupsPrinterInfo.printerCapability);
1586     printSystemData_.InsertCupsPrinter(printerId, cupsPrinterInfo, true);
1587     output.SetPrinterStatus(PRINTER_STATUS_IDLE);
1588     output.SetPrinterId(printerId);
1589     SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, output, true);
1590     SendPrinterChangeEvent(PRINTER_EVENT_ADDED, output);
1591     SendPrinterEventChangeEvent(PRINTER_EVENT_LAST_USED_PRINTER_CHANGED, output);
1592     SetLastUsedPrinter(printerId);
1593     return true;
1594 }
1595 
UpdatePrinterState(const std::string & printerId,uint32_t state)1596 int32_t PrintServiceAbility::UpdatePrinterState(const std::string &printerId, uint32_t state)
1597 {
1598     ManualStart();
1599     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1600         PRINT_HILOGE("no permission to access print service");
1601         return E_PRINT_NO_PERMISSION;
1602     }
1603 
1604     if (state > PRINTER_UNKNOWN) {
1605         return E_PRINT_INVALID_PARAMETER;
1606     }
1607 
1608     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1609     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1610     std::string printerExtId = PrintUtils::GetGlobalId(extensionId, printerId);
1611     PRINT_HILOGD("UpdatePrinterState started. %{private}s, state [%{public}d]", printerExtId.c_str(), state);
1612     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1613 
1614     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerExtId);
1615     if (printerInfo == nullptr) {
1616         PRINT_HILOGD("Invalid printer id");
1617         return E_PRINT_INVALID_PRINTER;
1618     }
1619 
1620     printerInfo->SetPrinterState(state);
1621     SendPrinterDiscoverEvent(PRINTER_CONNECTED, *printerInfo);
1622     SendPrinterEvent(*printerInfo);
1623     PRINT_HILOGD("UpdatePrinterState end.");
1624     return E_PRINT_NONE;
1625 }
1626 
checkJobState(uint32_t state,uint32_t subState)1627 bool PrintServiceAbility::checkJobState(uint32_t state, uint32_t subState)
1628 {
1629     if (state > PRINT_JOB_UNKNOWN) {
1630         return false;
1631     }
1632     if (state == PRINT_JOB_BLOCKED && subState < PRINT_JOB_BLOCKED_OFFLINE) {
1633         return false;
1634     }
1635     if (state == PRINT_JOB_COMPLETED && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT) {
1636         return false;
1637     }
1638 
1639     return true;
1640 }
1641 
UpdatePrintJobStateForNormalApp(const std::string & jobId,uint32_t state,uint32_t subState)1642 int32_t PrintServiceAbility::UpdatePrintJobStateForNormalApp(
1643     const std::string &jobId, uint32_t state, uint32_t subState)
1644 {
1645     ManualStart();
1646     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
1647         PRINT_HILOGE("no permission to access print service");
1648         return E_PRINT_NO_PERMISSION;
1649     }
1650     return UpdatePrintJobState(jobId, state, subState);
1651 }
1652 
UpdatePrintJobStateOnlyForSystemApp(const std::string & jobId,uint32_t state,uint32_t subState)1653 int32_t PrintServiceAbility::UpdatePrintJobStateOnlyForSystemApp(
1654     const std::string &jobId, uint32_t state, uint32_t subState)
1655 {
1656     ManualStart();
1657     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1658         PRINT_HILOGE("no permission to access print service");
1659         return E_PRINT_NO_PERMISSION;
1660     }
1661     return UpdatePrintJobState(jobId, state, subState);
1662 }
1663 
UpdatePrintJobState(const std::string & jobId,uint32_t state,uint32_t subState)1664 int32_t PrintServiceAbility::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState)
1665 {
1666     ManualStart();
1667     if (state == PRINT_JOB_CREATE_FILE_COMPLETED) {
1668         return AdapterGetFileCallBack(jobId, state, subState);
1669     }
1670 
1671     if (!checkJobState(state, subState)) {
1672         return E_PRINT_INVALID_PARAMETER;
1673     }
1674 
1675     PRINT_HILOGI("UpdatePrintJobState started jobId:%{public}s, state:[%{public}d %{public}s], subState[%{public}d]",
1676         jobId.c_str(), state, PrintUtils::GetJobStateChar(state).c_str(), subState);
1677     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1678 
1679     return CheckAndSendQueuePrintJob(jobId, state, subState);
1680 }
1681 
AdapterGetFileCallBack(const std::string & jobId,uint32_t state,uint32_t subState)1682 int32_t PrintServiceAbility::AdapterGetFileCallBack(const std::string &jobId, uint32_t state, uint32_t subState)
1683 {
1684     if (state != PRINT_JOB_CREATE_FILE_COMPLETED) {
1685         return E_PRINT_NONE;
1686     }
1687     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
1688         PRINT_HILOGE("no permission to access print service");
1689         return E_PRINT_NO_PERMISSION;
1690     }
1691 
1692     auto eventIt = registeredListeners_.find(PRINT_GET_FILE_EVENT_TYPE);
1693     if (eventIt != registeredListeners_.end() && eventIt->second != nullptr) {
1694         PRINT_HILOGI("print job adapter file created subState[%{public}d]", subState);
1695         uint32_t fileCompletedState = subState;
1696         if (subState == PRINT_JOB_CREATE_FILE_COMPLETED_SUCCESS) {
1697             fileCompletedState = PRINT_FILE_CREATED_SUCCESS;
1698         } else if (subState == PRINT_JOB_CREATE_FILE_COMPLETED_FAILED) {
1699             fileCompletedState = PRINT_FILE_CREATED_FAIL;
1700         }
1701         eventIt->second->OnCallbackAdapterGetFile(fileCompletedState);
1702     }
1703     return E_PRINT_NONE;
1704 }
1705 
CheckAndSendQueuePrintJob(const std::string & jobId,uint32_t state,uint32_t subState)1706 int32_t PrintServiceAbility::CheckAndSendQueuePrintJob(const std::string &jobId, uint32_t state, uint32_t subState)
1707 {
1708     auto userData = GetUserDataByJobId(jobId);
1709     if (userData == nullptr) {
1710         PRINT_HILOGE("Get user data failed.");
1711         return E_PRINT_INVALID_USERID;
1712     }
1713     auto jobIt = userData->queuedJobList_.find(jobId);
1714     bool jobInQueue = true;
1715     if (jobIt == userData->queuedJobList_.end()) {
1716         jobInQueue = false;
1717         jobIt = userData->printJobList_.find(jobId);
1718         if (jobIt == userData->printJobList_.end()) {
1719             PRINT_HILOGD("Invalid print job id");
1720             return E_PRINT_INVALID_PRINTJOB;
1721         }
1722     }
1723     jobIt->second->SetJobState(state);
1724     jobIt->second->SetSubState(subState);
1725     SendPrintJobEvent(*jobIt->second);
1726     notifyAdapterJobChanged(jobId, state, subState);
1727     CheckJobQueueBlocked(*jobIt->second);
1728 
1729     auto printerId = jobIt->second->GetPrinterId();
1730     if (state == PRINT_JOB_BLOCKED) {
1731         ReportHisysEvent(jobIt->second, printerId, subState);
1732     }
1733     if (state == PRINT_JOB_COMPLETED) {
1734         if (jobInQueue) {
1735             printerJobMap_[printerId].erase(jobId);
1736             userData->queuedJobList_.erase(jobId);
1737             queuedJobList_.erase(jobId);
1738         }
1739         auto iter = printerJobMap_.find(printerId);
1740         if (iter == printerJobMap_.end() || iter->second.empty()) {
1741             auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
1742             if (printerInfo != nullptr) {
1743                 printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE);
1744                 printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_IDLE);
1745                 SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
1746                 SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
1747             }
1748         }
1749         if (IsQueuedJobListEmpty(jobId)) {
1750             ReportCompletedPrint(printerId);
1751         }
1752         SendQueuePrintJob(printerId);
1753     }
1754     PRINT_HILOGD("CheckAndSendQueuePrintJob end.");
1755     return E_PRINT_NONE;
1756 }
1757 
IsQueuedJobListEmpty(const std::string & jobId)1758 bool PrintServiceAbility::IsQueuedJobListEmpty(const std::string &jobId)
1759 {
1760     auto userData = GetUserDataByJobId(jobId);
1761     if (userData == nullptr) {
1762         PRINT_HILOGE("Get user data failed.");
1763         return false;
1764     }
1765     if (!userData->queuedJobList_.empty()) {
1766         PRINT_HILOGD("This user still has print jobs in progress.");
1767         return false;
1768     }
1769     if (GetUserIdByJobId(jobId) != currentUserId_) {
1770         PRINT_HILOGE("The user corresponding to this task is different from the current user.");
1771         return false;
1772     }
1773     return true;
1774 }
1775 
ReportCompletedPrint(const std::string & printerId)1776 void PrintServiceAbility::ReportCompletedPrint(const std::string &printerId)
1777 {
1778     NotifyAppJobQueueChanged(QUEUE_JOB_LIST_COMPLETED);
1779     PRINT_HILOGD("no print job exists, destroy extension");
1780     PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
1781     if (queuedJobList_.size() == 0 && printAppCount_ == 0) {
1782         UnloadSystemAbility();
1783     }
1784     json msg;
1785     auto endPrintTime = std::chrono::high_resolution_clock::now();
1786     auto printTime = std::chrono::duration_cast<std::chrono::milliseconds>(endPrintTime - startPrintTime_);
1787     msg["PRINT_TIME"] = printTime.count();
1788     msg["INGRESS_PACKAGE"] = ingressPackage;
1789     msg["STATUS"] = 0;
1790     HisysEventUtil::reportPrintSuccess(msg.dump());
1791 }
1792 
ReportHisysEvent(const std::shared_ptr<PrintJob> & jobInfo,const std::string & printerId,uint32_t subState)1793 int32_t PrintServiceAbility::ReportHisysEvent(
1794     const std::shared_ptr<PrintJob> &jobInfo, const std::string &printerId, uint32_t subState)
1795 {
1796     json msg;
1797     auto endPrintTime = std::chrono::high_resolution_clock::now();
1798     auto printTime = std::chrono::duration_cast<std::chrono::milliseconds>(endPrintTime - startPrintTime_);
1799     msg["PRINT_TIME"] = printTime.count();
1800     msg["INGRESS_PACKAGE"] = ingressPackage;
1801     if (isEprint(printerId)) {
1802         msg["PRINT_TYPE"] = 1;
1803     } else {
1804         msg["PRINT_TYPE"] = 0;
1805     }
1806 
1807     std::vector<uint32_t> fdList;
1808     jobInfo->GetFdList(fdList);
1809     msg["FILE_NUM"] = fdList.size();
1810     msg["PAGE_NUM"] = fdList.size();
1811     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
1812     if (printerInfo == nullptr) {
1813         msg["MODEL"] = "";
1814     } else {
1815         msg["MODEL"] = printerInfo->GetPrinterName();
1816     }
1817     msg["COPIES_SETTING"] = jobInfo->GetCopyNumber();
1818     std::string option = jobInfo->GetOption();
1819     PRINT_HILOGI("option:%{public}s", option.c_str());
1820     std::string jobDescription = "";
1821     if (option != "") {
1822         if (json::accept(option)) {
1823             json optionJson = json::parse(option);
1824             PRINT_HILOGI("optionJson: %{public}s", optionJson.dump().c_str());
1825             if (optionJson.contains("jobDescription") && optionJson["jobDescription"].is_string()) {
1826                 jobDescription = optionJson["jobDescription"].get<std::string>();
1827                 PRINT_HILOGI("jobDescription: %{public}s", jobDescription.c_str());
1828             }
1829         }
1830     }
1831     msg["JOB_DESCRIPTION"] = jobDescription;
1832     msg["PRINT_STYLE_SETTING"] = jobInfo->GetDuplexMode();
1833     msg["FAIL_REASON_CODE"] = subState;
1834     HisysEventUtil::faultPrint("PRINT_JOB_BLOCKED", msg.dump());
1835     return msg.size();
1836 }
1837 
NotifyAppJobQueueChanged(const std::string & applyResult)1838 void PrintServiceAbility::NotifyAppJobQueueChanged(const std::string &applyResult)
1839 {
1840     PRINT_HILOGD("NotifyAppJobQueueChanged started. %{public}s ", applyResult.c_str());
1841     AAFwk::Want want;
1842     want.SetAction(ACTION_QUEUE_JOB_LIST_CHANGED);
1843     want.SetParam(QUEUE_JOB_LIST_CHANGED, applyResult);
1844     EventFwk::CommonEventData commonData { want };
1845     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1846     PRINT_HILOGD("NotifyAppJobQueueChanged end.");
1847 }
1848 
isEprint(const std::string & printerId)1849 bool PrintServiceAbility::isEprint(const std::string &printerId)
1850 {
1851     std::string ePrintID = "ePrintID";
1852     if (printerId.length() < ePrintID.length()) {
1853         return false;
1854     }
1855     return std::equal(ePrintID.rbegin(), ePrintID.rend(), printerId.rbegin());
1856 }
1857 
UpdateExtensionInfo(const std::string & extInfo)1858 int32_t PrintServiceAbility::UpdateExtensionInfo(const std::string &extInfo)
1859 {
1860     ManualStart();
1861     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1862         PRINT_HILOGE("no permission to access print service");
1863         return E_PRINT_NO_PERMISSION;
1864     }
1865 
1866     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1867     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1868 
1869     PRINT_HILOGD("UpdateExtensionInfo started. %{public}s, extInfo [%{public}s]",
1870         extensionId.c_str(), extInfo.c_str());
1871     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1872     if (extensionList_.find(extensionId) == extensionList_.end()) {
1873         PRINT_HILOGD("Invalid extension id");
1874         return E_PRINT_INVALID_EXTENSION;
1875     }
1876     SendExtensionEvent(extensionId, extInfo);
1877     PRINT_HILOGD("UpdateExtensionInfo end.");
1878     return E_PRINT_NONE;
1879 }
1880 
RequestPreview(const PrintJob & jobInfo,std::string & previewResult)1881 int32_t PrintServiceAbility::RequestPreview(const PrintJob &jobInfo, std::string &previewResult)
1882 {
1883     ManualStart();
1884     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1885         PRINT_HILOGE("no permission to access print service");
1886         return E_PRINT_NO_PERMISSION;
1887     }
1888     PRINT_HILOGD("RequestPreview started.");
1889     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1890 
1891     auto userData = GetCurrentUserData();
1892     if (userData == nullptr) {
1893         PRINT_HILOGE("Get user data failed.");
1894         return E_PRINT_INVALID_USERID;
1895     }
1896     auto jobId = jobInfo.GetJobId();
1897     auto printerId = jobInfo.GetPrinterId();
1898     auto extensionId = PrintUtils::GetExtensionId(printerId);
1899 
1900     auto jobIt = userData->printJobList_.find(jobId);
1901     if (jobIt == userData->printJobList_.end()) {
1902         PRINT_HILOGD("invalid job id");
1903         return E_PRINT_INVALID_PRINTJOB;
1904     }
1905 
1906     if (userData->printJobList_[jobId] == nullptr) {
1907         PRINT_HILOGE("printJob is nullptr.");
1908         return E_PRINT_INVALID_PRINTJOB;
1909     }
1910     if (userData->printJobList_[jobId]->GetJobState() < PRINT_JOB_QUEUED) {
1911         PRINT_HILOGD("invalid job state [%{public}d]", userData->printJobList_[jobId]->GetJobState());
1912         return E_PRINT_INVALID_PRINTJOB;
1913     }
1914     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
1915     if (printerInfo == nullptr) {
1916         PRINT_HILOGD("invalid printer of the print job");
1917         return E_PRINT_INVALID_PRINTJOB;
1918     }
1919 
1920     std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_REQUEST_PREVIEW);
1921     if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
1922         PRINT_HILOGW("RequestPreview Not Register Yet!!!");
1923         return E_PRINT_SERVER_FAILURE;
1924     }
1925 
1926     userData->printJobList_[jobId]->UpdateParams(jobInfo);
1927     return E_PRINT_NONE;
1928 }
1929 
QueryPrinterCapability(const std::string & printerId)1930 int32_t PrintServiceAbility::QueryPrinterCapability(const std::string &printerId)
1931 {
1932     ManualStart();
1933     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1934         PRINT_HILOGE("no permission to access print service");
1935         return E_PRINT_NO_PERMISSION;
1936     }
1937     PRINT_HILOGD("QueryPrinterCapability started %{private}s", printerId.c_str());
1938     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1939     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
1940     if (printerInfo == nullptr) {
1941         PRINT_HILOGE("Invalid printer id");
1942         return E_PRINT_INVALID_PRINTER;
1943     }
1944 
1945     std::string extensionId = PrintUtils::GetExtensionId(printerId);
1946     std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_REQUEST_CAP);
1947     if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
1948         PRINT_HILOGW("QueryPrinterCapability Not Register Yet!!!");
1949         return E_PRINT_SERVER_FAILURE;
1950     }
1951 
1952     auto cbFunc = extCallbackMap_[cid];
1953     auto callback = [=]() {
1954         if (cbFunc != nullptr) {
1955             cbFunc->OnCallback(printerId);
1956         }
1957     };
1958     if (helper_->IsSyncMode()) {
1959         callback();
1960     } else {
1961         serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1962     }
1963     return E_PRINT_NONE;
1964 }
1965 
NotifyPrintServiceEvent(std::string & jobId,uint32_t event)1966 int32_t PrintServiceAbility::NotifyPrintServiceEvent(std::string &jobId, uint32_t event)
1967 {
1968     ManualStart();
1969     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1970         PRINT_HILOGE("no permission to access print service");
1971         return E_PRINT_NO_PERMISSION;
1972     }
1973 
1974     if (event < APPLICATION_CREATED || event > APPLICATION_CLOSED_FOR_CANCELED) {
1975         PRINT_HILOGE("Invalid parameter");
1976         return E_PRINT_INVALID_PARAMETER;
1977     }
1978 
1979     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1980     switch (event) {
1981         case APPLICATION_CREATED:
1982             if (printJobList_.find(jobId) == printJobList_.end()) {
1983                 PRINT_HILOGI("add printJob from phone, jobId: %{public}s", jobId.c_str());
1984                 auto printJob = std::make_shared<PrintJob>();
1985                 if (printJob == nullptr) {
1986                     PRINT_HILOGE("printJob is nullptr.");
1987                     return E_PRINT_SERVER_FAILURE;
1988                 }
1989                 printJob->SetJobId(jobId);
1990                 printJob->SetJobState(PRINT_JOB_PREPARED);
1991                 RegisterAdapterListener(jobId);
1992                 AddToPrintJobList(jobId, printJob);
1993                 SendPrintJobEvent(*printJob);
1994             }
1995             printAppCount_++;
1996             PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
1997             break;
1998         case APPLICATION_CLOSED_FOR_STARTED:
1999             ReduceAppCount();
2000             break;
2001         case APPLICATION_CLOSED_FOR_CANCELED:
2002             ReduceAppCount();
2003             break;
2004         default:
2005             break;
2006     }
2007     return E_PRINT_NONE;
2008 }
2009 
UnloadSystemAbility()2010 void PrintServiceAbility::UnloadSystemAbility()
2011 {
2012     PRINT_HILOGI("delay unload task begin");
2013     auto unloadTask = [this]() {
2014         std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2015         unloadCount_--;
2016         PRINT_HILOGI("do unload task, unloadCount_: %{public}u", unloadCount_);
2017         if (printAppCount_ != 0 || queuedJobList_.size() > 0 || unloadCount_ != 0) {
2018             PRINT_HILOGE("There are still print jobs being executed.");
2019             return;
2020         }
2021         NotifyAppJobQueueChanged(QUEUE_JOB_LIST_UNSUBSCRIBE);
2022         int32_t ret = DestroyExtension();
2023         if (ret != E_PRINT_NONE) {
2024             PRINT_HILOGE("DestroyExtension failed.");
2025             return;
2026         }
2027 #ifdef CUPS_ENABLE
2028         DelayedSingleton<PrintCupsClient>::GetInstance()->StopCupsdService();
2029 #endif // CUPS_ENABLE
2030         auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2031         if (samgrProxy == nullptr) {
2032             PRINT_HILOGE("get samgr failed");
2033             return;
2034         }
2035         ret = samgrProxy->UnloadSystemAbility(PRINT_SERVICE_ID);
2036         if (ret != ERR_OK) {
2037             PRINT_HILOGE("unload print system ability failed");
2038             return;
2039         }
2040         PRINT_HILOGI("unload print system ability successfully");
2041     };
2042     serviceHandler_->PostTask(unloadTask, UNLOAD_SA_INTERVAL);
2043     unloadCount_++;
2044     PRINT_HILOGI("unloadCount_: %{public}u", unloadCount_);
2045 }
2046 
CheckPermission(const std::string & permissionName)2047 bool PrintServiceAbility::CheckPermission(const std::string &permissionName)
2048 {
2049     if (helper_ == nullptr) {
2050         return false;
2051     }
2052     return helper_->CheckPermission(permissionName);
2053 }
2054 
RegisterPrinterCallback(const std::string & type,const sptr<IPrintCallback> & listener)2055 int32_t PrintServiceAbility::RegisterPrinterCallback(const std::string &type, const sptr<IPrintCallback> &listener)
2056 {
2057     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2058         PRINT_HILOGE("no permission to access print service");
2059         return E_PRINT_NO_PERMISSION;
2060     }
2061     if (listener == nullptr) {
2062         PRINT_HILOGE("Invalid listener");
2063         return E_PRINT_INVALID_PARAMETER;
2064     }
2065     int64_t callerTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
2066     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2067     auto iter = printUserDataMap_.find(callerTokenId);
2068     if (iter == printUserDataMap_.end() || iter->second == nullptr) {
2069         PRINT_HILOGE("Invalid token");
2070         return E_PRINT_INVALID_TOKEN;
2071     }
2072     iter->second->RegisterPrinterCallback(type, listener);
2073     PRINT_HILOGD("PrintServiceAbility::RegisterPrinterCallback end.");
2074     return E_PRINT_NONE;
2075 }
2076 
UnregisterPrinterCallback(const std::string & type)2077 int32_t PrintServiceAbility::UnregisterPrinterCallback(const std::string &type)
2078 {
2079     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2080         PRINT_HILOGE("no permission to access print service");
2081         return E_PRINT_NO_PERMISSION;
2082     }
2083     int64_t callerTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
2084     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2085     auto iter = printUserDataMap_.find(callerTokenId);
2086     if (iter == printUserDataMap_.end() || iter->second == nullptr) {
2087         PRINT_HILOGE("Invalid token");
2088         return E_PRINT_INVALID_TOKEN;
2089     }
2090     iter->second->UnregisterPrinterCallback(type);
2091     PRINT_HILOGD("PrintServiceAbility::UnregisterPrinterCallback end.");
2092     if (type == PRINTER_CHANGE_EVENT_TYPE) {
2093         ReduceAppCount();
2094     }
2095     return E_PRINT_NONE;
2096 }
2097 
RegisterExtCallback(const std::string & extensionCID,const sptr<IPrintExtensionCallback> & listener)2098 int32_t PrintServiceAbility::RegisterExtCallback(const std::string &extensionCID,
2099     const sptr<IPrintExtensionCallback> &listener)
2100 {
2101     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2102         PRINT_HILOGE("no permission to access print service");
2103         return E_PRINT_NO_PERMISSION;
2104     }
2105     std::string extensionId = "";
2106     uint32_t callbackId = 0;
2107     if (!PrintUtils::DecodeExtensionCid(extensionCID, extensionId, callbackId)) {
2108         PRINT_HILOGE("Failed to decode extension");
2109         return E_PRINT_INVALID_PARAMETER;
2110     }
2111 
2112     PRINT_HILOGD("extensionCID = %{public}s, extensionId = %{public}s", extensionCID.c_str(), extensionId.c_str());
2113 
2114     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2115     auto extensionStateIt = extensionStateList_.find(extensionId);
2116     if (extensionStateIt == extensionStateList_.end()) {
2117         PRINT_HILOGE("Invalid extension id");
2118         return E_PRINT_INVALID_EXTENSION;
2119     }
2120 
2121     if (extensionStateIt->second != PRINT_EXTENSION_LOADING) {
2122         PRINT_HILOGE("Invalid Extension State [%{public}d]", extensionStateIt->second);
2123         return E_PRINT_INVALID_EXTENSION;
2124     }
2125 
2126     PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback started.");
2127     if (callbackId >= PRINT_EXTCB_MAX) {
2128         PRINT_HILOGE("Invalid callback id [%{public}d]", callbackId);
2129         return E_PRINT_INVALID_PARAMETER;
2130     }
2131 
2132     if (listener == nullptr) {
2133         PRINT_HILOGE("Invalid listener");
2134         return E_PRINT_INVALID_PARAMETER;
2135     }
2136 
2137     if (extCallbackMap_.find(extensionCID) == extCallbackMap_.end()) {
2138         extCallbackMap_.insert(std::make_pair(extensionCID, listener));
2139     } else {
2140         PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback Replace listener.");
2141         extCallbackMap_[extensionCID] = listener;
2142     }
2143 
2144     PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback end.");
2145     return E_PRINT_NONE;
2146 }
2147 
UnregisterAllExtCallback(const std::string & extensionId)2148 int32_t PrintServiceAbility::UnregisterAllExtCallback(const std::string &extensionId)
2149 {
2150     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2151         PRINT_HILOGE("no permission to access print service");
2152         return E_PRINT_NO_PERMISSION;
2153     }
2154 
2155     PRINT_HILOGD("PrintServiceAbility::UnregisterAllExtCallback started.");
2156     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2157     for (uint32_t callbackId = PRINT_EXTCB_START_DISCOVERY; callbackId < PRINT_EXTCB_MAX; callbackId++) {
2158         std::string cid = PrintUtils::EncodeExtensionCid(extensionId, callbackId);
2159         auto callbackIt = extCallbackMap_.find(cid);
2160         if (callbackIt != extCallbackMap_.end()) {
2161             extCallbackMap_.erase(callbackIt);
2162         }
2163     }
2164     PRINT_HILOGD("PrintServiceAbility::UnregisterAllExtCallback end.");
2165     return E_PRINT_NONE;
2166 }
2167 
LoadExtSuccess(const std::string & extensionId)2168 int32_t PrintServiceAbility::LoadExtSuccess(const std::string &extensionId)
2169 {
2170     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2171         PRINT_HILOGE("no permission to access print service");
2172         return E_PRINT_NO_PERMISSION;
2173     }
2174 
2175     PRINT_HILOGD("PrintServiceAbility::LoadExtSuccess started. extensionId=%{public}s:", extensionId.c_str());
2176     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2177     if (extensionStateList_.find(extensionId) == extensionStateList_.end()) {
2178         PRINT_HILOGE("Invalid extension id");
2179         return E_PRINT_INVALID_EXTENSION;
2180     }
2181 
2182     if (extensionStateList_[extensionId] != PRINT_EXTENSION_LOADING) {
2183         PRINT_HILOGE("Invalid Extension State");
2184         return E_PRINT_INVALID_EXTENSION;
2185     }
2186     extensionStateList_[extensionId] = PRINT_EXTENSION_LOADED;
2187 
2188     PRINT_HILOGD("Auto Stat Printer Discovery");
2189     auto callback = [=]() { DelayStartDiscovery(extensionId); };
2190     if (helper_->IsSyncMode()) {
2191         callback();
2192     } else {
2193         serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
2194     }
2195     PRINT_HILOGD("PrintServiceAbility::LoadExtSuccess end.");
2196     return E_PRINT_NONE;
2197 }
2198 
On(const std::string taskId,const std::string & type,const sptr<IPrintCallback> & listener)2199 int32_t PrintServiceAbility::On(const std::string taskId, const std::string &type, const sptr<IPrintCallback> &listener)
2200 {
2201     ManualStart();
2202     std::string permission = PERMISSION_NAME_PRINT;
2203     std::string eventType = type;
2204     if (type == PRINTER_EVENT_TYPE || type == PRINTJOB_EVENT_TYPE || type == EXTINFO_EVENT_TYPE) {
2205         permission = PERMISSION_NAME_PRINT_JOB;
2206     }
2207     if (!CheckPermission(permission)) {
2208         PRINT_HILOGE("no permission to access print service");
2209         return E_PRINT_NO_PERMISSION;
2210     }
2211     if (listener == nullptr) {
2212         PRINT_HILOGE("Invalid listener");
2213         return E_PRINT_INVALID_PARAMETER;
2214     }
2215     if (type == PRINT_CALLBACK_ADAPTER) {
2216         eventType = type;
2217     } else if (type == PRINTER_CHANGE_EVENT_TYPE || type == PRINTER_EVENT_TYPE) {
2218         int32_t userId = GetCurrentUserId();
2219         int32_t callerPid = IPCSkeleton::GetCallingPid();
2220         eventType = PrintUtils::GetEventTypeWithToken(userId, callerPid, type);
2221     }
2222     if (taskId != "") {
2223         eventType = PrintUtils::GetTaskEventId(taskId, type);
2224     }
2225     if (eventType == "") {
2226         PRINT_HILOGE("Invalid event type");
2227         return E_PRINT_INVALID_PARAMETER;
2228     }
2229     PRINT_HILOGD("PrintServiceAbility::On started. type=%{public}s", eventType.c_str());
2230     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2231     constexpr int32_t MAX_LISTENERS_COUNT = 1000;
2232     if (registeredListeners_.size() > MAX_LISTENERS_COUNT) {
2233         PRINT_HILOGE("Exceeded the maximum number of registration.");
2234         return E_PRINT_GENERIC_FAILURE;
2235     }
2236     if (registeredListeners_.find(eventType) == registeredListeners_.end()) {
2237         registeredListeners_.insert(std::make_pair(eventType, listener));
2238     } else {
2239         PRINT_HILOGD("PrintServiceAbility::On Replace listener.");
2240         registeredListeners_[eventType] = listener;
2241     }
2242     HandlePrinterStateChangeRegister(eventType);
2243     HandlePrinterChangeRegister(eventType);
2244     return E_PRINT_NONE;
2245 }
2246 
Off(const std::string taskId,const std::string & type)2247 int32_t PrintServiceAbility::Off(const std::string taskId, const std::string &type)
2248 {
2249     std::string permission = PERMISSION_NAME_PRINT;
2250     if (type == PRINTJOB_EVENT_TYPE || type == EXTINFO_EVENT_TYPE || type == PRINTER_EVENT_TYPE) {
2251         permission = PERMISSION_NAME_PRINT_JOB;
2252     }
2253     std::string eventType = type;
2254     if (taskId != "") {
2255         eventType = PrintUtils::GetTaskEventId(taskId, type);
2256     }
2257     if (type == PRINTER_CHANGE_EVENT_TYPE||type == PRINTER_EVENT_TYPE) {
2258         int32_t userId = GetCurrentUserId();
2259         int32_t callerPid = IPCSkeleton::GetCallingPid();
2260         eventType = PrintUtils::GetEventTypeWithToken(userId, callerPid, type);
2261     }
2262     if (!CheckPermission(permission)) {
2263         PRINT_HILOGE("no permission to access print service");
2264         return E_PRINT_NO_PERMISSION;
2265     }
2266 
2267     if (eventType == "") {
2268         PRINT_HILOGE("Invalid event type");
2269         return E_PRINT_INVALID_PARAMETER;
2270     }
2271 
2272     PRINT_HILOGD("PrintServiceAbility::Off started.");
2273     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2274     auto iter = registeredListeners_.find(eventType);
2275     if (iter != registeredListeners_.end()) {
2276         PRINT_HILOGD("PrintServiceAbility::Off delete type=%{public}s object message.", eventType.c_str());
2277         registeredListeners_.erase(iter);
2278         if (PrintUtils::GetEventType(eventType) == PRINTER_CHANGE_EVENT_TYPE) {
2279             ReduceAppCount();
2280         }
2281         return E_PRINT_NONE;
2282     }
2283     return E_PRINT_INVALID_PARAMETER;
2284 }
2285 
StartAbility(const AAFwk::Want & want)2286 bool PrintServiceAbility::StartAbility(const AAFwk::Want &want)
2287 {
2288     if (helper_ == nullptr) {
2289         return false;
2290     }
2291     return helper_->StartAbility(want);
2292 }
2293 
ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo & extInfo)2294 PrintExtensionInfo PrintServiceAbility::ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo &extInfo)
2295 {
2296     PrintExtensionInfo printExtInfo;
2297     printExtInfo.SetExtensionId(extInfo.bundleName);
2298     printExtInfo.SetVendorId(extInfo.bundleName);
2299     printExtInfo.SetVendorName(extInfo.bundleName);
2300     printExtInfo.SetVendorIcon(0);
2301     printExtInfo.SetVersion("1.0.0");
2302     return printExtInfo;
2303 }
2304 
SendPrinterDiscoverEvent(int event,const PrinterInfo & info)2305 int32_t PrintServiceAbility::SendPrinterDiscoverEvent(int event, const PrinterInfo &info)
2306 {
2307     int32_t num = 0;
2308     PRINT_HILOGD("PrintServiceAbility::SendPrinterDiscoverEvent type %{private}s, %{public}d",
2309         info.GetPrinterId().c_str(), event);
2310     for (auto &item : printUserDataMap_) {
2311         if (item.second != nullptr) {
2312             item.second->SendPrinterEvent(PRINTER_DISCOVER_EVENT_TYPE, event, info);
2313             num++;
2314         }
2315     }
2316     return num;
2317 }
2318 
SendPrinterChangeEvent(int event,const PrinterInfo & info)2319 int32_t PrintServiceAbility::SendPrinterChangeEvent(int event, const PrinterInfo &info)
2320 {
2321     int32_t num = 0;
2322     PRINT_HILOGD("PrintServiceAbility::SendPrinterChangeEvent type %{private}s, %{public}d",
2323         info.GetPrinterId().c_str(), event);
2324     for (auto &item : printUserDataMap_) {
2325         if (item.second != nullptr) {
2326             item.second->SendPrinterEvent(PRINTER_CHANGE_EVENT_TYPE, event, info);
2327             num++;
2328         }
2329     }
2330     return num;
2331 }
2332 
SendPrinterEvent(const PrinterInfo & info)2333 void PrintServiceAbility::SendPrinterEvent(const PrinterInfo &info)
2334 {
2335     PRINT_HILOGD("PrintServiceAbility::SendPrinterEvent type %{private}s, %{public}d",
2336                  info.GetPrinterId().c_str(), info.GetPrinterState());
2337     for (auto eventIt: registeredListeners_) {
2338         if (PrintUtils::GetEventType(eventIt.first) == PRINTER_EVENT_TYPE && eventIt.second != nullptr) {
2339             PRINT_HILOGD("PrintServiceAbility::SendPrinterEvent find PRINTER_EVENT_TYPE");
2340             eventIt.second->OnCallback(info.GetPrinterState(), info);
2341         }
2342     }
2343 }
2344 
SendPrinterEventChangeEvent(PrinterEvent printerEvent,const PrinterInfo & info,bool isSignalUser)2345 int32_t PrintServiceAbility::SendPrinterEventChangeEvent(
2346     PrinterEvent printerEvent, const PrinterInfo &info, bool isSignalUser)
2347 {
2348     int32_t num = 0;
2349     PRINT_HILOGD("PrintServiceAbility::SendPrinterEventChangeEvent printerId: %{public}s, printerEvent: %{public}d",
2350         info.GetPrinterId().c_str(), printerEvent);
2351     for (auto eventIt: registeredListeners_) {
2352         if (PrintUtils::GetEventType(eventIt.first) != PRINTER_CHANGE_EVENT_TYPE || eventIt.second == nullptr) {
2353             continue;
2354         }
2355         PRINT_HILOGD("PrintServiceAbility::SendPrinterEventChangeEvent eventType = %{public}s",
2356             eventIt.first.c_str());
2357         if (isSignalUser && CheckUserIdInEventType(eventIt.first)) {
2358             PRINT_HILOGI("PrintServiceAbility::SendPrinterEventChangeEvent update info for a signal user");
2359             PrinterInfo newInfo(info);
2360             newInfo.SetIsLastUsedPrinter(true);
2361             eventIt.second->OnCallback(printerEvent, newInfo);
2362             num++;
2363         } else if (printerEvent == PRINTER_EVENT_LAST_USED_PRINTER_CHANGED) {
2364             if (CheckUserIdInEventType(eventIt.first)) {
2365                 PRINT_HILOGI("PrintServiceAbility::SendPrinterEventChangeEvent last used printer event");
2366                 eventIt.second->OnCallback(printerEvent, info);
2367                 num++;
2368             }
2369         } else {
2370             eventIt.second->OnCallback(printerEvent, info);
2371             num++;
2372         }
2373     }
2374     return num;
2375 }
2376 
SendPrintJobEvent(const PrintJob & jobInfo)2377 void PrintServiceAbility::SendPrintJobEvent(const PrintJob &jobInfo)
2378 {
2379     PRINT_HILOGD("PrintServiceAbility::SendPrintJobEvent jobId: %{public}s, state: %{public}d, subState: %{public}d",
2380         jobInfo.GetJobId().c_str(), jobInfo.GetJobState(), jobInfo.GetSubState());
2381     auto eventIt = registeredListeners_.find(PRINTJOB_EVENT_TYPE);
2382     if (eventIt != registeredListeners_.end() && eventIt->second != nullptr) {
2383         eventIt->second->OnCallback(jobInfo.GetJobState(), jobInfo);
2384     }
2385 
2386     // notify securityGuard
2387     if (jobInfo.GetJobState() == PRINT_JOB_COMPLETED) {
2388         auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(jobInfo.GetPrinterId());
2389         if (printerInfo != nullptr) {
2390             securityGuardManager_.receiveJobStateUpdate(jobInfo.GetJobId(), *printerInfo, jobInfo);
2391         } else {
2392             PRINT_HILOGD("receiveJobStateUpdate printer is empty");
2393         }
2394     }
2395 
2396     std::string stateInfo = "";
2397     if (jobInfo.GetJobState() == PRINT_JOB_BLOCKED) {
2398         stateInfo = EVENT_BLOCK;
2399     } else if (jobInfo.GetJobState() == PRINT_JOB_COMPLETED) {
2400         switch (jobInfo.GetSubState()) {
2401             case PRINT_JOB_COMPLETED_SUCCESS:
2402                 stateInfo = EVENT_SUCCESS;
2403                 break;
2404 
2405             case PRINT_JOB_COMPLETED_FAILED:
2406                 stateInfo = EVENT_FAIL;
2407                 break;
2408 
2409             case PRINT_JOB_COMPLETED_CANCELLED:
2410                 stateInfo = EVENT_CANCEL;
2411                 break;
2412             default:
2413                 break;
2414         }
2415     }
2416     if (stateInfo != "") {
2417         std::string taskEvent = PrintUtils::GetTaskEventId(jobInfo.GetJobId(), stateInfo);
2418         auto taskEventIt = registeredListeners_.find(taskEvent);
2419         if (taskEventIt != registeredListeners_.end() && taskEventIt->second != nullptr) {
2420             taskEventIt->second->OnCallback();
2421         }
2422     }
2423 }
2424 
SendExtensionEvent(const std::string & extensionId,const std::string & extInfo)2425 int32_t PrintServiceAbility::SendExtensionEvent(const std::string &extensionId, const std::string &extInfo)
2426 {
2427     int32_t num = 0;
2428     PRINT_HILOGD("PrintServiceAbility::SendExtensionEvent type %{public}s", extInfo.c_str());
2429     auto eventIt = registeredListeners_.find(EXTINFO_EVENT_TYPE);
2430     if (eventIt != registeredListeners_.end() && eventIt->second != nullptr) {
2431         eventIt->second->OnCallback(extensionId, extInfo);
2432         num++;
2433     }
2434     return num;
2435 }
2436 
SetHelper(const std::shared_ptr<PrintServiceHelper> & helper)2437 void PrintServiceAbility::SetHelper(const std::shared_ptr<PrintServiceHelper> &helper)
2438 {
2439     helper_ = helper;
2440     DelayedSingleton<PrintBMSHelper>::GetInstance()->SetHelper(helper_);
2441 }
2442 
CheckJobQueueBlocked(const PrintJob & jobInfo)2443 void PrintServiceAbility::CheckJobQueueBlocked(const PrintJob &jobInfo)
2444 {
2445     PRINT_HILOGD("CheckJobQueueBlocked started,isJobQueueBlocked_=%{public}s", isJobQueueBlocked_ ? "true" : "false");
2446     PRINT_HILOGD("CheckJobQueueBlocked %{public}s, %{public}d", jobInfo.GetJobId().c_str(), jobInfo.GetJobState());
2447     if (!isJobQueueBlocked_ && jobInfo.GetJobState() == PRINT_JOB_BLOCKED) {
2448         // going blocked
2449         isJobQueueBlocked_ = true;
2450         if (GetUserIdByJobId(jobInfo.GetJobId()) == currentUserId_) {
2451             NotifyAppJobQueueChanged(QUEUE_JOB_LIST_BLOCKED);
2452         }
2453     }
2454 
2455     if (isJobQueueBlocked_ && jobInfo.GetJobState() != PRINT_JOB_BLOCKED) {
2456         bool hasJobBlocked = false;
2457         auto userData = GetUserDataByJobId(jobInfo.GetJobId());
2458         if (userData == nullptr) {
2459             PRINT_HILOGE("Get user data failed.");
2460             return;
2461         }
2462         for (auto printJob : userData->queuedJobList_) {
2463             if (printJob.second->GetJobState() == PRINT_JOB_BLOCKED) {
2464                 hasJobBlocked = true;
2465                 break;
2466             }
2467         }
2468         if (!hasJobBlocked) {
2469             // clear blocked
2470             isJobQueueBlocked_ = false;
2471             if (GetUserIdByJobId(jobInfo.GetJobId()) == currentUserId_) {
2472                 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_CLEAR_BLOCKED);
2473             }
2474         }
2475     }
2476     PRINT_HILOGD("CheckJobQueueBlocked end,isJobQueueBlocked_=%{public}s", isJobQueueBlocked_ ? "true" : "false");
2477 }
2478 
PrintByAdapter(const std::string jobName,const PrintAttributes & printAttributes,std::string & taskId)2479 int32_t PrintServiceAbility::PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes,
2480     std::string &taskId)
2481 {
2482     ManualStart();
2483     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2484         PRINT_HILOGE("no permission to access print service");
2485         return E_PRINT_NO_PERMISSION;
2486     }
2487     PRINT_HILOGI("PrintServiceAbility::PrintByAdapter start");
2488 
2489     std::vector<std::string> fileList;
2490     std::vector<uint32_t> fdList;
2491     int32_t ret = CallSpooler(fileList, fdList, taskId);
2492     if (ret != E_PRINT_NONE) {
2493         PRINT_HILOGE("PrintServiceAbility::PrintByAdapter CallSpooler failed, ret: %{public}d", ret);
2494     }
2495     PRINT_HILOGI("PrintServiceAbility::PrintByAdapter end");
2496     return ret;
2497 }
2498 
StartGetPrintFile(const std::string & jobId,const PrintAttributes & printAttributes,const uint32_t fd)2499 int32_t PrintServiceAbility::StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes,
2500     const uint32_t fd)
2501 {
2502     ManualStart();
2503     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2504         PRINT_HILOGE("no permission to access print service");
2505         return E_PRINT_NO_PERMISSION;
2506     }
2507     PRINT_HILOGI("PrintServiceAbility::StartGetPrintFile start");
2508     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2509     auto eventIt = adapterListenersByJobId_.find(jobId);
2510     if (eventIt != adapterListenersByJobId_.end() && eventIt->second != nullptr) {
2511         PrintAttributes oldAttrs;
2512         auto attrIt = printAttributesList_.find(jobId);
2513         if (attrIt == printAttributesList_.end()) {
2514             printAttributesList_.insert(std::make_pair(jobId, printAttributes));
2515         } else {
2516             oldAttrs = attrIt->second;
2517             PRINT_HILOGD("PrintServiceAbility::StartGetPrintFile Replace printAttributes.");
2518             printAttributesList_[jobId] = printAttributes;
2519         }
2520 
2521         eventIt->second->OnCallbackAdapterLayout(jobId, oldAttrs, printAttributes, fd);
2522     } else {
2523         PRINT_HILOGW("PrintServiceAbility find event:%{public}s not found", PRINT_ADAPTER_EVENT_TYPE.c_str());
2524     }
2525     PRINT_HILOGI("PrintServiceAbility::StartGetPrintFile end");
2526     return E_PRINT_NONE;
2527 }
2528 
NotifyPrintService(const std::string & jobId,const std::string & type)2529 int32_t PrintServiceAbility::NotifyPrintService(const std::string &jobId, const std::string &type)
2530 {
2531     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2532         PRINT_HILOGE("no permission to access print service");
2533         return E_PRINT_NO_PERMISSION;
2534     }
2535 
2536     if (type == "0" || type == NOTIFY_INFO_SPOOLER_CLOSED_FOR_STARTED) {
2537         PRINT_HILOGI("Notify Spooler Closed for started jobId : %{public}s", jobId.c_str());
2538         notifyAdapterJobChanged(jobId, PRINT_JOB_SPOOLER_CLOSED, PRINT_JOB_SPOOLER_CLOSED_FOR_STARTED);
2539         ReduceAppCount();
2540         return E_PRINT_NONE;
2541     }
2542 
2543     if (type == NOTIFY_INFO_SPOOLER_CLOSED_FOR_CANCELLED) {
2544         PRINT_HILOGI("Notify Spooler Closed for canceled jobId : %{public}s", jobId.c_str());
2545         notifyAdapterJobChanged(jobId, PRINT_JOB_SPOOLER_CLOSED, PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED);
2546         ReduceAppCount();
2547         return E_PRINT_NONE;
2548     }
2549     return E_PRINT_INVALID_PARAMETER;
2550 }
2551 
ReduceAppCount()2552 void PrintServiceAbility::ReduceAppCount()
2553 {
2554     printAppCount_ = printAppCount_ >= 1 ? printAppCount_ - 1 : 0;
2555     PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
2556     if (printAppCount_ == 0 && queuedJobList_.size() == 0) {
2557         UnloadSystemAbility();
2558     }
2559 }
2560 
notifyAdapterJobChanged(const std::string jobId,const uint32_t state,const uint32_t subState)2561 void PrintServiceAbility::notifyAdapterJobChanged(const std::string jobId, const uint32_t state,
2562     const uint32_t subState)
2563 {
2564     if (state != PRINT_JOB_BLOCKED && state != PRINT_JOB_COMPLETED && state != PRINT_JOB_SPOOLER_CLOSED) {
2565         return;
2566     }
2567     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2568     auto attrIt = printAttributesList_.find(jobId);
2569     if (attrIt != printAttributesList_.end()) {
2570         printAttributesList_.erase(attrIt);
2571     }
2572 
2573     PRINT_HILOGI("get adapterListenersByJobId_ %{public}s", jobId.c_str());
2574     auto eventIt = adapterListenersByJobId_.find(jobId);
2575     if (eventIt == adapterListenersByJobId_.end() || eventIt->second == nullptr) {
2576         return;
2577     }
2578 
2579     uint32_t printAdapterListeningState = GetListeningState(state, subState);
2580     PRINT_HILOGI("notifyAdapterJobChanged for subState: %{public}d, listeningState: %{public}d",
2581         subState, printAdapterListeningState);
2582     eventIt->second->onCallbackAdapterJobStateChanged(jobId, state, printAdapterListeningState);
2583 
2584     if (subState == PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED || state == PRINT_JOB_COMPLETED) {
2585         PRINT_HILOGI("erase adapterListenersByJobId_ %{public}s", jobId.c_str());
2586         adapterListenersByJobId_.erase(jobId);
2587     }
2588 }
2589 
GetListeningState(const uint32_t subState)2590 uint32_t PrintServiceAbility::GetListeningState(const uint32_t subState)
2591 {
2592     switch (subState) {
2593         case PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED:
2594             return PREVIEW_ABILITY_DESTROY_FOR_CANCELED;
2595             break;
2596         case PRINT_JOB_SPOOLER_CLOSED_FOR_STARTED:
2597             return PREVIEW_ABILITY_DESTROY_FOR_STARTED;
2598             break;
2599         default:
2600             return PREVIEW_ABILITY_DESTROY;
2601             break;
2602     }
2603 }
2604 
GetListeningState(uint32_t state,uint32_t subState)2605 uint32_t PrintServiceAbility::GetListeningState(uint32_t state, uint32_t subState)
2606 {
2607     uint32_t printAdapterListeningState = PRINT_TASK_FAIL;
2608     if (state == PRINT_JOB_SPOOLER_CLOSED) {
2609         printAdapterListeningState = GetListeningState(subState);
2610     } else if (state == PRINT_JOB_BLOCKED) {
2611         printAdapterListeningState = PRINT_TASK_BLOCK;
2612     } else {
2613         switch (subState) {
2614             case PRINT_JOB_COMPLETED_SUCCESS:
2615                 printAdapterListeningState = PRINT_TASK_SUCCEED;
2616                 break;
2617             case PRINT_JOB_COMPLETED_FAILED:
2618                 printAdapterListeningState = PRINT_TASK_FAIL;
2619                 break;
2620             case PRINT_JOB_COMPLETED_CANCELLED:
2621                 printAdapterListeningState = PRINT_TASK_CANCEL;
2622                 break;
2623             default:
2624                 printAdapterListeningState = PRINT_TASK_FAIL;
2625                 break;
2626         }
2627     }
2628     return printAdapterListeningState;
2629 }
2630 
CallStatusBar()2631 int32_t PrintServiceAbility::CallStatusBar()
2632 {
2633     PRINT_HILOGI("PrintServiceAbility CallStatusBar enter.");
2634     ManualStart();
2635     if (!CheckPermission(PERMISSION_NAME_PRINT) && !CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2636         PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION);
2637         return E_PRINT_NO_PERMISSION;
2638     }
2639     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2640     AAFwk::Want want;
2641     want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_STATUS_BAR_ABILITY_NAME);
2642     int32_t callerTokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
2643     std::string callerPkg = SPOOLER_PACKAGE_NAME;
2644     ingressPackage = callerPkg;
2645     int32_t callerUid = IPCSkeleton::GetCallingUid();
2646     int32_t callerPid = IPCSkeleton::GetCallingPid();
2647     want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId);
2648     want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid);
2649     want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid);
2650     want.SetParam(CALLER_PKG_NAME, callerPkg);
2651     if (!StartPluginPrintIconExtAbility(want)) {
2652         PRINT_HILOGE("Failed to start PluginPrintIconExtAbility");
2653         return E_PRINT_SERVER_FAILURE;
2654     }
2655     return E_PRINT_NONE;
2656 }
2657 
StartPluginPrintIconExtAbility(const AAFwk::Want & want)2658 bool PrintServiceAbility::StartPluginPrintIconExtAbility(const AAFwk::Want &want)
2659 {
2660     if (helper_ == nullptr) {
2661         PRINT_HILOGE("Invalid print service helper.");
2662         return false;
2663     }
2664     PRINT_HILOGI("enter PrintServiceAbility::StartPluginPrintIconExtAbility");
2665     return helper_->StartPluginPrintIconExtAbility(want);
2666 }
2667 
GetCurrentUserData()2668 std::shared_ptr<PrintUserData> PrintServiceAbility::GetCurrentUserData()
2669 {
2670     int32_t userId = GetCurrentUserId();
2671     if (userId == E_PRINT_INVALID_USERID) {
2672         PRINT_HILOGE("Invalid user id.");
2673         return nullptr;
2674     }
2675     auto iter = printUserMap_.find(userId);
2676     if (iter == printUserMap_.end()) {
2677         PRINT_HILOGE("Current user is not added, add it.");
2678         UpdatePrintUserMap();
2679         iter = printUserMap_.find(userId);
2680         if (iter == printUserMap_.end()) {
2681             PRINT_HILOGE("add user failed.");
2682             return nullptr;
2683         }
2684     }
2685     return iter->second;
2686 }
2687 
GetCurrentUserId()2688 int32_t PrintServiceAbility::GetCurrentUserId()
2689 {
2690     int32_t userId = IPCSkeleton::GetCallingUid() / UID_TRANSFORM_DIVISOR;
2691     PRINT_HILOGI("Current userId = %{public}d", userId);
2692     if (userId < START_USER_ID) {
2693         PRINT_HILOGE("id %{public}d is system reserved", userId);
2694         return E_PRINT_INVALID_USERID;
2695     }
2696     if (userId > MAX_USER_ID) {
2697         PRINT_HILOGE("id %{public}d is out of range", userId);
2698         return E_PRINT_INVALID_USERID;
2699     }
2700     return userId;
2701 }
2702 
GetUserDataByJobId(const std::string jobId)2703 std::shared_ptr<PrintUserData> PrintServiceAbility::GetUserDataByJobId(const std::string jobId)
2704 {
2705     int32_t userId = GetUserIdByJobId(jobId);
2706     PRINT_HILOGI("the job is belong to user-%{public}d.", userId);
2707     if (userId == E_PRINT_INVALID_PRINTJOB) {
2708         PRINT_HILOGE("Invalid job id.");
2709         return nullptr;
2710     }
2711     auto iter = printUserMap_.find(userId);
2712     if (iter == printUserMap_.end()) {
2713         PRINT_HILOGE("Current user is not added.");
2714         UpdatePrintUserMap();
2715         iter = printUserMap_.find(userId);
2716         if (iter == printUserMap_.end()) {
2717             PRINT_HILOGE("add user failed.");
2718             return nullptr;
2719         }
2720     }
2721     return iter->second;
2722 }
2723 
GetUserIdByJobId(const std::string jobId)2724 int32_t PrintServiceAbility::GetUserIdByJobId(const std::string jobId)
2725 {
2726     for (std::map<std::string, int32_t>::iterator it = userJobMap_.begin(); it != userJobMap_.end();
2727          ++it) {
2728         PRINT_HILOGI("jobId: %{public}s, userId: %{public}d.", it->first.c_str(), it->second);
2729     }
2730     auto iter = userJobMap_.find(jobId);
2731     if (iter == userJobMap_.end()) {
2732         PRINT_HILOGE("Invalid job id.");
2733         return E_PRINT_INVALID_PRINTJOB;
2734     }
2735     return iter->second;
2736 }
2737 
UpdatePrintUserMap()2738 void PrintServiceAbility::UpdatePrintUserMap()
2739 {
2740     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2741     int32_t userId = GetCurrentUserId();
2742     if (userId == E_PRINT_INVALID_USERID) {
2743         PRINT_HILOGE("Invalid user id.");
2744         return;
2745     }
2746     PRINT_HILOGI("new user id: %{public}d.", userId);
2747     currentUserId_ = userId;
2748     auto iter = printUserMap_.find(userId);
2749     if (iter == printUserMap_.end()) {
2750         auto userData = std::make_shared<PrintUserData>();
2751         if (userData != nullptr) {
2752             printUserMap_.insert(std::make_pair(userId, userData));
2753             userData->SetUserId(userId);
2754             userData->ParseUserData();
2755             PRINT_HILOGI("add user success");
2756         }
2757     }
2758 }
2759 
AddToPrintJobList(const std::string jobId,const std::shared_ptr<PrintJob> & printjob)2760 void PrintServiceAbility::AddToPrintJobList(const std::string jobId, const std::shared_ptr<PrintJob> &printjob)
2761 {
2762     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2763     PRINT_HILOGD("begin AddToPrintJobList.");
2764     UpdatePrintUserMap();
2765     printJobList_.insert(std::make_pair(jobId, printjob));
2766     for (auto printjob : printJobList_) {
2767         PRINT_HILOGI("printjob in printJobList_, jobId: %{public}s.", printjob.first.c_str());
2768     }
2769     int32_t userId = GetCurrentUserId();
2770     auto userData = GetCurrentUserData();
2771     if (userData == nullptr) {
2772         PRINT_HILOGE("Get user data failed.");
2773         return;
2774     }
2775     userJobMap_.insert(std::make_pair(jobId, userId));
2776     userData->AddToPrintJobList(jobId, printjob);
2777 }
2778 
RegisterAdapterListener(const std::string & jobId)2779 void PrintServiceAbility::RegisterAdapterListener(const std::string &jobId)
2780 {
2781     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2782     PRINT_HILOGD("RegisterAdapterListener for jobId %{public}s", jobId.c_str());
2783     auto eventIt = registeredListeners_.find(PRINT_ADAPTER_EVENT_TYPE);
2784     if (eventIt != registeredListeners_.end()) {
2785         PRINT_HILOGI("adapterListenersByJobId_ set adapterListenersByJobId_ %{public}s", jobId.c_str());
2786         adapterListenersByJobId_.insert(std::make_pair(jobId, eventIt->second));
2787     }
2788 }
2789 
SetDefaultPrinter(const std::string & printerId,uint32_t type)2790 int32_t PrintServiceAbility::SetDefaultPrinter(const std::string &printerId, uint32_t type)
2791 {
2792     ManualStart();
2793     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2794         PRINT_HILOGE("no permission to access print service");
2795         return E_PRINT_NO_PERMISSION;
2796     }
2797     PRINT_HILOGD("SetDefaultPrinter started.");
2798     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2799 
2800     auto userData = GetCurrentUserData();
2801     if (userData == nullptr) {
2802         PRINT_HILOGE("Get user data failed.");
2803         return E_PRINT_INVALID_USERID;
2804     }
2805     int32_t ret = userData->SetDefaultPrinter(printerId, type);
2806     if (ret != E_PRINT_NONE) {
2807         PRINT_HILOGE("SetDefaultPrinter failed.");
2808         return ret;
2809     }
2810     return E_PRINT_NONE;
2811 }
2812 
CheckIsDefaultPrinter(const std::string & printerId)2813 bool PrintServiceAbility::CheckIsDefaultPrinter(const std::string &printerId)
2814 {
2815     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2816     auto userData = GetCurrentUserData();
2817     if (userData == nullptr) {
2818         PRINT_HILOGE("Get user data failed.");
2819         return false;
2820     }
2821     if (printerId != userData->GetDefaultPrinter()) {
2822         PRINT_HILOGE("is not default printer");
2823         return false;
2824     }
2825     return true;
2826 }
2827 
CheckIsLastUsedPrinter(const std::string & printerId)2828 bool PrintServiceAbility::CheckIsLastUsedPrinter(const std::string &printerId)
2829 {
2830     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2831     auto userData = GetCurrentUserData();
2832     if (userData == nullptr) {
2833         PRINT_HILOGE("Get user data failed.");
2834         return false;
2835     }
2836     if (printerId != userData->GetLastUsedPrinter()) {
2837         PRINT_HILOGE("is not last used printer.");
2838         return false;
2839     }
2840     return true;
2841 }
2842 
DeletePrinterFromCups(const std::string & printerName)2843 int32_t PrintServiceAbility::DeletePrinterFromCups(const std::string &printerName)
2844 {
2845     ManualStart();
2846     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2847         PRINT_HILOGE("no permission to access print service");
2848         return E_PRINT_NO_PERMISSION;
2849     }
2850     PRINT_HILOGD("DeletePrinterFromCups started.");
2851     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2852 #ifdef CUPS_ENABLE
2853     std::string standardName = PrintUtil::StandardizePrinterName(printerName);
2854     DelayedSingleton<PrintCupsClient>::GetInstance()->DeleteCupsPrinter(standardName.c_str());
2855 #endif  // CUPS_ENABLE
2856     std::string printerId = printSystemData_.QueryPrinterIdByStandardizeName(printerName);
2857 #ifdef IPPOVERUSB_ENABLE
2858     DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->DisConnectPrinter(printerId);
2859 #endif // IPPOVERUSB_ENABLE
2860     vendorManager.MonitorPrinterStatus(printerId, false);
2861     DeletePrinterFromUserData(printerId);
2862     NotifyAppDeletePrinter(printerId);
2863     printSystemData_.DeleteCupsPrinter(printerId);
2864     return E_PRINT_NONE;
2865 }
2866 
AddPrinterToDiscovery(const PrinterInfo & printerInfo)2867 int32_t PrintServiceAbility::AddPrinterToDiscovery(const PrinterInfo &printerInfo)
2868 {
2869     ManualStart();
2870     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2871         PRINT_HILOGE("no permission to access print service");
2872         return E_PRINT_NO_PERMISSION;
2873     }
2874     if (PrintUtil::startsWith(printerInfo.GetPrinterId(), "mdns://") &&
2875         vendorManager.FindDriverByVendorName(VENDOR_BSUNI_DRIVER) != nullptr) {
2876         PRINT_HILOGD("AddPrinterToDiscovery skip %{public}s", printerInfo.GetPrinterId().c_str());
2877         return E_PRINT_NONE;
2878     }
2879     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2880     PRINT_HILOGD("AddPrinterToDiscovery started. Current total size is %{public}zd",
2881         printSystemData_.GetDiscoveredPrinterCount());
2882     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
2883     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
2884 
2885     int32_t result = AddSinglePrinterInfo(printerInfo, extensionId);
2886 
2887     PRINT_HILOGD("AddPrinterToDiscovery end. New total size is %{public}zd",
2888         printSystemData_.GetDiscoveredPrinterCount());
2889     return result;
2890 }
2891 
UpdatePrinterInDiscovery(const PrinterInfo & printerInfo)2892 int32_t PrintServiceAbility::UpdatePrinterInDiscovery(const PrinterInfo &printerInfo)
2893 {
2894     ManualStart();
2895     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2896         PRINT_HILOGE("no permission to access print service");
2897         return E_PRINT_NO_PERMISSION;
2898     }
2899 
2900     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2901     std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
2902     PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
2903     int32_t ret = E_PRINT_NONE;
2904     if (!PrintUtil::startsWith(extensionId, PRINT_EXTENSION_BUNDLE_NAME)) {
2905         ret = AddPrinterToCups(printerInfo.GetUri(), printerInfo.GetPrinterName(), printerInfo.GetPrinterMake());
2906     }
2907     if (ret == E_PRINT_NONE) {
2908         UpdateSinglePrinterInfo(printerInfo, extensionId);
2909     }
2910     return E_PRINT_NONE;
2911 }
2912 
RemovePrinterFromDiscovery(const std::string & printerId)2913 int32_t PrintServiceAbility::RemovePrinterFromDiscovery(const std::string &printerId)
2914 {
2915     ManualStart();
2916     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2917         PRINT_HILOGE("no permission to access print service");
2918         return E_PRINT_NO_PERMISSION;
2919     }
2920     std::string printerUri;
2921     std::string extensionId;
2922     std::string printerExtId;
2923     std::shared_ptr<PrinterInfo> printerInfo;
2924     {
2925         std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2926         extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
2927         PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
2928         printerExtId = PrintUtils::GetGlobalId(extensionId, printerId);
2929         printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerExtId);
2930         if (printerInfo == nullptr) {
2931             PRINT_HILOGE("invalid printer id");
2932             return E_PRINT_INVALID_PRINTER;
2933         }
2934         printerUri = printerInfo->GetUri();
2935     }
2936     bool mdnsPrinter = printerId.find("mdns") != string::npos;
2937     const uint32_t waitTime = 1000;
2938     JobMonitorParam monitorParam{ nullptr, "", 0, printerUri, "", printerId };
2939     PRINT_HILOGD("printerid is %{public}s, printer type is %{public}d", printerId.c_str(), mdnsPrinter);
2940     // 连接类型为mdns且为spooler显示的已经连接的打印机才判断是否离线
2941     if (!printerUri.empty() && mdnsPrinter &&
2942         DelayedSingleton<PrintCupsClient>::GetInstance()->CheckPrinterOnline(&monitorParam, waitTime)) {
2943         PRINT_HILOGD("printer is online, do not remove.");
2944         return E_PRINT_INVALID_PRINTER;
2945     }
2946     PRINT_HILOGD("printer uri is empty or priter is offline, printerUri = %{public}s", printerUri.c_str());
2947     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2948     bool result = RemoveSinglePrinterInfo(PrintUtils::GetGlobalId(extensionId, printerId));
2949     return result ? E_PRINT_NONE : E_PRINT_INVALID_PRINTER;
2950 }
2951 
UpdatePrinterInSystem(const PrinterInfo & printerInfo)2952 int32_t PrintServiceAbility::UpdatePrinterInSystem(const PrinterInfo &printerInfo)
2953 {
2954     ManualStart();
2955     if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2956         PRINT_HILOGE("no permission to access print service");
2957         return E_PRINT_NO_PERMISSION;
2958     }
2959 
2960     std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2961     if (!UpdatePrinterSystemData(printerInfo)) {
2962         PRINT_HILOGE("UpdatePrinterSystemData failed");
2963         return E_PRINT_INVALID_PARAMETER;
2964     }
2965 
2966     printSystemData_.SaveCupsPrinterMap();
2967     return E_PRINT_NONE;
2968 }
2969 
QueryPPDInformation(const char * makeModel,std::vector<std::string> & ppds)2970 bool PrintServiceAbility::QueryPPDInformation(const char *makeModel, std::vector<std::string> &ppds)
2971 {
2972     DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPPDInformation(makeModel, ppds);
2973     return !ppds.empty();
2974 }
2975 
DeletePrinterFromUserData(const std::string & printerId)2976 void PrintServiceAbility::DeletePrinterFromUserData(const std::string &printerId)
2977 {
2978     std::vector<int32_t> allPrintUserList;
2979     printSystemData_.GetAllPrintUser(allPrintUserList);
2980     for (auto userId : allPrintUserList) {
2981         PRINT_HILOGI("DeletePrinterFromUserData userId %{public}d.", userId);
2982         auto iter = printUserMap_.find(userId);
2983         if (iter != printUserMap_.end()) {
2984             ChangeDefaultPrinterForDelete(iter->second, printerId);
2985         } else {
2986             auto userData = std::make_shared<PrintUserData>();
2987             userData->SetUserId(userId);
2988             userData->ParseUserData();
2989             ChangeDefaultPrinterForDelete(userData, printerId);
2990         }
2991     }
2992 }
2993 
ChangeDefaultPrinterForDelete(std::shared_ptr<PrintUserData> & userData,const std::string & printerId)2994 void PrintServiceAbility::ChangeDefaultPrinterForDelete(
2995     std::shared_ptr<PrintUserData> &userData, const std::string &printerId)
2996 {
2997     if (userData == nullptr) {
2998         PRINT_HILOGE("Get user data failed.");
2999         return;
3000     }
3001     userData->DeletePrinter(printerId);
3002     std::string defaultPrinterId = userData->GetDefaultPrinter();
3003     bool ret = userData->CheckIfUseLastUsedPrinterForDefault();
3004     PRINT_HILOGI("DeletePrinterFromUserData defaultPrinterId %{public}s.", defaultPrinterId.c_str());
3005     if (!strcmp(printerId.c_str(), defaultPrinterId.c_str())) {
3006         if (!ret) {
3007             userData->SetDefaultPrinter("", DELETE_DEFAULT_PRINTER);
3008         } else {
3009             userData->SetDefaultPrinter("", DELETE_LAST_USED_PRINTER);
3010         }
3011     }
3012 }
3013 
GetUserDataByUserId(int32_t userId)3014 std::shared_ptr<PrintUserData> PrintServiceAbility::GetUserDataByUserId(int32_t userId)
3015 {
3016     auto iter = printUserMap_.find(userId);
3017     if (iter == printUserMap_.end()) {
3018         PRINT_HILOGE("Current user is not added, add it.");
3019         auto userData = std::make_shared<PrintUserData>();
3020         if (userData != nullptr) {
3021             printUserMap_.insert(std::make_pair(userId, userData));
3022             userData->SetUserId(userId);
3023             userData->ParseUserData();
3024             PRINT_HILOGI("add user success");
3025             return userData;
3026         } else {
3027             return nullptr;
3028         }
3029     }
3030     return iter->second;
3031 }
3032 
DetermineUserJobStatus(const std::map<std::string,std::shared_ptr<PrintJob>> & jobList)3033 PrintJobState PrintServiceAbility::DetermineUserJobStatus(
3034     const std::map<std::string, std::shared_ptr<PrintJob>> &jobList)
3035 {
3036     bool hasBlocked = std::any_of(jobList.begin(), jobList.end(),
3037         [](const auto& pair) { return pair.second->GetJobState() == PRINT_JOB_BLOCKED; });
3038     if (hasBlocked) {
3039         return PRINT_JOB_BLOCKED;
3040     }
3041     bool allComplete = std::all_of(jobList.begin(), jobList.end(),
3042         [](const auto& pair) { return pair.second->GetJobState() == PRINT_JOB_COMPLETED; });
3043     if (allComplete) {
3044         return PRINT_JOB_COMPLETED;
3045     }
3046     return PRINT_JOB_RUNNING;
3047 }
3048 
NotifyAppDeletePrinter(const std::string & printerId)3049 void PrintServiceAbility::NotifyAppDeletePrinter(const std::string &printerId)
3050 {
3051     auto userData = GetCurrentUserData();
3052     if (userData == nullptr) {
3053         PRINT_HILOGE("Get user data failed.");
3054         return;
3055     }
3056     std::string dafaultPrinterId = userData->GetDefaultPrinter();
3057     PrinterInfo printerInfo;
3058     printSystemData_.QueryPrinterInfoById(printerId, printerInfo);
3059     std::string ops = printerInfo.GetOption();
3060     if (!json::accept(ops)) {
3061         PRINT_HILOGW("ops can not parse to json object");
3062         return;
3063     }
3064     nlohmann::json opsJson = json::parse(ops);
3065     opsJson["nextDefaultPrinter"] = dafaultPrinterId;
3066     printerInfo.SetOption(opsJson.dump());
3067     SendPrinterEventChangeEvent(PRINTER_EVENT_DELETED, printerInfo);
3068     SendPrinterChangeEvent(PRINTER_EVENT_DELETED, printerInfo);
3069 
3070     std::string lastUsedPrinterId = userData->GetLastUsedPrinter();
3071     if (!lastUsedPrinterId.empty()) {
3072         PrinterInfo lastUsedPrinterInfo;
3073         printSystemData_.QueryPrinterInfoById(lastUsedPrinterId, lastUsedPrinterInfo);
3074         PRINT_HILOGI("NotifyAppDeletePrinter lastUsedPrinterId = %{public}s", lastUsedPrinterId.c_str());
3075         SendPrinterEventChangeEvent(PRINTER_EVENT_LAST_USED_PRINTER_CHANGED, lastUsedPrinterInfo);
3076     }
3077 }
3078 
DiscoverUsbPrinters(std::vector<PrinterInfo> & printers)3079 int32_t PrintServiceAbility::DiscoverUsbPrinters(std::vector<PrinterInfo> &printers)
3080 {
3081     ManualStart();
3082     if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
3083         PRINT_HILOGE("no permission to access print service");
3084         return E_PRINT_NO_PERMISSION;
3085     }
3086     PRINT_HILOGD("DiscoverUsbPrinters started.");
3087 #ifdef CUPS_ENABLE
3088     int32_t ret = DelayedSingleton<PrintCupsClient>::GetInstance()->DiscoverUsbPrinters(printers);
3089     if (ret != E_PRINT_NONE) {
3090         PRINT_HILOGE("DiscoverUsbDevices failed.");
3091         return ret;
3092     }
3093 #endif  // CUPS_ENABLE
3094     PRINT_HILOGD("DiscoverUsbDevices printers size: %{public}zu", printers.size());
3095     return E_PRINT_NONE;
3096 }
3097 
AddSinglePrinterInfo(const PrinterInfo & info,const std::string & extensionId)3098 int32_t PrintServiceAbility::AddSinglePrinterInfo(const PrinterInfo &info, const std::string &extensionId)
3099 {
3100     if (printSystemData_.QueryDiscoveredPrinterInfoById(info.GetPrinterId()) != nullptr) {
3101         PRINT_HILOGE("duplicate printer id, ignore it");
3102         return E_PRINT_INVALID_PRINTER;
3103     }
3104 
3105     auto infoPtr = std::make_shared<PrinterInfo>(info);
3106     infoPtr->SetPrinterId(PrintUtils::GetGlobalId(extensionId, infoPtr->GetPrinterId()));
3107     PRINT_HILOGD("Printer ID = %{public}s", infoPtr->GetPrinterId().c_str());
3108     infoPtr->SetPrinterState(PRINTER_ADDED);
3109     printSystemData_.AddPrinterToDiscovery(infoPtr);
3110 
3111     SendPrinterDiscoverEvent(PRINTER_ADDED, *infoPtr);
3112     SendPrinterEvent(*infoPtr);
3113 
3114     if (printSystemData_.IsPrinterAdded(infoPtr->GetPrinterId()) &&
3115         !printSystemData_.CheckPrinterBusy(infoPtr->GetPrinterId())) {
3116         if (CheckPrinterUriDifferent(infoPtr)) {
3117             if (UpdateAddedPrinterInCups(infoPtr->GetPrinterId(), infoPtr->GetUri())) {
3118                 printSystemData_.UpdatePrinterUri(infoPtr);
3119                 printSystemData_.SaveCupsPrinterMap();
3120             }
3121         }
3122         infoPtr->SetPrinterStatus(PRINTER_STATUS_IDLE);
3123         printSystemData_.UpdatePrinterStatus(infoPtr->GetPrinterId(), PRINTER_STATUS_IDLE);
3124         SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *infoPtr);
3125         SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *infoPtr);
3126     }
3127 
3128     return E_PRINT_NONE;
3129 }
3130 
UpdateSinglePrinterInfo(const PrinterInfo & info,const std::string & extensionId)3131 bool PrintServiceAbility::UpdateSinglePrinterInfo(const PrinterInfo &info, const std::string &extensionId)
3132 {
3133     std::string printExtId = info.GetPrinterId();
3134     printExtId = PrintUtils::GetGlobalId(extensionId, printExtId);
3135 
3136     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printExtId);
3137     if (printerInfo == nullptr) {
3138         PRINT_HILOGE("invalid printer id, ignore it");
3139         return false;
3140     }
3141     *printerInfo = info;
3142     printerInfo->SetPrinterState(PRINTER_UPDATE_CAP);
3143     printerInfo->SetPrinterId(printExtId);
3144     printerInfo->Dump();
3145 
3146     bool isCapabilityUpdated = false;
3147     if (printerInfo->HasCapability()) {
3148         isCapabilityUpdated = UpdatePrinterCapability(printExtId, info);
3149     }
3150 
3151     if (isCapabilityUpdated) {
3152         SendPrinterEvent(*printerInfo);
3153         SendPrinterDiscoverEvent(PRINTER_UPDATE_CAP, *printerInfo);
3154         printSystemData_.SaveCupsPrinterMap();
3155     }
3156 
3157     return isCapabilityUpdated;
3158 }
3159 
RemoveSinglePrinterInfo(const std::string & printerId)3160 bool PrintServiceAbility::RemoveSinglePrinterInfo(const std::string &printerId)
3161 {
3162     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
3163     if (printerInfo == nullptr) {
3164         PRINT_HILOGE("invalid printer id, ignore it");
3165         return false;
3166     }
3167     printerInfo->SetPrinterState(PRINTER_REMOVED);
3168     SendPrinterDiscoverEvent(PRINTER_REMOVED, *printerInfo);
3169     SendPrinterEvent(*printerInfo);
3170     printSystemData_.RemovePrinterFromDiscovery(printerId);
3171 
3172     if (printSystemData_.IsPrinterAdded(printerId)) {
3173         printerInfo->SetPrinterStatus(PRINTER_STATUS_UNAVAILABLE);
3174         printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_UNAVAILABLE);
3175         SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3176         SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3177     }
3178     return true;
3179 }
3180 
AddVendorPrinterToDiscovery(const std::string & globalVendorName,const PrinterInfo & info)3181 bool PrintServiceAbility::AddVendorPrinterToDiscovery(const std::string &globalVendorName, const PrinterInfo &info)
3182 {
3183     PRINT_HILOGI("AddPrinterToDiscovery");
3184     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, info.GetPrinterId());
3185     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3186     if (printerInfo == nullptr) {
3187         PRINT_HILOGI("new printer, add it");
3188         printerInfo = std::make_shared<PrinterInfo>(info);
3189         if (printerInfo == nullptr) {
3190             PRINT_HILOGW("allocate printer info fail");
3191             return false;
3192         }
3193         OHOS::Print::CupsPrinterInfo cupsPrinter;
3194         if (printSystemData_.QueryCupsPrinterInfoByPrinterId(globalPrinterId, cupsPrinter)) {
3195             printerInfo->SetPrinterName(cupsPrinter.name);
3196         }
3197         printerInfo->SetPrinterId(globalPrinterId);
3198         printSystemData_.AddPrinterToDiscovery(printerInfo);
3199     }
3200     printerInfo->SetPrinterState(PRINTER_ADDED);
3201     SendPrinterDiscoverEvent(PRINTER_ADDED, *printerInfo);
3202     SendPrinterEvent(*printerInfo);
3203     if (printSystemData_.IsPrinterAdded(printerInfo->GetPrinterId()) &&
3204         !printSystemData_.CheckPrinterBusy(printerInfo->GetPrinterId())) {
3205         if (CheckPrinterUriDifferent(printerInfo) &&
3206             UpdateAddedPrinterInCups(printerInfo->GetPrinterId(), printerInfo->GetUri())) {
3207             printSystemData_.UpdatePrinterUri(printerInfo);
3208             printSystemData_.SaveCupsPrinterMap();
3209         }
3210         printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE);
3211         printSystemData_.UpdatePrinterStatus(printerInfo->GetPrinterId(), PRINTER_STATUS_IDLE);
3212         SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3213         SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3214     }
3215     return true;
3216 }
3217 
UpdateVendorPrinterToDiscovery(const std::string & globalVendorName,const PrinterInfo & info)3218 bool PrintServiceAbility::UpdateVendorPrinterToDiscovery(const std::string &globalVendorName, const PrinterInfo &info)
3219 {
3220     PRINT_HILOGI("UpdatePrinterToDiscovery");
3221     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, info.GetPrinterId());
3222     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3223     if (printerInfo == nullptr) {
3224         printerInfo = std::make_shared<PrinterInfo>(info);
3225         if (printerInfo == nullptr) {
3226             PRINT_HILOGW("invalid printer id, ingore it");
3227             return false;
3228         }
3229         printerInfo->SetPrinterId(globalPrinterId);
3230         printSystemData_.AddPrinterToDiscovery(printerInfo);
3231     } else {
3232         if (info.HasCapability()) {
3233             *printerInfo = info;
3234             printerInfo->SetPrinterId(globalPrinterId);
3235         }
3236     }
3237     OHOS::Print::CupsPrinterInfo cupsPrinter;
3238     if (printSystemData_.QueryCupsPrinterInfoByPrinterId(globalPrinterId, cupsPrinter)) {
3239         printerInfo->SetPrinterName(cupsPrinter.name);
3240     }
3241     printerInfo->SetPrinterState(PRINTER_UPDATE_CAP);
3242     SendPrinterDiscoverEvent(PRINTER_UPDATE_CAP, *printerInfo);
3243     SendPrinterEvent(*printerInfo);
3244     return true;
3245 }
3246 
RemoveVendorPrinterFromDiscovery(const std::string & globalVendorName,const std::string & printerId)3247 bool PrintServiceAbility::RemoveVendorPrinterFromDiscovery(const std::string &globalVendorName,
3248     const std::string &printerId)
3249 {
3250     PRINT_HILOGI("RemovePrinterFromDiscovery");
3251     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, printerId);
3252     return RemoveSinglePrinterInfo(globalPrinterId);
3253 }
3254 
AddVendorPrinterToCupsWithPpd(const std::string & globalVendorName,const std::string & printerId,const std::string & ppdData)3255 bool PrintServiceAbility::AddVendorPrinterToCupsWithPpd(const std::string &globalVendorName,
3256     const std::string &printerId, const std::string &ppdData)
3257 {
3258     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, printerId);
3259     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3260     if (printerInfo == nullptr) {
3261         PRINT_HILOGW("printerInfo is null");
3262         return false;
3263     }
3264     if (!printerInfo->HasCapability() || !printerInfo->HasUri() || !printerInfo->HasPrinterMake()) {
3265         PRINT_HILOGW("empty capability or invalid printer info");
3266         return false;
3267     }
3268     printerInfo->SetPrinterName(RenamePrinterWhenAdded(*printerInfo));
3269     CupsPrinterInfo info;
3270     info.name = printerInfo->GetPrinterName();
3271     info.uri = printerInfo->GetUri();
3272     info.maker = printerInfo->GetPrinterMake();
3273 #ifdef CUPS_ENABLE
3274     int32_t ret = E_PRINT_NONE;
3275     if (ppdData.empty()) {
3276         ret = DelayedSingleton<PrintCupsClient>::GetInstance()->AddPrinterToCups(info.uri, info.name, info.maker);
3277     } else {
3278         ret = DelayedSingleton<PrintCupsClient>::GetInstance()->AddPrinterToCupsWithPpd(info.uri, info.name,
3279             "Brocadesoft Universal Driver", ppdData);
3280     }
3281     if (ret != E_PRINT_NONE) {
3282         PRINT_HILOGW("AddPrinterToCups error = %{public}d.", ret);
3283         return false;
3284     }
3285 #endif // CUPS_ENABLE
3286     info.printerStatus = PRINTER_STATUS_IDLE;
3287     printerInfo->GetCapability(info.printerCapability);
3288     WritePrinterPreference(globalPrinterId, info.printerCapability);
3289     printerInfo->SetPrinterState(PRINTER_CONNECTED);
3290     printerInfo->SetIsLastUsedPrinter(true);
3291     printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE);
3292     SetLastUsedPrinter(globalPrinterId);
3293     if (printSystemData_.IsPrinterAdded(globalPrinterId)) {
3294         SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3295         SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3296     } else {
3297         printSystemData_.InsertCupsPrinter(globalPrinterId, info, true);
3298         printSystemData_.SaveCupsPrinterMap();
3299         SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, *printerInfo, true);
3300         SendPrinterChangeEvent(PRINTER_EVENT_ADDED, *printerInfo);
3301     }
3302     SendPrinterDiscoverEvent(PRINTER_CONNECTED, *printerInfo);
3303     vendorManager.MonitorPrinterStatus(globalPrinterId, true);
3304     return true;
3305 }
3306 
AddVendorPrinterToCupsWithSpecificPpd(const std::string & globalVendorName,const std::string & printerId,const std::string & ppdData)3307 bool PrintServiceAbility::AddVendorPrinterToCupsWithSpecificPpd(const std::string &globalVendorName,
3308     const std::string &printerId, const std::string &ppdData)
3309 {
3310     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, printerId);
3311     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3312     if (printerInfo == nullptr) {
3313         PRINT_HILOGW("printerInfo is null");
3314         return false;
3315     }
3316     printerInfo->SetPrinterName(RenamePrinterWhenAdded(*printerInfo));
3317     CupsPrinterInfo info;
3318     info.name = printerInfo->GetPrinterName();
3319     info.uri = printerInfo->GetUri();
3320     info.maker = printerInfo->GetPrinterMake();
3321 #ifdef CUPS_ENABLE
3322     int32_t ret = E_PRINT_NONE;
3323     ret = DelayedSingleton<PrintCupsClient>::GetInstance()->AddPrinterToCupsWithSpecificPpd(info.uri, info.name,
3324         ppdData);
3325     if (ret != E_PRINT_NONE) {
3326         PRINT_HILOGW("AddPrinterToCups error = %{public}d.", ret);
3327         return false;
3328     }
3329     PrinterCapability printerCaps;
3330     ret = DelayedSingleton<PrintCupsClient>::GetInstance()->
3331         QueryPrinterCapabilityFromPPD(printerInfo->GetPrinterName(), printerCaps);
3332     if (ret != E_PRINT_NONE) {
3333         PRINT_HILOGW("QueryPrinterCapabilityFromPPD error = %{public}d.", ret);
3334     }
3335     printerInfo->SetCapability(printerCaps);
3336 #endif // CUPS_ENABLE
3337     info.printerStatus = PRINTER_STATUS_IDLE;
3338     printerInfo->GetCapability(info.printerCapability);
3339     WritePrinterPreference(globalPrinterId, info.printerCapability);
3340     printerInfo->SetPrinterState(PRINTER_CONNECTED);
3341     printerInfo->SetIsLastUsedPrinter(true);
3342     printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE);
3343     SetLastUsedPrinter(globalPrinterId);
3344     if (printSystemData_.IsPrinterAdded(globalPrinterId)) {
3345         SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3346         SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3347     } else {
3348         printSystemData_.InsertCupsPrinter(globalPrinterId, info, true);
3349         printSystemData_.SaveCupsPrinterMap();
3350         SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, *printerInfo, true);
3351         SendPrinterChangeEvent(PRINTER_EVENT_ADDED, *printerInfo);
3352     }
3353     SendPrinterDiscoverEvent(PRINTER_CONNECTED, *printerInfo);
3354     vendorManager.MonitorPrinterStatus(globalPrinterId, true);
3355     return true;
3356 }
3357 
RemoveVendorPrinterFromCups(const std::string & globalVendorName,const std::string & printerId)3358 bool PrintServiceAbility::RemoveVendorPrinterFromCups(const std::string &globalVendorName,
3359     const std::string &printerId)
3360 {
3361     PRINT_HILOGI("RemovePrinterFromCups");
3362     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, printerId);
3363     CupsPrinterInfo cupsPrinter;
3364     if (!printSystemData_.QueryCupsPrinterInfoByPrinterId(globalPrinterId, cupsPrinter)) {
3365         PRINT_HILOGW("cannot find printer");
3366         return false;
3367     }
3368 #ifdef CUPS_ENABLE
3369     std::string standardName = PrintUtil::StandardizePrinterName(cupsPrinter.name);
3370     auto ret = DelayedSingleton<PrintCupsClient>::GetInstance()->DeleteCupsPrinter(standardName.c_str());
3371     if (ret != E_PRINT_NONE) {
3372         PRINT_HILOGW("DeleteCupsPrinter error = %{public}d.", ret);
3373         return false;
3374     }
3375 #endif  // CUPS_ENABLE
3376     vendorManager.MonitorPrinterStatus(globalPrinterId, false);
3377     DeletePrinterFromUserData(globalPrinterId);
3378     NotifyAppDeletePrinter(globalPrinterId);
3379     printSystemData_.DeleteCupsPrinter(globalPrinterId);
3380     return true;
3381 }
3382 
OnVendorStatusUpdate(const std::string & globalVendorName,const std::string & printerId,const PrinterVendorStatus & status)3383 bool PrintServiceAbility::OnVendorStatusUpdate(const std::string &globalVendorName, const std::string &printerId,
3384     const PrinterVendorStatus &status)
3385 {
3386     PRINT_HILOGD("OnVendorStatusUpdate: %{public}d", static_cast<int32_t>(status.state));
3387     auto globalPrinterId = PrintUtils::GetGlobalId(globalVendorName, printerId);
3388     PRINT_HILOGD("OnVendorStatusUpdate %{public}s", globalPrinterId.c_str());
3389     printSystemData_.UpdatePrinterStatus(globalPrinterId, static_cast<PrinterStatus>(status.state));
3390     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3391     if (printerInfo == nullptr) {
3392         PRINT_HILOGW("printer info missing");
3393         return false;
3394     }
3395     printerInfo->SetPrinterStatus(static_cast<uint32_t>(status.state));
3396     SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3397     SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
3398     return true;
3399 }
3400 
QueryPrinterCapabilityByUri(const std::string & uri,PrinterCapability & printerCap)3401 bool PrintServiceAbility::QueryPrinterCapabilityByUri(const std::string &uri, PrinterCapability &printerCap)
3402 {
3403 #ifdef CUPS_ENABLE
3404     return DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPrinterCapabilityByUri(uri, "", printerCap) ==
3405         E_PRINT_NONE;
3406 #else
3407     return false;
3408 #endif
3409 }
3410 
QueryPrinterStatusByUri(const std::string & uri,PrinterStatus & status)3411 bool PrintServiceAbility::QueryPrinterStatusByUri(const std::string &uri, PrinterStatus &status)
3412 {
3413 #ifdef CUPS_ENABLE
3414     return DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPrinterStatusByUri(uri, status) == E_PRINT_NONE;
3415 #else
3416     return false;
3417 #endif
3418 }
3419 
StartExtensionDiscovery(const std::vector<std::string> & extensionIds)3420 int32_t PrintServiceAbility::StartExtensionDiscovery(const std::vector<std::string> &extensionIds)
3421 {
3422     std::map<std::string, AppExecFwk::ExtensionAbilityInfo> abilityList;
3423     for (auto const &extensionId : extensionIds) {
3424         if (extensionList_.find(extensionId) != extensionList_.end()) {
3425             abilityList.insert(std::make_pair(extensionId, extensionList_[extensionId]));
3426         }
3427     }
3428 
3429     if (abilityList.empty() && extensionIds.size() > 0) {
3430         PRINT_HILOGW("No valid extension found");
3431         return E_PRINT_INVALID_EXTENSION;
3432     }
3433 
3434     if (extensionIds.empty()) {
3435         for (auto extension : extensionList_) {
3436             abilityList.insert(std::make_pair(extension.first, extension.second));
3437         }
3438     }
3439 
3440     if (abilityList.empty()) {
3441         PRINT_HILOGW("No extension found");
3442         return E_PRINT_INVALID_EXTENSION;
3443     }
3444 
3445     for (auto ability : abilityList) {
3446         AAFwk::Want want;
3447         want.SetElementName(ability.second.bundleName, ability.second.name);
3448         if (!StartAbility(want)) {
3449             PRINT_HILOGE("Failed to load extension %{public}s", ability.second.name.c_str());
3450             continue;
3451         }
3452         extensionStateList_[ability.second.bundleName] = PRINT_EXTENSION_LOADING;
3453     }
3454     PRINT_HILOGD("StartDiscoverPrinter end.");
3455     return E_PRINT_NONE;
3456 }
3457 
StartPrintJobInternal(const std::shared_ptr<PrintJob> & printJob)3458 int32_t PrintServiceAbility::StartPrintJobInternal(const std::shared_ptr<PrintJob> &printJob)
3459 {
3460     if (printJob == nullptr) {
3461         PRINT_HILOGW("printJob is null");
3462         return E_PRINT_SERVER_FAILURE;
3463     }
3464     if (isEprint(printJob->GetPrinterId())) {
3465         auto extensionId = PrintUtils::GetExtensionId(printJob->GetPrinterId());
3466         std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT);
3467         auto cbIter = extCallbackMap_.find(cid);
3468         if (cbIter == extCallbackMap_.end()) {
3469             return E_PRINT_SERVER_FAILURE;
3470         }
3471         auto cbFunc = cbIter->second;
3472         auto callback = [=]() {
3473             if (cbFunc != nullptr) {
3474                 StartPrintJobCB(printJob->GetJobId(), printJob);
3475                 cbFunc->OnCallback(*printJob);
3476                 CallStatusBar();
3477             }
3478         };
3479         if (helper_->IsSyncMode()) {
3480             callback();
3481         } else {
3482             serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
3483         }
3484     } else {
3485 #ifdef CUPS_ENABLE
3486         NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
3487         DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(*printJob);
3488         CallStatusBar();
3489 #endif  // CUPS_ENABLE
3490     }
3491     return E_PRINT_NONE;
3492 }
QueryVendorPrinterInfo(const std::string & globalPrinterId,PrinterInfo & info)3493 int32_t PrintServiceAbility::QueryVendorPrinterInfo(const std::string &globalPrinterId, PrinterInfo &info)
3494 {
3495     auto discoveredInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3496     if (discoveredInfo != nullptr && discoveredInfo->HasCapability()) {
3497         info = *discoveredInfo;
3498         return E_PRINT_NONE;
3499     }
3500     const int waitTimeout = 5000;
3501     if (!vendorManager.QueryPrinterInfo(globalPrinterId, waitTimeout)) {
3502         return E_PRINT_INVALID_PRINTER;
3503     }
3504     discoveredInfo = printSystemData_.QueryDiscoveredPrinterInfoById(globalPrinterId);
3505     if (discoveredInfo != nullptr && discoveredInfo->HasCapability()) {
3506         info = *discoveredInfo;
3507         return E_PRINT_NONE;
3508     }
3509     return E_PRINT_INVALID_PRINTER;
3510 }
3511 
TryConnectPrinterByIp(const std::string & params)3512 int32_t PrintServiceAbility::TryConnectPrinterByIp(const std::string &params)
3513 {
3514     if (!json::accept(params)) {
3515         PRINT_HILOGW("invalid params");
3516         return E_PRINT_INVALID_PRINTER;
3517     }
3518     nlohmann::json connectParamJson = json::parse(params, nullptr, false);
3519     if (connectParamJson.is_discarded()) {
3520         PRINT_HILOGW("json discarded");
3521         return E_PRINT_INVALID_PRINTER;
3522     }
3523     if (!connectParamJson.contains("ip") || !connectParamJson["ip"].is_string()) {
3524         PRINT_HILOGW("ip missing");
3525         return E_PRINT_INVALID_PRINTER;
3526     }
3527     std::string ip = connectParamJson["ip"].get<std::string>();
3528     std::string protocol = "auto";
3529     if (connectParamJson.contains("protocol") && connectParamJson["protocol"].is_string()) {
3530         protocol = connectParamJson["protocol"].get<std::string>();
3531     }
3532     vendorManager.SetConnectingPrinter(IP_AUTO, ip);
3533     if (!vendorManager.ConnectPrinterByIp(ip, protocol)) {
3534         PRINT_HILOGW("ConnectPrinterByIp fail");
3535         return E_PRINT_SERVER_FAILURE;
3536     }
3537     PRINT_HILOGD("connecting printer by ip success");
3538     return E_PRINT_NONE;
3539 }
3540 
HandlePrinterStateChangeRegister(const std::string & eventType)3541 void PrintServiceAbility::HandlePrinterStateChangeRegister(const std::string &eventType)
3542 {
3543     if (PrintUtils::GetEventType(eventType) == PRINTER_EVENT_TYPE) {
3544         PRINT_HILOGI("begin HandlePrinterStateChangeRegister");
3545         std::map <std::string, std::shared_ptr<PrinterInfo>> discoveredPrinterInfoList_ =
3546                 printSystemData_.GetDiscoveredPrinterInfo();
3547         for (const auto &pair: discoveredPrinterInfoList_) {
3548             std::string key = pair.first;
3549             std::shared_ptr <PrinterInfo> printerInfoPtr = pair.second;
3550             SendPrinterEvent(*printerInfoPtr);
3551         }
3552         PRINT_HILOGI("end HandlePrinterStateChangeRegister");
3553     }
3554 }
3555 
HandlePrinterChangeRegister(const std::string & eventType)3556 void PrintServiceAbility::HandlePrinterChangeRegister(const std::string &eventType)
3557 {
3558     if (PrintUtils::GetEventType(eventType) == PRINTER_CHANGE_EVENT_TYPE) {
3559         PRINT_HILOGD("begin HandlePrinterChangeRegister, StartDiscoverPrinter");
3560         std::vector <PrintExtensionInfo> extensionInfos;
3561         QueryAllExtension(extensionInfos);
3562         std::vector <std::string> extensionIds;
3563         StartDiscoverPrinter(extensionIds);
3564         printAppCount_++;
3565         PRINT_HILOGD("end HandlePrinterChangeRegister, printAppCount_: %{public}u", printAppCount_);
3566     }
3567 }
3568 
UpdateAddedPrinterInCups(const std::string & printerId,const std::string & printerUri)3569 bool PrintServiceAbility::UpdateAddedPrinterInCups(const std::string &printerId, const std::string &printerUri)
3570 {
3571     CupsPrinterInfo cupsPrinter;
3572     if (printSystemData_.QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinter)) {
3573         int32_t ret = DelayedSingleton<PrintCupsClient>::GetInstance()->
3574             AddPrinterToCups(printerUri, cupsPrinter.name, cupsPrinter.maker);
3575         if (ret != E_PRINT_NONE) {
3576             PRINT_HILOGE("UpdateAddedPrinterInCups error = %{public}d.", ret);
3577             return false;
3578         }
3579         return true;
3580     }
3581     return false;
3582 }
3583 
RenamePrinterWhenAdded(const PrinterInfo & info)3584 std::string PrintServiceAbility::RenamePrinterWhenAdded(const PrinterInfo &info)
3585 {
3586     static uint32_t repeatNameLimit = 10;
3587     if (printSystemData_.IsPrinterAdded(info.GetPrinterId())) { // 相同ID已添加,沿用之前的名字,更新信息
3588         return info.GetPrinterName();
3589     }
3590     std::vector<std::string> printerNameList;
3591     printSystemData_.GetAddedPrinterListFromSystemData(printerNameList);
3592     uint32_t nameIndex = 1;
3593     auto printerName = info.GetPrinterName();
3594     auto iter = printerNameList.begin();
3595     auto end = printerNameList.end();
3596     do {
3597         iter = std::find(iter, end, printerName);
3598         if (iter == end) {
3599             break;
3600         }
3601         printerName = info.GetPrinterName();
3602         printerName += " ";
3603         printerName += std::to_string(nameIndex);
3604         if (nameIndex == repeatNameLimit) {
3605             break;
3606         }
3607         ++nameIndex;
3608         iter = printerNameList.begin();
3609     } while (iter != end);
3610     return printerName;
3611 }
3612 
QueryDiscoveredPrinterInfoById(const std::string & printerId)3613 std::shared_ptr<PrinterInfo> PrintServiceAbility::QueryDiscoveredPrinterInfoById(const std::string &printerId)
3614 {
3615     return printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
3616 }
3617 
CheckUserIdInEventType(const std::string & type)3618 bool PrintServiceAbility::CheckUserIdInEventType(const std::string &type)
3619 {
3620     int32_t callerUserId = GetCurrentUserId();
3621     PRINT_HILOGD("callerUserId = %{public}d", callerUserId);
3622     if (PrintUtils::CheckUserIdInEventType(type, callerUserId)) {
3623         PRINT_HILOGD("find current user");
3624         return true;
3625     }
3626     return false;
3627 }
3628 
ConnectIppOverUsbPrinter(const std::string & printerId)3629 void PrintServiceAbility::ConnectIppOverUsbPrinter(const std::string &printerId)
3630 {
3631 #ifdef IPPOVERUSB_ENABLE
3632     auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
3633     if (printerInfo == nullptr) {
3634         PRINT_HILOGD("ConnectIppOverUsbPrinter get printer info failed.");
3635         return;
3636     }
3637     OHOS::Uri uri(printerInfo->GetUri());
3638     int32_t port = uri.GetPort();
3639     DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->ConnectPrinter(printerId, port);
3640 #endif
3641 }
3642 } // namespace OHOS::Print
3643