This commit is contained in:
chenlang10 2023-10-10 16:04:32 +08:00
commit 1096998c7a
5 changed files with 513 additions and 457 deletions

View File

@ -1,228 +1,254 @@
/**
* Copyright (c) 2021-2023 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.
*/
/**
* Copyright (c) 2021-2023 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 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';
import common from '@ohos.app.ability.common';
import Audio from '@ohos.multimedia.audio';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility';
import rpc from '@ohos.rpc';
import process from '@ohos.process';
import settings from '@ohos.settings';
import relationalStore from '@ohos.data.relationalStore';
import Want from '@ohos.app.ability.Want';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { AsyncCallback, BusinessError } from '@ohos.base';
import SettingsDataConfig from '../Utils/SettingsDataConfig';
import SettingsDBHelper from '../Utils/SettingsDBHelper';
import { Log } from '../Utils/Log';
import { GlobalContext} from '../Utils/GlobalContext';
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) {
interface IRequest {
operation:string ;
columns:string[];
predicates:dataSharePredicates.DataSharePredicates|relationalStore.RdbPredicates|null;
value:relationalStore.ValuesBucket|null
}
let rdbStore:relationalStore.RdbStore;
let requests:IRequest[] = [];
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
];
let ret:number = 0;
let err:BusinessError = {"code":-1} as BusinessError;
globalThis.abilityContext = this.context;
this.onInitialized();
}
export default class DataExtAbility extends DataShareExtensionAbility {
onCreate(want) {
GlobalContext.thisContext = this.context;
this.onInitialized();
Log.info('onCreate context'+ JSON.stringify(this.context));
}
onInitialized() {
Log.info('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.info('onInitialized insert ret: ' + ret);
});
} else if (opt == "query") {
rdbStore.query(predicates, columns, function (err, resultSet) {
onInitialized() {
Log.info('onInitialize start');
let context = GlobalContext.thisContext as common.Context;
Log.info('onInitialize start context: '+ JSON.stringify(this.context));
if (context !== undefined) {
SettingsDBHelper.getInstance().getRdbStore().then((rdb: relationalStore.RdbStore) => {
rdbStore = rdb;
for (let i = 0; i < requests.length; i++) {
let opt: string = requests[i].operation;
let columns: string[] = requests[i].columns;
let predicates = (requests[i].predicates) as dataSharePredicates.DataSharePredicates;
let value: relationalStore.ValuesBucket|null = requests[i].value;
if (opt == "insert") {
if(value){
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, (err, ret) => {
Log.info('onInitialized insert ret: ' + ret);
});
}
} else if (opt == "query") {
if(predicates){
rdbStore.query(SettingsDataConfig.TABLE_NAME, predicates, columns, (err: BusinessError, resultSet: relationalStore.ResultSet) => {
Log.info('onInitialized query ret: ' + JSON.stringify(resultSet));
});
} else if (opt == "update") {
rdbStore.update(value, predicates, function (err, ret) {
Log.info('onInitialized update ret: ' + ret);
});
}
}
}).catch(err => {
Log.error('onInitialize failed:' + JSON.stringify(err));
})
} else {
Log.info('onInitialize context error!');
} else if (opt == "update") {
if(value){
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates, (err, ret) => {
Log.info('onInitialized update ret: ' + ret);
});
}
}
}
Log.info('onInitialize end');
}).catch((err: Error) => {
Log.error('onInitialize failed:' + JSON.stringify(err));
})
} else {
Log.info('onInitialize context error!');
}
Log.info('onInitialize end');
}
insert(uri: string, value: relationalStore.ValuesBucket, callback : AsyncCallback<number>) {
Log.info('insert keyword = ' + value[SettingsDataConfig.FIELD_KEYWORD] + ' start:' + uri);
let rdbInsert = (GrantStatus: boolean) => {
if (!GrantStatus) {
callback(err, ret);
return;
}
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD]?.toString(), value[SettingsDataConfig.FIELD_VALUE]?.toString());
insert(uri, value, callback) {
Log.info('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.info('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.info('insert result: ' + ret);
});
}
}
if (rdbStore == null) {
let request: IRequest= {
operation: "insert", columns: [], predicates: null, value: value
};
Log.info('insert request = ' + JSON.stringify(request));
requests.push(request);
callback(err, ret);
} else {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, (err, ret) => {
callback(err, ret);
Log.info('insert result: ' + ret);
});
}
}
try {
Log.info('Start to verify permissions.');
this.verifyPermission(value, rdbInsert);
} catch (err) {
Log.error('Insert Data error:' + JSON.stringify(err));
callback(err, ret);
}
}
update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value:relationalStore.ValuesBucket, callback: AsyncCallback<number>) {
Log.info('update keyword = ' + value[SettingsDataConfig.FIELD_KEYWORD] + ' start:' + uri);
let rdbUpData = (GrantStatus:boolean) => {
if (!GrantStatus) {
callback(err, ret);
return;
}
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD]?.toString(), value[SettingsDataConfig.FIELD_VALUE]?.toString());
if (rdbStore == null) {
let request : IRequest= {
operation: "update", columns: [], predicates: predicates, value: value
};
Log.info('update request = ' + JSON.stringify(request));
requests.push(request);
callback(err, ret);
} else {
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates , (err, ret)=> {
callback(err, ret);
Log.info('update result: ' + ret);
});
}
}
try {
Log.info('Start to verify permissions.');
this.verifyPermission(value, rdbUpData);
} catch (err) {
Log.error('upData error:' + JSON.stringify(err));
callback(err, ret);
}
}
delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>) {
Log.info('nothing to do');
}
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: string[], callback: AsyncCallback<Object>) {
Log.info( 'query start uri:' + uri);
if (rdbStore == null) {
let request: IRequest= {operation:"query", columns : columns, predicates : predicates, value:null};
Log.info('query request = '+ JSON.stringify(request));
requests.push(request);
callback(err, {"_napiwrapper":{}});
} else {
rdbStore.query(SettingsDataConfig.TABLE_NAME, predicates, columns, (err:BusinessError, resultSet:relationalStore.ResultSet)=> {
callback(err, resultSet);
Log.info('query result: '+ JSON.stringify(resultSet.rowCount) +'columnNames'+ JSON.stringify(resultSet.columnNames));
})
}
}
private DoSystemSetting(settingsKey: string, settingsValue: string) {
switch (settingsKey) {
case SETTINGS_AUDIO_RINGTONE:
try {
Log.info('Start to verify permissions.');
this.verifyPermission(value, rdbInsert);
} catch (err) {
Log.error('Insert Data error:' + JSON.stringify(err));
callback(-1, 0);
}
}
update(uri: string, predicates, value, callback) {
Log.info('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.info('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.info('update result: ' + ret);
});
}
}
try {
Log.info('Start to verify permissions.');
this.verifyPermission(value, rdbUpData);
} catch (err) {
Log.error('upData error:' + JSON.stringify(err));
callback(-1, 0);
}
}
delete(uri: string, predicates, callback) {
Log.info('nothing to do');
}
query(uri: string, predicates, columns: Array<string>, callback) {
Log.info( 'query start uri:' + uri);
if (rdbStore == null) {
let request= {"operation":"query", "columns" : columns, "predicates" : predicates, value:""};
Log.info('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.info('query result: '+ JSON.stringify(resultSet.rowCount) +'columnNames'+ JSON.stringify(resultSet.columnNames));
let volumeType = Audio.AudioVolumeType.RINGTONE;
Audio.getAudioManager().setVolume(volumeType, Number(settingsValue)).then(() => {
Log.info('settings Promise returned to indicate a successful RINGTONE setting.')
});
}
}
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.info('settings Promise returned to indicate a successful RINGTONE setting.')
});
} catch (err) {
Log.info('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.info('settings Promise returned to indicate a successful MEDIA setting.')
});
} catch (err) {
Log.info('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.info('settings Promise returned to indicate a successful VOICE_CALL setting.')
});
} catch (err) {
Log.info('settings VOICE_CALL failed error = ' + JSON.stringify(err));
}
break
default:
Log.info(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.info('tokenID = ' + tokenID);
let grantStatus = abilityAccessCtrl.createAtManager().verifyAccessToken(tokenID, "ohos.permission.MANAGE_SECURE_SETTINGS");
grantStatus.then(data => {
if (data == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
Log.info('MANAGE_SECURE_SETTINGS active');
callBack(true);
} else {
Log.warn('MANAGE_SECURE_SETTINGS grantStatus= ' + JSON.stringify(data));
callBack(false);
}
}).catch((err) => {
Log.error('tokenID = ' + tokenID + ' verifyAccessToken is failed: ' + JSON.stringify(err));
callBack(false);
})
} catch (err) {
Log.error('err = ' + JSON.stringify(err));
Log.info('settings RINGTONE failed error = ' + JSON.stringify(err));
}
break
case SETTINGS_AUDIO_MEDIA:
try {
let volumeType = Audio.AudioVolumeType.MEDIA;
Audio.getAudioManager().setVolume(volumeType, Number(settingsValue)).then(() => {
Log.info('settings Promise returned to indicate a successful MEDIA setting.')
});
} catch (err) {
Log.info('settings MEDIA failed error = ' + JSON.stringify(err));
}
break
case SETTINGS_AUDIO_VOICE_CALL:
try {
let volumeType = Audio.AudioVolumeType.VOICE_CALL;
Audio.getAudioManager().setVolume(volumeType, Number(settingsValue)).then(() => {
Log.info('settings Promise returned to indicate a successful VOICE_CALL setting.')
});
} catch (err) {
Log.info('settings VOICE_CALL failed error = ' + JSON.stringify(err));
}
break
default:
Log.info(settingsKey + ' key is not audio');
break
}
}
private verifyPermission(value: relationalStore.ValuesBucket, callBack: (GrantStatus: boolean) => void ) {
if (this.isTrustList(value[SettingsDataConfig.FIELD_KEYWORD]?.toString()) || process.uid == rpc.IPCSkeleton.getCallingUid()) {
callBack(true);
return;
}
try {
let tokenID = rpc.IPCSkeleton.getCallingTokenId();
Log.info('tokenID = ' + tokenID);
let grantStatus = abilityAccessCtrl.createAtManager().verifyAccessToken(tokenID, "ohos.permission.MANAGE_SECURE_SETTINGS");
grantStatus.then(data => {
if (data == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
Log.info('MANAGE_SECURE_SETTINGS active');
callBack(true);
} else {
Log.warn('MANAGE_SECURE_SETTINGS grantStatus= ' + JSON.stringify(data));
callBack(false);
}
}
}).catch((err) => {
Log.error('tokenID = ' + tokenID + ' verifyAccessToken is failed: ' + JSON.stringify(err));
callBack(false);
})
} catch (err) {
Log.error('err = ' + JSON.stringify(err));
callBack(false);
}
}
private isTrustList(keyWord: String): boolean {
return trustList.includes(keyWord)
}
}
private isTrustList(keyWord: string): boolean {
return trustList.includes(keyWord)
}
}

View File

@ -1,61 +1,64 @@
/**
* Copyright (c) 2021-2023 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.
*/
/**
* Copyright (c) 2021-2023 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 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';
import SettingsDataConfig from '../Utils/SettingsDataConfig';
import SettingsDBHelper from '../Utils/SettingsDBHelper';
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility';
import { Log } from '../Utils/Log';
import commonEventManager from '@ohos.commonEventManager';
const CURRENT_USER_TABLE_DROP: string = `DROP TABLE IF EXISTS ${SettingsDataConfig.USER_TABLE_NAME}_`
const TAG: string = 'UserChangeStaticSubscriber : '
const CURRENT_USER_TABLE_DROP: string = `DROP TABLE IF EXISTS ${SettingsDataConfig.USER_TABLE_NAME}_`
const TAG: string = 'UserChangeStaticSubscriber : '
interface IContent {
settings: Array<Map<string,string>> ;
}
export default class UserChangeStaticSubscriber extends StaticSubscriberExtensionAbility {
async onReceiveEvent(event) {
if (!event) {
return
}
Log.info(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.error("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.error("loadDefaultSettingsData failed! err = " + err);
}
break
case commonEventManager.Support.COMMON_EVENT_USER_REMOVED:
// 删除对应用户的数据表
rdb.executeSql(CURRENT_USER_TABLE_DROP + event.code, []);
break
default:
break
}
export default class UserChangeStaticSubscriber extends StaticSubscriberExtensionAbility {
async onReceiveEvent(event: commonEventManager.CommonEventData) {
if (!event) {
return
}
}
Log.info(TAG + 'onReceiveEvent, event' + JSON.stringify(event))
let rdb = 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() as IContent;
if (!content) {
Log.error("readDefaultFile is failed!");
return
}
for (let 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)
Log.info("content.settings[index]"+content.settings[index]["value"]);
}
}
} catch (err) {
Log.error("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

@ -13,13 +13,18 @@
* limitations under the License.
*/
const SettingsDataConfig = {
DB_NAME: 'settingsdata.db',
TABLE_NAME: 'SETTINGSDATA',
USER_TABLE_NAME: 'USER_SETTINGSDATA',
FIELD_ID: 'ID',
FIELD_KEYWORD: 'KEYWORD',
FIELD_VALUE: 'VALUE'
};
import hiLog from '@ohos.hilog';
import common from '@ohos.app.ability.common';
import SettingsDBHelper from './SettingsDBHelper';
export default SettingsDataConfig;
const DOMAIN: number = 0x0500;
const TAG = 'SettingsData';
/**
* GlobalContext class
*/
export class GlobalContext {
public static dbHelper:Object | undefined = undefined;
public static thisContext: Object | undefined = undefined;
}

View File

@ -1,178 +1,192 @@
/**
* Copyright (c) 2021-2023 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.
*/
/**
* Copyright (c) 2021-2023 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 deviceInfo from '@ohos.deviceInfo';
import ohosDataRdb from '@ohos.data.rdb';
import i18n from '@ohos.i18n';
import settings from '@ohos.settings';
import systemParameter from '@ohos.systemparameter';
import SettingsDataConfig from '../Utils/SettingsDataConfig';
import { Log } from '../Utils/Log';
import common from '@ohos.app.ability.common';
import dataStorage from '@ohos.data.preferences';
import deviceInfo from '@ohos.deviceInfo';
import relationalStore from '@ohos.data.relationalStore';
import i18n from '@ohos.i18n';
import settings from '@ohos.settings';
import systemParameter from '@ohos.systemparameter';
import SettingsDataConfig from './SettingsDataConfig';
import { Log } from '../Utils/Log';
import { GlobalContext } from './GlobalContext';
const DEFAULT_JSON_FILE_NAME : string = "default_settings.json";
const SETTINGSDATA_PREFERENCE : string = "SettingsDataPreference";
interface TIME_FORMAT_DATA {
TIME_FORMAT_24: string ;
TIME_FORMAT_12: string ;
}
const TIME_FORMAT: TIME_FORMAT_DATA = {
TIME_FORMAT_24: "24",
TIME_FORMAT_12: "12",
}
interface IContent {
settings: Array<Map<string,string>> ;
}
class SettingsDBHelper {
static readonly SHARED_TABLE_CREATE_PREFIX = `CREATE TABLE IF NOT EXISTS ${SettingsDataConfig.TABLE_NAME}`;
// 需要在在表名后拼接当前的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))`;
const DEFAULT_JSON_FILE_NAME : string = "default_settings.json";
const SETTINGSDATA_PREFERENCE : string = "SettingsDataPreference";
private rdbStore_?: relationalStore.RdbStore;
private context_ ;
private readonly DEFAULT_USER_ID: number = 100;
const TIME_FORMAT = {
TIME_FORMAT_24: "24",
TIME_FORMAT_12: "12",
private constructor() {
this.rdbStore_ = undefined;
this.context_ = GlobalContext.thisContext as common.BaseContext;
Log.info("context_ start"+ JSON.stringify(this.context_));
}
class SettingsDBHelper {
static readonly SHARED_TABLE_CREATE_PREFIX = `CREATE TABLE IF NOT EXISTS ${SettingsDataConfig.TABLE_NAME}`;
// 需要在在表名后拼接当前的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 async firstStartupConfig() : Promise<void> {
Log.info("firstStartupConfig start");
let storage = await dataStorage.getPreferences(this.context_, SETTINGSDATA_PREFERENCE);
Log.info("context_ storage = " + this.context_);
let isFirst: dataStorage.ValueType = await storage.get('isFirstStartUp', true);
Log.info("firstStartupConfig isFirstStartUp = " + isFirst);
if (isFirst) {
// 创建公共数据表
await this.rdbStore_?.executeSql(SettingsDBHelper.SHARED_TABLE_CREATE_PREFIX + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
// 创建默认用户数据表
await this.rdbStore_?.executeSql(SettingsDBHelper.CURRENT_USER_TABLE_CREATE_PREFIX + this.DEFAULT_USER_ID + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
await storage.put('isFirstStartUp', false);
await storage.flush();
await this.loadDefaultSettingsData();
}
Log.info("firstStartupConfig end");
return;
}
private rdbStore_: ohosDataRdb.RdbStore;
private context_;
private readonly DEFAULT_USER_ID: number = 100;
private constructor() {
this.rdbStore_ = undefined;
this.context_ = globalThis.abilityContext;
public async initRdbStore() {
Log.info('call initRdbStore start');
let rdbStore = await relationalStore.getRdbStore(this.context_, { name: SettingsDataConfig.DB_NAME,securityLevel:1 });
if(rdbStore){
this.rdbStore_ = rdbStore;
}
private async firstStartupConfig() : Promise<void> {
Log.info("firstStartupConfig start");
let storage = await dataStorage.getPreferences(this.context_, SETTINGSDATA_PREFERENCE)
let isFirst = await storage.get('isFirstStartUp', true)
Log.info("firstStartupConfig isFirstStartUp = " + isFirst);
if (isFirst) {
// 创建公共数据表
await this.rdbStore_.executeSql(SettingsDBHelper.SHARED_TABLE_CREATE_PREFIX + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
// 创建默认用户数据表
await this.rdbStore_.executeSql(SettingsDBHelper.CURRENT_USER_TABLE_CREATE_PREFIX + this.DEFAULT_USER_ID + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
await storage.put('isFirstStartUp', false);
await storage.flush();
await this.loadDefaultSettingsData();
}
Log.info("firstStartupConfig end");
return;
await this.firstStartupConfig();
Log.info('call initRdbStore end');
return this.rdbStore_;
}
public static getInstance(): SettingsDBHelper {
Log.info("getInstance GlobalContext" + JSON.stringify(GlobalContext));
if(GlobalContext.dbHelper === undefined){
GlobalContext.dbHelper = new SettingsDBHelper();
}
return GlobalContext.dbHelper as SettingsDBHelper;
}
public async initRdbStore() {
Log.info('call initRdbStore start');
this.rdbStore_ = await ohosDataRdb.getRdbStore(this.context_, { name: SettingsDataConfig.DB_NAME }, 1);
await this.firstStartupConfig();
Log.info('call initRdbStore end');
return this.rdbStore_;
public async getRdbStore() {
if (!this.rdbStore_) {
return await (GlobalContext.dbHelper as SettingsDBHelper).initRdbStore();
// return await globalThis.settingsDBHelper.initRdbStore();
}
return this.rdbStore_
}
public static getInstance() {
if (!globalThis.settingsDBHelper) {
globalThis.settingsDBHelper = new SettingsDBHelper();
}
return globalThis.settingsDBHelper;
private async loadGlobalSettings(key: string, value: string): Promise<void> {
if (!this.rdbStore_) {
Log.error('rdbStore is null!');
return
}
public async getRdbStore() {
if (!this.rdbStore_) {
return await globalThis.settingsDBHelper.initRdbStore();
}
return this.rdbStore_
}
private async loadGlobalSettings(key, value): Promise<void> {
if (!this.rdbStore_) {
Log.error('rdbStore is null!');
return
}
Log.info("key=" + key + " value " + value);
await this.rdbStore_.insert(SettingsDataConfig.TABLE_NAME, { "KEYWORD": key, "VALUE": value }, (err, ret) => {
if (err) {
Log.error("loadGlobalSettings insert error:" + JSON.stringify(err));
}
Log.info("loadGlobalSettings insert ret = " + ret);
}
);
}
public async loadUserSettings(key, value, userId: number): Promise<void> {
if (!this.rdbStore_) {
Log.error('rdbStore is null!');
return
}
Log.info("key=" + key + " value " + value + " userid " + userId);
await this.rdbStore_.insert(SettingsDataConfig.USER_TABLE_NAME + '_' + userId,
{ "KEYWORD": key, "VALUE": value }, (err, ret) => {
Log.info("key=" + key + " value " + value);
await this.rdbStore_.insert(SettingsDataConfig.TABLE_NAME, { "KEYWORD": key, "VALUE": value }, (err, ret) => {
if (err) {
Log.error("loadGlobalSettings insert error:" + JSON.stringify(err));
}
Log.info("loadGlobalSettings insert ret = " + ret);
});
}
public async readDefaultFile() {
let rawStr: string = "";
try {
let content = await this.context_.resourceManager.getRawFile(DEFAULT_JSON_FILE_NAME);
rawStr = String.fromCharCode.apply(null, content);
} catch (err) {
Log.error("readDefaultFile readRawFile err" + err);
}
if (rawStr) {
Log.info("readDefaultFile success");
return JSON.parse(rawStr);
}
return rawStr;
}
private async loadDefaultSettingsData() {
Log.info("loadDefaultSettingsData start");
try {
let content = await this.readDefaultFile();
if (!content) {
Log.error("readDefaultFile is failed!");
return
}
for (var index = 0; index < content.settings.length; index++) {
if (content.settings[index].userConfig) {
// 加载用户数据表的默认值
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) {
Log.error("loadDefaultSettingsData catch error! err = " + err);
}
// 初始化设备名称
let deviceName: string = deviceInfo.marketName;
if (deviceName.startsWith('"') && deviceName.endsWith('"')) {
deviceName = JSON.parse(deviceName);
}
await this.loadGlobalSettings(settings.general.DEVICE_NAME, deviceName);
// 初始化24小时制
await this.loadGlobalSettings(settings.date.TIME_FORMAT, i18n.is24HourClock() ? TIME_FORMAT.TIME_FORMAT_24 : TIME_FORMAT.TIME_FORMAT_12);
// 初始化亮度值
let defaultBrightness = systemParameter.getSync('const.display.brightness.default');
if (defaultBrightness) {
await this.loadGlobalSettings(settings.display.SCREEN_BRIGHTNESS_STATUS, defaultBrightness);
}
Log.info("loadDefaultSettingsData end");
}
);
}
export default SettingsDBHelper;
public async loadUserSettings(key: string, value: string, userId: number): Promise<void> {
if (!this.rdbStore_) {
Log.error('rdbStore is null!');
return
}
Log.info("key=" + key + " value " + value + " userid " + userId);
await this.rdbStore_.insert(SettingsDataConfig.USER_TABLE_NAME + '_' + userId,
{ "KEYWORD": key, "VALUE": value }, (err, ret) => {
if (err) {
Log.error("loadGlobalSettings insert error:" + JSON.stringify(err));
}
Log.info("loadGlobalSettings insert ret = " + ret);
});
}
public async readDefaultFile(): Promise<Object> {
let rawStr: string = "";
try {
let content: number[] = await this.context_?.resourceManager.getRawFile(DEFAULT_JSON_FILE_NAME);
rawStr = String.fromCharCode(...Array.from(content));
} catch (err) {
Log.error("readDefaultFile readRawFile err" + err);
}
if (rawStr) {
Log.info("readDefaultFile success");
return JSON.parse(rawStr);
}
return rawStr;
}
private async loadDefaultSettingsData(): Promise<void> {
Log.info("loadDefaultSettingsData start");
try {
let content = await this.readDefaultFile() as IContent;
if (!content) {
Log.error("readDefaultFile is failed!");
return;
}
for (let index = 0; index < content.settings.length; index++) {
if (content.settings[index]["userConfig"]) {
// 加载用户数据表的默认值
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) {
Log.error("loadDefaultSettingsData catch error! err = " + err);
}
// 初始化设备名称
let deviceName: string = deviceInfo.marketName;
if (deviceName.startsWith('"') && deviceName.endsWith('"')) {
deviceName = JSON.parse(deviceName);
}
await this.loadGlobalSettings(settings.general.DEVICE_NAME, deviceName);
// 初始化24小时制
await this.loadGlobalSettings(settings.date.TIME_FORMAT, i18n.is24HourClock() ? TIME_FORMAT.TIME_FORMAT_24 : TIME_FORMAT.TIME_FORMAT_12);
// 初始化亮度值
let defaultBrightness = systemParameter.getSync('const.display.brightness.default');
if (defaultBrightness) {
await this.loadGlobalSettings(settings.display.SCREEN_BRIGHTNESS_STATUS, defaultBrightness);
}
Log.info("loadDefaultSettingsData end");
}
}
export default SettingsDBHelper;

View File

@ -1,25 +1,33 @@
/**
* Copyright (c) 2021-2023 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.
*/
/**
* Copyright (c) 2021-2023 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.
*/
const SettingsDataConfig = {
DB_NAME: 'settingsdata.db',
TABLE_NAME: 'SETTINGSDATA',
USER_TABLE_NAME: 'USER_SETTINGSDATA',
FIELD_ID: 'ID',
FIELD_KEYWORD: 'KEYWORD',
FIELD_VALUE: 'VALUE'
};
interface SettingsDataBaseConfig {
DB_NAME: string;
TABLE_NAME: string;
USER_TABLE_NAME: string;
FIELD_ID: string;
FIELD_KEYWORD: string;
FIELD_VALUE: string;
}
const SettingsDataConfig: SettingsDataBaseConfig = {
DB_NAME: 'settingsdata.db',
TABLE_NAME: 'SETTINGSDATA',
USER_TABLE_NAME: 'USER_SETTINGSDATA',
FIELD_ID: 'ID',
FIELD_KEYWORD: 'KEYWORD',
FIELD_VALUE: 'VALUE'
};
export default SettingsDataConfig;
export default SettingsDataConfig;