1 /*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #define MLOG_TAG "Mediatool"
17
18 #include "control_main.h"
19
20 #include <array>
21 #include <unistd.h>
22
23 #include "command/command.h"
24 #include "command_line.h"
25 #include "constant.h"
26 #include "directory_ex.h"
27 #include "exec_env.h"
28 #include "get_self_permissions.h"
29 #include "iservice_registry.h"
30 #include "media_log.h"
31 #include "medialibrary_errno.h"
32 #include "mimetype_utils.h"
33 #include "system_ability_definition.h"
34 #include "userfile_client_ex.h"
35
36 namespace OHOS {
37 namespace Media {
38 namespace MediaTool {
39
40 constexpr int32_t ROOT_UID = 0;
41
Finish()42 static void Finish()
43 {
44 UserFileClientEx::Clear();
45 }
46
Init(ExecEnv & env,const std::vector<std::string> & args)47 static int32_t Init(ExecEnv &env, const std::vector<std::string> &args)
48 {
49 env.args.assign(args.begin(), args.end());
50 std::array<char, PATH_MAX> buffer {0};
51 getcwd(buffer.data(), PATH_MAX);
52 env.workPath.append(buffer.data());
53 env.workPath = IncludeTrailingPathDelimiter(env.workPath);
54 env.isRoot = getuid() == ROOT_UID;
55 return Media::E_OK;
56 }
57
Main(const std::vector<std::string> & args)58 int32_t ControlMain::Main(const std::vector<std::string> &args)
59 {
60 ExecEnv env;
61 int32_t res = Init(env, args);
62 if (res != Media::E_OK) {
63 MEDIA_ERR_LOG("Init failed, res: %{public}d", res);
64 return res;
65 }
66 res = CommandLine::Parser(env);
67 if (res != Media::E_OK) {
68 MEDIA_ERR_LOG("Parse args failed, res: %{public}d", res);
69 return res;
70 }
71 do {
72 res = UserFileClientEx::Init();
73 if (res != Media::E_OK) {
74 MEDIA_ERR_LOG("UserfileClient init failed, res: %{public}d", res);
75 break;
76 }
77 std::unique_ptr<Command> cmd = Command::Create(env);
78 if (cmd == nullptr) {
79 res = Media::E_ERR;
80 MEDIA_ERR_LOG("Create command failed, res: %{public}d", res);
81 break;
82 }
83 MEDIA_INFO_LOG("Mediatool command prepare done, start to execute env:{%{public}s}",
84 env.ToStr().c_str());
85 res = cmd->Start(env);
86 if (res != Media::E_OK) {
87 MEDIA_ERR_LOG("Mediatool main error, res: %{public}d", res);
88 break;
89 }
90 } while (0);
91 Finish();
92 return res;
93 }
94 } // namespace MediaTool
95 } // namespace Media
96 } // namespace OHOS
97