1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "create_zip.h"
17
18 #include <memory>
19 #include <tuple>
20
21 #include "app_log_wrapper.h"
22 #include "class_zip/zip_entity.h"
23 #include "class_zip/zip_n_exporter.h"
24 #include "common/common_func.h"
25 #include "common/file_utils.h"
26 #include "zip_entity.h"
27
28 namespace OHOS {
29 namespace AppExecFwk {
30 namespace LIBZIP {
31 using namespace std;
32
InstantiateZip(napi_env env)33 static NapiValue InstantiateZip(napi_env env)
34 {
35 napi_value objZip = NapiClass::InstantiateClass(env, ZipNExporter::className_, {});
36 if (!objZip) {
37 NapiBusinessError().ThrowErr(env, EFAULT);
38 return NapiValue();
39 }
40
41 auto zipEntity = NapiClass::GetEntityOf<ZipEntity>(env, objZip);
42 if (!zipEntity) {
43 NapiBusinessError().ThrowErr(env, EFAULT);
44 return NapiValue();
45 }
46
47 return { env, objZip };
48 }
49
Sync(napi_env env,napi_callback_info info)50 napi_value CreateZip::Sync(napi_env env, napi_callback_info info)
51 {
52 return InstantiateZip(env).val_;
53 }
54
Async(napi_env env,napi_callback_info info)55 napi_value CreateZip::Async(napi_env env, napi_callback_info info)
56 {
57 NapiFuncArg funcArg(env, info);
58 if (!funcArg.InitArgs(ArgumentCount::ZERO, ArgumentCount::ONE)) {
59 APP_LOGE("Number of arguments unmatched");
60 NapiBusinessError().ThrowErr(env, EINVAL);
61 return nullptr;
62 }
63
64 auto cbExec = [](napi_env env) -> NapiBusinessError {
65 return NapiBusinessError(ERRNO_NOERR);
66 };
67
68 auto cbCompl = [](napi_env env, NapiBusinessError err) -> NapiValue {
69 if (err) {
70 return { env, err.GetNapiErr(env) };
71 }
72 return InstantiateZip(env);
73 };
74
75 NapiValue thisVar(env, funcArg.GetThisVar());
76 if (funcArg.GetArgc() == ArgumentCount::ZERO) {
77 return NapiAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_CREATE_ZIP_NAME, cbExec, cbCompl).val_;
78 } else {
79 NapiValue cb(env, funcArg[ArgumentPosition::FIRST]);
80 return NapiAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_CREATE_ZIP_NAME, cbExec, cbCompl).val_;
81 }
82 }
83 } // namespace LIBZIP
84 } // namespace AppExecFwk
85 } // namespace OHOS