整个集合公共方法库
import { promptAction, router } from '@kit.ArkUI';
import { call } from '@kit.TelephonyKit';
import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
import CryptoJS from '@ohos/crypto-js'
import { abilityAccessCtrl, bundleManager, Context } from '@kit.AbilityKit';
import { client_secret, test_public_key } from './until/config';
import { ResponseResult } from './until/api';
import { localStorage } from './until/GlobalContext';
import { buffer, util } from '@kit.ArkTS';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { routerParamsType } from './until/type';
import { geoLocationManager } from '@kit.LocationKit';
class ShowToast {
private longToastTime: number = 3000;
private shortToastTime: number = 1000;
showToast(message: ResourceStr, duration: number) {
promptAction.showToast({ message: message, duration: duration, bottom: 200 });
}
shortToast(message: ResourceStr) {
this.showToast(message, this.shortToastTime);
}
longToast(message: ResourceStr) {
this.showToast(message, this.longToastTime);
}
}
let ShowT = new ShowToast()
function expMobile(phoneNumber: string): boolean {
const regex = /^1\d{10}$/;
const isValid = regex.test(phoneNumber);
if (isValid) {
return true
} else {
console.log("手机号码不合规");
return false
}
}
function callForAnyone(mobile: string): void {
if (canIUse("SystemCapability.Applications.Contacts")) {
call.makeCall(mobile, (err: BusinessError) => {
if (err) {
console.error(`makeCall fail, err->${JSON.stringify(err)}`);
} else {
console.log(`makeCall success`);
}
});
} else {
let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, '4009960033');
pasteboard.getSystemPasteboard().setData(pasteData, (error) => {
if (error.code) {
ShowT.shortToast(error.message)
} else {
ShowT.shortToast('该设备不支持拨打电话,已帮您复制到剪切板')
}
})
}
}
function checkPassword(password: string) {
const regex = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
return regex.test(password);
}
interface custom_dialog_list_int {
icon?: Resource | string
value: string
id?: number
}
@CustomDialog
struct customDialog_Text {
private controller: CustomDialogController = new CustomDialogController({
builder: customDialog_Text()
});
@Prop showBtn: boolean
@Prop backgroundC: string | Resource
@Prop menjin_name: string
@State c_m_name: string = ''
private confirm: Function = () => {
}
aboutToAppear(): void {
this.c_m_name = this.menjin_name
}
build() {
Column() {
Text('编辑门禁名称').margin({ top: 20, bottom: 20 })
TextInput({ placeholder: '请填写', text: this.c_m_name })
.placeholderColor('#888')
.backgroundColor('#fff')
.width('100%')
.padding({ left: 0 })
.margin({ bottom: 20 })
.fontSize($r('app.float.progress_font'))
.selectedBackgroundColor('#fff')
.placeholderFont({ size: $r('app.float.progress_font') })
.border({
width: 1,
color: $r('app.color.gray_color')
})
.onChange((val: string) => this.c_m_name = val)
if (this.showBtn) {
Row() {
Button('取消').margin(10).backgroundColor('#fff').fontColor('#000')
.onClick(() => {
this.controller.close()
console.info(JSON.stringify(this.controller.close))
})
Button('确定').margin(10).backgroundColor($r('app.color.theme_color'))
.onClick(() => {
this.confirm(this.c_m_name)
})
}.width('100%').justifyContent(FlexAlign.SpaceBetween)
}
}.padding(12).backgroundColor(this.backgroundC || '#fff').width('100%')
}
}
function signInfo(params: string): string {
return CryptoJS.MD5(sortQueryStringByParamName(params) + "&secret=" + client_secret).toString().toUpperCase()
}
function sortQueryStringByParamName(queryString: string): string {
let keyValuePairs: string[]
keyValuePairs = queryString.split('&');
const sortedParamNames = keyValuePairs.map(pair => pair.split('=')[0]).sort();
let list: string[] = [];
sortedParamNames.map((name: string) => {
let new_arr: string = keyValuePairs.filter((item: string) => {
return item.indexOf(name + '=') != -1
})[0] || ''
if (new_arr) {
list.push(new_arr)
}
});
return list.join('&');
}
function generateRandomString(length = 32) {
const characters: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
result += characters[randomIndex];
}
return result.toString().toUpperCase();
}
function returnBundleInfo(): Promise<bundleManager.BundleInfo> {
return new Promise((resolve: Function, reject: Function) => {
bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo) => {
resolve(bundleInfo)
}).catch((error: BusinessError) => {
reject({})
console.error("get bundleInfo failed,error is " + error)
})
})
}
function urlEncode(str: string) {
return encodeURIComponent(str)
.replace(/[!'()*]/g, (c) => {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
async function login_to_do(res: ResponseResult) {
let data = res as ResponseResult
if (!data.token_type) {
return
} else {
if (typeof res == 'object' && res.access_token) {
await localStorage.setItem('token', data.access_token || '');
await localStorage.setItem('refresh_token', data.refresh_token || '')
routerClear()
routerReplace('pages/home/homePage')
}
}
}
async function encryptRSA(message: string) {
let pubKeyStr = test_public_key;
let base64Helper = new util.Base64Helper();
let pubKeyBlob: cryptoFramework.DataBlob = { data: base64Helper.decodeSync(pubKeyStr) };
let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
let keyPair = await rsaGenerator.convertKey(pubKeyBlob, null);
let cipher = cryptoFramework.createCipher('RSA1024|PKCS1');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
let plainTextBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
let encryptBlob = await cipher.doFinal(plainTextBlob);
return base64Helper.encodeToStringSync(encryptBlob.data);
}
class routerList {
public url: string = '';
public params: routerParamsType = {}
constructor(url: string, params?: routerParamsType) {
this.url = url;
if (params) {
this.params = params
}
}
}
let r_list: routerList[] = [new routerList('pages/welcome/welcome')]
function pushUrl(url: string, params?: routerParamsType) {
if (params) {
}
if (r_list.length < 30) {
r_list.push(new routerList(url, params))
} else {
r_list.shift()
r_list.push(new routerList(url, params))
}
router.pushUrl({
url: url,
params: params
})
}
function routerBack(url?: string | number, param?: routerParamsType) {
console.log(JSON.stringify(r_list))
if (typeof url == 'string') {
let needChangeIndex = -1;
let index = r_list.length;
let r_param: routerParamsType = {}
r_list.map((v, i) => {
if (v.url == url) {
needChangeIndex = i
r_param = v.params
}
})
r_list.splice(needChangeIndex, index - needChangeIndex);
r_list.push(new routerList(url, param || r_param))
router.pushUrl({
url: url,
params: param || r_param
})
} else if (typeof url == 'number') {
for (let i = 0; i < url; i++) {
r_list.pop();
}
let index = r_list.length;
if (index == 0) {
router.back()
} else {
router.back({
url: r_list[index-1].url,
params: r_list[index-1].params
})
}
} else {
r_list.pop();
let index = r_list.length;
if (index == 0) {
router.back()
} else {
router.back({
url: r_list[index-1].url,
params: r_list[index-1].params
})
}
}
}
function routerClear() {
r_list = []
router.clear()
}
function routerReplace(url: string, params?: routerParamsType) {
r_list.pop();
r_list.push(new routerList(url, params))
router.replaceUrl({
url: url,
params: params
})
}
function missToken(msg: string) {
let str = false;
console.log(msg, 'missToken')
switch (msg) {
case '无效的color-token':
str = true;
break;
case 'oauth认证失败':
str = true;
break;
case 'The refresh token is invalid.':
str = true;
break;
default:
break;
}
return str
}
function hidePhoneNumber(phoneNumber: string): string {
if (phoneNumber.length !== 11) {
return phoneNumber
}
const prefix = phoneNumber.substring(0, 3);
const suffix = phoneNumber.substring(7);
return `${prefix}****${suffix}`;
}
async function saveCache(name: string, reload?: boolean): Promise<string> {
if (reload) {
return ''
} else {
let data: string;
if (name.indexOf('big') != -1) {
data = await localStorage.getBigItem(name)
} else {
data = await localStorage.getItem(name) as string
}
if (data && typeof data == 'string') {
return data
} else {
return ''
}
}
}
function validateEmail(email: string) {
const re = /\S+@\S+.\S+/;
return re.test(email);
}
function jumpUrl(str: string) {
if (str.indexOf('http') == -1) {
ShowT.longToast('请扫描二维码链接')
routerBack()
} else {
pushUrl('pages/web/webPage', { link: str })
}
}
function getLocation(context: Context): Promise<geoLocationManager.GeoAddress[]> {
return new Promise(async (resolve: Function, reject: Function) => {
let isLocation_flag = await localStorage.getItem('privacy_location')
if (isLocation_flag && String(isLocation_flag) != 'true') {
ShowT.shortToast('请先打开隐私=>通过地理位置搜索到我')
reject([])
return
}
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(context,
['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
.then(async (data) => {
const requestResponse = async (location: geoLocationManager.Location) => {
console.info(`enter requestResponse`)
let reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest = {
"latitude": location.latitude,
"longitude": location.longitude,
"maxItems": 1
};
try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, async (err, data) => {
if (err) {
console.info('getAddressesFromLocation: err=' + JSON.stringify(err));
reject([])
}
if (data) {
let administrativeArea = data[0].administrativeArea as string;
if (administrativeArea.length > 4) {
if (administrativeArea.length === 6) {
administrativeArea = '内蒙古'
} else {
let arr = administrativeArea.split('')
arr.length = 2
administrativeArea = arr.join('')
}
} else {
let arr = administrativeArea.split('')
arr.length = arr.length - 1
administrativeArea = arr.join('')
}
console.info('getAddressesFromLocation: data=' + JSON.stringify(data));
resolve(data)
await geoLocationManager.off('locationChange')
}
});
} catch (error) {
reject([])
console.info(`http request error: ${JSON.stringify(error)}`)
}
}
let requestInfo: geoLocationManager.LocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'scenario': geoLocationManager.LocationRequestScenario.UNSET,
'timeInterval': 1,
'distanceInterval': 0,
'maxAccuracy': 0
};
try {
geoLocationManager.on('locationChange', requestInfo, async (location: geoLocationManager.Location) => {
console.log(JSON.stringify(location), 'location')
await requestResponse(location)
});
} catch (err) {
console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
reject([])
}
console.info(`on locationChange end`)
})
.catch((err: BusinessError) => {
console.warn(`err:APPROXIMATELY_LOCATION ${JSON.stringify(err)}`)
ShowT.shortToast('您关闭了定位服务,请开启')
})
} catch (err) {
console.warn(`catch errAPPROXIMATELY_LOCATION->${JSON.stringify(err)}`)
reject([])
}
})
}
function timestampToTime(params: number, jestDate?: boolean) {
const date = new Date(params);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
let formattedDateTime: string
if (jestDate) {
formattedDateTime = `${year}-${month}-${day} `;
} else {
formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
return formattedDateTime
}
function formatDuration(timestamp: number) {
const seconds = Math.floor(timestamp / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(months / 12);
const remainingDays = days % 30;
const remainingHours = hours % 24;
if (years > 0) {
return years + '年';
} else if (months > 0) {
return months + '个月';
} else if (remainingDays > 0) {
return remainingDays + '天';
} else {
return remainingHours + '小时';
}
}
interface calculateTimestampType{
currentTimestamp:number,
futureTimestamp:number
}
function calculateTimestamp(value: number): calculateTimestampType {
const now = new Date();
let futureDate = new Date();
if (value === 1) {
futureDate.setDate(now.getDate() + 7);
} else if (value === 2) {
futureDate.setMonth(now.getMonth() + 1);
} else if (value === 3) {
futureDate.setMonth(now.getMonth() + 6);
} else if (value === 4) {
futureDate.setFullYear(now.getFullYear() + 1);
}
const currentTimestamp = now.getTime();
const futureTimestamp = futureDate.getTime();
return {
currentTimestamp: Math.floor(currentTimestamp / 1000),
futureTimestamp: Math.floor(futureTimestamp / 1000)
};
}
function gotoWeb(url: string) {
if (url.indexOf('http') == 0) {
pushUrl('pages/web/webPage', { link: url })
} else if (url.indexOf('pages') != -1) {
ShowT.shortToast('暂不支持跳转小程序,请等待')
} else if (url.indexOf('colourlife') == 0) {
ShowT.shortToast('开发中,敬请期待')
} else {
}
}
function hideName(name: string): string {
if (name.length > 1) {
const hiddenPart = '*'.repeat(name.length - 1);
return hiddenPart + name.charAt(name.length - 1);
} else if (name.length === 1) {
return name;
} else {
return ''
}
}
function isValidIDCard(idCard: string): boolean {
if (idCard.length !== 18) {
return false;
}
const idRegex = /^\d{17}[\dXx]$/;
if (!idRegex.test(idCard)) {
return false;
}
const birthDateStr = idCard.substring(6, 14);
const year = parseInt(birthDateStr.substring(0, 4), 10);
const month = parseInt(birthDateStr.substring(4, 6), 10);
const day = parseInt(birthDateStr.substring(6, 8), 10);
const birthDate = new Date(year, month - 1, day);
if (
birthDate.getFullYear() !== year ||
birthDate.getMonth() + 1 !== month ||
birthDate.getDate() !== day
) {
return false;
}
const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const checkSumChars = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let sum = 0;
for (let i = 0; i < 17; i++) {
sum += parseInt(idCard[i], 10) * weightFactors[i];
}
const modValue = sum % 11;
const checkChar = checkSumChars[modValue];
return checkChar === idCard[17].toUpperCase();
}
function getMonthRangeTimestamps(year: number, month: number): [number, number] {
const startOfMonth = new Date(year, month - 1, 1);
const startTimestamp = startOfMonth.getTime() / 1000;
let endOfMonth: Date;
if (month === 12) {
endOfMonth = new Date(year + 1, 0, 1);
} else {
endOfMonth = new Date(year, month, 1);
}
const endTimestamp = (endOfMonth.getTime() / 1000) - 1;
return [startTimestamp, endTimestamp];
}
function isValidPassword(password: string): boolean {
const hasNumber = /[0-9]/.test(password);
const hasLetter = /[a-zA-Z]/.test(password);
const isAlphanumeric = /^[a-zA-Z0-9]{6,20}$/.test(password);
return hasNumber && hasLetter && isAlphanumeric;
}
export { ShowT,
expMobile,
checkPassword,
customDialog_Text,
signInfo,
returnBundleInfo,
generateRandomString,
login_to_do,
encryptRSA,
pushUrl,
routerBack,
routerClear,
routerReplace,
missToken,
hidePhoneNumber,
callForAnyone,
saveCache,
validateEmail,
urlEncode,
jumpUrl,
getLocation,
timestampToTime,
calculateTimestamp,
gotoWeb,
hideName,
isValidIDCard,getMonthRangeTimestamps ,isValidPassword};
其中 引入部分有些字段根据你实际项目决定是否保留,如有需要,则自行补充
config.ts
./until/config.ts
client_secret
test_public_key
api.ets
./until/api.ets
class ResponseResult {
code: number;
message: string ;
content: string | Object | ArrayBuffer;
contentEncrypt: string
token_type?: string;
expires_in?: number;
access_token?: string;
refresh_token?: string;
specialInfo?: string;
constructor() {
this.code = -1;
this.message = '';
this.content = '';
this.contentEncrypt = ''
}
}
export {ResponseResult}
GlobalContext.ets
import { distributedKVStore, preferences } from '@kit.ArkData'
import { BusinessError } from '@kit.BasicServicesKit';
import { bundleManager } from '@kit.AbilityKit';
class GlobalContext {
private constructor() {
}
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
let that = this
class LocalStorage {
public getKvStore(): Promise<distributedKVStore.SingleKVStore> {
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA;
let info_: bundleManager.BundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags)
let kvManagerConfig: distributedKVStore.KVManagerConfig = {
context: getContext(that),
bundleName: info_.name
};
let kvManager: distributedKVStore.KVManager = distributedKVStore.createKVManager(kvManagerConfig)
return new Promise((resolve: Function, reject: Function) => {
try {
const options: distributedKVStore.Options = {
createIfMissing: true,
encrypt: false,
backup: false,
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
securityLevel: distributedKVStore.SecurityLevel.S2
};
kvManager.getKVStore('storeId', options, (err, kvStore: distributedKVStore.SingleKVStore) => {
if (err) {
console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`);
reject('err')
return;
}
console.info('Succeeded in getting KVStore.');
resolve(kvStore)
});
} catch (e) {
reject('err')
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
}
})
}
getItem(value: string): Promise<string | Object | number | boolean | null | undefined> {
return new Promise((resolve: Function, reject: Function) => {
preferences.getPreferences(getContext(this), 'myStore').then((obj: preferences.Preferences) => {
obj.has(value).then(async (isExit: Boolean) => {
if (!isExit) {
resolve('')
} else {
let res: preferences.ValueType = await obj.get(value, '');
resolve(res)
}
}).catch((err: Error) => {
reject(JSON.stringify(err))
})
}).catch((err: Error) => {
reject(JSON.stringify(err))
})
})
}
setItem(value: string, data: preferences.ValueType): Promise<null> {
return new Promise((resolve: Function) => {
preferences.getPreferences(getContext(this), 'myStore').then((obj: preferences.Preferences) => {
obj.has(value).then(async (isExit: Boolean) => {
obj.put(value, data)
obj.flush()
resolve(null)
})
})
})
}
clearItem(): Promise<null> {
return new Promise((resolve: Function) => {
preferences.deletePreferences(getContext(this), 'myStore', (err: BusinessError) => {
if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return;
}
resolve(null)
console.info("Succeeded in deleting preferences.");
})
})
}
getBigItem(value: string): Promise<string> {
return new Promise((resolve: Function) => {
this.getKvStore().then((kvStore: distributedKVStore.SingleKVStore) => {
try {
kvStore.get(value, (err, data) => {
if (err !== undefined) {
console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
resolve('')
return;
}
resolve(data)
});
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
resolve('')
}
})
})
}
setBigItem(value: string, data: string): Promise<string> {
return new Promise((resolve: Function) => {
this.getKvStore().then((kvStore: distributedKVStore.SingleKVStore) => {
try {
kvStore.put(value, data, (err) => {
if (err !== undefined) {
console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
resolve('')
return;
}
resolve('success')
console.info('Succeeded in putting data.');
});
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
resolve('')
}
})
})
}
deleteBigItem(value: string): Promise<string> {
return new Promise((resolve: Function) => {
this.getKvStore().then((kvStore: distributedKVStore.SingleKVStore) => {
kvStore.delete(value, (err) => {
if (err !== undefined) {
console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
resolve('')
return;
}
resolve('success')
console.info('Succeeded in deleting data.');
})
})
})
}
}
const localStorage = new LocalStorage()
export {
GlobalContext, LocalStorage, localStorage, }
type.ets
interface routerParamsType {
mobile?: string,
psw?: string,
link?: string,
prev_page_url?: string,
sms_token?: string,
hasGesture?:number,
hasPassword?:number,
hasOptions?:boolean,
isCallback?:boolean,
result?:Array<scanBarcode.ScanResult>,
uri?:string,
infoW?:number,
infoH?:number,
options?:scanBarcode.ScanOptions,
identity_id?:number,
invalid_unit?: getAllCommunityKeyDataListinvalid_unitType[],
authorization_detail_item?:remoteDoorAuthorizeListApply_listType | remoteDoorAuthorizeListAuthorization_listType,
title?:string,
pano?:string,
mobileInfo?:wallet_getInfoByMobileType,
amount?:number,
state?:number,
token?:string,
sn?:string,
}
export {routerParamsType}