Layout也跟昨天一樣先多加一行:
基本上前置作業都和Day11一樣,差別只在於Ptt搜尋作者的按鍵是"a"。
private suspend fun searchAuthor(author: String) {
delay(200L)
PttClient.getInstance().send("a$author\r\n")
delay(200L)
when (PttClient.getInstance().expect(searchTitleOrAuthorPattern)) {
0 -> {
//TODO show Alert
Log.d(mTag, "Up to limit")
}
1 -> {
parseBoardArticle(PttClient.getInstance().getScreen())
}
else -> {
Log.e(
mTag,
"Wrong screen: \n${PttClient.getInstance().getScreen()}"
)
PttClient.getInstance().send("\r\nqqqqqqqqqqqq")
//TODO show alert
}
}
}
可以看到內容也與搜尋標題重覆性很高,因此決定把兩段的程式分別提取成searchDetailProcess與searchDetail兩方法。
searchTitle.setOnClickListener {
val word = searchTitleInput.text.toString()
if (word.isEmpty()) return@setOnClickListener
searchTitleInput.setText("")
searchDetailProcess("/$word\r\n")
}
searchAuthor.setOnClickListener {
val author = searchAuthorInput.text.toString()
if (author.isEmpty()) return@setOnClickListener
searchAuthorInput.setText("")
searchDetailProcess("a$author\r\n")
}
差別只在於將不同的command送入。
private fun searchDetailProcess(command:String) {
when (PttClient.getInstance().expect(inBoardPattern)) {
0 -> {
// first go into the board
val board = searchBoardInput.text.toString().trim()
if (board.isEmpty()) return
PttClient.getInstance().send("s${board}\r\n")
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
delay(200L)
var ret = PttClient.getInstance().expect(inBoardPattern)
while (ret == 1) {
if (ret == 1) {
PttClient.getInstance().send("q")
delay(200L)
ret = PttClient.getInstance().expect(inBoardPattern)
}
}
when (ret) {
0 -> { // "【主功能表】" -> 在看板外,無法搜尋文章
Log.e(mTag, "Out of board.\n${PttClient.getInstance().getScreen()}")
return@launch
}
2 -> { // "文章選讀" -> 在看板內
searchDetail(command)
}
}
}
}
2 -> {
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
searchDetail(command)
}
}
else -> {
Log.e(mTag, "Wrong screen: \n${PttClient.getInstance().getScreen()}")
PttClient.getInstance().send("\r\nqqqqqqqqqqqq")
//TODO show alert
}
}
}
private suspend fun searchDetail(command: String) {
delay(200L)
PttClient.getInstance().send(command)
delay(200L)
when (PttClient.getInstance().expect(searchTitleOrAuthorPattern)) {
0 -> {
//TODO show Alert
Log.d(mTag, "Up to limit")
}
1 -> {
parseBoardArticle(PttClient.getInstance().getScreen())
}
else -> {
Log.e(
mTag,
"Wrong screen: \n${PttClient.getInstance().getScreen()}"
)
PttClient.getInstance().send("\r\nqqqqqqqqqqqq")
//TODO show alert
}
}
}
兩方法的內容都和Day11一致。
目前進度先到這邊,明天預計就是parseBoardArticle的內容了。