• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { Constants } from '@ohos/common';
17import FileUtil from './FileUtil';
18import type common from '@ohos.app.ability.common';
19import CheckEmptyUtils, { Log, PrinterInfo } from '@ohos/common';
20
21const usedPrinterFileName: string = 'lastUsedPrinter';
22const TAG = 'Util';
23/**
24 * Util class
25 */
26export default class Util {
27
28  /**
29   * 是否为mdns打印
30   *
31   * @param printerId printerId
32   * @return result
33   */
34  public static isMdnsPrinter(printerId: string): boolean {
35    if (CheckEmptyUtils.checkStrIsEmpty(printerId)) {
36      return false;
37    }
38    return printerId.includes(Constants.MDNS_PRINTER);
39  }
40
41  /**
42   * 查询当前连接的Printer信息
43   *
44   * @param context 应用上下文
45   * @return printerInfo Printer信息
46   */
47  public static queryLastUsedPrinter(context: common.Context): string {
48    if (CheckEmptyUtils.isEmpty(context)) {
49      Log.warn(TAG, 'queryLastUsedPrinter failed:invalid param.');
50      return null;
51    }
52    let printerInfo = FileUtil.readStringFromFile(usedPrinterFileName, context);
53    if (!CheckEmptyUtils.checkStrIsEmpty(printerInfo)) {
54      return printerInfo;
55    }
56    return null;
57  }
58
59  /**
60   * 查询当前连接的PrinterId
61   *
62   * @param context 应用上下文
63   * @return PrinterId
64   */
65  public static getLastUsedPrinterId(context: common.Context): string {
66    let printerInfo = this.queryLastUsedPrinter(context);
67    if (CheckEmptyUtils.checkStrIsEmpty(printerInfo)) {
68      return null;
69    }
70    try {
71      let printer = JSON.parse(printerInfo);
72      return printer?.printerId?? null;
73    } catch (err) {
74      Log.error(TAG, 'getLastUsedPrinterId failed: parse error.');
75      return null;
76    }
77  }
78
79  /**
80   * 查询当前连接的PrinterInfo
81   *
82   * @param context 应用上下文
83   * @return PrinterId
84   */
85  public static getLastUsedPrinterInfo(context: common.Context): PrinterInfo {
86    let printerInfo = this.queryLastUsedPrinter(context);
87    if (CheckEmptyUtils.checkStrIsEmpty(printerInfo)) {
88      return null;
89    }
90    try {
91      let printer:PrinterInfo = JSON.parse(printerInfo);
92      return printer;
93    } catch (err) {
94      Log.error(TAG, 'getLastUsedPrinterInfo failed: parse error.');
95      return null;
96    }
97  }
98}