Layout的部份新增一個EditText以及ImageView,目前畫面如下:
首先點擊按紐時先取得目前輸入的內容並做前置的判斷
val word = searchTitleInput.text.toString()
if (word.isEmpty()) return@setOnClickListener
searchTitleInput.setText("")
之所以會把EditText清空是因為Ptt有增加搜尋條件。
接著是判斷目前畫面狀態
private val inBoardPattern = arrayOf(
"【主功能表】",
"請按任意鍵繼續", // 進板畫面
"文章選讀", // 看板內
)
when (PttClient.getInstance().expect(inBoardPattern)) {
0 -> {
// first go into the board
val board = searchBoardInput.text.toString().trim()
if (board.isEmpty()) return@setOnClickListener
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 -> { // "文章選讀" -> 在看板內
searchTitle(word)
}
}
}
}
2 -> {
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
searchTitle(word)
}
}
else -> {
Log.e(mTag, "Wrong screen: \n${PttClient.getInstance().getScreen()}")
PttClient.getInstance().send("\r\nqqqqqqqqqqqq")
//TODO show alert
}
}
要是目前畫面在主功能表的話,需要先進入看板再開始查詢,進入看板相關的條件請見Day08及Day10,最後結果要是還是在主功能表的話代表找不到看板,那就不繼續了。反之則進入searchTitle方法:要是目前畫面已經在看板內的話,直接進入searchTitle方法即可。
會用到的Pattern
private val searchTitlePattern = arrayOf(
"抱歉,已達搜尋條件上限。",
"文章選讀"
)
private suspend fun searchTitle(word: String) {
delay(200L)
PttClient.getInstance().send("/$word\r\n")
delay(200L)
when (PttClient.getInstance().expect(searchTitlePattern)) {
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
}
}
}
搜尋文章標題需使用"/",接著輸入搜尋內容以及Enter即可。結果會有裡面的兩種情況,
目前進度就先到這邊,parseBoardArticle是在解析搜尋的畫面結果,我打算放在搜尋作者之後再做說明。