第一次提交

This commit is contained in:
xiaoxiao
2025-05-09 15:47:54 +08:00
parent 25e596b591
commit f9d7986df0
357 changed files with 26943 additions and 0 deletions
@@ -0,0 +1,84 @@
import util from '@ohos.util';
import { buffer } from '@kit.ArkTS';
/**
* Base64 工具类
* author: 鸿蒙布道师
* since: 2025/03/31
*/
export class Base64Util {
/**
* 创建 Base64Helper 实例
* @returns Base64Helper 实例
*/
private static createBase64Helper(): util.Base64Helper {
return new util.Base64Helper();
}
/**
* 编码为 Uint8Array(异步)
* @param array 输入的 Uint8Array 数据
* @returns 编码后的 Uint8Array 对象
*/
static encode(array: Uint8Array): Promise<Uint8Array> {
const base64 = Base64Util.createBase64Helper();
return base64.encode(array);
}
/**
* 编码为 Uint8Array(同步)
* @param array 输入的 Uint8Array 数据
* @returns 编码后的 Uint8Array 对象
*/
static encodeSync(array: Uint8Array): Uint8Array {
const base64 = Base64Util.createBase64Helper();
return base64.encodeSync(array);
}
/**
* 编码为字符串(异步)
* @param array 输入的 Uint8Array 数据
* @param options 可选参数
* @returns 编码后的字符串
*/
static encodeToStr(array: Uint8Array, options?: util.Type): Promise<string> {
const base64 = Base64Util.createBase64Helper();
return base64.encodeToString(array, options);
}
/**
* 编码为字符串(同步)
* @param array 输入的 Uint8Array 数据
* @param options 可选参数
* @returns 编码后的字符串
*/
static encodeToStrSync(keyValueStr:string): string {
let array: Uint8Array=new Uint8Array(buffer.from(keyValueStr, 'utf-8').buffer)
const base64 = Base64Util.createBase64Helper();
return base64.encodeToStringSync(array, util.Type.BASIC).replaceAll("=", "");
}
/**
* 解码为 Uint8Array(异步)
* @param input 输入的 Uint8Array 或字符串
* @param options 可选参数
* @returns 解码后的 Uint8Array 对象
*/
static decode(input: Uint8Array | string, options?: util.Type): Promise<Uint8Array> {
const base64 = Base64Util.createBase64Helper();
return base64.decode(input, options);
}
/**
* 解码为 Uint8Array(同步)
* @param input 输入的 Uint8Array 或字符串
* @param options 可选参数
* @returns 解码后的 Uint8Array 对象
*/
static decodeSync(input: Uint8Array | string, options?: util.Type): Uint8Array {
const base64 = Base64Util.createBase64Helper();
return base64.decodeSync(input, options);
}
}
@@ -0,0 +1,61 @@
import HashMap from '@ohos.util.HashMap';
import { Base64Util } from './Base64Util';
export class ChangeUtil {
/**
* 将HashMap转成JsonString
* @param map
* @returns
*/
static map2Json(map:HashMap<string, string>): string {
let jsonObject: Record<string, Object> = {};
map.forEach((value, key) => {
if(key != undefined && value != undefined){
jsonObject[key] = value;
}
})
return JSON.stringify(jsonObject);
}
static getSign(extraDatas1:HashMap<string, string>): string {
let secret= extraDatas1.get("timestamp")
if(secret!=null) {
let keyValueStr: string = "";
let entriesArray: Array<string> = Array.from(extraDatas1.keys());
entriesArray.sort();
let sortedMap:HashMap<string, string> = new HashMap();
entriesArray.forEach((value: string, index: number) => {
sortedMap.set(value,extraDatas1.get(value));
keyValueStr +=value+extraDatas1.get(value)
});
keyValueStr = keyValueStr.replace(" ", "");
keyValueStr = keyValueStr + CryptoJS.MD5(secret).toString();
let Md5keyValueStr: string = CryptoJS.MD5(keyValueStr).toString();
let base64Str:string=Base64Util.encodeToStrSync(Md5keyValueStr);
return base64Str;
}
else
{
return '';
}
}
static isMobileNum(mobiles:string): boolean {
const reg2: RegExp = new RegExp('^(1[3-9])[0-9]{9}$')
return reg2.test(mobiles);
}
static isPassword(password:string): boolean {
const reg2: RegExp = new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$')
return reg2.test(password);
}
}
@@ -0,0 +1,33 @@
import hilog from '@ohos.hilog'
const DOMAIN = 0xFF09
const PREFIX = 'PASS_INTERVIEW_LOGGER'
const FORMAT = '%{public}s, %{public}s'
class Logger {
debug(...args: string[]) {
hilog.debug(DOMAIN, PREFIX, FORMAT, args)
}
info(...args: string[]) {
hilog.info(DOMAIN, PREFIX, FORMAT, args)
}
warn(...args: string[]) {
hilog.warn(DOMAIN, PREFIX, FORMAT, args)
}
error(...args: string[]) {
hilog.error(DOMAIN, PREFIX, FORMAT, args)
}
fatal(...args: string[]) {
hilog.fatal(DOMAIN, PREFIX, FORMAT, args)
}
isLoggable(level: hilog.LogLevel) {
hilog.isLoggable(DOMAIN, PREFIX, level)
}
}
export const logger = new Logger()
@@ -0,0 +1,288 @@
import { http } from '@kit.NetworkKit';
import { promptAction, router } from '@kit.ArkUI';
import { BusinessError } from '@ohos.base';
import { HashMap } from '@kit.ArkTS';
import { CryptoJS } from '@ohos/crypto-js'
import { Base64Util } from './Base64Util';
import { ChangeUtil } from './ChangeUtil'
import { logger } from './logger'
interface HdRequestOptions {
baseURL?: string
}
type HdParams = Record<string, string | number | boolean>
export interface HdResponse<T> {
code: number
message: string
data: T
}
export interface TimestampBean {
timestamp:string
}
class HdHttp {
baseURL: string
constructor(options: HdRequestOptions) {
this.baseURL = options.baseURL || ''
}
private request1<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraDatas:HashMap<string, string>) {
const httpInstance = http.createHttp()
let fullUrl = this.baseURL + path
let promise = httpInstance.request(
// 请求url地址
fullUrl,
{
// 请求方式
method: http.RequestMethod.POST,
// 可选,默认为60s
connectTimeout: 60000,
// 可选,默认为60s
readTimeout: 60000,
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json',
'sign':this.getSign(extraDatas)
},
extraData:ChangeUtil.map2Json(extraDatas)
});
logger.info('Response JSON.stringify(extraDatas)' + ChangeUtil.map2Json(extraDatas))
return promise.then((data) => {
logger.info('Response request:' + data.result);
if (data.result) {
const result = data.result as HdResponse<T>
logger.info('Response result:' + result);
return result
}
return Promise.reject(data.result)
// if (data.responseCode === http.ResponseCode.OK) {
// console.info('Response request:' + data.result);
//
// }
// else
// {
//
// }
// return Promise.reject(data.result)
}
).catch((err:BusinessError) => {
logger.info('Response httpReq request:' + JSON.stringify(err));
return Promise.reject(err)
}).finally(() => {
httpInstance.destroy()
})
}
private request<T>(path: string, method: http.RequestMethod = http.RequestMethod.POST, extraDatas :HashMap<string, string>) {
const httpInstance = http.createHttp()
const options: http.HttpRequestOptions = {
method: http.RequestMethod.POST,
// 可选,默认为60s
connectTimeout: 60000,
// 可选,默认为60s
readTimeout: 60000,
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json',
'sign':this.getSign(extraDatas)
},
extraData:ChangeUtil.map2Json(extraDatas)
}
let fullUrl = this.baseURL + path
return httpInstance.request(fullUrl, options).then((res) => {
logger.info('Response fullUrl:' +fullUrl+ res.result);
const result = res.result as HdResponse<T>
return result
}).catch((err: BusinessError) => {
logger.info(fullUrl+`Response succeeded: ${err}`);
promptAction.showToast({ message: err.message || '网络错误' })
return Promise.reject(err)
}).finally(() => {
httpInstance.destroy()
})
}
private requestafter<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraData?: Object) {
const httpInstance = http.createHttp()
const options: http.HttpRequestOptions = {
method: http.RequestMethod.GET,
// 可选,默认为60s
connectTimeout: 60000,
// 可选,默认为60s
readTimeout: 60000,
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
}
}
let fullUrl = this.baseURL + path
if (method === http.RequestMethod.GET && extraData) {
const strArr = Object.keys(extraData)
.filter(key => (extraData as HdParams)[key] !== undefined)
.map(key => `${key}=${(extraData as HdParams)[key]}`)
fullUrl += `?${strArr.join('&')}`
} else {
options.extraData = extraData
}
return httpInstance.request(fullUrl, options).then((res) => {
return Promise.reject(res.result)
}).catch((err: BusinessError) => {
logger.error(fullUrl+`Response succeeded: ${err}+${err.name}+${err.message}+${err.data}+${err.stack}`);
// logger.error(fullUrl, err.code?.toString(), err.message)
promptAction.showToast({ message: err.message || '网络错误' })
return Promise.reject(err)
}).finally(() => {
httpInstance.destroy()
})
}
get<T>(url: string, data?: Object): Promise<HdResponse<T>> {
return this.requestafter<T>(url, http.RequestMethod.GET, data)
}
post<T>(url: string, data?: Object): Promise<HdResponse<T>> {
return this.requestafter<T>(url, http.RequestMethod.POST, data)
}
put<T>(url: string, data?: Object): Promise<HdResponse<T>> {
return this.requestafter<T>(url, http.RequestMethod.PUT, data)
}
delete<T>(url: string, data?: Object): Promise<HdResponse<T>> {
return this.requestafter<T>(url, http.RequestMethod.DELETE, data)
}
posts<T>(url: string, data: HashMap<string, string>): Promise<HdResponse<T>> {
return this.request<T>(url, http.RequestMethod.POST, data)
}
httpReq<T>(url: string, datas: HashMap<string, string>): Promise<HdResponse<T>> {
// 创建httpRequest对象。
let httpRequest = http.createHttp();
let url1 = "https://dev-app.igandan.com/app/manager/getSystemTimeStamp";
let promise = httpRequest.request(
// 请求url地址
url1,
{
// 请求方式
method: http.RequestMethod.GET,
// 可选,默认为60s
connectTimeout: 60000,
// 可选,默认为60s
readTimeout: 60000,
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
}
});
// 处理响应结果。
return promise.then((data) => {
if (data.responseCode === http.ResponseCode.OK) {
logger.info('Response httpReq:' + data.result);
let json:TimestampBean = JSON.parse(data.result.toString()) as TimestampBean;
let tp = json.timestamp;
datas.set("user_uuid", '');
datas.set("client_type", 'A');
datas.set("version",'4.0.0' );
datas.set('timestamp',tp+'');
return this.posts<T>(url, datas);
}
else
{
return this.posts<T>(url, datas);
}
}
).catch((err:BusinessError) => {
logger.info('Response httpReq error:' + JSON.stringify(err));
return Promise.reject(err);
}).finally(() => {
httpRequest.destroy()
})
}
httpReqSimply<T>(url: string) {
// 创建httpRequest对象。
let httpRequest = http.createHttp();
let promise = httpRequest.request(
// 请求url地址
url,
{
// 请求方式
method: http.RequestMethod.POST,
// 可选,默认为60s
connectTimeout: 60000,
// 可选,默认为60s
readTimeout: 60000,
// 开发者根据自身业务需要添加header字段
header: {
'Content-Type': 'application/json'
}
});
// 处理响应结果。
return promise.then((data) => {
logger.info('Response httpReqSimply:' + JSON.stringify(data));
const result = data.result as HdResponse<T>
return result
}
).catch((err:BusinessError) => {
logger.info('Response httpReq error:' + JSON.stringify(err));
return Promise.reject(err);
}).finally(() => {
httpRequest.destroy()
})
}
getSign(extraDatas1:HashMap<string, string>): string {
let secret= extraDatas1.get("timestamp")
if(secret!=null) {
let keyValueStr: string = "";
let entriesArray: Array<string> = Array.from(extraDatas1.keys());
entriesArray.sort();
let sortedMap:HashMap<string, string> = new HashMap();
entriesArray.forEach((value: string, index: number) => {
sortedMap.set(value,extraDatas1.get(value));
keyValueStr +=value+extraDatas1.get(value)
});
keyValueStr = keyValueStr.replace(" ", "");
keyValueStr = keyValueStr + CryptoJS.MD5(secret).toString();
let Md5keyValueStr: string = CryptoJS.MD5(keyValueStr).toString();
let base64Str:string=Base64Util.encodeToStrSync(Md5keyValueStr);
return base64Str;
}
else
{
return '';
}
}
}
export const hdHttp = new HdHttp({ baseURL: '' })
+11
View File
@@ -0,0 +1,11 @@
{
"module": {
"name": "utils",
"type": "har",
"deviceTypes": [
"default",
"tablet",
"2in1"
]
}
}
@@ -0,0 +1,8 @@
{
"float": [
{
"name": "page_text_font_size",
"value": "50fp"
}
]
}
@@ -0,0 +1,8 @@
{
"string": [
{
"name": "page_show",
"value": "page from package"
}
]
}
@@ -0,0 +1,35 @@
import { hilog } from '@kit.PerformanceAnalysisKit';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function abilityTest() {
describe('ActsAbilityTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
})
})
}
@@ -0,0 +1,5 @@
import abilityTest from './Ability.test';
export default function testsuite() {
abilityTest();
}
+13
View File
@@ -0,0 +1,13 @@
{
"module": {
"name": "utils_test",
"type": "feature",
"deviceTypes": [
"default",
"tablet",
"2in1"
],
"deliveryWithInstall": true,
"installationFree": false
}
}
+5
View File
@@ -0,0 +1,5 @@
import localUnitTest from './LocalUnit.test';
export default function testsuite() {
localUnitTest();
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function localUnitTest() {
describe('localUnitTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
});
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
});
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
});
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
});
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
});
});
}