1. model 领域模型

  1. package com.example.ticket
  2. import java.util.*
  3. enum class SeatPriceType(val seatType: String, val priceType: String, val desc: String) {
  4. SP_SEAT("P", "A6", "特等座"),
  5. L1_SEAT("M", "M", "一等座"),
  6. L2_SEAT("O", "O", "二等座"),
  7. NO_SEAT("O", "WZ", "无座"),
  8. BUS_SEAT("9", "A9", "商务座"),
  9. HARD_SEAT("1", "A1", "硬座"),
  10. SOFT_SEAT("2", "A2", "软座"),
  11. HARD_SLEEPER("3", "A3", "硬卧"),
  12. SORT_SLEEPER("4", "A4", "软卧");
  13. }
  14. data class Station(
  15. var cnName: String,
  16. var code: String,
  17. var pinyin: String,
  18. var enName: String,
  19. var enName_2: String,
  20. var index: Int
  21. ) : Comparable<Station> {
  22. override fun compareTo(other: Station) = this.index - other.index
  23. override fun equals(other: Any?): Boolean {
  24. if (this === other) return true
  25. if (javaClass != other?.javaClass) return false
  26. other as Station
  27. if (code != other.code) return false
  28. return true
  29. }
  30. override fun hashCode() = Objects.hashCode(code)
  31. }
  32. data class TicketData(
  33. var flag: String,
  34. var map: HashMap<String?, String?>,
  35. var result: List<String?>
  36. )
  37. data class TicketDetail(
  38. /**
  39. * 列车号 2
  40. */
  41. val trainNo: String?,
  42. /**
  43. * 车次 3
  44. */
  45. val trainNum: String?,
  46. /**
  47. * 出发站序号 16
  48. */
  49. val fromStationNo: String?,
  50. /**
  51. * 出发站代码 6
  52. */
  53. val fromStationCode: String?,
  54. /**
  55. * 出发站名称
  56. */
  57. val fromStationName: String?,
  58. /**
  59. * 到达站序号 17
  60. */
  61. val toStationNo: String?,
  62. /**
  63. * 到达站代码 7
  64. */
  65. val toStationCode: String?,
  66. /**
  67. * 到达站名称
  68. */
  69. val toStationName: String?,
  70. /**
  71. * 始发站代码 4
  72. */
  73. val startStationCode: String?,
  74. /**
  75. * 始发站名称
  76. */
  77. val startStationName: String?,
  78. /**
  79. * 终点站代码 5
  80. */
  81. val endStationCode: String?,
  82. /**
  83. * 终点站名称
  84. */
  85. val endStationName: String?,
  86. /**
  87. * 出发时间 8
  88. */
  89. val goOffTime: String?,
  90. /**
  91. * 到达时间 9
  92. */
  93. val arrivalTime: String?,
  94. /**
  95. * 历时时间 10
  96. */
  97. val lastTime: String?,
  98. /**
  99. * 备注 1
  100. */
  101. val remark: String?,
  102. /**
  103. * 座席类型 35
  104. */
  105. val seatTypes: String?,
  106. /**
  107. * 商务特等座 32
  108. */
  109. val businessSeat: String?,
  110. /**
  111. * 一等座 31
  112. */
  113. val l1Seat: String?,
  114. /**
  115. * 二等座 30
  116. */
  117. val l2Seat: String?,
  118. /**
  119. * 软卧一等卧 23
  120. */
  121. val l1SoftBerth: String?,
  122. /**
  123. * 硬卧二等卧 28
  124. */
  125. val l2HardBerth: String?,
  126. /**
  127. * 硬座 29
  128. */
  129. val hardSeat: String?,
  130. /**
  131. * 软座 24
  132. */
  133. val softSeat: String?,
  134. /**
  135. * 无座 26
  136. */
  137. val noSeat: String?,
  138. /**
  139. * 不可候补座席 38
  140. */
  141. val canNotAlternateSeatType: String?,
  142. /**
  143. * 是否可以候补 37 === '1'
  144. */
  145. val canAlternate: Boolean?,
  146. /**
  147. * 密钥串 0
  148. */
  149. val secretStr: String?
  150. ) {
  151. /**
  152. * 商务特等座价格
  153. */
  154. var businessSeatPrice: String? = null
  155. /**
  156. * 一等座价格
  157. */
  158. var l1SeatPrice: String? = null
  159. /**
  160. * 二等座价格
  161. */
  162. var l2SeatPrice: String? = null
  163. /**
  164. * 软卧一等卧价格
  165. */
  166. var l1SoftBerthPrice: String? = null
  167. /**
  168. * 硬卧二等卧价格
  169. */
  170. var l2HardBerthPrice: String? = null
  171. /**
  172. * 硬座价格
  173. */
  174. var hardSeatPrice: String? = null
  175. /**
  176. * 软座价格
  177. */
  178. var softSeatPrice: String? = null
  179. /**
  180. * 无座价格
  181. */
  182. var noSeatPrice: String? = null
  183. }
  184. class TicketPriceResponse(
  185. var httpstatus: Int?,
  186. var status: Boolean?,
  187. var data: Map<String, String>?
  188. )
  189. data class TicketResponse(
  190. var httpstatus: Int?,
  191. var messages: String?,
  192. var status: Boolean?,
  193. var data: TicketData?
  194. )
  195. data class TrainData(
  196. val arrive_time: String?,
  197. val end_station_name: String?,
  198. var end_station_code: String?,
  199. val isEnabled: Boolean?,
  200. val service_type: String?,
  201. val start_station_name: String?,
  202. var start_station_code: String?,
  203. val start_time: String?,
  204. val station_name: String?,
  205. var station_code: String?,
  206. val station_no: String?,
  207. val station_train_code: String?,
  208. val stopover_time: String?,
  209. val train_class_name: String?
  210. )
  211. data class TrainDataWrap(
  212. val data: List<TrainData>?
  213. )
  214. data class TrainResponse(
  215. var httpstatus: Int?,
  216. var messages: String?,
  217. var status: Boolean?,
  218. var data: TrainDataWrap?
  219. )

2. 车站代码名称映射解析

package com.example.ticket

import org.apache.commons.lang3.StringUtils
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils
import java.nio.charset.Charset
import java.util.function.Function
import java.util.stream.Collectors

class StationUtil {
    companion object {
        val stations = loadStationData()
        val stationCodeMap = stationDataToCodeMap(stations)
        val stationCnNameMap = stationDataToCnNameMap(stations)

        private fun stationDataToCodeMap(stations: MutableList<Station>): Map<String, Station> {
            return stations.stream().collect(Collectors.toMap(Station::code, Function.identity()))
        }

        private fun stationDataToCnNameMap(stations: MutableList<Station>): Map<String, Station> {
            return stations.stream().collect(Collectors.toMap(Station::cnName, Function.identity()))
        }

        private fun loadStationData(): MutableList<Station> {
            val httpClient = HttpClientBuilder.create().build()
            val httpGet = HttpGet("https://www.12306.cn/index/script/core/common/station_name_v10145.js")
            val httpResponse: CloseableHttpResponse = httpClient.execute(httpGet)

            val result = EntityUtils.toString(httpResponse.entity, Charset.forName("UTF-8"))
                .replace(";", "")
                .replace("'", "")

            return result.split("@").stream().skip(1)
                .filter(StringUtils::isNotBlank)
                .map { stationStr ->
                    val stationArray: List<String> = stationStr.split("|")

                    Station(
                        enName_2 = stationArray[0],
                        cnName = stationArray[1],
                        code = stationArray[2],
                        pinyin = stationArray[3],
                        enName = stationArray[4],
                        index = (stationArray[5].toInt() + 1)
                    )
                }
                .distinct()
                .collect(Collectors.toList())
        }
    }
}

3. 业务逻辑

package com.example.ticket

import com.alibaba.fastjson.JSON
import com.example.ticket.SeatPriceType.*
import org.apache.commons.lang3.StringUtils
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils
import java.util.*
import java.util.function.Function
import java.util.function.Predicate
import java.util.stream.Collectors

fun main() {
    val trainDate = "2021-09-30"
    val fromStation = "HZH"
    val toStation = "FYH"

    val selectTrains = listOf("K1238")

    val matchTrains = matchTicket(trainDate, fromStation, toStation) { selectTrains.contains(it.trainNum) }

    for (matchTrain in matchTrains) {
        val trainDataMap = queryByTrainNo(matchTrain, trainDate)
        if (trainDataMap != null) {
            val fromStationNo = Optional.ofNullable(matchTrain.fromStationNo).map { it.toInt() }.orElse(-1)
            val toStationNo = Optional.ofNullable(matchTrain.toStationNo).map { it.toInt() }.orElse(-1)
            // 目的地后面的站数
            val afterNum = trainDataMap.size - toStationNo
            // 出发地前面的站数
            val beforeNum = fromStationNo - 1

            // 依据12306的区间限售原则,优先向距离 终点站或始发站 较远的方向延长线路,这样单边延长可以使路线尽可能的长
            val resultTickets = arrayListOf<TicketDetail>()
            if (beforeNum >= afterNum) {
                for (stationNo in (fromStationNo - 1) downTo 1) {
                    val trainData = trainDataMap[stationNo]

                    val resultList = trainData?.station_code?.let {
                        matchTicket(
                            trainDate,
                            it,
                            toStation
                        ) { d -> selectTrains.contains(d.trainNum) }
                    }
                    if (resultList != null) {
                        resultTickets.addAll(resultList)
                    }
                }
            } else {
                for (stationNo in (toStationNo + 1)..(trainDataMap.size)) {
                    println("后面开始: $stationNo")
                }
            }

            println(resultTickets)

        }
    }
}

fun matchTicket(
    trainDate: String,
    fromStation: String,
    toStation: String,
    filter: Predicate<TicketDetail>
): List<TicketDetail> {
    // 查询车票信息
    val ticketDetails = queryTicket(trainDate, fromStation, toStation)

    return ticketDetails.stream()
        .filter(filter)
        .peek { fillPrice(it, trainDate) }.collect(Collectors.toList())
}

fun queryTicket(trainDate: String, fromStation: String, toStation: String): MutableList<TicketDetail> {
    val result = doGet(
        "https://kyfw.12306.cn/otn/leftTicket/queryO?leftTicketDTO.train_date=${trainDate}" +
                "&leftTicketDTO.from_station=${fromStation}&leftTicketDTO.to_station=${toStation}&purpose_codes=ADULT"
    )

    val ticketResponse = JSON.parseObject(result, TicketResponse::class.java)

    val ticketData = ticketResponse.data

    val ticketDetails: MutableList<TicketDetail> = ArrayList()
    val resultDataList = ticketData?.result
    if (resultDataList != null) {
        for (resultData in resultDataList) {
            val ticketInfoArray = resultData?.split("|")?.toTypedArray()

            val startStationCode = ticketInfoArray?.get(4)
            val endStationCode = ticketInfoArray?.get(5)
            val fromStationCode = ticketInfoArray?.get(6)
            val toStationCode = ticketInfoArray?.get(7)

            val ticketDetail = TicketDetail(
                secretStr = ticketInfoArray?.get(0),
                trainNo = ticketInfoArray?.get(2),
                trainNum = ticketInfoArray?.get(3),
                fromStationNo = ticketInfoArray?.get(16),
                fromStationCode = fromStationCode,
                fromStationName = StationUtil.stationCodeMap[fromStationCode]?.cnName,
                toStationNo = ticketInfoArray?.get(17),
                toStationCode = toStationCode,
                toStationName = StationUtil.stationCodeMap[toStationCode]?.cnName,
                startStationCode = startStationCode,
                startStationName = StationUtil.stationCodeMap[startStationCode]?.cnName,
                endStationCode = endStationCode,
                endStationName = StationUtil.stationCodeMap[endStationCode]?.cnName,
                goOffTime = ticketInfoArray?.get(8),
                arrivalTime = ticketInfoArray?.get(9),
                lastTime = ticketInfoArray?.get(10),
                remark = ticketInfoArray?.get(1),
                seatTypes = ticketInfoArray?.get(35),
                businessSeat = ticketInfoArray?.get(32),
                l1Seat = ticketInfoArray?.get(31),
                l2Seat = ticketInfoArray?.get(30),
                l1SoftBerth = ticketInfoArray?.get(23),
                l2HardBerth = ticketInfoArray?.get(28),
                hardSeat = ticketInfoArray?.get(29),
                softSeat = ticketInfoArray?.get(24),
                noSeat = ticketInfoArray?.get(26),
                canNotAlternateSeatType = ticketInfoArray?.get(38),
                canAlternate = "1" == ticketInfoArray?.get(37),
            )
            ticketDetails.add(ticketDetail)
        }
    }

    return ticketDetails
}

private fun queryTicketPrice(
    trainNo: String?,
    fromStationNo: String?,
    toStationNo: String?,
    seatTypes: String?,
    trainDate: String?
): Map<String, String>? {
    val result = doGet(
        "https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=${trainNo}" +
                "&from_station_no=${fromStationNo}&to_station_no=${toStationNo}" +
                "&seat_types=${seatTypes}&train_date=${trainDate}"
    )

    val ticketPriceResponse = JSON.parseObject(result, TicketPriceResponse::class.java)

    return ticketPriceResponse?.data
}

fun fillPrice(ticketDetail: TicketDetail, trainDate: String) {
    val (trainNo, _, fromStationNo, _, _, toStationNo, _, _,
        _, _, _, _, _, _, _, _, seatTypes, _, _, _, _, _, _, _, _, _, _, _) = ticketDetail

    val ticketPriceMap = queryTicketPrice(trainNo, fromStationNo, toStationNo, seatTypes, trainDate)
    if (ticketPriceMap != null) {
        ticketDetail.businessSeatPrice = Optional.ofNullable(calculatePrice(ticketPriceMap[BUS_SEAT.priceType]))
            .orElse(calculatePrice(ticketPriceMap[SP_SEAT.priceType]))

        ticketDetail.l1SeatPrice = calculatePrice(ticketPriceMap[L1_SEAT.priceType])

        ticketDetail.l2SeatPrice = calculatePrice(ticketPriceMap[L2_SEAT.priceType])

        ticketDetail.l1SoftBerthPrice = calculatePrice(ticketPriceMap[SORT_SLEEPER.priceType])

        ticketDetail.l2HardBerthPrice = calculatePrice(ticketPriceMap[HARD_SLEEPER.priceType])

        ticketDetail.hardSeatPrice = calculatePrice(ticketPriceMap[HARD_SEAT.priceType])

        ticketDetail.softSeatPrice = calculatePrice(ticketPriceMap[SOFT_SEAT.priceType])

        ticketDetail.noSeatPrice = calculatePrice(ticketPriceMap[NO_SEAT.priceType])
    }
}

private fun calculatePrice(price: String?): String? {
    return Optional.ofNullable(price)
        .filter(StringUtils::isNotBlank)
        .filter { it.startsWith("¥") }
        .map { it.replace("¥", "") }.orElse(null)
}

fun queryByTrainNo(
    ticketDetail: TicketDetail, trainDate: String
): Map<Int, TrainData>? {
    val result = doGet(
        "https://kyfw.12306.cn/otn/czxx/queryByTrainNo?train_no=${ticketDetail.trainNo}" +
                "&from_station_telecode=${ticketDetail.fromStationCode}&to_station_telecode=${ticketDetail.toStationCode}" +
                "&depart_date=${trainDate}"
    )

    val trainResponse = JSON.parseObject(result, TrainResponse::class.java)

    val trainDataList = trainResponse?.data?.data

    if (trainDataList != null && trainDataList.isNotEmpty()) {
        trainDataList.forEach {
            it.start_station_name.let { name ->
                it.start_station_code = StationUtil.stationCnNameMap[name]?.code
            }

            it.end_station_name.let { name ->
                it.end_station_code = StationUtil.stationCnNameMap[name]?.code
            }

            it.station_name.let { name ->
                it.station_code = StationUtil.stationCnNameMap[name]?.code
            }
        }
    }

    return trainDataList?.stream()?.collect(Collectors.toMap({ it.station_no?.toInt() }, Function.identity()))
}

fun doGet(url: String): String {
    val httpClient = HttpClientBuilder.create().build()
    val httpGet = HttpGet(url)
    val httpResponse = httpClient.execute(httpGet)

    val result = EntityUtils.toString(httpResponse.entity)
    httpClient.close()

    return result
}