SettingsData支持多用户隔离

Signed-off-by: liminjie10 <liminjie10@huawei.com>
This commit is contained in:
liminjie10 2023-02-21 10:31:58 +08:00
parent 5f228180ae
commit 0c4d60ee81
14 changed files with 416 additions and 481 deletions

4
.gitignore vendored
View File

@ -1,4 +1,6 @@
/node_modules /node_modules
/local.properties /local.properties
/.idea /.idea
**/build **/build
/.hvigor
/.idea

View File

@ -1,14 +1,14 @@
{ {
"license":"ISC", "license": "ISC",
"devDependencies":{}, "devDependencies": {},
"name":"entry", "name": "entry",
"ohos":{ "ohos": {
"org":"huawei", "org": "huawei",
"directoryLevel":"module", "directoryLevel": "module",
"buildTool":"hvigor" "buildTool": "hvigor"
}, },
"description":"example description", "description": "example description",
"repository":{}, "repository": {},
"version":"1.0.0", "version": "1.0.0",
"dependencies":{} "dependencies": {}
} }

View File

@ -1,7 +0,0 @@
import AbilityStage from "@ohos.app.ability.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.info("[Demo] MyAbilityStage onCreate")
}
}

View File

@ -0,0 +1,13 @@
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
*/
import { Log } from '../Utils/Log';
import AbilityStage from "@ohos.app.ability.AbilityStage"
export default class DataAbilityStage extends AbilityStage {
onCreate() {
Log.I('DataAbilityStage onCreate');
globalThis.abilityContext = this.context;
}
}

View File

@ -0,0 +1,215 @@
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
*/
import Audio from '@ohos.multimedia.audio';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility';
import rpc from '@ohos.rpc';
import SettingsDataConfig from '../Utils/SettingsDataConfig';
import SettingsDBHelper from '../Utils/SettingsDBHelper';
import { Log } from '../Utils/Log';
import process from '@ohos.process';
import settings from '@ohos.settings';
let rdbStore;
let requests:any[] = [];
let SETTINGS_AUDIO_RINGTONE = "settings.audio.ringtone"
let SETTINGS_AUDIO_MEDIA = "settings.audio.media"
let SETTINGS_AUDIO_VOICE_CALL = "settings.audio.voicecall"
let trustList: Array<String> = [
settings.display.SCREEN_BRIGHTNESS_STATUS,
settings.display.AUTO_SCREEN_BRIGHTNESS,
settings.display.SCREEN_OFF_TIMEOUT
];
export default class DataExtAbility extends DataShareExtensionAbility {
onCreate(want) {
this.onInitialized();
}
onInitialized() {
Log.I('onInitialize start');
let context = globalThis.abilityContext;
if (context != null) {
SettingsDBHelper.getInstance().getRdbStore().then((rdb: any) => {
rdbStore = rdb;
for (let i = 0; i < requests.length; i++) {
let opt: string = requests[i]["operation"];
let columns = requests[i]["columns"];
let predicates = requests[i]["predicates"];
let value = requests[i]["value"];
if (opt == "insert") {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, function (err, ret) {
Log.I('onInitialized insert ret: ' + ret);
});
} else if (opt == "query") {
rdbStore.query(predicates, columns, function (err, resultSet) {
Log.I('onInitialized query ret: ' + JSON.stringify(resultSet));
});
} else if (opt == "update") {
rdbStore.update(value, predicates, function (err, ret) {
Log.I('onInitialized update ret: ' + ret);
});
}
}
}).catch(err => {
Log.E('onInitialize failed:' + JSON.stringify(err));
})
} else {
Log.I('onInitialize context error!');
}
Log.I('onInitialize end');
}
insert(uri, value, callback) {
Log.I('insert keyword = ' + value[SettingsDataConfig.FIELD_KEYWORD] + ' start:' + uri);
let rdbInsert = (GrantStatus) => {
if (!GrantStatus) {
callback(-1, 0);
return;
}
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD], value[SettingsDataConfig.FIELD_VALUE]);
if (rdbStore == null) {
let request = {
"operation": "insert", "columns": null, "predicates": null, value: value
};
Log.I('insert request = ' + JSON.stringify(request));
requests.push(request);
callback(-1, 0);
} else {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, function (err, ret) {
callback(err, ret);
Log.I('insert result: ' + ret);
});
}
}
try {
Log.I('Start to verify permissions.');
this.verifyPermission(value, rdbInsert);
} catch (err) {
Log.E('Insert Data error:' + JSON.stringify(err));
callback(-1, 0);
}
}
update(uri: string, predicates, value, callback) {
Log.I('update keyword = ' + value[SettingsDataConfig.FIELD_KEYWORD] + ' start:' + uri);
let rdbUpData = (GrantStatus) => {
if (!GrantStatus) {
callback(-1, 0);
return;
}
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD], value[SettingsDataConfig.FIELD_VALUE]);
if (rdbStore == null) {
let request = {
"operation": "update", "columns": null, "predicates": predicates, value: value
};
Log.I('update request = ' + JSON.stringify(request));
requests.push(request);
callback(-1, 0);
} else {
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates, function (err, ret) {
callback(err, ret);
Log.I('update result: ' + ret);
});
}
}
try {
Log.I('Start to verify permissions.');
this.verifyPermission(value, rdbUpData);
} catch (err) {
Log.E('upData error:' + JSON.stringify(err));
callback(-1, 0);
}
}
delete(uri: string, predicates, callback) {
Log.I('nothing to do');
}
query(uri: string, predicates, columns: Array<string>, callback) {
Log.I( 'query start uri:' + uri);
if (rdbStore == null) {
let request= {"operation":"query", "columns" : columns, "predicates" : predicates, value:""};
Log.I('query request = '+ JSON.stringify(request));
requests.push(request);
callback(-1, {"_napiwrapper":{}});
} else {
rdbStore.query(SettingsDataConfig.TABLE_NAME, predicates, columns, function (err, resultSet) {
callback(err, resultSet);
Log.I('query result: '+ JSON.stringify(resultSet.rowCount) +'columnNames'+ JSON.stringify(resultSet.columnNames));
});
}
}
private DoSystemSetting(settingsKey: string, settingsValue: string) {
switch (settingsKey) {
case SETTINGS_AUDIO_RINGTONE:
try {
let volumeType = Audio.AudioVolumeType.RINGTONE;
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Log.I('settings Promise returned to indicate a successful RINGTONE setting.')
});
} catch (err) {
Log.I('settings RINGTONE failed error = ' + JSON.stringify(err));
}
break
case SETTINGS_AUDIO_MEDIA:
try {
let volumeType = Audio.AudioVolumeType.MEDIA;
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Log.I('settings Promise returned to indicate a successful MEDIA setting.')
});
} catch (err) {
Log.I('settings MEDIA failed error = ' + JSON.stringify(err));
}
break
case SETTINGS_AUDIO_VOICE_CALL:
try {
let volumeType = Audio.AudioVolumeType.VOICE_CALL;
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Log.I('settings Promise returned to indicate a successful VOICE_CALL setting.')
});
} catch (err) {
Log.I('settings VOICE_CALL failed error = ' + JSON.stringify(err));
}
break
default:
Log.I(settingsKey + ' key is not audio');
break
}
}
private verifyPermission(value, callBack) {
if (this.isTrustList(value[SettingsDataConfig.FIELD_KEYWORD]) || process.uid == rpc.IPCSkeleton.getCallingUid()) {
callBack(true);
return;
}
try {
let tokenID = rpc.IPCSkeleton.getCallingTokenId();
Log.I('tokenID = ' + tokenID);
let grantStatus = abilityAccessCtrl.createAtManager().verifyAccessToken(tokenID, "ohos.permission.MANAGE_SECURE_SETTINGS");
grantStatus.then(data => {
if (data == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
Log.I('MANAGE_SECURE_SETTINGS active');
callBack(true);
} else {
Log.W('MANAGE_SECURE_SETTINGS grantStatus= ' + JSON.stringify(data));
callBack(false);
}
}).catch((err) => {
Log.E('tokenID = ' + tokenID + ' verifyAccessToken is failed: ' + JSON.stringify(err));
callBack(false);
})
} catch (err) {
Log.E('err = ' + JSON.stringify(err));
callBack(false);
}
}
private isTrustList(keyWord: String): boolean {
return trustList.includes(keyWord)
}
}

View File

@ -1,247 +0,0 @@
import Audio from '@ohos.multimedia.audio';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import bluetooth from '@ohos.bluetooth';
import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility';
import rpc from '@ohos.rpc';
import settings from '@ohos.settings';
import SettingsDataConfig from '../Utils/SettingsDataConfig';
import SettingsDBHelper from '../Utils/SettingsDBHelper';
import { Log } from '../Utils/Log';
import process from '@ohos.process';
let rdbStore;
let requests:any[] = [];
function DoSystemSetting(settingsKey: string, settingsValue: string) {
switch (settingsKey) {
case SettingsDataConfig.SettingsKey.SETTINGS_AUDIO_RINGTONE: {
try {
let volumeType = Audio.AudioVolumeType.RINGTONE;
Log.I('settings RINGTONE start')
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Log.I('settings Promise returned to indicate a successful RINGTONE setting.')
});
} catch (err) {
Log.I('settings RINGTONE failed error = ' + JSON.stringify(err));
}
}
break
case SettingsDataConfig.SettingsKey.SETTINGS_AUDIO_MEDIA: {
try {
let volumeType = Audio.AudioVolumeType.MEDIA;
Log.I('settings MEDIA start')
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Log.I('settings Promise returned to indicate a successful MEDIA setting.')
});
} catch (err) {
Log.I('settings MEDIA failed error = ' + JSON.stringify(err));
}
}
break
case SettingsDataConfig.SettingsKey.SETTINGS_AUDIO_VOICE_CALL: {
try {
let volumeType = Audio.AudioVolumeType.VOICE_CALL;
Log.I('settings VOICE_CALL start')
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Log.I('settings Promise returned to indicate a successful VOICE_CALL setting.')
});
} catch (err) {
Log.I('settings VOICE_CALL failed error = ' + JSON.stringify(err));
}
}
break
case settings.general.DEVICE_NAME: {
try {
let result = bluetooth.setLocalName(settingsValue);
Log.I('settings bluetooth_name res = ' + result)
} catch (err) {
Log.I('settings bluetooth_name failed, error = ' + JSON.stringify(err));
}
}
break
default: {
Log.I(settingsKey + ' key is not brightness or audio or deviceName');
}
}
}
function verifyPermission(callBack) {
if (process.uid == rpc.IPCSkeleton.getCallingUid()) {
callBack(true);
return;
}
try {
let tokenID = rpc.IPCSkeleton.getCallingTokenId();
Log.I('tokenID = ' + tokenID);
let grantStatus = abilityAccessCtrl.createAtManager().verifyAccessToken(tokenID, "ohos.permission.MANAGE_SECURE_SETTINGS");
grantStatus.then(data => {
if (data == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
Log.I('MANAGE_SECURE_SETTINGS active');
callBack(true);
} else {
Log.W('MANAGE_SECURE_SETTINGS grantStatus= ' + JSON.stringify(data));
callBack(false);
}
}).catch((err) => {
Log.E('tokenID = ' + tokenID + ' verifyAccessToken is failed: ' + JSON.stringify(err));
callBack(false);
})
} catch (err) {
Log.E('err = ' + JSON.stringify(err));
callBack(false);
}
}
function isTrustList(keyWord: String) {
let ret = -1;
let trustList: Array<String> = [
settings.display.SCREEN_BRIGHTNESS_STATUS,
settings.display.AUTO_SCREEN_BRIGHTNESS,
settings.display.SCREEN_OFF_TIMEOUT
];
ret = trustList.findIndex((trustItem) => {
return trustItem === keyWord
})
return ret != -1;
}
export default class UserDsExtAbility extends DataShareExtensionAbility {
onCreate(want) {
console.info('[ttt] [DataShareTest] <<Extension>> DataShareExtAbility onCreate, want:' + want.abilityName);
console.info('[ttt] [DataShareTest] <<Extension>> this.context:' + this.context);
globalThis.abilityContext = this.context;
this.onInitialized(null);
}
onInitialized (abilityInfo) {
Log.I('onInitialize getContext start');
let context = globalThis.abilityContext;
if(context != null) {
SettingsDBHelper.getInstance().getRdbStore().then((rdb: any) => {
Log.I(" onInitialized rdb:" + rdb);
rdbStore = rdb;
Log.I(" onInitialized requests:" + JSON.stringify(requests));
for (let i = 0; i < requests.length; i++) {
let opt: string = requests[i]["operation"];
let columns = requests[i]["columns"];
let predicates = requests[i]["predicates"];
let value = requests[i]["value"];
if (opt == "insert") {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, function (err, ret) {
Log.I('onInitialized insert ret: ' + ret);
});
} else if (opt == "query") {
rdbStore.query(predicates, columns, function (err, resultSet) {
Log.I('onInitialized query ret: ' + JSON.stringify(resultSet));
});
} else if (opt == "update") {
rdbStore.update(value, predicates, function (err, ret) {
Log.I('onInitialized update ret: ' + ret);
});
}
}
}).catch(err => {
Log.E('onInitialize failed:'+JSON.stringify(err));
})
Log.I('onInitialize end');
} else {
Log.I('onInitialize context error!');
}
}
insert(uri, value, callback) {
Log.I('insert keyword = ' + value["KEYWORD"] + ' start:' + uri);
let rdbInsert = (GrantStatus) => {
if (!GrantStatus) {
callback(-1, 0);
return;
}
DoSystemSetting(value["KEYWORD"], value["VALUE"]);
if (rdbStore == null) {
let request = {
"operation": "insert", "columns": null, "predicates": null, value: value
};
Log.I('insert request = ' + JSON.stringify(request));
requests.push(request);
callback(-1, 0);
} else {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, function (err, ret) {
Log.I('insert before callback ');
callback(err, ret);
Log.I('insert after callback ');
Log.I('insert result: ' + ret);
});
}
}
try {
if (isTrustList(value["KEYWORD"])) {
Log.I('trustList data exists.');
rdbInsert(true);
} else {
Log.I('Start to verify permissions.');
verifyPermission(rdbInsert);
}
} catch (err) {
Log.E('Insert Data error:' + JSON.stringify(err));
callback(-1, 0);
}
}
update(uri: string, predicates, value, callback) {
Log.I('update keyword = ' + value["KEYWORD"] + ' start:' + uri);
let rdbUpData = (GrantStatus) => {
if (!GrantStatus) {
callback(-1, 0);
return;
}
DoSystemSetting(value["KEYWORD"], value["VALUE"]);
if (rdbStore == null) {
let request = {"operation":"update", "columns" : null, "predicates" : predicates, value : value};
Log.I('update request = '+ JSON.stringify(request));
requests.push(request);
callback(-1, 0);
} else {
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates, function (err, ret) {
Log.I('update before callback ' + JSON.stringify(err));
callback(err, ret);
Log.I('update after callback ' + JSON.stringify(ret));
Log.I('update result: ' + ret);
});
}
}
try {
if (isTrustList(value["KEYWORD"])) {
Log.I('trustList data exists.');
rdbUpData(true);
} else {
Log.I('Start to verify permissions.');
verifyPermission(rdbUpData);
}
} catch (err) {
Log.E('upData error:' + JSON.stringify(err));
callback(-1, 0);
}
}
delete(uri: string, predicates, callback) {
Log.I('nothing to do');
}
query(uri: string, predicates, columns: Array<string>, callback) {
Log.I( 'query start uri:' + uri);
if (rdbStore == null) {
let request= {"operation":"query", "columns" : columns, "predicates" : predicates, value:""};
Log.I('query request = '+ JSON.stringify(request));
requests.push(request);
callback(-1, {"_napiwrapper":{}});
} else {
rdbStore.query(SettingsDataConfig.TABLE_NAME, predicates, columns, function (err, resultSet) {
Log.I('query before callback err:' + JSON.stringify(err) + " ResultSet" + JSON.stringify(resultSet));
callback(err, resultSet);
Log.I('query after callback ');
Log.I('query result: '+ JSON.stringify(resultSet.rowCount) +'columnNames'+ JSON.stringify(resultSet.columnNames));
});
}
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
*/
import SettingsDataConfig from '../Utils/SettingsDataConfig';
import SettingsDBHelper from '../Utils/SettingsDBHelper';
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility';
import { Log } from '../Utils/Log';
import ohosDataRdb from '@ohos.data.rdb';
import commonEventManager from '@ohos.commonEventManager';
const CURRENT_USER_TABLE_DROP: string = `DROP TABLE IF EXISTS ${SettingsDataConfig.USER_TABLE_NAME}_`
const TAG: string = 'UserChangeStaticSubscriber : '
export default class UserChangeStaticSubscriber extends StaticSubscriberExtensionAbility {
async onReceiveEvent(event) {
if (!event) {
return
}
Log.I(TAG + 'onReceiveEvent, event' + JSON.stringify(event))
let rdb: ohosDataRdb.RdbStore = await SettingsDBHelper.getInstance().getRdbStore();
switch (event.event) {
case commonEventManager.Support.COMMON_EVENT_USER_ADDED:
// 创建对应用户的数据表
await rdb.executeSql(SettingsDBHelper.CURRENT_USER_TABLE_CREATE_PREFIX + event.code + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
// 加载用户数据表的默认值
try {
let content = await SettingsDBHelper.getInstance().readDefaultFile();
if (!content) {
Log.E("readDefaultFile is failed!");
return
}
for (var index = 0; index < content.settings.length; index++) {
if (content.settings[index].userConfig) {
await SettingsDBHelper.getInstance().loadUserSettings(content.settings[index].name, content.settings[index].value, event.code)
}
}
} catch (err) {
Log.E("loadDefaultSettingsData failed! err = " + err);
}
break
case commonEventManager.Support.COMMON_EVENT_USER_REMOVED:
// 删除对应用户的数据表
rdb.executeSql(CURRENT_USER_TABLE_DROP + event.code, []);
break
default:
break
}
}
}

View File

@ -1,17 +1,7 @@
/** /*
* Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
import hiLog from '@ohos.hilog'; import hiLog from '@ohos.hilog';
const DOMAIN: number = 0x0500; const DOMAIN: number = 0x0500;

View File

@ -1,17 +1,5 @@
/** /*
* @file Describe the file * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
import dataStorage from '@ohos.data.preferences'; import dataStorage from '@ohos.data.preferences';
@ -23,65 +11,44 @@ import systemParameter from '@ohos.systemparameter';
import SettingsDataConfig from '../Utils/SettingsDataConfig'; import SettingsDataConfig from '../Utils/SettingsDataConfig';
import { Log } from '../Utils/Log'; import { Log } from '../Utils/Log';
let DDL_TABLE_CREATE = `CREATE TABLE IF NOT EXISTS ${SettingsDataConfig.TABLE_NAME} (`
+ `${SettingsDataConfig.FIELD_ID} INTEGER PRIMARY KEY AUTOINCREMENT, `
+ `KEYWORD TEXT, `
+ `VALUE TEXT CHECK (LENGTH(VALUE)<=1000))`;
const DEFAULT_JSON_FILE_NAME : string = "default_settings.json"; const DEFAULT_JSON_FILE_NAME : string = "default_settings.json";
const SETTINGSDATA_PREFERENCE : string = "SettingsDataPreference"; const SETTINGSDATA_PREFERENCE : string = "SettingsDataPreference";
let DefaultKey = SettingsDataConfig.DefaultKey;
let SettingsKey = SettingsDataConfig.SettingsKey;
const DefalutKVGlobal = {
"settings.screen.brightness.default": "50",
"settings.time.format.default": "24",
"settings.audio.ringtone.default": "5",
"settings.audio.media.default": "5",
"settings.audio.voicecall.default": "5",
"settings.display.navigationbar_status.default": "1",
"cellular_data_enable.default": "1",
};
const TIME_FORMAT = { const TIME_FORMAT = {
TIME_FORMAT_24: "24", TIME_FORMAT_24: "24",
TIME_FORMAT_12: "12", TIME_FORMAT_12: "12",
} }
class SettingsDBHelper { class SettingsDBHelper {
private firstStartupFlag: boolean; static readonly SHARED_TABLE_CREATE_PREFIX = `CREATE TABLE IF NOT EXISTS ${SettingsDataConfig.TABLE_NAME}`;
private rdbStore_; // 需要在在表名后拼接当前的userid
static readonly CURRENT_USER_TABLE_CREATE_PREFIX = `CREATE TABLE IF NOT EXISTS ${SettingsDataConfig.USER_TABLE_NAME}_`
static readonly TABLE_CREATE_SUFFIX = ` (${SettingsDataConfig.FIELD_ID} INTEGER PRIMARY KEY AUTOINCREMENT, `
+ `${SettingsDataConfig.FIELD_KEYWORD} TEXT, `
+ `${SettingsDataConfig.FIELD_VALUE} TEXT CHECK (LENGTH(VALUE)<=1000))`;
private rdbStore_: ohosDataRdb.RdbStore;
private context_; private context_;
private static instance_: SettingsDBHelper; private readonly DEFAULT_USER_ID: number = 100;
private constructor() { private constructor() {
this.firstStartupFlag = false;
this.rdbStore_ = undefined; this.rdbStore_ = undefined;
this.context_ = globalThis.abilityContext; this.context_ = globalThis.abilityContext;
Log.I('call construstor');
} }
private async firstStartupConfig() : Promise<void> { private async firstStartupConfig() : Promise<void> {
Log.I("firstStartupConfig start"); Log.I("firstStartupConfig start");
let storage = await dataStorage.getPreferences(this.context_, SETTINGSDATA_PREFERENCE) let storage = await dataStorage.getPreferences(this.context_, SETTINGSDATA_PREFERENCE)
Log.I("firstStartupConfig getStorage = " + storage); let isFirst = await storage.get('isFirstStartUp', true)
let isExist = await storage.has('isFirstStartUp') Log.I("firstStartupConfig isFirstStartUp = " + isFirst);
Log.I("firstStartupConfig has isFirstStartUp = " + isExist); if (isFirst) {
if (!isExist) { // 创建公共数据表
Log.I("The key of isFirstStartUp is not contained.") await this.rdbStore_.executeSql(SettingsDBHelper.SHARED_TABLE_CREATE_PREFIX + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
Log.I("firstStartupConfig put start"); // 创建默认用户数据表
await storage.put('isFirstStartUp', 'true'); await this.rdbStore_.executeSql(SettingsDBHelper.CURRENT_USER_TABLE_CREATE_PREFIX + this.DEFAULT_USER_ID + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
Log.I("firstStartupConfig flush start"); await storage.put('isFirstStartUp', false);
await storage.flush(); await storage.flush();
Log.I("firstStartupConfig flush end"); await this.loadDefaultSettingsData();
this.firstStartupFlag = true;
} else {
let startup = await storage.get('isFirstStartUp', 'null');
if (startup != 'true') {
Log.I("firstStartupConfig get startup = " + startup);
this.firstStartupFlag = true;
}
} }
Log.I("firstStartupConfig end"); Log.I("firstStartupConfig end");
return; return;
@ -90,137 +57,110 @@ class SettingsDBHelper {
public async initRdbStore() { public async initRdbStore() {
Log.I('call initRdbStore start'); Log.I('call initRdbStore start');
this.rdbStore_ = await ohosDataRdb.getRdbStore(this.context_, { name: SettingsDataConfig.DB_NAME }, 1); this.rdbStore_ = await ohosDataRdb.getRdbStore(this.context_, { name: SettingsDataConfig.DB_NAME }, 1);
Log.I('call initRdbStore, rdbStore_ = ' + this.rdbStore_);
Log.I("initRdbStore executeSql");
await this.rdbStore_.executeSql(DDL_TABLE_CREATE, []);
Log.I('getRdbStore firstStartupConfig');
await this.firstStartupConfig(); await this.firstStartupConfig();
if (this.firstStartupFlag) {
Log.I('initRdbStore getDefaultSettingsKV');
let defaultKV = await this.getDefaultSettingsKV();
Log.I('initRdbStore loadDefaultSettings');
await this.loadDefaultSettings(defaultKV);
} else {
Log.I('initRdbStore not need loadDefaultSettings');
}
Log.I('call initRdbStore end'); Log.I('call initRdbStore end');
return this.rdbStore_; return this.rdbStore_;
} }
public static getInstance() { public static getInstance() {
if (!SettingsDBHelper.instance_) { if (!globalThis.settingsDBHelper) {
Log.I('call getInstance start'); globalThis.settingsDBHelper = new SettingsDBHelper();
SettingsDBHelper.instance_ = new SettingsDBHelper();
Log.I('call getInstance end');
} }
return SettingsDBHelper.instance_; return globalThis.settingsDBHelper;
} }
public async getRdbStore() { public async getRdbStore() {
Log.I('call getRdbStore start'); if (!this.rdbStore_) {
return await SettingsDBHelper.instance_.initRdbStore(); return await globalThis.settingsDBHelper.initRdbStore();
}
return this.rdbStore_
} }
private async loadSettings(rdbStore_, key, value): Promise<void> { private async loadGlobalSettings(key, value): Promise<void> {
if (!this.rdbStore_) {
Log.E('rdbStore is null!');
return
}
Log.I("key=" + key + " value " + value); Log.I("key=" + key + " value " + value);
await this.rdbStore_.insert( await this.rdbStore_.insert(SettingsDataConfig.TABLE_NAME, { "KEYWORD": key, "VALUE": value }, (err, ret) => {
SettingsDataConfig.TABLE_NAME,
{ "KEYWORD": key, "VALUE": value },
(err, ret) => {
if (err) { if (err) {
Log.E("loadSettings insert error:" + JSON.stringify(err)); Log.E("loadGlobalSettings insert error:" + JSON.stringify(err));
} }
Log.I("loadSettings insert ret = " + ret); Log.I("loadGlobalSettings insert ret = " + ret);
}); }
);
} }
private async loadDefaultSettings(defaultKV) { public async loadUserSettings(key, value, userId: number): Promise<void> {
Log.I("loadDefaultSettings start"); if (!this.rdbStore_) {
Log.E('rdbStore is null!');
await this.loadSettings(this.rdbStore_, return
settings.display.SCREEN_BRIGHTNESS_STATUS, defaultKV[DefaultKey.SETTINGS_SCREEN_BRIGHTNESS_DEFAULT]); }
Log.I("key=" + key + " value " + value + " userid " + userId);
await this.loadSettings(this.rdbStore_, await this.rdbStore_.insert(SettingsDataConfig.USER_TABLE_NAME + '_' + userId,
settings.date.TIME_FORMAT, defaultKV[DefaultKey.SETTINGS_TIME_FORMAT_DEFAULT]); { "KEYWORD": key, "VALUE": value }, (err, ret) => {
if (err) {
await this.loadSettings(this.rdbStore_, Log.E("loadGlobalSettings insert error:" + JSON.stringify(err));
SettingsKey.SETTINGS_AUDIO_RINGTONE, defaultKV[DefaultKey.SETTINGS_AUDIO_RINGTONE_DEFAULT]); }
Log.I("loadGlobalSettings insert ret = " + ret);
await this.loadSettings(this.rdbStore_, });
SettingsKey.SETTINGS_AUDIO_MEDIA, defaultKV[DefaultKey.SETTINGS_AUDIO_MEDIA_DEFAULT]);
await this.loadSettings(this.rdbStore_,
SettingsKey.SETTINGS_AUDIO_VOICE_CALL, defaultKV[DefaultKey.SETTINGS_AUDIO_VOICE_CALL_DEFAULT]);
await this.loadSettings(this.rdbStore_,
settings.general.DEVICE_NAME, defaultKV[DefaultKey.SETTINGS_GENERAL_DEVICE_NAME_DEFAULT]);
await this.loadSettings(this.rdbStore_,
SettingsKey.SETTINGS_DISPALY_NAVBAR_STATUS, defaultKV[DefaultKey.SETTINGS_DISPALY_NAVBAR_STATUS_DEFAULT]);
await this.loadSettings(this.rdbStore_,
SettingsKey.CELLULAR_DATA_ENABLE, defaultKV[DefaultKey.CELLULAR_DATA_ENABLE_DEFAULT]);
await this.loadSettings(this.rdbStore_,
SettingsKey.LOCATION_ENABLE, defaultKV[DefaultKey.LOCATION_ENABLE_DEFAULT]);
Log.I("loadDefaultSettings end");
return;
} }
private async readDefaultFile(): Promise<string> { public async readDefaultFile() {
Log.I("readDefaultFile start");
let rawStr: string = ""; let rawStr: string = "";
try { try {
let resManager = this.context_.resourceManager; let content = await this.context_.resourceManager.getRawFile(DEFAULT_JSON_FILE_NAME);
Log.I("readDefaultFile resManager=" + resManager);
let content = await resManager.getRawFile(DEFAULT_JSON_FILE_NAME);
rawStr = String.fromCharCode.apply(null, content); rawStr = String.fromCharCode.apply(null, content);
} catch (err) { } catch (err) {
Log.E("readDefaultFile readRawFile err" + err); Log.E("readDefaultFile readRawFile err" + err);
} }
Log.I("readDefaultFile end");
if (rawStr) {
Log.I("readDefaultFile success");
return JSON.parse(rawStr);
}
return rawStr; return rawStr;
} }
private async getDefaultSettingsKV() { private async loadDefaultSettingsData() {
Log.I("getDefaultSettingsKV start"); Log.I("loadDefaultSettingsData start");
let defaultKV = {};
try { try {
let content: string = await this.readDefaultFile(); let content = await this.readDefaultFile();
if (!content) { if (!content) {
Log.I("getDefaultSettingsKV readDefaultFile err! content = " + content); Log.E("readDefaultFile is failed!");
throw new Error("readfile error!") return
} }
let defaultJson = JSON.parse(content); for (var index = 0; index < content.settings.length; index++) {
Log.I("getDefaultSettingsKV parse = " + JSON.stringify(defaultJson)); if (content.settings[index].userConfig) {
for (var index = 0; index < defaultJson.settings.length; index++) { // 加载用户数据表的默认值
defaultKV[defaultJson.settings[index].name] = defaultJson.settings[index].value; await this.loadUserSettings(content.settings[index].name, content.settings[index].value, this.DEFAULT_USER_ID)
} else {
// 加载公共数据表的默认值
await this.loadGlobalSettings(content.settings[index].name, content.settings[index].value);
}
} }
} catch (err) { } catch (err) {
Log.E("getDefaultSettingsKV catch err! err = " + err); Log.E("loadDefaultSettingsData catch error! err = " + err);
defaultKV = DefalutKVGlobal;
} }
// 初始化设备名称
let deviceName: string = deviceInfo.marketName; let deviceName: string = deviceInfo.marketName;
if (deviceName.startsWith('"') && deviceName.endsWith('"')) { if (deviceName.startsWith('"') && deviceName.endsWith('"')) {
deviceName = JSON.parse(deviceName); deviceName = JSON.parse(deviceName);
} }
defaultKV[DefaultKey.SETTINGS_GENERAL_DEVICE_NAME_DEFAULT] = deviceName; await this.loadGlobalSettings(settings.general.DEVICE_NAME, deviceName);
if (i18n.is24HourClock()) { // 初始化24小时制
defaultKV[DefaultKey.SETTINGS_TIME_FORMAT_DEFAULT] = TIME_FORMAT.TIME_FORMAT_24; await this.loadGlobalSettings(settings.date.TIME_FORMAT, i18n.is24HourClock() ? TIME_FORMAT.TIME_FORMAT_24 : TIME_FORMAT.TIME_FORMAT_12);
} else {
defaultKV[DefaultKey.SETTINGS_TIME_FORMAT_DEFAULT] = TIME_FORMAT.TIME_FORMAT_12;
}
// 初始化亮度值
let defaultBrightness = systemParameter.getSync('const.display.brightness.default'); let defaultBrightness = systemParameter.getSync('const.display.brightness.default');
if (defaultBrightness.length > 0) { if (defaultBrightness) {
defaultKV[DefaultKey.SETTINGS_SCREEN_BRIGHTNESS_DEFAULT] = defaultBrightness; await this.loadGlobalSettings(settings.display.SCREEN_BRIGHTNESS_STATUS, defaultBrightness);
} }
return defaultKV; Log.I("loadDefaultSettingsData end");
} }
} }

View File

@ -1,51 +1,14 @@
/** /*
* @file Describe the file * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
enum DefaultKey {
SETTINGS_SCREEN_BRIGHTNESS_DEFAULT = "settings.screen.brightness.default",
SETTINGS_TIME_FORMAT_DEFAULT = "settings.time.format.default",
SETTINGS_AUDIO_RINGTONE_DEFAULT = "settings.audio.ringtone.default",
SETTINGS_AUDIO_MEDIA_DEFAULT = "settings.audio.media.default",
SETTINGS_AUDIO_VOICE_CALL_DEFAULT = "settings.audio.voicecall.default",
SETTINGS_GENERAL_DEVICE_NAME_DEFAULT = "settings.general.device_name.default",
SETTINGS_DISPALY_NAVBAR_STATUS_DEFAULT = "settings.display.navigationbar_status.default",
CELLULAR_DATA_ENABLE_DEFAULT = "cellular_data_enable.default",
LOCATION_ENABLE_DEFAULT = "location_enable.default",
};
enum SettingsKey {
SETTINGS_SCREEN_BRIGHTNESS = "settings.screen.brightness",
SETTINGS_TIME_FORMAT = "settings.time.format",
SETTINGS_AUDIO_RINGTONE = "settings.audio.ringtone",
SETTINGS_AUDIO_MEDIA = "settings.audio.media",
SETTINGS_AUDIO_VOICE_CALL = "settings.audio.voicecall",
SETTINGS_GENERAL_DEVICE_NAME = "settings.general.device_name",
SETTINGS_DISPALY_NAVBAR_STATUS = "settings.display.navigationbar_status",
CELLULAR_DATA_ENABLE = "cellular_data_enable",
LOCATION_ENABLE = "location_enable",
};
const SettingsDataConfig = { const SettingsDataConfig = {
DB_NAME: 'settingsdata.db', DB_NAME: 'settingsdata.db',
TABLE_NAME: 'SETTINGSDATA', TABLE_NAME: 'SETTINGSDATA',
USER_TABLE_NAME: 'USER_SETTINGSDATA',
FIELD_ID: 'ID', FIELD_ID: 'ID',
FIELD_KEYWORD: 'KEYWORD', FIELD_KEYWORD: 'KEYWORD',
FIELD_VALUE: 'VALUE', FIELD_VALUE: 'VALUE'
DefaultKey: DefaultKey,
SettingsKey: SettingsKey,
}; };
export default SettingsDataConfig; export default SettingsDataConfig;

View File

@ -2,7 +2,7 @@
"module": { "module": {
"name": "entry", "name": "entry",
"type": "entry", "type": "entry",
"srcEntrance": "./ets/Application/AbilityStage.ts", "srcEntrance": "./ets/Application/DataAbilityStage.ts",
"description": "$string:entry_desc", "description": "$string:entry_desc",
"mainElement": "MainAbility", "mainElement": "MainAbility",
"deviceTypes": [ "deviceTypes": [
@ -21,8 +21,8 @@
"uiSyntax": "ets", "uiSyntax": "ets",
"extensionAbilities": [ "extensionAbilities": [
{ {
"srcEntrance": "./ets/DataAbility/dataExtAbility.ts", "srcEntrance": "./ets/DataAbility/DataExtAbility.ets",
"name": "SettingsDsExtAbility", "name": "DataExtAbility",
"icon": "$media:icon", "icon": "$media:icon",
"description": "$string:description_datashareextability", "description": "$string:description_datashareextability",
"type": "dataShare", "type": "dataShare",
@ -30,6 +30,18 @@
"visible": true, "visible": true,
"writePermission": "ohos.permission.MANAGE_SECURE_SETTINGS", "writePermission": "ohos.permission.MANAGE_SECURE_SETTINGS",
"metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}] "metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}]
},
{
"name": "UserChangeStaticSubscriber",
"type": "staticSubscriber",
"visible": true,
"description": "UserChangeStaticSubscriber",
"icon": "$media:icon",
"metadata": [{
"name": "ohos.extension.staticSubscriber",
"resource": "$profile:static_subscriber_config"
}],
"srcEntrance": "./ets/StaticSubscriber/UserChangeStaticSubscriber.ets"
} }
] ]
} }

View File

@ -3,13 +3,13 @@
{ {
"uri": "*" "uri": "*"
}, },
{
"uri": "datashare:///com.ohos.settingsdata/entry/settingsdata",
"crossUserMode": 1
},
{ {
"uri": "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA", "uri": "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA",
"crossUserMode": 1 "crossUserMode": 1
},
{
"uri": "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA",
"crossUserMode": 2
} }
] ]
} }

View File

@ -0,0 +1,12 @@
{
"commonEvents": [
{
"name": "UserChangeStaticSubscriber",
"permission": "",
"events":[
"usual.event.USER_ADDED",
"usual.event.USER_REMOVED"
]
}
]
}

View File

@ -1,35 +1,27 @@
{ {
"settings": [ "settings": [
{ {
"name": "settings.screen.brightness.default", "name": "settings.audio.ringtone",
"value": "50"
},
{
"name": "settings.time.format.default",
"value": "24"
},
{
"name": "settings.audio.ringtone.default",
"value": "5" "value": "5"
}, },
{ {
"name": "settings.audio.media.default", "name": "settings.audio.media",
"value": "5" "value": "5"
}, },
{ {
"name": "settings.audio.voicecall.default", "name": "settings.audio.voicecall",
"value": "5" "value": "5"
}, },
{ {
"name": "settings.display.navigationbar_status.default", "name": "settings.display.navigationbar_status",
"value": "1" "value": "1"
}, },
{ {
"name": "cellular_data_enable.default", "name": "cellular_data_enable",
"value": "1" "value": "1"
}, },
{ {
"name": "location_enable.default", "name": "settings.display.auto_screen_brightness",
"value": "1" "value": "1"
} }
] ]