Skip to content

Commit

Permalink
完善浏览历史记录功能
Browse files Browse the repository at this point in the history
  • Loading branch information
Luxcis committed Dec 15, 2024
1 parent c75dedb commit 1c4ab76
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 47 deletions.
2 changes: 1 addition & 1 deletion entry/patch.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"app": {
"bundleName": "com.picacomic.next",
"patchVersionCode": 2001074,
"patchVersionCode": 2001086,
"versionCode": 1000000
},
"module": {
Expand Down
2 changes: 2 additions & 0 deletions entry/src/main/ets/entryability/EntryAbility.ets
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import { AppUtil, LogUtil } from '@pura/harmony-utils'
import { StorageKey } from '../common/Consts'
import { PreferenceManager } from '../utils/Preference'
import { ImageKnife } from '@ohos/imageknife'
import { HistoryUtil } from '../utils/History'

export default class EntryAbility extends UIAbility {
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'PicaAbilityLog', '%{public}s', 'Ability onCreate')
AppUtil.init(this.context)
LogUtil.init(0x0000, 'PicaLog', true)
await HistoryUtil.init()
await ImageKnife.getInstance().initFileCache(this.context, 256, 256 * 1024 * 1024)
}

Expand Down
28 changes: 25 additions & 3 deletions entry/src/main/ets/pages/Settings.ets
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { Api, ImageApi, ImageQuality } from '../common/Config'
import { StorageKey } from '../common/Consts'
import { PreferenceItem, PreferenceManager, PreferenceStorageKey } from '../utils/Preference'
import { BackType, TitleBar, TitleType } from './component/TitleBar'
import { router } from '@kit.ArkUI'
import { promptAction, router } from '@kit.ArkUI'
import { DialogAction } from '@pura/harmony-utils/src/main/ets/entity/constraint'
import { HistoryUtil } from '../utils/History'

@Entry
@Component
Expand Down Expand Up @@ -125,6 +126,29 @@ struct Settings {
.margin({ top: 15 })
.borderRadius(10)

Column() {
Row() {
Text('清除历史')
.padding({ left: 10 })
.width('87%')

Image($r('app.media.ic_public_arrow_right'))
.width(20)
.height(20)
.fillColor($r('app.color.common_button_background_light'))
.align(Alignment.End)
}
.width('90%')
.height(50)
.backgroundColor(Color.White)
.onClick(() => {
HistoryUtil.clear()
promptAction.showToast({ message: '浏览历史清空成功', });
})
}
.margin({ top: 15 })
.borderRadius(10)

if (this.token) {
Column() {
Row() {
Expand All @@ -144,8 +168,6 @@ struct Settings {
.onClick(() => {
this.logout()
})

Divider().width('90%')
}
.margin({ top: 15 })
.borderRadius(10)
Expand Down
60 changes: 35 additions & 25 deletions entry/src/main/ets/pages/component/ComicList.ets
Original file line number Diff line number Diff line change
Expand Up @@ -32,36 +32,46 @@ export default struct ComicList {
if (this.attr.type === 'history') {
LogUtil.debug('加载浏览历史')
setTimeout(() => {
animateTo({ duration: 500 }, () => {
this.comics = HistoryUtil.get()
this.isRefreshing = false
this.scroll.scrollEdge(Edge.Top)
})
this.loadHistory()
}, 500)
} else if (this.attr.type === 'remote') {
LogUtil.debug('加载远程数据')
if (this.attr.api !== undefined) {
this.attr.api(this.page, this.attr.sort, this.attr.param1, this.attr.param2)
.then(res => {
animateTo({ duration: 500 }, () => {
if (this.page === 1) {
this.comics = res.comics.docs
this.scroll.scrollEdge(Edge.Top)
} else {
this.comics.push(...res.comics.docs)
}
})
LogUtil.debug(`加载第${this.page}页,共${res.comics.docs.length}条`)
this.page = res.comics.page
this.maxPage = res.comics.pages
this.loadRemote()
}
}

loadHistory() {
animateTo({ duration: 500 }, () => {
HistoryUtil.get().then(res => {
this.comics = res
this.isRefreshing = false
this.scroll.scrollEdge(Edge.Top)
})
})
}

loadRemote() {
if (this.attr.api !== undefined) {
this.attr.api(this.page, this.attr.sort, this.attr.param1, this.attr.param2)
.then(res => {
animateTo({ duration: 500 }, () => {
if (this.page === 1) {
this.comics = res.comics.docs
this.scroll.scrollEdge(Edge.Top)
} else {
this.comics.push(...res.comics.docs)
}
})
.finally(() => {
animateTo({ duration: 500 }, () => {
this.isRefreshing = false
this.isLoading = false
})
LogUtil.debug(`加载第${this.page}页,共${res.comics.docs.length}条`)
this.page = res.comics.page
this.maxPage = res.comics.pages
})
.finally(() => {
animateTo({ duration: 500 }, () => {
this.isRefreshing = false
this.isLoading = false
})
}
})
}
}

Expand Down
20 changes: 17 additions & 3 deletions entry/src/main/ets/pages/view/ComicDetail.ets
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default struct ComicDetail {
@State eps: ComicEp[] = []
@State recommend: ComicCardInterface[] = []
@State showComments: boolean = false
@State currentOrder: number = 0

build() {
NavDestination() {
Expand Down Expand Up @@ -185,11 +186,11 @@ export default struct ComicDetail {
Row() {
// 开始阅读
Column() {
Button('开始阅读')
Button(this.currentOrder > 0 ? '继续阅读' : '开始阅读')
.width('80%')
.backgroundColor($r('app.color.custom_pink'))
.onClick(() => {
this.goToReader(1)
this.goToReader(this.currentOrder > 0 ? this.currentOrder : 1)
})
}
.width('49%')
Expand Down Expand Up @@ -340,7 +341,7 @@ export default struct ComicDetail {
ForEach(this.eps, (ep: ComicEp) => {
Button() {
Text(ep.title)
.fontColor($r('app.color.custom_pink'))
.fontColor(this.currentOrder === ep.order ? Color.White : $r('app.color.custom_pink'))
.maxLines(2)
.minFontSize(10)
.maxFontSize(16)
Expand All @@ -355,6 +356,7 @@ export default struct ComicDetail {
.borderWidth(2)
.borderColor($r('app.color.custom_pink'))
.borderRadius(10)
.backgroundColor(this.currentOrder === ep.order ? $r('app.color.custom_pink') : Color.White)
.onClick(() => {
this.goToReader(ep.order)
})
Expand Down Expand Up @@ -422,6 +424,17 @@ export default struct ComicDetail {
})
})
})

HistoryUtil.getRead(this.comic.id).then(res => {
this.currentOrder = res
})
})
.onShown(() => {
if (this.detail) {
HistoryUtil.getRead(this.detail._id).then(res => {
this.currentOrder = res
})
}
})
}

Expand All @@ -446,6 +459,7 @@ export default struct ComicDetail {
goToReader(chapter: number) {
if (this.detail) {
HistoryUtil.add(this.detail)
HistoryUtil.setRead(this.detail._id, chapter)
this.pageStack.pushPathByName(
'ComicReader',
{ comicId: this.detail._id, order: chapter } as ComicChapterInterface
Expand Down
3 changes: 3 additions & 0 deletions entry/src/main/ets/pages/view/ComicReader.ets
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ComicEp } from '../../api/models'
import { PreferenceItem, PreferenceManager, PreferenceStorageKey } from '../../utils/Preference'
import { BackType, TitleBar, TitleType } from '../component/TitleBar'
import { ImageQuality } from '../../common/Config'
import { HistoryUtil } from '../../utils/History'

@Builder
export function ComicReaderBuilder(name: string, param: Object) {
Expand Down Expand Up @@ -351,6 +352,7 @@ export default struct ComicReader {
}

load() {
HistoryUtil.get()
chapter(this.chapter.comicId, this.chapter.order, this.page).then(res => {
animateTo({ duration: 200 }, () => {
this.title = res.ep.title
Expand Down Expand Up @@ -387,6 +389,7 @@ export default struct ComicReader {
goToEp(order: number) {
this.disappear = this.chapter.order < order ? TransitionEffect.move(TransitionEdge.START) :
TransitionEffect.move(TransitionEdge.END)
HistoryUtil.setRead(this.chapter.comicId, order)
animateTo({ duration: 500 }, () => {
this.scroll.scrollToIndex(0, true)
this.chapter.order = order
Expand Down
81 changes: 66 additions & 15 deletions entry/src/main/ets/utils/History.ets
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
import { KvUtil } from '@pura/harmony-utils';
import { AppUtil, LogUtil } from '@pura/harmony-utils';
import { ComicDetailInfo } from '../api/models';
import { JSON } from '@kit.ArkTS';
import { StorageKey } from '../common/Consts';
import { distributedKVStore } from '@kit.ArkData';

export class HistoryUtil {
private static defaultOptions: distributedKVStore.Options = {
createIfMissing: true, //当数据库文件不存在时是否创建数据库
encrypt: true, //设置数据库文件是否加密
backup: false, //设置数据库文件是否备份
autoSync: false, //设置数据库是否为跨设备自动同步
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, //设置要创建的数据库类型
securityLevel: distributedKVStore.SecurityLevel.S1 //设置数据库安全级别
}
private static comicStore: distributedKVStore.SingleKVStore
private static readHistoryStore: distributedKVStore.SingleKVStore

public static async init(options?: distributedKVStore.Options) {
let kvManager = distributedKVStore.createKVManager({
context: AppUtil.getContext(),
bundleName: AppUtil.getBundleName()
});
HistoryUtil.comicStore = await kvManager.getKVStore<distributedKVStore.SingleKVStore>("comic_store",
options ? options : HistoryUtil.defaultOptions);
HistoryUtil.readHistoryStore = await kvManager.getKVStore<distributedKVStore.SingleKVStore>("read_history_store",
options ? options : HistoryUtil.defaultOptions);
}

public static add(comic: ComicDetailInfo) {
KvUtil.put(comic._id, JSON.stringify(comic)).then(() => {
HistoryUtil.comicStore.put(comic._id, JSON.stringify(comic), (callback) => {
LogUtil.info('历史添加回调:', JSON.stringify(callback))
let hisIds = AppStorage.get<string[]>(StorageKey.HISTORY)
if (hisIds && hisIds.indexOf(comic._id) < 0) {
hisIds.push(comic._id)
Expand All @@ -16,24 +40,51 @@ export class HistoryUtil {
})
}

public static get() {
let hisIds = AppStorage.get<string[]>(StorageKey.HISTORY)
if (hisIds && hisIds.length !== 0) {
let comics: ComicDetailInfo[] = []
hisIds.forEach(async (id) => {
comics.push(JSON.parse(await KvUtil.getString(id)) as ComicDetailInfo)
})
return comics
} else {
return []
}
public static get(): Promise<ComicDetailInfo[]> {
return new Promise<ComicDetailInfo[]>(async (resolve, reject) => {
let hisIds = AppStorage.get<string[]>(StorageKey.HISTORY)
if (hisIds && hisIds.length !== 0) {
LogUtil.info('获取浏览历史 size ', hisIds.length.toString())
let comics: ComicDetailInfo[] = []
for (let id of hisIds) {
let data = await HistoryUtil.comicStore.get(id)
LogUtil.info('获取浏览历史: ', id)
LogUtil.info('获取浏览历史: ', data.toString())
comics.push(JSON.parse(data as string) as ComicDetailInfo)
}
LogUtil.info('获取浏览历史结束')
resolve(comics)
} else {
LogUtil.info('当前不存在浏览历史')
resolve([])
}
})
}

public static on(func: (data: distributedKVStore.ChangeNotification) => void) {
HistoryUtil.comicStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, func)
}

public static getRead(comicId: string): Promise<number> {
return new Promise<number>(async (resolve, _) => {
resolve(await HistoryUtil.readHistoryStore.get(comicId) as number)
})
}

public static setRead(comicId: string, order: number) {
HistoryUtil.readHistoryStore.put(comicId, order)
}

public static clear() {
let hisIds = AppStorage.get<string[]>(StorageKey.HISTORY)
if (hisIds) {
KvUtil.deleteBatch(hisIds)
AppStorage.set<string[]>(StorageKey.HISTORY, hisIds)
AppStorage.set<string[]>(StorageKey.HISTORY, [])
HistoryUtil.comicStore.deleteBatch([...hisIds]).then(() => {
LogUtil.info('历史清空完成')
})
HistoryUtil.readHistoryStore.deleteBatch([...hisIds]).then(() => {
LogUtil.info('历史清空完成')
})
}
}
}

0 comments on commit 1c4ab76

Please sign in to comment.