Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 书源管理从保存的本地json文件中读取,新增和和导入将数据存入到本地json文件中 #172

Merged
merged 1 commit into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 33 additions & 38 deletions entry/src/main/ets/common/utils/FileHandler.ets
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { chaptersItem } from 'ets/componets/dataList/ReaderChaptersItem';
import { BookList } from '../../componets/dataList/bookList';
import { addShelfBook } from '../../storage/bookListData';
import { showMessage } from '../../componets/common/promptShow';
import { picker } from '@kit.CoreFileKit';
import { fileIo, picker } from '@kit.CoreFileKit';
import { util } from '@kit.ArkTS';

let context = getContext(this) as common.UIAbilityContext;
Expand Down Expand Up @@ -87,51 +87,46 @@ export class FileHandler {
}
}

static async readJsonFile(pathUrl: string) {
static async readJsonFile<T>(pathUrl: string): Promise<T | undefined> {
console.info('TagInfo', '文件路径:' + pathUrl);
try {
console.info('文件目录:' + pathUrl);
let file = fs.openSync(pathUrl, fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(40960000);
fs.readSync(file.fd, buf);
fs.closeSync(file);
let uint8View = new Uint8Array(buf);
// 设置编码格式为“utf-8”
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true });
// 解码输后获取对应文本
let readString = textDecoder.decodeWithStream(uint8View, { stream: false });
console.log('读取的数据内容:' + readString);
return JSON.parse(readString)
const readString = await fs.readText(pathUrl);
console.info('TagInfo', '读取的数据内容:' + readString);
const data: T = JSON.parse(readString)
return data
} catch (err) {
console.error(`读取失败:${err}`);
return Promise.reject(err)
console.error('TagInfo', `未读取到:${err}`);
return undefined
}
}

// TODO 目前写入存在问题,等官方回复
static async writeJsonFile(pathUrl: string, context: ArrayBuffer | string) {
console.info('文件目录:' + pathUrl);
static writeJsonFile(pathUrl: string, context: ArrayBuffer | string) {
console.info('TagInfo', '文件地址:' + pathUrl);
try {
let file = fs.openSync(filePath, fs.OpenMode.TRUNC);
try {
let writeLen = fs.writeSync(file.fd, context);
fs.closeSync(file);
console.info('文件写入成功,文件长度:' + writeLen);
} catch (e) {
return Promise.reject('写入失败')
// 创建文件,并且写入内容,若是存在则重写内容
let res = fs.accessSync(pathUrl);
let file: fs.File
if (res) {
file = fs.openSync(pathUrl, fs.OpenMode.WRITE_ONLY | fs.OpenMode.TRUNC);
} else {
file = fs.openSync(pathUrl, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
}
return Promise.resolve('写入成功')
fs.writeSync(file.fd, context)
fs.close(file);
return '写入成功'
} catch (e) {
console.info("文件不存在,开始创建文件");
try {
let file = fs.openSync(filePath, fs.OpenMode.CREATE);
let writeLen = fs.writeSync(file.fd, context);
fs.closeSync(file);
console.info('文件写入成功,文件长度:' + writeLen);
return Promise.resolve('写入成功')
} catch (e) {
console.error('写入失败'+JSON.stringify(e))
return Promise.reject('写入失败'+JSON.stringify(e))
}
console.error('TagInfo', '写入失败' + JSON.stringify(e))
return '写入失败' + JSON.stringify(e)
}
}

static deleteJsonFile(pathUrl: string) {
try {
fs.unlinkSync(pathUrl);
return '删除成功'
} catch (e) {
console.error('TagError', '删除失败' + JSON.stringify(e))
return '删除失败'
}
}
}
30 changes: 15 additions & 15 deletions entry/src/main/ets/componets/dataList/BookSource.ets
Original file line number Diff line number Diff line change
Expand Up @@ -69,20 +69,20 @@ export interface BookSource {
bookSourceUrl: string;
bookSourceType: number;
bookSourceGroup: string;
grade: number,
score: string,
bookSourceComment: string;
loginUrl: string;
loginUi: string;
loginCheckJs: string;
bookUrlPattern: string;
coverDecodeJs: string;
header: string;
variableComment: string;
concurrentRate: string;
jsLib: string;
bookSourceGrade?: number,
bookSourceScore?: string,
bookSourceComment?: string;
loginUrl?: string;
loginUi?: string;
loginCheckJs?: string;
bookUrlPattern?: string;
coverDecodeJs?: string;
header?: string;
variableComment?: string;
concurrentRate?: string;
jsLib?: string;
enabled: boolean;
enabledCookieJar: boolean;
enabledCookieJar?: boolean;
enabledExplore: boolean;
lastUpdateTime: number;
respondTime: number;
Expand All @@ -91,10 +91,10 @@ export interface BookSource {
exploreRule?: ExploreRule;
searchRule?: SearchRule;
tocRule?: TocRule;
searchUrl: string;
searchUrl?: string;

customOrder: number;
exploreUrl: string;
exploreUrl?: string;
weight: number;
}

Expand Down
12 changes: 11 additions & 1 deletion entry/src/main/ets/componets/import/ImportCommon.ets
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
* @className: ImportCommon
* 通用导入页
*/
import { FileHandler } from '../../common/utils/FileHandler';
import ClassifyList from '../common/ClassifyList';
import { showMessage } from '../common/promptShow';
import Score from '../common/Score';
import Tag from '../common/Tag';
import { BookSource, GroupList } from '../dataList/BookSource';

@Component
@Preview
export default struct ImportCommon {
@StorageProp('pathBookSource') pathBookSource: string = ''
@State localSourceList: BookSource[] = []
@Prop sourceList: BookSource[] = []
@Link show: boolean;
@State groupList: GroupList[] = []
Expand All @@ -23,6 +27,10 @@ export default struct ImportCommon {
private secondScroll = new Scroller()

aboutToAppear() {
FileHandler.readJsonFile<BookSource[]>(this.pathBookSource).then(data => {
const bookSource = data ?? []
this.localSourceList = bookSource
})
this.getGroupList()
}

Expand Down Expand Up @@ -155,9 +163,11 @@ export default struct ImportCommon {
.backgroundColor(0xff6600)
.layoutWeight(1)
.onClick(() => {
const dataList = this.sourceList.filter(item => this.activeNameMap[item.bookSourceName] ?? false)
FileHandler.writeJsonFile(this.pathBookSource, JSON.stringify(dataList))
this.show = false;
this.resetState()
console.log('确定')
showMessage('添加成功')
})
}
.width('100%')
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 @@ -42,6 +42,8 @@ export default class EntryAbility extends UIAbility {
// 获取本地文件存储路径
const pathDir = this.context.filesDir;
AppStorage.setOrCreate('pathDir', pathDir);
// 书源存入的地址
AppStorage.setOrCreate('pathBookSource', pathDir + '/bookSource.json');
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
// 全屏
Expand Down
49 changes: 31 additions & 18 deletions entry/src/main/ets/pages/view/Find/BookSource/AddSourcePage.ets
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import SourceDebug from './components/SourceDebug';
struct AddSourcePage {
titleArray: string[] = ['小说', '漫画', '有声书']
dialogRightData: string[] = ['搜索源码', '书籍源码', '目录源码', '正文源码', '帮助']
@StorageProp('pathDir') pathDir: string = ''
@StorageProp('pathBookSource') pathBookSource: string = ''
@State isShowHelp: boolean = false
@State sourceList: dataItem[] = [
new dataItem("编辑", 1),
Expand All @@ -27,12 +27,19 @@ struct AddSourcePage {
private scroller: Scroller = new Scroller()
private controller: TabsController = new TabsController()
private headController: TabsController = new TabsController()
@State formModel: Partial<BookSource> = {
bookInfoRule: {},
contentRule: {},
exploreRule: {},
searchRule: {},
tocRule: {}
@State formModel: BookSource = {
bookSourceName: '',
bookSourceUrl: '',
bookSourceType: 0,
bookSourceGroup: '男频',
bookSourceGrade: 2,
bookSourceScore: '5.0分',
enabled: true,
enabledExplore: true,
lastUpdateTime: 0,
respondTime: 180000,
customOrder: 0,
weight: 0
}

onReadChange() {
Expand Down Expand Up @@ -131,15 +138,21 @@ struct AddSourcePage {
.fontColor(Color.White)
.backgroundColor(0xff6600)
.layoutWeight(1)
.onClick(() => {
.onClick(async () => {
if (!this.formModel.bookSourceName || !this.formModel.bookSourceUrl) {
this.readIndex = 0
this.currentIndex = 0
this.controller.changeIndex(0)
this.scroller.scrollEdge(Edge.Top)
}
// FileHandler.writeJsonFile(this.pathDir+'/tests.json', JSON.stringify(this.formModel))
console.log('保存', JSON.stringify(this.formModel))
showMessage('红星标记的内容不能为空')
}
const data = await FileHandler.readJsonFile<BookSource[]>(this.pathBookSource) ?? [];
data.push(this.formModel as BookSource)
FileHandler.writeJsonFile(this.pathBookSource, JSON.stringify(data))
showMessage('保存成功')
setTimeout(() => {
router.back()
}, 1000)
})
.opacity(1)
}
Expand Down Expand Up @@ -246,7 +259,7 @@ struct AddSourcePage {
.value(this.formModel.bookSourceGroup ?? '男频')
.borderRadius(4)
.fontColor(this.formModel.bookSourceGroup ? '#E0000000' : '#73000000')
.onSelect((index: number, text?: string | undefined) => {
.onSelect((index: number, text: string) => {
this.formModel.bookSourceGroup = text
})
.backgroundColor('#f5f5f5')
Expand Down Expand Up @@ -274,11 +287,11 @@ struct AddSourcePage {
{ value: '优质' },
{ value: '精品' }
])
.value(GRADE_TYPE[this.formModel.grade ?? 0])
.value(GRADE_TYPE[this.formModel.bookSourceGrade ?? 0])
.borderRadius(4)
.fontColor(this.formModel.grade !== undefined ? '#E0000000' : '#73000000')
.fontColor(this.formModel.bookSourceGrade !== undefined ? '#E0000000' : '#73000000')
.onSelect((index: number, text?: string | undefined) => {
this.formModel.grade = index
this.formModel.bookSourceGrade = index
})
.backgroundColor('#f5f5f5')
.layoutWeight(1)
Expand All @@ -290,11 +303,11 @@ struct AddSourcePage {
{ value: '2.0分' },
{ value: '1.0分' },
])
.value(this.formModel.score ?? '5.0分')
.value(this.formModel.bookSourceScore ?? '5.0分')
.borderRadius(4)
.fontColor(this.formModel.score ? '#E0000000' : '#73000000')
.fontColor(this.formModel.bookSourceScore ? '#E0000000' : '#73000000')
.onSelect((index: number, text?: string | undefined) => {
this.formModel.score = text
this.formModel.bookSourceScore = text
})
.backgroundColor('#f5f5f5')
.layoutWeight(1)
Expand Down
4 changes: 2 additions & 2 deletions entry/src/main/ets/pages/view/Find/BookSource/Index.ets
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ struct BookSourcePage {
barPosition: BarPosition.Start,
controller: this.tabsController
}) {
ForEach(this.titleArray, (item: string) => {
ForEach(this.titleArray, (item: string, index: number) => {
TabContent() {
SourceView({ item: item, isBatch: this.isBatch })
SourceView({ index, isBatch: this.isBatch })
}
.align(Alignment.Top)
})
Expand Down
Loading
Loading