!57 arkts整改

Merge pull request !57 from chenlang/master
This commit is contained in:
openharmony_ci 2023-10-12 10:01:20 +00:00 committed by Gitee
commit 806040aef7
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
9 changed files with 175 additions and 1363 deletions

View File

@ -1,5 +0,0 @@
{
"name": "entry",
"version": "1.0.0",
"lockfileVersion": 1
}

View File

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

View File

@ -13,18 +13,31 @@
* limitations under the License.
*/
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 process from '@ohos.process';
import settings from '@ohos.settings';
import { GlobalContext} from '../Utils/GlobalContext';
let rdbStore;
let requests:any[] = [];
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"
@ -33,39 +46,51 @@ 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;
export default class DataExtAbility extends DataShareExtensionAbility {
onCreate(want) {
globalThis.abilityContext = this.context;
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) => {
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 = requests[i]["columns"];
let predicates = requests[i]["predicates"];
let value = requests[i]["value"];
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") {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, function (err, ret) {
Log.info('onInitialized insert ret: ' + ret);
});
if(value){
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, (err, ret) => {
Log.info('onInitialized insert ret: ' + ret);
});
}
} else if (opt == "query") {
rdbStore.query(predicates, columns, function (err, resultSet) {
Log.info('onInitialized query ret: ' + JSON.stringify(resultSet));
});
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);
});
if(value){
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates, (err, ret) => {
Log.info('onInitialized update ret: ' + ret);
});
}
}
}
}).catch(err => {
}).catch((err: Error) => {
Log.error('onInitialize failed:' + JSON.stringify(err));
})
} else {
@ -74,23 +99,24 @@ export default class DataExtAbility extends DataShareExtensionAbility {
Log.info('onInitialize end');
}
insert(uri, value, callback) {
insert(uri: string, value: relationalStore.ValuesBucket, callback : AsyncCallback<number>) {
Log.info('insert keyword = ' + value[SettingsDataConfig.FIELD_KEYWORD] + ' start:' + uri);
let rdbInsert = (GrantStatus) => {
let rdbInsert = (GrantStatus: boolean) => {
if (!GrantStatus) {
callback(-1, 0);
callback(err, ret);
return;
}
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD], value[SettingsDataConfig.FIELD_VALUE]);
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD]?.toString(), value[SettingsDataConfig.FIELD_VALUE]?.toString());
if (rdbStore == null) {
let request = {
"operation": "insert", "columns": null, "predicates": null, value: value
let request: IRequest= {
operation: "insert", columns: [], predicates: null, value: value
};
Log.info('insert request = ' + JSON.stringify(request));
requests.push(request);
callback(-1, 0);
callback(err, ret);
} else {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, function (err, ret) {
rdbStore.insert(SettingsDataConfig.TABLE_NAME, value, (err, ret) => {
callback(err, ret);
Log.info('insert result: ' + ret);
});
@ -102,27 +128,28 @@ export default class DataExtAbility extends DataShareExtensionAbility {
this.verifyPermission(value, rdbInsert);
} catch (err) {
Log.error('Insert Data error:' + JSON.stringify(err));
callback(-1, 0);
callback(err, ret);
}
}
update(uri: string, predicates, value, callback) {
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) => {
let rdbUpData = (GrantStatus:boolean) => {
if (!GrantStatus) {
callback(-1, 0);
callback(err, ret);
return;
}
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD], value[SettingsDataConfig.FIELD_VALUE]);
this.DoSystemSetting(value[SettingsDataConfig.FIELD_KEYWORD]?.toString(), value[SettingsDataConfig.FIELD_VALUE]?.toString());
if (rdbStore == null) {
let request = {
"operation": "update", "columns": null, "predicates": predicates, value: value
let request : IRequest= {
operation: "update", columns: [], predicates: predicates, value: value
};
Log.info('update request = ' + JSON.stringify(request));
requests.push(request);
callback(-1, 0);
callback(err, ret);
} else {
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates, function (err, ret) {
rdbStore.update(SettingsDataConfig.TABLE_NAME, value, predicates , (err, ret)=> {
callback(err, ret);
Log.info('update result: ' + ret);
});
@ -133,26 +160,26 @@ export default class DataExtAbility extends DataShareExtensionAbility {
this.verifyPermission(value, rdbUpData);
} catch (err) {
Log.error('upData error:' + JSON.stringify(err));
callback(-1, 0);
callback(err, ret);
}
}
delete(uri: string, predicates, callback) {
delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>) {
Log.info('nothing to do');
}
query(uri: string, predicates, columns: Array<string>, callback) {
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: string[], callback: AsyncCallback<Object>) {
Log.info( 'query start uri:' + uri);
if (rdbStore == null) {
let request= {"operation":"query", "columns" : columns, "predicates" : predicates, value:""};
let request: IRequest= {operation:"query", columns : columns, predicates : predicates, value:null};
Log.info('query request = '+ JSON.stringify(request));
requests.push(request);
callback(-1, {"_napiwrapper":{}});
callback(err, {"_napiwrapper":{}});
} else {
rdbStore.query(SettingsDataConfig.TABLE_NAME, predicates, columns, function (err, resultSet) {
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));
});
})
}
}
@ -161,7 +188,7 @@ export default class DataExtAbility extends DataShareExtensionAbility {
case SETTINGS_AUDIO_RINGTONE:
try {
let volumeType = Audio.AudioVolumeType.RINGTONE;
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Audio.getAudioManager().setVolume(volumeType, Number(settingsValue)).then(() => {
Log.info('settings Promise returned to indicate a successful RINGTONE setting.')
});
} catch (err) {
@ -171,7 +198,7 @@ export default class DataExtAbility extends DataShareExtensionAbility {
case SETTINGS_AUDIO_MEDIA:
try {
let volumeType = Audio.AudioVolumeType.MEDIA;
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Audio.getAudioManager().setVolume(volumeType, Number(settingsValue)).then(() => {
Log.info('settings Promise returned to indicate a successful MEDIA setting.')
});
} catch (err) {
@ -181,7 +208,7 @@ export default class DataExtAbility extends DataShareExtensionAbility {
case SETTINGS_AUDIO_VOICE_CALL:
try {
let volumeType = Audio.AudioVolumeType.VOICE_CALL;
Audio.getAudioManager().setVolume(volumeType, parseInt(settingsValue)).then(() => {
Audio.getAudioManager().setVolume(volumeType, Number(settingsValue)).then(() => {
Log.info('settings Promise returned to indicate a successful VOICE_CALL setting.')
});
} catch (err) {
@ -194,8 +221,8 @@ export default class DataExtAbility extends DataShareExtensionAbility {
}
}
private verifyPermission(value, callBack) {
if (this.isTrustList(value[SettingsDataConfig.FIELD_KEYWORD]) || process.uid == rpc.IPCSkeleton.getCallingUid()) {
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;
}
@ -221,7 +248,7 @@ export default class DataExtAbility extends DataShareExtensionAbility {
}
}
private isTrustList(keyWord: String): boolean {
private isTrustList(keyWord: string): boolean {
return trustList.includes(keyWord)
}
}

View File

@ -17,33 +17,36 @@ 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 : '
interface IContent {
settings: Array<Map<string,string>> ;
}
export default class UserChangeStaticSubscriber extends StaticSubscriberExtensionAbility {
async onReceiveEvent(event) {
async onReceiveEvent(event: commonEventManager.CommonEventData) {
if (!event) {
return
}
Log.info(TAG + 'onReceiveEvent, event' + JSON.stringify(event))
let rdb: ohosDataRdb.RdbStore = await SettingsDBHelper.getInstance().getRdbStore();
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, []);
await rdb?.executeSql(SettingsDBHelper.CURRENT_USER_TABLE_CREATE_PREFIX + event.code + SettingsDBHelper.TABLE_CREATE_SUFFIX, []);
// 加载用户数据表的默认值
try {
let content = await SettingsDBHelper.getInstance().readDefaultFile();
let content = await SettingsDBHelper.getInstance().readDefaultFile() as IContent;
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)
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) {
@ -52,7 +55,7 @@ export default class UserChangeStaticSubscriber extends StaticSubscriberExtensio
break
case commonEventManager.Support.COMMON_EVENT_USER_REMOVED:
// 删除对应用户的数据表
rdb.executeSql(CURRENT_USER_TABLE_DROP + event.code, []);
rdb?.executeSql(CURRENT_USER_TABLE_DROP + event.code, []);
break
default:
break

View File

@ -0,0 +1,30 @@
/**
* 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 hiLog from '@ohos.hilog';
import common from '@ohos.app.ability.common';
import SettingsDBHelper from './SettingsDBHelper';
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

@ -13,23 +13,29 @@
* limitations under the License.
*/
import common from '@ohos.app.ability.common';
import dataStorage from '@ohos.data.preferences';
import deviceInfo from '@ohos.deviceInfo';
import ohosDataRdb from '@ohos.data.rdb';
import relationalStore from '@ohos.data.relationalStore';
import i18n from '@ohos.i18n';
import settings from '@ohos.settings';
import systemParameter from '@ohos.systemparameter';
import SettingsDataConfig from '../Utils/SettingsDataConfig';
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";
const TIME_FORMAT = {
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
@ -38,25 +44,27 @@ class SettingsDBHelper {
+ `${SettingsDataConfig.FIELD_KEYWORD} TEXT, `
+ `${SettingsDataConfig.FIELD_VALUE} TEXT CHECK (LENGTH(VALUE)<=1000))`;
private rdbStore_: ohosDataRdb.RdbStore;
private context_;
private rdbStore_?: relationalStore.RdbStore;
private context_ ;
private readonly DEFAULT_USER_ID: number = 100;
private constructor() {
this.rdbStore_ = undefined;
this.context_ = globalThis.abilityContext;
this.context_ = GlobalContext.thisContext as common.BaseContext;
Log.info("context_ start"+ JSON.stringify(this.context_));
}
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)
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.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 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();
@ -67,7 +75,11 @@ class SettingsDBHelper {
public async initRdbStore() {
Log.info('call initRdbStore start');
this.rdbStore_ = await ohosDataRdb.getRdbStore(this.context_, { name: SettingsDataConfig.DB_NAME }, 1);
let rdbStore = await relationalStore.getRdbStore(this.context_, { name: SettingsDataConfig.DB_NAME,securityLevel:1 });
if(rdbStore){
this.rdbStore_ = rdbStore;
}
await this.firstStartupConfig();
@ -75,21 +87,23 @@ class SettingsDBHelper {
return this.rdbStore_;
}
public static getInstance() {
if (!globalThis.settingsDBHelper) {
globalThis.settingsDBHelper = new SettingsDBHelper();
public static getInstance(): SettingsDBHelper {
Log.info("getInstance GlobalContext" + JSON.stringify(GlobalContext));
if(GlobalContext.dbHelper === undefined){
GlobalContext.dbHelper = new SettingsDBHelper();
}
return globalThis.settingsDBHelper;
return GlobalContext.dbHelper as SettingsDBHelper;
}
public async getRdbStore() {
if (!this.rdbStore_) {
return await globalThis.settingsDBHelper.initRdbStore();
return await (GlobalContext.dbHelper as SettingsDBHelper).initRdbStore();
// return await globalThis.settingsDBHelper.initRdbStore();
}
return this.rdbStore_
}
private async loadGlobalSettings(key, value): Promise<void> {
private async loadGlobalSettings(key: string, value: string): Promise<void> {
if (!this.rdbStore_) {
Log.error('rdbStore is null!');
return
@ -104,7 +118,7 @@ class SettingsDBHelper {
);
}
public async loadUserSettings(key, value, userId: number): Promise<void> {
public async loadUserSettings(key: string, value: string, userId: number): Promise<void> {
if (!this.rdbStore_) {
Log.error('rdbStore is null!');
return
@ -119,11 +133,11 @@ class SettingsDBHelper {
});
}
public async readDefaultFile() {
public async readDefaultFile(): Promise<Object> {
let rawStr: string = "";
try {
let content = await this.context_.resourceManager.getRawFile(DEFAULT_JSON_FILE_NAME);
rawStr = String.fromCharCode.apply(null, content);
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);
}
@ -135,21 +149,21 @@ class SettingsDBHelper {
return rawStr;
}
private async loadDefaultSettingsData() {
private async loadDefaultSettingsData(): Promise<void> {
Log.info("loadDefaultSettingsData start");
try {
let content = await this.readDefaultFile();
let content = await this.readDefaultFile() as IContent;
if (!content) {
Log.error("readDefaultFile is failed!");
return
return;
}
for (var index = 0; index < content.settings.length; index++) {
if (content.settings[index].userConfig) {
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)
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);
await this.loadGlobalSettings(content.settings[index]["name"], content.settings[index]["value"]);
}
}
} catch (err) {

View File

@ -13,7 +13,15 @@
* limitations under the License.
*/
const SettingsDataConfig = {
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',

1232
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,19 +0,0 @@
{
"license":"ISC",
"devDependencies":{},
"name":"applications_settings_data",
"ohos":{
"org":"huawei",
"directoryLevel":"project",
"buildTool":"hvigor"
},
"description":"example description",
"repository":{},
"version":"1.0.0",
"dependencies":{
"@ohos/hypium":"1.0.1",
"@ohos/hvigor-ohos-plugin":"1.1.6",
"hypium":"^1.0.0",
"@ohos/hvigor":"1.1.6"
}
}