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