Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/tauri-cli/src/helpers/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub fn known_plugins() -> HashMap<&'static str, PluginMetadata> {
"fs",
"http",
"notification",
"ohos-permissions",
"os",
"process",
"shell",
Expand Down
5 changes: 5 additions & 0 deletions crates/tauri-cli/src/mobile/open_harmony/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ const BUILTIN_PLUGINS: &[(&str, &str, &str)] = &[
"@tauri/plugin-global-shortcut",
"GlobalShortcutPlugin",
),
(
"ohos-permissions",
"@tauri/plugin-ohos-permissions",
"OhosPermissionsPlugin",
),
];

pub fn detect_all_plugins(project_dir: &Path) -> Result<Vec<DetectedPlugin>> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"apiType": "stageMode",
"buildOption": {
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": false
}
}
}
},
"targets": [
{
"name": "default"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { harTasks } from '@ohos/hvigor-ohos-plugin';

export default {
system: harTasks,
plugins: []
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@tauri/plugin-ohos-permissions",
"version": "0.1.0",
"description": "OHOS permissions plugin for Tauri on OpenHarmony",
"main": "src/main/ets/index.ets",
"author": "Tauri Programme within The Commons Conservancy",
"license": "Apache-2.0 OR MIT",
"dependencies": {
"@tauri/app": "file:../tauri"
},
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { abilityAccessCtrl, bundleManager, common, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Plugin, Invoke } from '@tauri/app';

// ─── Permission name mapping ───

const PERMISSION_MAP: Record<string, Permissions> = {
'camera': 'ohos.permission.CAMERA',
'microphone': 'ohos.permission.MICROPHONE',
};

// ─── Plugin Implementation ───

export class OhosPermissionsPlugin extends Plugin {

getCommands(): Map<string, (invoke: Invoke) => void> {
const commands: Map<string, (invoke: Invoke) => void> = new Map();
commands.set('checkCameraPermission', (invoke: Invoke): void => { this.handleCheck(invoke, 'camera'); });
commands.set('requestCameraPermission', (invoke: Invoke): void => { this.handleRequest(invoke, 'camera'); });
commands.set('checkMicrophonePermission', (invoke: Invoke): void => { this.handleCheck(invoke, 'microphone'); });
commands.set('requestMicrophonePermission', (invoke: Invoke): void => { this.handleRequest(invoke, 'microphone'); });
return commands;
}

// ─── Generic check handler ───

private handleCheck(invoke: Invoke, permissionKey: string): void {
this.checkPermission(permissionKey).then((granted: boolean) => {
invoke.resolve(JSON.stringify(granted));
}).catch((err: BusinessError) => {
console.error('[OhosPermissionsPlugin] checkPermission failed for ' + permissionKey + ': ' + err.message);
invoke.resolve(JSON.stringify(false));
});
}

// ─── Generic request handler ───

private handleRequest(invoke: Invoke, permissionKey: string): void {
const ohosPermission = PERMISSION_MAP[permissionKey];
if (ohosPermission === undefined) {
invoke.reject('Unknown permission: ' + permissionKey);
return;
}

const permissions: Array<Permissions> = [ohosPermission];
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();

if (this.context === undefined || this.context === null) {
console.error('[OhosPermissionsPlugin] UIAbilityContext not available');
invoke.reject('UIAbilityContext not available');
return;
}

atManager.requestPermissionsFromUser(this.context, permissions).then((data) => {
const authResults: number[] = data.authResults;
if (authResults.length > 0 && authResults[0] === 0) {
invoke.resolve('');
} else {
console.warn('[OhosPermissionsPlugin] Permission ' + permissionKey + ' denied by user.');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [F3/spec] denial 分支仅 console.warn + invoke.resolve(''),未调用 atManager.requestPermissionOnSetting(this.context, [ohosPermission]) 引导用户到系统设置。

这与 spec(camera/microphone 的 “永久拒绝后引导设置” Scenario,SHALL 措辞)、design.md(Goals + R2)、tasks.md 3.4(标记 [x] 但 step ③ 未实现)三处冲突。

建议在此分支补上 requestPermissionOnSetting 调用;若该 API 对三方应用不可用,应同步更新 spec/design 并修正 tasks.md 3.4 状态。

invoke.resolve('');
}
}).catch((err: BusinessError) => {
console.error('[OhosPermissionsPlugin] requestPermissionsFromUser failed: code=' + err.code + ', message=' + err.message);
invoke.resolve('');
});
}

// ─── Core: check if a permission is granted ───

private async checkPermission(permissionKey: string): Promise<boolean> {
const ohosPermission = PERMISSION_MAP[permissionKey];
if (ohosPermission === undefined) {
throw new Error('Unknown permission: ' + permissionKey);
}

const tokenId = await this.getAccessTokenId();
const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();

const grantStatus: abilityAccessCtrl.GrantStatus =
await atManager.checkAccessToken(tokenId, ohosPermission);

return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
}

// ─── Core: get the app's access token ID ───

private async getAccessTokenId(): Promise<number> {
const bundleInfo: bundleManager.BundleInfo =
await bundleManager.getBundleInfoForSelf(
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
);
return bundleInfo.appInfo.accessTokenId;
}
}

export default OhosPermissionsPlugin;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { OhosPermissionsPlugin as default } from './Plugin';
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"module": {
"name": "ohospermissions",
"type": "har",
"deviceTypes": [
"default",
"phone",
"tablet",
"2in1"
],
"requestPermissions": [
{
"name": "ohos.permission.CAMERA",
"reason": "$string:ohos_permissions_camera_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.MICROPHONE",
"reason": "$string:ohos_permissions_microphone_reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
}
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"string": [
{
"name": "ohos_permissions_camera_reason",
"value": "This app needs camera access to take photos and record videos."
},
{
"name": "ohos_permissions_microphone_reason",
"value": "This app needs microphone access to record audio."
}
]
}
3 changes: 2 additions & 1 deletion examples/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"@tauri-apps/plugin-os": "file:../../../plugins-workspace/plugins/os",
"@tauri-apps/plugin-process": "file:../../../plugins-workspace/plugins/process",
"@tauri-apps/plugin-shell": "file:../../../plugins-workspace/plugins/shell",
"@tauri-apps/plugin-updater": "file:../../../plugins-workspace/plugins/updater"
"@tauri-apps/plugin-updater": "file:../../../plugins-workspace/plugins/updater",
"@tauri-apps/plugin-ohos-permissions": "file:../../../plugins-workspace/plugins/ohos-permissions"
},
"devDependencies": {
"@iconify-json/codicon": "^1.2.49",
Expand Down
1 change: 1 addition & 0 deletions examples/api/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ tauri-plugin-updater = { path = "../../../../plugins-workspace/plugins/updater"
tauri-plugin-autostart = { path = "../../../../plugins-workspace/plugins/autostart" }
tauri-plugin-log = { path = "../../../../plugins-workspace/plugins/log" }
tauri-plugin-notification = { path = "../../../../plugins-workspace/plugins/notification" }
tauri-plugin-ohos-permissions = { path = "../../../../plugins-workspace/plugins/ohos-permissions" }
sentry = { version = "0.42", default-features = false, features = ["reqwest", "rustls", "backtrace", "contexts", "panic", "debug-images"] }
tauri-plugin-sentry = { path = "../../../../sentry-tauri" }
chrono = "0.4"
Expand Down
3 changes: 2 additions & 1 deletion examples/api/src-tauri/capabilities/run-app.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@
"global-shortcut:allow-register",
"global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all",
"global-shortcut:allow-is-registered"
"global-shortcut:allow-is-registered",
"ohos-permissions:default"
]
}
3 changes: 2 additions & 1 deletion examples/api/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ pub fn run_app<R: Runtime, F: FnOnce(&App<R>) + Send + 'static>(
tauri_plugin_autostart::MacosLauncher::LaunchAgent,
None,
))
.plugin(tauri_plugin_global_shortcut::Builder::new().build());
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
.plugin(tauri_plugin_ohos_permissions::init());
}

#[cfg(target_env = "ohos")]
Expand Down
Loading
Loading