content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.fitness.domain.usecase.search
import usecase.LocalUseCase
abstract class EdamamAutoCompleteUseCase: LocalUseCase<EdamamAutoCompleteUseCase.Params, List<String>>(){
data class Params(val search: String)
}
| body-balance/domain/api/src/main/kotlin/com/fitness/domain/usecase/search/EdamamAutoCompleteUseCase.kt | 2604531181 |
package com.fitness.domain.usecase.search
import com.fitness.domain.model.nutrition.Ingredient
import usecase.DataStateUseCase
abstract class EdamamFetchAllIngredientsUseCase: DataStateUseCase<EdamamFetchAllIngredientsUseCase.Params, List<Ingredient>>(){
object Params
} | body-balance/domain/api/src/main/kotlin/com/fitness/domain/usecase/search/EdamamFetchAllIngredientsUseCase.kt | 933956093 |
package com.fitness.domain.usecase.nutrition
import com.fitness.domain.model.nutrition.Recipe
import enums.EMealType
import usecase.DataStateUseCase
abstract class CreateNutritionRecordUseCase: DataStateUseCase<CreateNutritionRecordUseCase.Params, Unit>() {
data class Params(
val userId: String,
val date: Long,
val hour: Int,
val minute: Int,
val mealType: EMealType,
val recipe: Recipe,
)
} | body-balance/domain/api/src/main/kotlin/com/fitness/domain/usecase/nutrition/CreateNutritionRecordUseCase.kt | 3632070317 |
package com.fitness.domain.usecase.nutrition
import com.fitness.domain.model.nutrition.Nutrition
import usecase.DataStateUseCase
abstract class GetEditableNutritionRecordsUseCase: DataStateUseCase<GetEditableNutritionRecordsUseCase.Params, List<Nutrition>>() {
data class Params(val userId: String)
} | body-balance/domain/api/src/main/kotlin/com/fitness/domain/usecase/nutrition/GetEditableNutritionRecordsUseCase.kt | 551401739 |
package com.example
import com.example.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
configureRouting()
}
client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("Hello World!", bodyAsText())
}
}
}
| class_log/src/test/kotlin/com/example/ApplicationTest.kt | 2082981148 |
package com.example
import com.example.plugins.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
fun main() {
embeddedServer(CIO, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
fun Application.module() {
configureSecurity()
configureRouting()
}
| class_log/src/main/kotlin/com/example/Application.kt | 2912074236 |
package com.example.plugins
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureRouting() {
routing {
get("/") {
call.respondText("Hello World!")
}
}
}
| class_log/src/main/kotlin/com/example/plugins/Routing.kt | 3219711335 |
package com.example.plugins
import io.ktor.server.application.*
fun Application.configureSecurity() {
}
| class_log/src/main/kotlin/com/example/plugins/Security.kt | 1555138223 |
package com.ubaya.project_uts_160420147
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.ubaya.project_uts_160420147", appContext.packageName)
}
} | Adv160420147ProjectUts/app/src/androidTest/java/com/ubaya/project_uts_160420147/ExampleInstrumentedTest.kt | 241382339 |
package com.ubaya.project_uts_160420147
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Adv160420147ProjectUts/app/src/test/java/com/ubaya/project_uts_160420147/ExampleUnitTest.kt | 393755714 |
package com.ubaya.project_uts_160420147.viewmodel
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.ubaya.project_uts_160420147.model.Game
import org.json.JSONException
class DetailViewModel(application: Application) : AndroidViewModel(application) {
private val _gameData = MutableLiveData<Game?>()
val gameData: LiveData<Game?> = _gameData
private val requestQueue: RequestQueue by lazy {
Volley.newRequestQueue(application.applicationContext)
}
fun fetch(gameId: Int) {
val url = "http://192.168.1.80/anmp_uts/games.php?gameID=$gameId"
Log.d("DetailViewModel", "Fetching data from URL: $url")
val gameRequest = StringRequest(Request.Method.GET, url,
{ response ->
try {
val game = Gson().fromJson(response, Game::class.java)
_gameData.postValue(game)
} catch (e: Exception) {
Log.e("JSON Parse Error", "Error parsing game details", e)
}
},
{ error ->
Log.e("API Error", "Error fetching game details: ${error.message}")
}
)
requestQueue.add(gameRequest)
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/viewmodel/DetailViewModel.kt | 1855448068 |
package com.ubaya.project_uts_160420147.viewmodel
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.ubaya.project_uts_160420147.model.Game
class GameListModel(application: Application) : AndroidViewModel(application) {
val gameLD = MutableLiveData<List<Game>>()
val gameLoadErrorLD = MutableLiveData<Boolean>()
val loadingLD = MutableLiveData<Boolean>()
var dataFetched = false // Flag to track if data has been fetched
private val TAG = "volleyTag"
private var queue: RequestQueue? = Volley.newRequestQueue(application)
fun refresh() {
if (!dataFetched || gameLD.value.isNullOrEmpty()) {
gameLoadErrorLD.value = false
loadingLD.value = true
Log.d("CekMasuk", "masukvolley")
val url = "http://192.168.1.80/anmp_uts/game.json"
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
try {
val gson = Gson()
val game = gson.fromJson(response, Array<Game>::class.java).toList()
gameLD.value = game
gameLoadErrorLD.value = false
loadingLD.value = false
dataFetched = true // Set flag to true as data is now fetched
Log.d("showVolley", game.toString())
} catch (e: Exception) {
Log.e(TAG, "Error parsing JSON: ", e)
gameLoadErrorLD.value = true
loadingLD.value = false
}
},
{ error ->
Log.e(TAG, "Volley error: $error")
gameLoadErrorLD.value = true
loadingLD.value = false
}
)
stringRequest.tag = TAG
queue?.add(stringRequest)
}
}
override fun onCleared() {
super.onCleared()
queue?.cancelAll(TAG)
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/viewmodel/GameListModel.kt | 153940045 |
package com.ubaya.project_uts_160420147.viewmodel
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
class ProfileViewModel(application: Application) : AndroidViewModel(application) {
private val prefs = application.getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
val username = MutableLiveData<String>()
val firstName = MutableLiveData<String>()
val lastName = MutableLiveData<String>()
val password = MutableLiveData<String>()
init {
username.value = prefs.getString("username", "")
firstName.value = prefs.getString("first_name", "")
lastName.value = prefs.getString("last_name", "")
password.value = prefs.getString("password", "")
}
fun saveUserData(fName: String, lName: String, pwd: String) {
prefs.edit().apply {
putString("username", username.value ?: "") // Ensure username is not null
putString("first_name", fName)
putString("last_name", lName)
putString("password", pwd) // Reconsider saving passwords in SharedPreferences for security reasons.
apply()
}
firstName.value = fName
lastName.value = lName
password.value = pwd
}
fun clearUserData() {
prefs.edit().clear().apply()
username.value = ""
firstName.value = ""
lastName.value = ""
password.value = ""
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/viewmodel/ProfileViewModel.kt | 1035586506 |
package com.ubaya.project_uts_160420147.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.ubaya.project_uts_160420147.model.Game
class SharedViewModel : ViewModel() {
val lastVisitedGame = MutableLiveData<Game?>()
fun setLastVisitedGame(game: Game) {
lastVisitedGame.value = game
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/viewmodel/SharedViewModel.kt | 3608167761 |
package com.ubaya.project_uts_160420147.util
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import com.ubaya.project_uts_160420147.R
fun ImageView.loadImage(url: String?, progressBar: ProgressBar) {
Picasso.get()
.load(url)
.resize(400,400)
.centerCrop()
.error(R.drawable.ic_baseline_error_24)
.into(this, object: Callback {
override fun onSuccess() {
progressBar.visibility = View.GONE
}
override fun onError(e: Exception?) {
}
})
} | Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/util/util.kt | 2366078278 |
package com.ubaya.project_uts_160420147.model
import android.util.Log
import java.util.Date
data class Game(
val gameID: Int,
val title: String,
val developer: String,
val genre: String,
val description: String,
val imageURL: String,
val releaseDate: Date,
val news: News
)
data class News (
val title: String,
val author: String,
val imageURL: String,
val pages: List<String>
)
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/model/model.kt | 893882196 |
package com.ubaya.project_uts_160420147.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.ubaya.project_uts_160420147.R
import com.ubaya.project_uts_160420147.viewmodel.SharedViewModel
class MainActivity : AppCompatActivity() {
private lateinit var sharedViewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.HostFragment) as NavHostFragment
val navController = navHostFragment.navController
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNav)
// Initialize ViewModel
sharedViewModel = ViewModelProvider(this)[SharedViewModel::class.java]
// Setup BottomNavigationView with NavController
bottomNavigationView.setupWithNavController(navController)
bottomNavigationView.setOnNavigationItemSelectedListener() { item ->
when (item.itemId) {
R.id.itemHome -> {
navController.navigate(R.id.itemHome)
true
}
R.id.itemReadHistory -> {
// Accessing LiveData directly, ensure it's initialized properly in the ViewModel
if (sharedViewModel.lastVisitedGame.value != null) {
navController.navigate(R.id.itemReadHistory)
} else {
Toast.makeText(this, "Please select an item from Home first.", Toast.LENGTH_SHORT).show()
}
true
}
R.id.itemProfile -> {
navController.navigate(R.id.itemProfile)
true
}
else -> false
}
}
navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.loginFragment, R.id.registerFragment -> bottomNavigationView.visibility = View.GONE
else -> bottomNavigationView.visibility = View.VISIBLE
}
}
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/MainActivity.kt | 3220055985 |
package com.ubaya.project_uts_160420147.view
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.ubaya.project_uts_160420147.R
import org.json.JSONException
import org.json.JSONObject
class LoginFragment : Fragment() {
private lateinit var editTextUsername: EditText
private lateinit var editTextPassword: EditText
private lateinit var buttonLogin: Button
private lateinit var txtBuatAkun : TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_login, container, false)
editTextUsername = view.findViewById(R.id.editTextUsername)
editTextPassword = view.findViewById(R.id.editTextPassword)
buttonLogin = view.findViewById(R.id.buttonLogin)
txtBuatAkun = view.findViewById(R.id.txtBuatAkun)
buttonLogin.setOnClickListener {
login()
}
txtBuatAkun.setOnClickListener {
navigateToRegisterFragment()
}
return view
}
private fun navigateToRegisterFragment() {
// Use findNavController to perform navigation action
findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
}
private fun login() {
val queue = Volley.newRequestQueue(context)
val url = "http://192.168.1.80/anmp_uts/login.php"
val stringRequest = object : StringRequest(Method.POST, url,
Response.Listener<String> { response ->
try {
val jsonObject = JSONObject(response)
val status = jsonObject.getString("status")
if (status == "success") {
val userData = jsonObject.getJSONObject("userData")
saveUserData(userData)
findNavController().navigate(R.id.action_loginFragment_to_itemHome)
Toast.makeText(context, "Login successful.", Toast.LENGTH_SHORT).show()
} else {
val message = jsonObject.getString("message")
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Toast.makeText(context, "JSON parsing error: " + e.message, Toast.LENGTH_SHORT).show()
Log.e("LoginFragment", "JSON parsing error: " + e.message)
}
},
Response.ErrorListener { error ->
Toast.makeText(context, "Volley error: " + error.message, Toast.LENGTH_SHORT).show()
Log.e("LoginFragment", "Volley error: " + error.message)
}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["username"] = editTextUsername.text.toString()
params["password"] = editTextPassword.text.toString()
return params
}
}
queue.add(stringRequest)
}
private fun saveUserData(userData: JSONObject) {
val sharedPreferences = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
sharedPreferences.edit().apply {
putString("username", userData.getString("username"))
putString("first_name", userData.getString("FirstName"))
putString("last_name", userData.getString("LastName"))
apply()
}
Log.d("LoginFragment", "User data saved successfully: Username: ${userData.getString("username")}")
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/LoginFragment.kt | 264409851 |
package com.ubaya.project_uts_160420147.view
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ubaya.project_uts_160420147.R
class NewsAdapter : RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {
private var currentPage: String? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false)
return NewsViewHolder(view)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
currentPage?.let { holder.bind(it) }
}
override fun getItemCount(): Int = if (currentPage != null) 1 else 0
class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textView: TextView = itemView.findViewById(R.id.text_view_news_page)
fun bind(page: String) {
textView.text = page
}
}
fun updatePage(newPage: String?) {
currentPage = newPage
notifyDataSetChanged() // Notify that the data has changed
}
fun updatePages(newPages: List<String>) {
currentPage = newPages.toString()
notifyDataSetChanged()
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/NewsAdapter.kt | 1827390608 |
package com.ubaya.project_uts_160420147.view
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.ubaya.project_uts_160420147.databinding.FragmentGameListBinding
import com.ubaya.project_uts_160420147.viewmodel.GameListModel
class GameListFragment : Fragment() {
private lateinit var gamesViewModel: GameListModel
private lateinit var gamesListAdapter: GameListAdapter
private lateinit var binding: FragmentGameListBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentGameListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
gamesViewModel = ViewModelProvider(this).get(GameListModel::class.java)
gamesListAdapter = GameListAdapter(listOf())
binding.recView.apply {
layoutManager = LinearLayoutManager(context)
adapter = gamesListAdapter
}
binding.refreshLayout.setOnRefreshListener {
// Always refresh on user action, even if data is already fetched
gamesViewModel.refresh()
binding.refreshLayout.isRefreshing = false
}
observeViewModel()
}
override fun onResume() {
super.onResume()
// Check if data is not fetched then refresh
if (!gamesViewModel.dataFetched) {
gamesViewModel.refresh()
}
}
private fun observeViewModel() {
gamesViewModel.gameLD.observe(viewLifecycleOwner, Observer { games ->
games?.let {
binding.recView.visibility = View.VISIBLE
gamesListAdapter.updateGameList(it)
}
})
gamesViewModel.gameLoadErrorLD.observe(viewLifecycleOwner, Observer { isError ->
binding.txtError.visibility = if (isError) View.VISIBLE else View.GONE
})
gamesViewModel.loadingLD.observe(viewLifecycleOwner, Observer { isLoading ->
if (isLoading) {
binding.progressLoad.visibility = View.VISIBLE
binding.recView.visibility = View.GONE
binding.txtError.visibility = View.GONE
} else {
binding.progressLoad.visibility = View.GONE
}
})
}
} | Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/GameListFragment.kt | 392338030 |
package com.ubaya.project_uts_160420147.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.ubaya.project_uts_160420147.R
import org.json.JSONException
import org.json.JSONObject
class RegisterFragment : Fragment() {
private lateinit var editTextFirstName: EditText
private lateinit var editTextLastName: EditText
private lateinit var editTextUsername: EditText
private lateinit var editTextPassword: EditText
private lateinit var editTextEmail: EditText
private lateinit var buttonRegister: Button
private lateinit var buttonBack : Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_register, container, false)
editTextFirstName = view.findViewById(R.id.editTextFirstName)
editTextLastName = view.findViewById(R.id.editTextLastName)
editTextUsername = view.findViewById(R.id.editTextUsername)
editTextEmail = view.findViewById(R.id.editTextEmail)
editTextPassword = view.findViewById(R.id.editTextPassword)
buttonRegister = view.findViewById(R.id.buttonRegister)
buttonBack = view.findViewById(R.id.btnBackLogin)
buttonRegister.setOnClickListener {
registerUser()
}
buttonBack.setOnClickListener{
findNavController().popBackStack()
}
return view
}
private fun registerUser() {
val firstName = editTextFirstName.text.toString().trim()
val lastName = editTextLastName.text.toString().trim()
val username = editTextUsername.text.toString().trim()
val email = editTextEmail.text.toString().trim()
val password = editTextPassword.text.toString().trim()
// Validasi dasar untuk memastikan bahwa semua field diisi
if (firstName.isEmpty() || lastName.isEmpty() || username.isEmpty() || password.isEmpty() || email.isEmpty()) {
Toast.makeText(context, "All fields must be filled", Toast.LENGTH_SHORT).show()
return
}
val queue = Volley.newRequestQueue(context)
val url = "http://192.168.1.80/anmp_uts/register.php" // Gunakan IP khusus emulator atau konfigurasi server Anda
val stringRequest = object : StringRequest(Method.POST, url,
Response.Listener { response ->
try {
val obj = JSONObject(response)
Toast.makeText(context, obj.getString("message"), Toast.LENGTH_LONG).show()
// Jika berhasil, mungkin navigasi ke Login Fragment atau menutup fragment ini
if (obj.getString("message") == "User registered successfully") {
// Implement navigasi jika diperlukan
}
} catch (e: JSONException) {
e.printStackTrace()
Toast.makeText(context, "Error parsing JSON response", Toast.LENGTH_LONG).show()
}
},
Response.ErrorListener { volleyError ->
Toast.makeText(context, "Error: ${volleyError.message}", Toast.LENGTH_LONG).show()
volleyError.printStackTrace()
}
) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["firstName"] = firstName
params["lastName"] = lastName
params["username"] = username
params["email"] = email
params["password"] = password
return params
}
}
queue.add(stringRequest)
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/RegisterFragment.kt | 3136500883 |
package com.ubaya.project_uts_160420147.view
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.squareup.picasso.Picasso
import com.ubaya.project_uts_160420147.databinding.FragmentGameDetailBinding
import com.ubaya.project_uts_160420147.model.Game
import com.ubaya.project_uts_160420147.viewmodel.DetailViewModel
import com.ubaya.project_uts_160420147.viewmodel.SharedViewModel
import java.util.logging.Logger
class GameDetailFragment : Fragment() {
private lateinit var viewModel: DetailViewModel
private lateinit var sharedViewModel: SharedViewModel
private lateinit var binding: FragmentGameDetailBinding
private var currentPageIndex = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentGameDetailBinding.inflate(inflater, container, false)
viewModel = ViewModelProvider(this)[DetailViewModel::class.java]
sharedViewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val args: GameDetailFragmentArgs by navArgs()
val gameId = args.gameId
viewModel.fetch(gameId)
val adapter = NewsAdapter()
binding.recyclerViewNews.layoutManager = LinearLayoutManager(context)
binding.recyclerViewNews.adapter = adapter
viewModel.gameData.observe(viewLifecycleOwner, Observer { game ->
game?.let {
Log.d("GameDetailFragment", "Game data received: ${it.title}")
sharedViewModel.setLastVisitedGame(it)
updateUI(it)
updatePage(adapter)
}
})
sharedViewModel.lastVisitedGame.observe(viewLifecycleOwner, Observer { game ->
game?.let {
updateUI(it)
updatePages(adapter, it.news.pages)
if (it.news.pages.size > 1) {
binding.buttonNext.visibility = View.VISIBLE
binding.buttonPrev.visibility = View.VISIBLE
} else {
binding.buttonNext.visibility = View.GONE
binding.buttonPrev.visibility = View.GONE
}
} ?: run {
Toast.makeText(context, "No game details available. Please select a game from the list.", Toast.LENGTH_LONG).show()
// Hide buttons as there's no data to navigate
binding.buttonNext.visibility = View.GONE
binding.buttonPrev.visibility = View.GONE
}
})
setupButtonListeners(adapter)
}
private fun setupButtonListeners(adapter: NewsAdapter) {
binding.buttonNext.setOnClickListener {
val pages = viewModel.gameData.value?.news?.pages ?: emptyList()
if (currentPageIndex < pages.size - 1) {
currentPageIndex++
updatePage(adapter)
}
}
binding.buttonPrev.setOnClickListener {
if (currentPageIndex > 0) {
currentPageIndex--
updatePage(adapter)
}
}
}
private fun updateUI(game: Game) {
binding.textViewTitle.text = game.title
binding.textViewAuthor.text = game.news.author
Picasso.get().load(game.news.imageURL).into(binding.imageViewNews)
}
private fun updatePage(adapter: NewsAdapter) {
val pages = viewModel.gameData.value?.news?.pages ?: emptyList()
if (pages.isNotEmpty()) {
adapter.updatePage(pages[currentPageIndex])
}
}
private fun updatePages(adapter: NewsAdapter, pages: List<String>) {
adapter.updatePages(pages)
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/GameDetailFragment.kt | 1587314601 |
package com.ubaya.project_uts_160420147.view
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation.findNavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.ubaya.project_uts_160420147.databinding.FragmentProfilBinding
import com.ubaya.project_uts_160420147.viewmodel.ProfileViewModel
import org.json.JSONException
import org.json.JSONObject
class ProfileFragment : Fragment() {
private lateinit var binding: FragmentProfilBinding
private lateinit var viewModel: ProfileViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentProfilBinding.inflate(inflater, container, false)
viewModel = ViewModelProvider(this).get(ProfileViewModel::class.java)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadUserData()
viewModel.firstName.observe(viewLifecycleOwner) { firstName ->
binding.editTextFirstName.setText(firstName)
Log.d("ProfileFragment", "First Name loaded: $firstName")
}
viewModel.lastName.observe(viewLifecycleOwner) { lastName ->
binding.editTextLastName.setText(lastName)
Log.d("ProfileFragment", "Last Name loaded: $lastName")
}
binding.buttonSaveChanges.setOnClickListener {
saveUserData()
Toast.makeText(context, "Profile Updated Successfully", Toast.LENGTH_SHORT).show()
Log.d("ProfileFragment", "Data saved: First Name: ${binding.editTextFirstName.text}, Last Name: ${binding.editTextLastName.text}")
}
binding.buttonSignOut.setOnClickListener {
logout()
Toast.makeText(context, "Logged out Successfully", Toast.LENGTH_SHORT).show()
Log.d("ProfileFragment", "User logged out")
}
}
private fun loadUserData() {
val sharedPreferences = activity?.getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
binding.editTextFirstName.setText(sharedPreferences?.getString("first_name", ""))
binding.editTextLastName.setText(sharedPreferences?.getString("last_name", ""))
}
private fun saveUserData() {
val firstName = binding.editTextFirstName.text.toString()
val lastName = binding.editTextLastName.text.toString()
val password = binding.editTextPassword.text.toString()
val sharedPreferences = activity?.getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
val storedFirstName = sharedPreferences?.getString("first_name", "")
val storedLastName = sharedPreferences?.getString("last_name", "")
val storedPassword = sharedPreferences?.getString("password", "")
val queue = Volley.newRequestQueue(context)
val url = "http://192.168.1.80/anmp_uts/update.php"
val stringRequest = object : StringRequest(Method.POST, url,
Response.Listener<String> { response ->
try {
val jsonObject = JSONObject(response)
val status = jsonObject.getString("status")
val message = jsonObject.getString("message")
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
// Refresh UI if changes are successful
if (status == "success") {
// Update SharedPreferences with new data
val editor = sharedPreferences?.edit()
if (firstName != storedFirstName) editor?.putString("first_name", firstName)
if (lastName != storedLastName) editor?.putString("last_name", lastName)
if (password != storedPassword) editor?.putString("password", password)
editor?.apply()
viewModel.firstName.postValue(firstName)
viewModel.lastName.postValue(lastName)
}
} catch (e: JSONException) {
e.printStackTrace()
Toast.makeText(context, "JSON parsing error: " + e.message, Toast.LENGTH_SHORT).show()
}
},
Response.ErrorListener { error ->
Toast.makeText(context, "Volley error: " + error.message, Toast.LENGTH_SHORT).show()
}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["username"] = viewModel.username.value ?: ""
params["firstName"] = firstName
params["lastName"] = lastName
params["password"] = password
return params
}
}
queue.add(stringRequest)
}
private fun logout() {
viewModel.clearUserData()
findNavController().navigate(ProfileFragmentDirections.actionItemProfileToLoginFragment())
Log.d("ProfileFragment", "Clearing user data and navigating to login")
}
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/ProfileFragment.kt | 2256479957 |
package com.ubaya.project_uts_160420147.view
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.ubaya.project_uts_160420147.databinding.GamesCardItemsBinding
import com.ubaya.project_uts_160420147.model.Game
import com.ubaya.project_uts_160420147.util.loadImage
class GameListAdapter(private var games: List<Game>) : RecyclerView.Adapter<GameListAdapter.GameViewHolder>() {
class GameViewHolder(val binding: GamesCardItemsBinding) : RecyclerView.ViewHolder(binding.root)
fun updateGameList(newGames: List<Game>) {
games = newGames
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameViewHolder {
val binding = GamesCardItemsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return GameViewHolder(binding)
}
override fun onBindViewHolder(holder: GameViewHolder, position: Int) {
val game = games[position]
with(holder.binding) {
textViewTitle.text = game.title
textViewAuthor.text = game.developer
textViewGenre.text = game.genre
textViewShortDescription.text = game.description
imageViewCard.loadImage(game.imageURL, holder.binding.progressBar)
buttonDetail.setOnClickListener {
Log.d("GameListAdapter", "Navigating with game ID: ${game.gameID}")
val action = GameListFragmentDirections.actionGameListFragmentToGameDetailFragment(game.gameID)
it.findNavController().navigate(action)
}
}
}
override fun getItemCount(): Int = games.size
}
| Adv160420147ProjectUts/app/src/main/java/com/ubaya/project_uts_160420147/view/GameListAdapter.kt | 1613448902 |
package com.example.test
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.test", appContext.packageName)
}
} | test-shift/app/src/androidTest/java/com/example/test/ExampleInstrumentedTest.kt | 3708327992 |
package com.example.test
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | test-shift/app/src/test/java/com/example/test/ExampleUnitTest.kt | 13367193 |
package com.example.test
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private val retrofit = Retrofit.Builder()
.baseUrl("https://randomuser.me/")
.addConverterFactory(GsonConverterFactory.create())
.build()
private val service = retrofit.create(ApiService::class.java)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
GlobalScope.launch(Dispatchers.Main) {
val response = service.getRandomUsers(60)
if (response.isSuccessful) {
val randomUserResponse = response.body()
val userList: List<RandomUser> = randomUserResponse?.results ?: emptyList()
val adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_list_item_1, userList.map { "${it.name.first} ${it.name.last}" })
val listView: ListView = findViewById(R.id.listView)
listView.adapter = adapter
} else {
// Обработка ошибки
}
}
}
data class RandomUserResponse(val results: List<RandomUser>)
data class RandomUser(val gender: String, val name: Name, val email: String)
data class Name(val title: String, val first: String, val last: String)
interface ApiService {
@GET("/api")
suspend fun getRandomUsers(@Query("results") results: Int): Response<RandomUserResponse>
}
} | test-shift/app/src/main/java/com/example/test/MainActivity.kt | 40419604 |
package com.polarbookshop.configservice
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class ConfigServiceApplicationTests {
@Test
fun contextLoads() {
}
}
| config-service/src/test/kotlin/com/polarbookshop/configservice/ConfigServiceApplicationTests.kt | 3020073078 |
package com.polarbookshop.configservice
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.config.server.EnableConfigServer
@SpringBootApplication
@EnableConfigServer
class ConfigServiceApplication
fun main(args: Array<String>) {
runApplication<ConfigServiceApplication>(*args)
}
| config-service/src/main/kotlin/com/polarbookshop/configservice/ConfigServiceApplication.kt | 2885103096 |
package com.boringkm.imagecompress
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.boringkm.imagecompress", appContext.packageName)
}
} | ImageCompressApp-Android/app/src/androidTest/java/com/boringkm/imagecompress/ExampleInstrumentedTest.kt | 1398779203 |
package com.boringkm.imagecompress
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | ImageCompressApp-Android/app/src/test/java/com/boringkm/imagecompress/ExampleUnitTest.kt | 3665188438 |
package com.boringkm.imagecompress.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | ImageCompressApp-Android/app/src/main/java/com/boringkm/imagecompress/ui/theme/Color.kt | 983337108 |
package com.boringkm.imagecompress.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun ImageCompressAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | ImageCompressApp-Android/app/src/main/java/com/boringkm/imagecompress/ui/theme/Theme.kt | 605447500 |
package com.boringkm.imagecompress.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | ImageCompressApp-Android/app/src/main/java/com/boringkm/imagecompress/ui/theme/Type.kt | 4012443273 |
package com.boringkm.imagecompress
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import coil.compose.AsyncImage
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class MainActivity : ComponentActivity() {
private val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
openImagePicker()
}
}
private val pickImageLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
result.data?.data?.let { uri ->
imageUriState.value = uri
val inputStream = contentResolver.openInputStream(uri)
if (inputStream != null) {
val bytes = inputStream.available()
originalImageKB.intValue = bytes / 1024
val bitmap = BitmapFactory.decodeStream(inputStream)
val quality = 75
val outputPath = filesDir.absolutePath + "/output.webp"
saveBitmapAsWebP(bitmap, outputPath, quality)
inputStream.close()
}
}
}
}
private fun saveBitmapAsWebP(bitmap: Bitmap, outputPath: String, quality: Int) {
var fos: FileOutputStream? = null
try {
val file = File(outputPath)
if (!file.exists()) {
file.createNewFile()
} else {
file.delete()
}
fos = FileOutputStream(file)
// WebP 형식으로 압축된 이미지를 저장
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSY, quality, fos)
} else {
@Suppress("DEPRECATION")
bitmap.compress(Bitmap.CompressFormat.WEBP, quality, fos)
}
Log.d("MainActivity", "WebP 이미지가 저장되었습니다: $outputPath")
} catch (e: IOException) {
e.printStackTrace()
Log.e("MainActivity", "WebP 이미지 저장 중 오류 발생: " + e.message)
} finally {
if (fos != null) {
try {
fos.close()
// get compressed image size
val bytes = File(outputPath).length().toInt()
compressedImageKB.intValue = bytes / 1024
// get uri of compressed image
compressedImageUriState.value = Uri.parse(outputPath)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
private val originalImageKB = mutableIntStateOf(0)
private val compressedImageKB = mutableIntStateOf(0)
private val imageUriState = mutableStateOf<Uri?>(null)
private val compressedImageUriState = mutableStateOf<Uri?>(null)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Scaffold {
val imageUri by imageUriState
val compressedImageUri by compressedImageUriState
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (imageUri != null) {
AsyncImage(
model = imageUri!!,
contentDescription = "Selected Image",
contentScale = ContentScale.Fit,
modifier = Modifier.height(200.dp)
)
AsyncImage(
model = compressedImageUri!!,
contentDescription = "Compressed Image",
contentScale = ContentScale.Fit,
modifier = Modifier.height(200.dp)
)
Text(text = "Original Image Size: ${originalImageKB.intValue} KB")
Text(text = "Compressed Image Size: ${compressedImageKB.intValue} KB")
}
Button(
onClick = {
requestPermissionAndOpenImagePicker()
},
modifier = Modifier.padding(8.dp)
) {
Text(text = "Select Image")
}
}
}
}
}
private fun openImagePicker() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
pickImageLauncher.launch(intent)
}
private fun requestPermissionAndOpenImagePicker() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_MEDIA_IMAGES
) == PackageManager.PERMISSION_GRANTED
) {
openImagePicker()
} else {
requestPermissionLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES)
}
} else {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
openImagePicker()
} else {
requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
}
}
| ImageCompressApp-Android/app/src/main/java/com/boringkm/imagecompress/MainActivity.kt | 1926951235 |
package com.blr19c.falowp.bot.signin.vo
import java.time.LocalDate
/**
* 签到记录
*/
data class SigninRecordVo(
val id: Int,
/**
* 用户id
*/
val userId: String,
/**
* 签到时间
*/
val signinDate: LocalDate,
)
| falowp-bot-plugins/falowp-bot-plugin-signin/src/main/kotlin/com/blr19c/falowp/bot/signin/vo/SigninRecordVo.kt | 1163938830 |
package com.blr19c.falowp.bot.signin.database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.javatime.date
import org.jetbrains.exposed.sql.transactions.transaction
/**
* 签到记录
*/
object SigninRecord : Table("signin_record") {
val id = integer("id").autoIncrement()
/**
* 用户id
*/
val userId = varchar("user_id", 64).index()
/**
* 签到时间
*/
val signinDate = date("signin_date")
override val primaryKey = PrimaryKey(id, name = "pk_signin_record_id")
init {
transaction {
uniqueIndex(userId, signinDate)
SchemaUtils.create(SigninRecord)
}
}
} | falowp-bot-plugins/falowp-bot-plugin-signin/src/main/kotlin/com/blr19c/falowp/bot/signin/database/SigninRecord.kt | 1277377922 |
package com.blr19c.falowp.bot.signin.plugins.signin
import com.blr19c.falowp.bot.signin.database.SigninRecord
import com.blr19c.falowp.bot.signin.vo.SigninRecordVo
import com.blr19c.falowp.bot.user.vo.BotUserVo
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import java.time.LocalDate
import java.time.YearMonth
/**
* 签到
*/
fun BotUserVo.signin() {
return transaction {
SigninRecord.insert {
it[userId] = [email protected]
it[signinDate] = LocalDate.now()
}
}
}
/**
* 获取累计签到次数
*/
fun BotUserVo.queryCumulativeSignin(): Long {
return transaction {
val userId = [email protected]
SigninRecord.selectAll().where { SigninRecord.userId eq userId }.count()
}
}
/**
* 获取本月签到信息
*/
fun BotUserVo.queryCurrentMonthSignin(): List<SigninRecordVo> {
val start = LocalDate.now().withDayOfMonth(1)
val end = YearMonth.now().atEndOfMonth()
return transaction {
SigninRecord.selectAll()
.where {
val userEq = SigninRecord.userId eq [email protected]
SigninRecord.signinDate.between(start, end).and(userEq)
}.map { convertVo(it) }
}
}
private fun convertVo(resultRow: ResultRow): SigninRecordVo {
return SigninRecordVo(
resultRow[SigninRecord.id],
resultRow[SigninRecord.userId],
resultRow[SigninRecord.signinDate],
)
} | falowp-bot-plugins/falowp-bot-plugin-signin/src/main/kotlin/com/blr19c/falowp/bot/signin/plugins/signin/SigninRecordOption.kt | 3692809138 |
package com.blr19c.falowp.bot.signin.plugins.signin
import com.blr19c.falowp.bot.system.api.SendMessage
import com.blr19c.falowp.bot.system.expand.ImageUrl
import com.blr19c.falowp.bot.system.expand.encodeToBase64String
import com.blr19c.falowp.bot.system.json.Json
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.message
import com.blr19c.falowp.bot.system.readPluginResource
import com.blr19c.falowp.bot.system.systemConfigProperty
import com.blr19c.falowp.bot.system.web.htmlToImageBase64
import com.blr19c.falowp.bot.user.plugins.user.currentUser
import com.blr19c.falowp.bot.user.plugins.user.incrementCoins
import com.blr19c.falowp.bot.user.plugins.user.incrementImpression
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup
import org.jsoup.select.Elements
import java.math.RoundingMode
import java.sql.SQLException
import java.time.LocalDate
import kotlin.random.Random
/**
* 签到
*/
@Plugin(name = "签到", desc = "每日一签,能增加金币&好感度")
class Signin {
private val signin = message(Regex("签到")) {
val currentUser = this.currentUser()
val addCoins = Random.nextDouble(10.0, 50.0).toBigDecimal().setScale(2, RoundingMode.HALF_UP)
val addImpression = Random.nextDouble(0.5, 5.0).toBigDecimal().setScale(2, RoundingMode.HALF_UP)
try {
//签到&增加金币和好感度
currentUser.signin()
currentUser.incrementCoins(addCoins)
currentUser.incrementImpression(addImpression)
val backgroundImg = withContext(Dispatchers.IO) {
readPluginResource("background.png").encodeToBase64String()
}
val html = readPluginResource("signin.html") { inputStream ->
inputStream.bufferedReader().use { Jsoup.parse(it.readText()) }
}
val monthSignin = currentUser.queryCurrentMonthSignin().map { it.signinDate }
html.select("#app").backgroundUrl(backgroundImg)
html.select("#nickname").html(currentUser.nickname)
html.select("#uid").html(currentUser.userId)
html.select("#qqAvatar").attr("src", "data:image/png;base64,${currentUser.avatar.toHtmlBase64()}")
html.select("#signin-day").html(currentUser.queryCumulativeSignin().toString())
html.select("#signin-impression").html(addImpression.toString())
html.select("#signin-coins").html(addCoins.toString())
html.select("#impression").html((currentUser.impression + addImpression).toString())
html.select("#coins").html((currentUser.coins + addCoins).toPlainString())
html.select("#by").html(systemConfigProperty("nickname") + LocalDate.now())
html.select("#selectDate").`val`(Json.toJsonString(monthSignin))
val replyImgBase64 = htmlToImageBase64(html.html(), "#app")
this.sendReply(SendMessage.builder().image(replyImgBase64).build())
} catch (e: SQLException) {
this.sendReply("你今天已经签到过了", reference = true)
}
}
private suspend fun Elements.backgroundUrl(url: String) {
var style = this.attr("style")
if (style.isNotBlank() && !style.endsWith(";")) {
style += ";"
}
style += """
background-image: url("data:image/png;base64,${ImageUrl(url.trim()).toBase64()}");
background-size: cover;
""".trimIndent()
this.attr("style", style)
}
init {
signin.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-signin/src/main/kotlin/com/blr19c/falowp/bot/signin/plugins/signin/Signin.kt | 697478871 |
package com.blr19c.falowp.bot.kfc.plugins.kfc
import com.blr19c.falowp.bot.system.api.SendMessage
import com.blr19c.falowp.bot.system.json.Json
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Task.cronScheduling
import com.blr19c.falowp.bot.system.readPluginResource
import com.fasterxml.jackson.databind.node.ArrayNode
import kotlin.random.Random
/**
* 肯德基疯狂星期四
*/
@Plugin(
name = "肯德基疯狂星期四",
tag = "聊天",
desc = """
<p>每周四12点推送</p>
"""
)
class KFC {
private val kfc = cronScheduling("0 0 12 ? * THU") {
val message = readPluginResource("kfc.json") {
val jsonNode = Json.readJsonNode(it.readBytes().decodeToString()) as ArrayNode
val randomIndex = Random.nextInt(jsonNode.size())
jsonNode[randomIndex].asText()
}
this.sendAllGroup(SendMessage.builder(message).build())
}
init {
kfc.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-kfc/src/main/kotlin/com/blr19c/falowp/bot/kfc/plugins/kfc/KFC.kt | 3432224053 |
package com.blr19c.falowp.bot.coin.plugins.work
import com.blr19c.falowp.bot.system.plugin.MessagePluginRegisterMatch
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.message
import com.blr19c.falowp.bot.system.plugin.hook.awaitReply
import com.blr19c.falowp.bot.user.plugins.user.currentUser
import com.blr19c.falowp.bot.user.plugins.user.incrementCoins
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.random.Random
import kotlin.time.Duration.Companion.seconds
@Plugin(
name = "打工",
desc = """
<p>打工</p>
<p>打工赚取金币</p>
""",
tag = "小游戏"
)
class Work {
private val work = message(Regex("打工")) {
val int1 = listOf(Random.nextInt(1, 100), Random.nextInt(1, 100))
val int2 = listOf(Random.nextInt(1, 100), Random.nextInt(1, 100))
val int3 = listOf(Random.nextInt(1, 100), Random.nextInt(1, 100))
val int4 = listOf(Random.nextInt(1, 100), Random.nextInt(1, 100))
val int5 = listOf(Random.nextInt(1, 100), Random.nextInt(1, 100))
val replyQuestion = """
请在120秒内完成以下5道题目,输入'提交 X X X'进行提交:
${int1[0]}+${int1[1]}=?
${int2[0]}+${int2[1]}=?
${int3[0]}+${int3[1]}=?
${int4[0]}+${int4[1]}=?
${int5[0]}+${int5[1]}=?
""".trimIndent()
this.sendReply(replyQuestion)
val inputAnswerList = withTimeoutOrNull(120.seconds) {
val answer = awaitReply(MessagePluginRegisterMatch(regex = Regex("提交([\\d ]+)"))) { (answer) -> answer }
Regex("\\b\\d+\\b").findAll(answer).map { it.value.toInt() }.toList()
} ?: return@message this.sendReply("你做的太慢了,没得到任何奖励", reference = true)
val answerList = listOf(int1.sum(), int2.sum(), int3.sum(), int4.sum(), int5.sum())
if (inputAnswerList != answerList) {
return@message this.sendReply("回答错误,你的奖励消失了")
}
val award = Random.nextInt(100, 500)
currentUser().incrementCoins(award.toBigDecimal())
this.sendReply("你获得了${award}金币的奖励")
}
init {
work.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-coin/src/main/kotlin/com/blr19c/falowp/bot/coin/plugins/work/Work.kt | 3386118089 |
package com.blr19c.falowp.bot.coin.plugins.robbery
import com.blr19c.falowp.bot.coin.plugins.robbery.database.RobberyInfo
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.message
import com.blr19c.falowp.bot.user.plugins.user.currentUser
import com.blr19c.falowp.bot.user.plugins.user.decrementCoins
import com.blr19c.falowp.bot.user.plugins.user.incrementCoins
import com.blr19c.falowp.bot.user.plugins.user.queryByUserId
import com.blr19c.falowp.bot.user.vo.BotUserVo
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import java.math.BigDecimal
import java.math.RoundingMode
import java.sql.SQLException
import java.time.LocalDate
import kotlin.random.Random
/**
* 打劫
*/
@Plugin(
name = "打劫",
desc = """
<p>@某人 打劫</p>
<p>好感度会影响打劫成功率</p>
""",
tag = "小游戏"
)
class Robbery {
private val robbery = message(Regex("打劫")) {
val currentUser = this.currentUser()
val atList = this.receiveMessage.content.at
if (atList.size > 1 && successRate(currentUser, 9)) {
val medicalExpenses = Random.nextDouble(100.0, 500.0)
.toBigDecimal().setScale(2, RoundingMode.HALF_UP)
currentUser.decrementCoins(medicalExpenses)
this.sendReply(
"对方人多,你被打了一顿,损失了${medicalExpenses.toPlainString()}金币的医药费",
reference = true
)
return@message
}
try {
var sum = BigDecimal.ZERO
transaction {
for (user in atList) {
if (successRate(currentUser)) {
val toUser = queryByUserId(user.id, receiveMessage.source.id)!!
val coins = Random.nextDouble(10.0, 300.0)
.toBigDecimal()
.setScale(2, RoundingMode.HALF_UP)
.min(toUser.coins)
toUser.decrementCoins(coins)
currentUser.incrementCoins(coins)
sum = sum.add(coins)
}
RobberyInfo.insert {
it[userId] = currentUser.userId
it[robbedUserId] = user.id
it[createDate] = LocalDate.now()
}
}
}
this.sendReply("你抢到了${sum.toPlainString()}个金币")
} catch (e: SQLException) {
this.sendReply("这些人你今天已经抢过了")
}
}
private fun successRate(botUserVo: BotUserVo, cardinality: Int = 6): Boolean {
val impressionRate = botUserVo.impression.divide(BigDecimal(100)).max(BigDecimal(3)).toInt()
return Random.nextInt(1, 10) > cardinality - impressionRate
}
init {
robbery.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-coin/src/main/kotlin/com/blr19c/falowp/bot/coin/plugins/robbery/Robbery.kt | 1917950384 |
package com.blr19c.falowp.bot.coin.plugins.robbery.database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.javatime.date
import org.jetbrains.exposed.sql.transactions.transaction
/**
* 打劫记录
*/
object RobberyInfo : Table("robbery_info") {
val id = integer("id").autoIncrement()
/**
* 用户id
*/
val userId = varchar("user_id", 64).index()
/**
* 被打劫的用户id
*/
val robbedUserId = varchar("robbed_user_id", 64).index()
/**
* 打劫日期
*/
val createDate = date("event_date_time")
override val primaryKey = PrimaryKey(id, name = "pk_robbery_info_id")
init {
transaction {
uniqueIndex(userId, robbedUserId, createDate)
SchemaUtils.create(RobberyInfo)
}
}
} | falowp-bot-plugins/falowp-bot-plugin-coin/src/main/kotlin/com/blr19c/falowp/bot/coin/plugins/robbery/database/RobberyInfo.kt | 3384243208 |
package com.blr19c.falowp.bot.bili.plugins.bili.vo
/**
* b站up主信息
*/
data class BiliUpInfoVo(
val id: Int,
/**
* b站id
*/
val mid: String,
/**
* 直播id
*/
val roomId: String,
/**
* up名称
*/
val name: String,
/**
* 直播状态
*/
val liveStatus: Boolean,
) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/vo/BiliUpInfoVo.kt | 2240238419 |
package com.blr19c.falowp.bot.bili.plugins.bili.vo
/**
* b站订阅
*/
data class BiliSubscriptionVo(
val id: Int,
/**
* b站id
*/
val mid: String,
/**
* 来源id
*/
val sourceId: String,
/**
* 来源类型
*/
val sourceType: String
) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/vo/BiliSubscriptionVo.kt | 3366045932 |
package com.blr19c.falowp.bot.bili.plugins.bili.database
import com.blr19c.falowp.bot.bili.plugins.bili.vo.BiliUpInfoVo
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
/**
* b站up主信息
*/
object BiliUpInfo : Table("bili_up_info") {
val id = integer("id").autoIncrement()
/**
* b站id
*/
val mid = varchar("mid", 32).uniqueIndex()
/**
* 直播id
*/
val roomId = varchar("room_id", 32)
/**
* up名称
*/
val name = varchar("name", 128)
/**
* 直播状态
*/
val liveStatus = bool("live_status")
override val primaryKey = PrimaryKey(id, name = "pk_bili_up_info_id")
init {
transaction {
SchemaUtils.create(BiliUpInfo)
}
}
fun queryAll(): List<BiliUpInfoVo> {
return transaction {
BiliUpInfo.selectAll().map {
BiliUpInfoVo(
it[BiliUpInfo.id],
it[mid],
it[roomId],
it[name],
it[liveStatus]
)
}.toList()
}
}
fun queryByMid(mid: String): BiliUpInfoVo? {
return transaction {
BiliUpInfo.selectAll().where { BiliUpInfo.mid eq mid }.map {
BiliUpInfoVo(
it[BiliUpInfo.id],
it[BiliUpInfo.mid],
it[roomId],
it[name],
it[liveStatus]
)
}.firstOrNull()
}
}
fun queryByLiveStatus(liveStatus: Boolean): List<BiliUpInfoVo> {
return transaction {
BiliUpInfo.selectAll().where { BiliUpInfo.liveStatus eq liveStatus }.map {
BiliUpInfoVo(
it[BiliUpInfo.id],
it[mid],
it[roomId],
it[name],
it[BiliUpInfo.liveStatus]
)
}.toList()
}
}
fun updateLiveStatus(mid: String, liveStatus: Boolean) {
transaction {
BiliUpInfo.update({ BiliUpInfo.mid eq mid }) {
it[BiliUpInfo.liveStatus] = liveStatus
}
}
}
fun insert(mid: String, roomId: String, name: String) {
transaction {
BiliUpInfo.insert {
it[BiliUpInfo.mid] = mid
it[BiliUpInfo.roomId] = roomId
it[BiliUpInfo.name] = name
it[liveStatus] = false
}
}
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/database/BiliUpInfo.kt | 1291867130 |
package com.blr19c.falowp.bot.bili.plugins.bili.database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
/**
* b站动态
*/
object BiliDynamic : Table("bili_dynamic") {
val id = integer("id").autoIncrement()
/**
* b站id
*/
val mid = varchar("mid", 32).index()
/**
* 动态id
*/
val dynamic = varchar("dynamic", 64)
override val primaryKey = PrimaryKey(id, name = "pk_bili_dynamic_id")
init {
transaction {
SchemaUtils.create(BiliDynamic)
}
}
fun queryByMid(mid: String): List<String> {
return transaction {
BiliDynamic.selectAll().where(BiliDynamic.mid eq mid).map { it[dynamic] }.toList()
}
}
fun insert(mid: String, dynamic: String) {
transaction {
BiliDynamic.insert {
it[BiliDynamic.mid] = mid
it[BiliDynamic.dynamic] = dynamic
}
}
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/database/BiliDynamic.kt | 4187339493 |
package com.blr19c.falowp.bot.bili.plugins.bili.database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.transactions.transaction
/**
* b站登录的cookie
*/
object BiliCookie : Table("bili_cookie") {
val id = integer("id").autoIncrement()
/**
* cookie
*/
val cookie = text("cookie")
override val primaryKey = PrimaryKey(id, name = "pk_bili_cookie_id")
init {
transaction {
SchemaUtils.create(BiliCookie)
}
}
}
| falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/database/BiliCookie.kt | 2585178962 |
package com.blr19c.falowp.bot.bili.plugins.bili.database
import com.blr19c.falowp.bot.bili.plugins.bili.vo.BiliSubscriptionVo
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
/**
* b站订阅
*/
object BiliSubscription : Table("bili_subscription") {
val id = integer("id").autoIncrement()
/**
* b站id
*/
val mid = varchar("mid", 32).index()
/**
* 来源id
*/
val sourceId = varchar("source_id", 128).index()
/**
* 来源类型
*/
val sourceType = varchar("source_type", 16)
/**
* 动态列表
*/
override val primaryKey = PrimaryKey(id, name = "pk_bili_subscription_id")
init {
transaction {
uniqueIndex(mid, sourceId)
SchemaUtils.create(BiliSubscription)
}
}
fun insert(mid: String, sourceId: String, sourceType: String) {
transaction {
BiliSubscription.insert {
it[BiliSubscription.mid] = mid
it[BiliSubscription.sourceId] = sourceId
it[BiliSubscription.sourceType] = sourceType
}
}
}
fun queryByMid(mid: String): List<BiliSubscriptionVo> {
return transaction {
BiliSubscription.selectAll().where(BiliSubscription.mid eq mid).map {
BiliSubscriptionVo(
it[BiliSubscription.id],
it[BiliSubscription.mid],
it[sourceId],
it[sourceType],
)
}.toList()
}
}
fun queryBySourceId(sourceId: String): List<BiliSubscriptionVo> {
return transaction {
BiliSubscription.selectAll().where(BiliSubscription.sourceId eq sourceId).map {
BiliSubscriptionVo(
it[BiliSubscription.id],
it[mid],
it[BiliSubscription.sourceId],
it[sourceType],
)
}.toList()
}
}
}
| falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/database/BiliSubscription.kt | 1270126319 |
package com.blr19c.falowp.bot.bili.plugins.bili
import com.blr19c.falowp.bot.bili.plugins.bili.api.DatabaseCookiesStorage
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliLiveInfo
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliVideoAiSummary
import com.blr19c.falowp.bot.bili.plugins.bili.vo.BiliUpInfoVo
import com.blr19c.falowp.bot.system.Log
import com.blr19c.falowp.bot.system.cache.CacheReference
import com.blr19c.falowp.bot.system.expand.ImageUrl
import com.blr19c.falowp.bot.system.expand.encodeToBase64String
import com.blr19c.falowp.bot.system.readPluginResource
import com.blr19c.falowp.bot.system.systemConfigProperty
import com.blr19c.falowp.bot.system.web.*
import com.microsoft.playwright.BrowserContext
import com.microsoft.playwright.ElementHandle
import com.microsoft.playwright.Page
import com.microsoft.playwright.options.Cookie
import com.microsoft.playwright.options.LoadState
import com.microsoft.playwright.options.ScreenshotType
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup
import org.jsoup.select.Elements
import java.net.URI
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.time.Duration.Companion.days
/**
* b站获取信息工具
*/
object BLiveUtils : Log {
private val ticket by CacheReference(1.days) { genWebTicket() }
private suspend fun genWebTicket(): String {
val ts = System.currentTimeMillis() / 1000
val hmacKey = SecretKeySpec("XgwSnGZ1p".toByteArray(), "HmacSHA256")
val mac = Mac.getInstance("HmacSHA256")
mac.init(hmacKey)
val hexSign = mac.doFinal("ts$ts".toByteArray()).joinToString("") { "%02x".format(it) }
val formData = Parameters.build {
append("key_id", "ec02")
append("hexsign", hexSign)
append("context[ts]", ts.toString())
append("csrf", "")
}
return webclient().post("https://api.bilibili.com/bapis/bilibili.api.ticket.v1.Ticket/GenWebTicket?${formData.formUrlEncode()}") {
for (cookie in DatabaseCookiesStorage.getAll()) {
cookie(cookie.name, cookie.value)
}
}.bodyAsJsonNode()["data"]["ticket"].asText()
}
private suspend fun <T> browserContext(block: BrowserContext.() -> T): T {
return withContext(Dispatchers.IO) {
val cookies = DatabaseCookiesStorage.getAll().map {
Cookie(it.name, it.value)
.setDomain(".bilibili.com")
.setPath(it.path)
.setHttpOnly(it.httpOnly)
.setSecure(it.secure)
}.toMutableList()
cookies.add(Cookie("bili_ticket", ticket).setDomain(".bilibili.com").setPath("/"))
commonWebdriverContext {
this.addCookies(cookies)
block(this)
}
}
}
/**
* b站动态截屏
*/
suspend fun dynamicScreenshot(dynamicId: String): String? = coroutineScope {
val url = "https://www.bilibili.com/opus/$dynamicId"
browserContext {
this.newPage().use { page ->
page.navigate(url)
page.waitForLoadState(LoadState.NETWORKIDLE)
if (page.title().contains("验证码")) {
log().info("b站动态截屏出现验证码,等待下次重试:{}", dynamicId)
return@browserContext null
}
if (page.title().contains("出错")) {
log().info("b站动态截屏出现页面错误,等待下次重试:{}", dynamicId)
return@browserContext null
}
removeDynamicUselessParts(page)
//老页面
val biliDynPage = page.existsToExecute(".bili-dyn-item__main") {
biliDynPage(page)
}
//新页面
val biliOpusPage = page.existsToExecute(".bili-opus-view") {
biliOpusPage(page)
}
//专栏页面
val articlePage = page.existsToExecute(".article-container") {
articlePage(page)
}
(biliDynPage + biliOpusPage + articlePage).firstOrNull() ?: screenshot("body", page)
}
}
}
/**
* 删除动态列表中的无用处部分
*/
private fun removeDynamicUselessParts(page: Page) {
scrollToBottom(page)
//通用的头
page.existsToExecute(".bili-header") {
page.evaluate("""document.querySelector(".bili-header").remove();""")
}
//消除当页面下滑时固定顶部的浮动的header
page.existsToExecute(".fixed-top-header") {
page.evaluate("""document.querySelector(".fixed-top-header").remove();""")
}
//消除推荐内容
page.existsToExecute(".bili-dyn-card-link-common") {
page.evaluate("""document.querySelector(".bili-dyn-card-link-common").remove();""")
}
//消除自己的回复输入框
page.existsToExecute(".fixed-reply-box") {
page.evaluate("""document.querySelector(".fixed-reply-box").remove();""")
}
//消除推荐关注当前UP
page.existsToExecute(".fixed-author-header") {
page.evaluate("""document.querySelector(".fixed-author-header").remove();""")
}
}
/**
* 处理专栏的article-container页面
*/
private fun articlePage(page: Page): String {
//消除底部版权信息
page.existsToExecute(".article-footer-box") {
page.evaluate("""document.querySelector(".article-footer-box").remove();""")
}
//消除分享
page.existsToExecute(".interaction-info") {
page.evaluate("""document.querySelector(".interaction-info").remove();""")
}
//消除评论(专栏一般比较长)
page.existsToExecute(".comment-wrapper") {
page.evaluate("""document.querySelector(".comment-wrapper").remove();""")
}
return screenshot(".article-detail", page)
}
/**
* 处理新的bili-opus页面
*/
private fun biliOpusPage(page: Page): String {
//获取前三个评论
page.existsToExecute(".bili-comment-container") {
page.evaluate(
"""const replyList = Array.from(document.querySelectorAll(".reply-item")).slice(0, 3);
replyList.forEach(item=> document.querySelector(".opus-module-content").appendChild(item));
""".trimIndent()
)
}
return screenshot(".bili-opus-view", page)
}
/**
* 处理老的bili-dyn动态页面
*/
private fun biliDynPage(page: Page): String {
//获取前三个评论
page.existsToExecute(".bili-dyn-item") {
page.evaluate(
"""const replyList = Array.from(document.querySelectorAll(".reply-item")).slice(0, 3);
replyList.forEach(item=> document.querySelector(".bili-dyn-item__main").appendChild(item));
""".trimIndent()
)
}
return screenshot(".bili-dyn-item__main", page)
}
/**
* 滚动到底部
*/
private fun scrollToBottom(page: Page) {
val viewportHeight = page.viewportSize().height.toDouble()
val scrollHeight = page.evaluate("document.documentElement.scrollHeight").toString().toDouble()
val scrollStep = viewportHeight / 10.0
var currentScroll = 0.0
while (currentScroll < scrollHeight) {
currentScroll += scrollStep
page.evaluate("window.scrollTo(0, $currentScroll)")
page.waitForTimeout(100.0)
}
}
/**
* 截图
*/
private fun screenshot(selector: String, page: Page): String {
val screenshot = page.querySelector(selector)
?.screenshot(ElementHandle.ScreenshotOptions().setQuality(100).setType(ScreenshotType.JPEG))
?: page.screenshot(Page.ScreenshotOptions().setQuality(100).setType(ScreenshotType.JPEG))
return screenshot.encodeToBase64String()
}
/**
* 通过url获取bv号
*/
fun extractBvFromBiliUrl(biliUrl: String): String? {
val url = URI.create(biliUrl)
val pathSegments = url.path.split("/")
val bvIndex = pathSegments.indexOf("video") + 1
if (bvIndex > 0 && bvIndex < pathSegments.size) {
return pathSegments[bvIndex]
}
return null
}
/**
* ai总结
*/
suspend fun videoSummarize(biliVideoAiSummary: BiliVideoAiSummary): String? {
if (!biliVideoAiSummary.support()) return null
val htmlString = readPluginResource("ai/aiSummary.html") { inputStream ->
inputStream.bufferedReader().use { it.readText() }
}
val htmlBody = Jsoup.parse(htmlString)
htmlBody.select("#summary").html(biliVideoAiSummary.modelResult.summary)
val lineList = mutableListOf<String>()
for (outline in biliVideoAiSummary.modelResult.outline) {
val titleLine = """<div class="section-title" id="title">${outline.title}</div>"""
val partList = mutableListOf<String>()
for (part in outline.part) {
val time = formatTimestamp(part.timestamp)
val contentLine = """<span class="content">${part.content}</span>"""
val timeLine = """<span class="timestamp"><span class="timestamp-inner">$time</span></span>"""
val partLine = """<div class="bullet">$timeLine$contentLine</div>"""
partList.add(partLine)
}
val line = """<div class="section">$titleLine${partList.joinToString("")}</div>"""
lineList.add(line)
}
htmlBody.select("#outline").html(lineList.joinToString(""))
return browserContext {
this.newPage().use { page ->
page.setContent(htmlBody.html())
page.waitForLoadState(LoadState.NETWORKIDLE)
page.querySelector(".ai-summary").screenshot().encodeToBase64String()
}
}
}
/**
* b站直播卡片
*/
suspend fun liveCard(liveInfo: BiliLiveInfo, userInfo: BiliUpInfoVo): String {
val liveLogoImg = withContext(Dispatchers.IO) {
readPluginResource("live/live-logo.png").encodeToBase64String()
}
val htmlString = readPluginResource("live/live.html") { inputStream ->
inputStream.bufferedReader().use { it.readText() }
}
val htmlBody = Jsoup.parse(htmlString)
val cover = "data:image/png;base64,${ImageUrl(liveInfo.cover.trim()).toBase64()}"
htmlBody.select("#background").attr("src", cover)
//标题
htmlBody.select(".title").html(liveInfo.title)
//头像
htmlBody.select(".face").backgroundUrl(liveInfo.face)
//头像添加直播
htmlBody.select(".live-logo").backgroundUrl(liveLogoImg)
//直播人
htmlBody.select(".live-user").html("UP猪: ${userInfo.name}")
//房间号
htmlBody.select(".room-id").html("房间号: ${liveInfo.roomId}")
//底栏
htmlBody.select(".bottom-bar-title").html("${systemConfigProperty("nickname")}直播推送")
return htmlToImageBase64(htmlBody.html(), "#background")
}
private suspend fun Elements.backgroundUrl(url: String) {
var style = this.attr("style")
if (style.isNotBlank() && !style.endsWith(";")) {
style += ";"
}
style += """background-image: url("data:image/png;base64,${ImageUrl(url.trim()).toBase64()}");"""
this.attr("style", style)
}
private fun formatTimestamp(time: Long): String {
val minutes = time / 60
val seconds = time % 60
return "%02d:%02d".format(minutes, seconds)
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/BLiveUtils.kt | 1482241966 |
package com.blr19c.falowp.bot.bili.plugins.bili
import com.blr19c.falowp.bot.bili.plugins.bili.BLiveUtils.extractBvFromBiliUrl
import com.blr19c.falowp.bot.bili.plugins.bili.BLiveUtils.videoSummarize
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.api.*
import com.blr19c.falowp.bot.bili.plugins.bili.database.BiliDynamic
import com.blr19c.falowp.bot.bili.plugins.bili.database.BiliSubscription
import com.blr19c.falowp.bot.bili.plugins.bili.database.BiliUpInfo
import com.blr19c.falowp.bot.bili.plugins.bili.vo.BiliSubscriptionVo
import com.blr19c.falowp.bot.system.Log
import com.blr19c.falowp.bot.system.api.*
import com.blr19c.falowp.bot.system.expand.encodeToBase64String
import com.blr19c.falowp.bot.system.plugin.MessagePluginRegisterMatch
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.message
import com.blr19c.falowp.bot.system.plugin.Plugin.Task.periodicScheduling
import com.blr19c.falowp.bot.system.web.urlToRedirectUrl
import com.blr19c.falowp.bot.system.web.webclient
import com.google.zxing.BarcodeFormat
import com.google.zxing.client.j2se.MatrixToImageWriter
import com.google.zxing.qrcode.QRCodeWriter
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import java.io.ByteArrayOutputStream
import javax.imageio.ImageIO
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
@Plugin(
name = "b站订阅",
desc = """
<p>B站直播,UP动态等提醒(0-6点不会推送)</p>
<p>指令:</p>
<p>登录 [bB]站登录</p>
<p>添加订阅 [bB]站订阅 uid</p>
<p>删除订阅 删除[bB]站订阅 uid</p>
<p>查看订阅 查看[bB]站订阅</p>
<p>示例: B站订阅 123 b站订阅123</p>
<p>示例: 删除B站订阅 123 删除b站订阅123</p>
<p>示例: 查看b站订阅</p>
<p>被动1: 当接收到视频分享后会自动查询视频的AI总结信息</p>
<p>被动2: 当UP开播后会推送开播信息</p>
<p>被动3: 当UP发送动态后会推送动态信息</p>
"""
)
class Subscription : Log {
private val client by lazy { BiliClient.load() }
private suspend fun BotApi.send(
subscriptionList: List<BiliSubscriptionVo>,
sendMessageChain: SendMessageChain
) {
for (biliSubscriptionVo in subscriptionList) {
if (biliSubscriptionVo.sourceType == SourceTypeEnum.PRIVATE.name) {
this.sendPrivate(sendMessageChain, sourceId = biliSubscriptionVo.sourceId)
}
if (biliSubscriptionVo.sourceType == SourceTypeEnum.GROUP.name) {
this.sendGroup(sendMessageChain, sourceId = biliSubscriptionVo.sourceId)
}
}
}
/**
* 定时查询动态/直播
*/
private val dynamicTask = periodicScheduling(30.seconds) {
for (biliUpInfoVo in BiliUpInfo.queryAll()) {
//订阅列表
val subscriptionList = BiliSubscription.queryByMid(biliUpInfoVo.mid)
if (subscriptionList.isEmpty()) continue
//动态列表
val dynamicList = client.spaceDynamicInfo(biliUpInfoVo.mid.toLong()).items
//将已经发送过的去除
val alreadyPushDynamicList = BiliDynamic.queryByMid(biliUpInfoVo.mid)
val prePushDynamicList = dynamicList.filter { !alreadyPushDynamicList.contains(it.id) }
for (prePushDynamic in prePushDynamicList) {
//直播
if (prePushDynamic.type.startsWith("DYNAMIC_TYPE_LIVE") && !biliUpInfoVo.liveStatus) {
val liveInfo = client.getLiveInfo(biliUpInfoVo.roomId.toLong())
val liveCard = BLiveUtils.liveCard(liveInfo, biliUpInfoVo)
val message = SendMessage.builder()
.text("${biliUpInfoVo.name}猪开播啦!")
.image(liveCard)
.build()
send(subscriptionList, message)
transaction {
BiliUpInfo.updateLiveStatus(biliUpInfoVo.mid, true)
BiliDynamic.insert(biliUpInfoVo.mid, prePushDynamic.id)
}
continue
}
//动态
val dynamicScreenshot = BLiveUtils.dynamicScreenshot(prePushDynamic.id) ?: continue
val message = SendMessage.builder()
.text("${biliUpInfoVo.name}猪有新动态!")
.image(dynamicScreenshot)
.build()
send(subscriptionList, message)
BiliDynamic.insert(biliUpInfoVo.mid, prePushDynamic.id)
}
}
}
/**
* 定时查询已开播的up的开播状态
*/
private val liveTask = periodicScheduling(1.minutes) {
for (biliUpInfoVo in BiliUpInfo.queryByLiveStatus(true)) {
if (!client.getLiveInfo(biliUpInfoVo.roomId.toLong()).liveStatus) {
BiliUpInfo.updateLiveStatus(biliUpInfoVo.mid, false)
val message = SendMessage.builder("${biliUpInfoVo.name}猪直播结束了,下次再看吧~").build()
send(BiliSubscription.queryByMid(biliUpInfoVo.mid), message)
}
}
}
/**
* 更新up信息
*/
private val updateUserInfoTask = periodicScheduling(1.days) {
for (biliUpInfo in BiliUpInfo.queryAll()) {
val userInfo = client.getUserInfo(biliUpInfo.mid.toLong())
if (biliUpInfo.name != userInfo.name) {
BiliUpInfo.update({ BiliUpInfo.mid eq biliUpInfo.mid }) {
it[name] = userInfo.name
}
}
}
}
/**
* 订阅
*/
private val subscription = message(Regex("[bB]站订阅\\s?(\\d+)"), auth = ApiAuth.MANAGER) { (subscriptionMid) ->
try {
if (BiliSubscription.queryByMid(subscriptionMid).any { it.sourceId == this.receiveMessage.source.id }) {
return@message this.sendReply("此up已被订阅")
}
val userInfo = client.getUserInfo(subscriptionMid.toLong())
val dynamicList = client.spaceDynamicInfo(subscriptionMid.toLong())
.items
.filter { !it.type.startsWith("DYNAMIC_TYPE_LIVE") }
.map { it.id }
val roomId = userInfo.liveRoom?.roomId?.toString() ?: ""
val midString = userInfo.mid.toString()
transaction {
dynamicList.forEach { BiliDynamic.insert(midString, it) }
BiliSubscription.insert(
midString,
[email protected],
[email protected]
)
if (BiliUpInfo.queryByMid(midString) == null) {
BiliUpInfo.insert(midString, roomId, userInfo.name)
}
}
this.sendReply("订阅:$subscriptionMid(${userInfo.name})完成")
} catch (e: Exception) {
this.sendReply("订阅失败:${e.message}")
}
}
/**
* 删除订阅
*/
private val delSubscription = message(Regex("删除[bB]站订阅\\s?(\\d+)"), auth = ApiAuth.MANAGER) { (deleteMid) ->
val subscriptionList = BiliSubscription.queryByMid(deleteMid)
val subscription = subscriptionList.firstOrNull { it.sourceId == this.receiveMessage.source.id }
if (subscription == null) {
return@message this.sendReply("此订阅不存在")
}
val upInfo = BiliUpInfo.queryByMid(subscription.mid)
transaction {
BiliSubscription.deleteWhere { id eq subscription.id }
BiliUpInfo.queryByMid(subscription.mid)
if (subscriptionList.size == 1) {
BiliUpInfo.deleteWhere { mid eq subscription.mid }
BiliDynamic.deleteWhere { mid eq subscription.mid }
}
}
this.sendReply("已删除(${upInfo?.name})的订阅")
}
/**
* 登录
*/
private val login = message(Regex("[bB]站登录"), auth = ApiAuth.ADMINISTRATOR) {
try {
client.login { url ->
val loginQrcode = with(QRCodeWriter()) {
val matrix = encode(url, BarcodeFormat.QR_CODE, 250, 250)
val image = MatrixToImageWriter.toBufferedImage(matrix)
val byteArrayOutputStream = ByteArrayOutputStream()
ImageIO.write(image, "PNG", byteArrayOutputStream)
byteArrayOutputStream.toByteArray().encodeToBase64String()
}
val message = SendMessage.builder().image(loginQrcode).build()
[email protected](message)
}
[email protected]("登录成功")
} catch (e: Exception) {
[email protected](e.message ?: "登录失败")
}
}
/**
* 视频ai描述
*/
private val videoAi = message(MessagePluginRegisterMatch(customBlock = { receiveMessage ->
if (receiveMessage.content.share.isEmpty()) {
return@MessagePluginRegisterMatch false
}
receiveMessage.content.share.any { it.appName == "哔哩哔哩" }
})) {
val webclient = webclient()
val sourceUrlList = this.receiveMessage.content.share
.filter { it.appName == "哔哩哔哩" }
.map { it.sourceUrl }
.toList()
val replyMessages = sourceUrlList
.mapNotNull { webclient.urlToRedirectUrl(it) }
.mapNotNull { extractBvFromBiliUrl(it) }
.mapNotNull { videoSummarize(client.getVideoAiSummary(it)) }
.map { SendMessage.builder().image(it).build() }
.toTypedArray()
if (replyMessages.isEmpty()) {
this.sendReply("看不懂啊")
}
this.sendReply(*replyMessages)
}
/**
* 查看b站订阅
*/
private val viewSubscription = message(Regex("查看[bB]站订阅")) {
val subscriptionList = BiliSubscription.queryBySourceId(this.receiveMessage.source.id)
.map { BiliUpInfo.queryByMid(it.mid) }
.map { "${it?.name}(${it?.mid})" }
.toList()
if (subscriptionList.isEmpty()) {
return@message this.sendReply("当前没有任何订阅")
}
this.sendReply(subscriptionList.joinToString("\n"))
}
init {
subscription.register()
delSubscription.register()
login.register()
dynamicTask.register()
liveTask.register()
videoAi.register()
viewSubscription.register()
updateUserInfoTask.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/Subscription.kt | 3782986474 |
package com.blr19c.falowp.bot.bili.plugins.bili.api
import com.blr19c.falowp.bot.bili.plugins.bili.database.BiliCookie
import com.blr19c.falowp.bot.system.Log
import com.blr19c.falowp.bot.system.json.Json
import io.ktor.client.plugins.cookies.*
import io.ktor.http.*
import io.ktor.util.*
import io.ktor.util.date.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.jetbrains.exposed.sql.deleteAll
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.min
object DatabaseCookiesStorage : CookiesStorage, Log {
private val container by lazy {
transaction {
BiliCookie.selectAll()
.map { Json.readObj(it[BiliCookie.cookie], Cookie::class) }
.toMutableList()
}
}
private val oldestCookie = AtomicLong(0L)
private val mutex = Mutex()
override suspend fun addCookie(requestUrl: Url, cookie: Cookie): Unit = mutex.withLock {
if (cookie.name.isBlank()) return@withLock
container.removeAll { it.name == cookie.name && it.matches(requestUrl) }
container.add(cookie.fillDefaults(requestUrl))
cookie.expires?.timestamp?.let { expires ->
if (oldestCookie.get() > expires) {
oldestCookie.set(expires)
}
}
transaction {
BiliCookie.deleteAll()
container.map { Json.toJsonString(it) }
.forEach { cookieJson -> BiliCookie.insert { it[BiliCookie.cookie] = cookieJson } }
}
}
override suspend fun get(requestUrl: Url): List<Cookie> = mutex.withLock {
val now = getTimeMillis()
if (now >= oldestCookie.get()) cleanup(now)
return@withLock container.filter { it.matches(requestUrl) }
}
suspend fun getAll(): List<Cookie> = mutex.withLock { container }
override fun close() {
}
private fun cleanup(timestamp: Long) {
container.removeAll { cookie ->
val expires = cookie.expires?.timestamp ?: return@removeAll false
expires < timestamp
}
val newOldest = container.fold(Long.MAX_VALUE) { acc, cookie ->
cookie.expires?.timestamp?.let { min(acc, it) } ?: acc
}
oldestCookie.set(newOldest)
}
private fun Cookie.matches(requestUrl: Url): Boolean {
val domain = domain?.toLowerCasePreservingASCIIRules()?.trimStart('.')
?: error("Domain field should have the default value")
val path = with(path) {
val current = path ?: error("Path field should have the default value")
if (current.endsWith('/')) current else "$path/"
}
val host = requestUrl.host.toLowerCasePreservingASCIIRules()
val requestPath = let {
val pathInRequest = requestUrl.encodedPath
if (pathInRequest.endsWith('/')) pathInRequest else "$pathInRequest/"
}
if (host != domain && (hostIsIp(host) || !host.endsWith(".$domain"))) {
return false
}
if (path != "/" &&
requestPath != path &&
!requestPath.startsWith(path)
) {
return false
}
return !(secure && !requestUrl.protocol.isSecure())
}
private fun Cookie.fillDefaults(requestUrl: Url): Cookie {
var result = this
if (result.path?.startsWith("/") != true) {
result = result.copy(path = requestUrl.encodedPath)
}
if (result.domain.isNullOrBlank()) {
result = result.copy(domain = requestUrl.host)
}
return result
}
}
| falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/DatabaseCookiesStorage.kt | 2829230411 |
package com.blr19c.falowp.bot.bili.plugins.bili.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.api.JSON_IGNORE
import com.blr19c.falowp.bot.bili.plugins.bili.api.api.SPACE
import com.blr19c.falowp.bot.bili.plugins.bili.api.api.WBI
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.WbiImages
import com.blr19c.falowp.bot.system.Log
import com.blr19c.falowp.bot.system.cache.CacheReference
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.network.sockets.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.compression.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.cookies.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.errors.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.isActive
import kotlinx.coroutines.supervisorScope
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import kotlin.time.Duration.Companion.hours
open class BiliClient(private val timeout: Long = 15_000L) : Closeable, Log {
companion object {
val Json = Json {
prettyPrint = true
ignoreUnknownKeys = System.getProperty(JSON_IGNORE, "true").toBoolean()
isLenient = true
allowStructuredMapKeys = true
}
val DefaultIgnore: suspend (Throwable) -> Boolean = { it is IOException }
internal fun getMixinKey(ae: String): String {
val oe = arrayOf(
46,
47,
18,
2,
53,
8,
23,
32,
15,
50,
10,
31,
58,
3,
45,
35,
27,
43,
5,
49,
33,
9,
42,
19,
29,
28,
14,
39,
12,
38,
41,
13,
37,
48,
7,
16,
24,
55,
40,
61,
26,
17,
0,
1,
60,
51,
30,
4,
22,
25,
54,
21,
56,
59,
6,
63,
57,
62,
11,
36,
20,
34,
44,
52
)
return buildString {
for (i in oe) {
append(ae[i])
if (length >= 32) break
}
}
}
fun load(): BiliClient {
return object : BiliClient() {
override val ignore: suspend (Throwable) -> Boolean = { cause ->
when (cause) {
is ConnectTimeoutException,
is SocketTimeoutException -> {
log().warn("Ignore ${cause.message}")
true
}
is java.net.NoRouteToHostException,
is java.net.UnknownHostException -> false
is java.io.IOException -> {
log().warn("Ignore ", cause)
true
}
else -> false
}
}
override val mutex: BiliApiMutex = BiliApiMutex(interval = 10 * 1000)
}
}
}
override fun close() = clients.forEach { it.close() }
protected open val ignore: suspend (exception: Throwable) -> Boolean = DefaultIgnore
private val storage = DatabaseCookiesStorage
val AcceptAllCookiesStorage.container: MutableList<Cookie> by reflect()
val salt by CacheReference(1.hours) { salt() }
protected open fun client() = HttpClient(CIO) {
defaultRequest {
header(HttpHeaders.Origin, SPACE)
header(HttpHeaders.Referrer, SPACE)
}
expectSuccess = true
install(ContentNegotiation) {
json(json = Json)
}
install(HttpTimeout) {
socketTimeoutMillis = timeout
connectTimeoutMillis = timeout
requestTimeoutMillis = null
}
install(HttpCookies) {
storage = [email protected]
}
install(UserAgent) {
agent =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
}
ContentEncoding()
}
protected open val clients = MutableList(3) { client() }
protected open var index = 0
protected open val mutex = BiliApiMutex(10 * 1000L)
suspend fun <T> useHttpClient(block: suspend (HttpClient, BiliApiMutex) -> T): T = supervisorScope {
var cause: Throwable? = null
while (isActive) {
try {
return@supervisorScope block(clients[index], mutex)
} catch (throwable: Throwable) {
cause = throwable
if (isActive && ignore(throwable)) {
index = (index + 1) % clients.size
} else {
throw throwable
}
}
}
throw CancellationException(null, cause)
}
private suspend fun salt(): String {
val body = useHttpClient { http, _ ->
http.get(WBI).body<JsonObject>()
}
val data = body.getValue("data") as JsonObject
val images = Json.decodeFromJsonElement<WbiImages>(data.getValue("wbi_img"))
val a = images.imgUrl.substringAfter("wbi/").substringBefore(".")
val b = images.subUrl.substringAfter("wbi/").substringBefore(".")
return getMixinKey(a + b)
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/BiliClient.kt | 4277872607 |
package com.blr19c.falowp.bot.bili.plugins.bili.api
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
import kotlin.properties.ReadOnlyProperty
internal fun timestamp(sec: Long) = OffsetDateTime.ofInstant(Instant.ofEpochSecond(sec), ZoneOffset.systemDefault())
/**
* 2017-07-01 00:00:00
*/
private const val DYNAMIC_START = 1498838400L
internal fun dynamictime(id: Long): Long = (id shr 32) + DYNAMIC_START
internal inline fun <reified T : Any, reified R> reflect() = ReadOnlyProperty<T, R> { thisRef, property ->
thisRef::class.java.getDeclaredField(property.name).apply { isAccessible = true }.get(thisRef) as R
}
| falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/Load.kt | 3953679369 |
package com.blr19c.falowp.bot.bili.plugins.bili.api
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class BiliApiMutex(private val interval: Long) : Mutex by Mutex() {
private val map = HashMap<String, Long>()
suspend fun wait(type: String): Unit = withLock {
val last = map[type] ?: 0
while (System.currentTimeMillis() - last <= interval) {
delay(1000L)
}
map[type] = System.currentTimeMillis()
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/BiliApiMutex.kt | 234635582 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.*
import io.ktor.client.request.*
/**
* 搜索用户
* @param keyword 关键词
* @param order 排序方式 粉丝数:fans; 用户等级:level
* @param type 过滤类型 全部用户:0; up主:1; 普通用户:2; 认证用户:3
*/
suspend fun BiliClient.searchUser(
keyword: String,
order: String? = null,
asc: Boolean = false,
type: Int = 0,
page: Int = 1,
url: String = SEARCH_TYPE
): SearchResult<SearchUser> = json(url) {
parameter("keyword", keyword)
parameter("search_type", SearchType.USER.value)
parameter("order", order)
parameter("order_sort", if (asc) 1 else 0)
parameter("user_type", type)
parameter("page", page)
}
/**
* 搜索番剧
* @param keyword 关键词
*/
suspend fun BiliClient.searchBangumi(
keyword: String,
page: Int = 1,
url: String = SEARCH_TYPE
): SearchResult<SearchSeason> = json(url) {
parameter("keyword", keyword)
parameter("search_type", SearchType.BANGUMI.value)
parameter("page", page)
}
/**
* 搜索影视
* @param keyword 关键词
*/
suspend fun BiliClient.searchFT(
keyword: String,
page: Int = 1,
url: String = SEARCH_TYPE
): SearchResult<SearchSeason> = json(url) {
parameter("keyword", keyword)
parameter("search_type", SearchType.FILM_AND_TELEVISION.value)
parameter("page", page)
}
/**
* 搜索直播间
* @param keyword 关键词
* @param order 排序方式 人气直播:online; 最新开播:live_time
*/
suspend fun BiliClient.searchLiveRoom(
keyword: String,
order: String? = null,
page: Int = 1,
url: String = SEARCH_TYPE
): SearchResult<SearchLiveRoom> = json(url) {
parameter("keyword", keyword)
parameter("search_type", SearchType.LIVE_ROOM.value)
parameter("order", order)
parameter("page", page)
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Search.kt | 1729860237 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.*
import io.ktor.client.request.*
import java.time.OffsetDateTime
suspend fun BiliClient.getRoomInfo(
roomId: Long,
url: String = ROOM_INIT
): BiliRoomInfo = json(url) {
parameter("id", roomId)
}
suspend fun BiliClient.getRoomInfoOld(
uid: Long,
url: String = ROOM_INFO_OLD
): BiliRoomSimple = json(url) {
parameter("mid", uid)
}
suspend fun BiliClient.getOffLiveList(
roomId: Long,
count: Int,
timestamp: Long = System.currentTimeMillis() / 1_000,
url: String = ROOM_OFF_LIVE
): BiliLiveOff = json(url) {
parameter("room_id", roomId)
parameter("count", count)
parameter("rnd", timestamp)
}
suspend fun BiliClient.getRoundPlayVideo(
roomId: Long,
timestamp: Long = System.currentTimeMillis() / 1_000,
type: String = "flv",
url: String = ROOM_ROUND_PLAY
): BiliRoundPlayVideo = json(url) {
parameter("room_id", roomId)
parameter("a", timestamp)
parameter("type", type)
}
suspend fun BiliClient.getMultiple(
vararg uids: Long,
url: String = ROOM_MULTIPLE
): Map<Long, UserMultiple> = json(url) {
parameter("attributes[]", "card")
for (uid in uids) parameter("uids[]", uid)
}
suspend fun BiliClient.getRegisterTime(
uid: Long,
url: String = ROOM_MULTIPLE
): OffsetDateTime {
return getMultiple(uid, url = url).values.single().card.datetime
}
suspend fun BiliClient.getLiveInfo(
roomId: Long,
url: String = ROOM_INFO
): BiliLiveInfo = json(url) {
parameter("room_id", roomId)
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Live.kt | 3140318691 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliSeasonInfo
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliSeasonSection
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliSectionMedia
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.SeasonTimeline
import io.ktor.client.request.*
suspend fun BiliClient.getSeasonMedia(
mediaId: Long,
url: String = SEASON_MEDIA_INFO
): BiliSectionMedia = json(url) {
parameter("media_id", mediaId)
}
suspend fun BiliClient.getSeasonInfo(
seasonId: Long,
url: String = SEASON_INFO
): BiliSeasonInfo = json(url) {
parameter("season_id", seasonId)
}
suspend fun BiliClient.getEpisodeInfo(
episodeId: Long,
url: String = SEASON_INFO
): BiliSeasonInfo = json(url) {
parameter("ep_id", episodeId)
}
suspend fun BiliClient.getSeasonSection(
seasonId: Long,
url: String = SEASON_SECTION
): BiliSeasonSection = json(url) {
parameter("season_id", seasonId)
}
suspend fun BiliClient.getSeasonTimeline(
url: String = BANGUMI_TIMELINE
): List<SeasonTimeline> = json(url) {
//
}
| falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Season.kt | 1862700700 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.TempData
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import kotlinx.serialization.SerializationException
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.decodeFromJsonElement
import java.io.File
import java.security.MessageDigest
// Base
const val INDEX_PAGE = "https://www.bilibili.com"
const val SPACE = "https://space.bilibili.com"
// Login
const val QRCODE_GENERATE = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"
const val QRCODE_POLL = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll"
const val QRCODE_SSO_LIST = "https://passport.bilibili.com/x/passport-login/web/sso/list"
const val QRCODE_SSO_SET = "https://passport.bilibili.cn/x/passport-login/web/sso/set"
// Nav
const val WBI = "https://api.bilibili.com/x/web-interface/nav"
// User
const val SPACE_INFO = "https://api.bilibili.com/x/space/wbi/acc/info"
// Video
const val VIDEO_USER = "https://api.bilibili.com/x/space/wbi/arc/search"
const val VIDEO_INFO = "https://api.bilibili.com/x/web-interface/view"
const val VIDEO_AI_SUMMARY = "https://api.bilibili.com/x/web-interface/view/conclusion/get"
// Dynamic
const val DYNAMIC_HISTORY = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history"
const val DYNAMIC_INFO = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/get_dynamic_detail"
const val SPACE_DYNAMIC_INFO = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space"
// Live
const val ROOM_INIT = "https://api.live.bilibili.com/room/v1/Room/room_init"
const val ROOM_INFO_OLD = "https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld"
const val ROOM_INFO = "https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom"
const val ROOM_OFF_LIVE = "https://api.live.bilibili.com/xlive/web-room/v1/index/getOffLiveList"
const val ROOM_ROUND_PLAY = "https://api.live.bilibili.com/live/getRoundPlayVideo"
const val ROOM_MULTIPLE = "https://api.live.bilibili.com/user/v3/User/getMultiple"
// Article
const val MORE = "https://api.bilibili.com/x/article/more?aid=15155534&platform=h5"
const val ARTICLES = "https://api.bilibili.com/x/article/list/web/articles"
const val ARTICLE_LIST_INFO = "https://api.bilibili.com/x/article/listinfo"
const val ARTICLE_VIEW_INFO = "https://api.bilibili.com/x/article/viewinfo"
// Music
const val MUSIC_INFO = "https://www.bilibili.com/audio/music-service-c/web/song/info"
// Media
const val SEASON_MEDIA_INFO = "https://api.bilibili.com/pgc/review/user"
const val SEASON_INFO = "https://api.bilibili.com/pgc/view/web/season"
const val SEASON_RECOMMEND = "https://api.bilibili.com/pgc/season/web/related/recommend?season_id=38234"
const val SEASON_SECTION = "https://api.bilibili.com/pgc/web/season/section"
const val SEASON_EPISODE = "https://api.bilibili.com/pgc/view/web/section/order?ep_id=395214"
const val BANGUMI_TIMELINE = "https://bangumi.bilibili.com/api/timeline_v2_global"
const val BANGUMI_TIMELINE_CN = "https://bangumi.bilibili.com/api/timeline_v2_cn"
// Tag
const val TAG_INFO = "https://api.bilibili.com/x/tag/info?tag_name=MEGALOBOX"
const val TAG_DETAIL = "https://api.bilibili.com/x/tag/detail?pn=0&ps=1&tag_id=18828932"
const val TAG_VIDEO = "https://api.bilibili.com/x/web-interface/tag/top?pn=1&ps=10&tid=18828932"
// Search
const val SEARCH_ALL = "https://api.bilibili.com/x/web-interface/search/all/v2"
const val SEARCH_TYPE = "https://api.bilibili.com/x/web-interface/search/type"
// Suit
const val SUIT_ITEMS = "https://api.bilibili.com/x/garb/mall/item/suit/v2"
// Emote
const val EMOTE_PANEL = "https://api.bilibili.com/x/emote/setting/panel"
const val EMOTE_PACKAGE = "https://api.bilibili.com/x/emote/package"
data class BiliApiException(
val data: TempData,
val url: Url
) : IllegalStateException() {
override val message = data.message
}
const val EXCEPTION_JSON_CACHE = "com.blr19c.falowp.bot.dynamic.bili.bilibili.api.exception"
const val JSON_IGNORE = "com.blr19c.falowp.bot.dynamic.bili.bilibili.api.ignore"
val WBI_URL = listOf(VIDEO_AI_SUMMARY)
internal suspend inline fun <reified T> BiliClient.json(
urlString: String,
crossinline block: HttpRequestBuilder.() -> Unit
): T = useHttpClient { client, mutex ->
val url = Url(urlString)
mutex.wait(url.encodedPath)
client.prepareGet(url) {
block.invoke(this)
if ("wbi" in url.encodedPath || WBI_URL.contains(urlString)) {
encodeWbi(builder = this.url.parameters)
}
}.execute { response ->
val temp = response.body<TempData>()
if (temp.code != 0) throw BiliApiException(temp, response.request.url)
val element = temp.data ?: temp.result ?: throw BiliApiException(temp, response.request.url)
try {
BiliClient.Json.decodeFromJsonElement(element)
} catch (cause: SerializationException) {
val path = System.getProperty(EXCEPTION_JSON_CACHE)
supervisorScope {
if (path != null) launch {
val folder = File(path)
folder.mkdirs()
folder.resolve("exception.${System.currentTimeMillis()}.json")
.writeText(BiliClient.Json.encodeToString(element))
}
}
throw cause
}
}
}
internal fun BiliClient.encodeWbi(builder: ParametersBuilder) {
builder.append("wts", (System.currentTimeMillis() / 1000).toString())
val digest = MessageDigest.getInstance("MD5")
val parameters = builder.build().entries()
.flatMap { e -> e.value.map { e.key to it } }
.sortedBy { it.first }.formUrlEncode()
val md5 = digest.digest((parameters + salt).encodeToByteArray())
builder.append("w_rid", md5.joinToString("") { "%02x".format(it) })
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Api.kt | 597119679 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliDynamicInfo
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliDynamicList
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliSpaceDynamicInfo
import io.ktor.client.request.*
suspend fun BiliClient.getSpaceHistory(
uid: Long,
url: String = DYNAMIC_HISTORY
): BiliDynamicList = json(url) {
parameter("visitor_uid", uid)
parameter("host_uid", uid)
parameter("offset_dynamic_id", 0)
parameter("need_top", 0)
}
suspend fun BiliClient.getDynamicInfo(
dynamicId: Long,
url: String = DYNAMIC_INFO
): BiliDynamicInfo = json(url) {
parameter("dynamic_id", dynamicId)
}
suspend fun BiliClient.spaceDynamicInfo(
uid: Long,
url: String = SPACE_DYNAMIC_INFO
): BiliSpaceDynamicInfo = json(url) {
parameter("offset", "")
parameter("host_mid", uid)
parameter("timezone_offset", -480)
parameter("platform", "web")
parameter("features", "itemOpusStyle,listOnlyfans")
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Dynamic.kt | 3474291118 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliSearchResult
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliVideoAiSummary
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliVideoInfo
import io.ktor.client.request.*
suspend fun BiliClient.getVideoInfo(
aid: Long,
url: String = VIDEO_INFO
): BiliVideoInfo = json(url) {
parameter("aid", aid)
}
suspend fun BiliClient.getVideoInfo(
bvid: String,
url: String = VIDEO_INFO
): BiliVideoInfo = json(url) {
parameter("bvid", bvid)
}
suspend fun BiliClient.getVideos(
uid: Long,
keyword: String = "",
pageSize: Int = 30,
pageNum: Int = 1,
url: String = VIDEO_USER
): BiliSearchResult = json(url) {
parameter("mid", uid)
parameter("keyword", keyword)
parameter("order", "pubdate")
parameter("jsonp", "jsonp")
parameter("ps", pageSize)
parameter("pn", pageNum)
parameter("tid", 0)
}
/**
* 获取视频的ai总结
*/
suspend fun BiliClient.getVideoAiSummary(
bvid: String,
url: String = VIDEO_AI_SUMMARY
): BiliVideoAiSummary {
val videoInfo = this.getVideoInfo(bvid)
return json(url) {
parameter("bvid", bvid)
parameter("cid", videoInfo.cid)
parameter("up_mid", videoInfo.mid)
parameter("web_location", 333.788)
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Video.kt | 1541212287 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliArticleList
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliArticleView
import io.ktor.client.request.*
suspend fun BiliClient.getArticleList(
cid: Long,
url: String = ARTICLE_LIST_INFO
): BiliArticleList = json(url) {
parameter("id", cid)
}
suspend fun BiliClient.getArticleView(
cid: Long,
url: String = ARTICLE_VIEW_INFO
): BiliArticleView = json<BiliArticleView>(url) {
parameter("id", cid)
}.copy(id = cid) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Article.kt | 515568759 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.LoginSso
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.Qrcode
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.QrcodeStatus
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.http.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withTimeout
suspend fun BiliClient.login(push: suspend (url: String) -> Unit) {
val qrcode = json<Qrcode>(QRCODE_GENERATE) {
// ...
}
push(qrcode.url)
val status = withTimeout(300_000) {
while (isActive) {
delay(3_000)
val status = json<QrcodeStatus>(QRCODE_POLL) {
parameter("qrcode_key", qrcode.key)
}
when (status.code) {
0 -> return@withTimeout status
86038 -> throw IllegalStateException(status.message)
else -> Unit
}
}
return@withTimeout null
} ?: return
val regex = "bili_jct=([^&]+)".toRegex()
val matchResult = regex.find(status.url)
val csrf = matchResult?.groupValues?.get(1) ?: return
val sso = json<LoginSso>(QRCODE_SSO_LIST) {
setBody(FormDataContent(Parameters.build { append("csrf", csrf) }))
}
for (ticketUrl in sso.sso) {
try {
json<String>(ticketUrl) {
request { method = HttpMethod.Post }
}
} catch (e: Exception) {
log().error("登录请求sso-ticket失败", e)
}
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Login.kt | 163317181 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.EmoteBusiness
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.EmotePackage
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.EmotePanel
import io.ktor.client.request.*
suspend fun BiliClient.getEmotePanel(
business: EmoteBusiness = EmoteBusiness.dynamic,
url: String = EMOTE_PANEL
): EmotePanel = json(url) {
parameter("business", business)
}
suspend fun BiliClient.getEmotePackage(
vararg id: Long,
business: EmoteBusiness = EmoteBusiness.dynamic,
url: String = EMOTE_PACKAGE
): EmotePackage = json(url) {
parameter("ids", id.joinToString(","))
parameter("business", business)
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Emote.kt | 498549382 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.BiliUserInfo
import io.ktor.client.request.*
suspend fun BiliClient.getUserInfo(
uid: Long,
url: String = SPACE_INFO
): BiliUserInfo = json(url) {
parameter("mid", uid)
parameter("token", "")
parameter("platform", "web")
parameter("web_location", 1550101)
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/User.kt | 4270614052 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.api
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.data.GarbSuit
import io.ktor.client.request.*
suspend fun BiliClient.getGarbSuit(
itemId: Long,
url: String = SUIT_ITEMS
): GarbSuit = json(url) {
parameter("item_id", itemId)
parameter("part", "suit")
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/api/Suit.kt | 1963572831 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
sealed interface Entry | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Entry.kt | 1067083362 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
enum class SearchType {
/**
* 视频
*/
VIDEO,
/**
* 番剧
*/
BANGUMI {
override val value = "media_bangumi"
},
/**
* 影视
*/
FILM_AND_TELEVISION {
override val value = "media_ft"
},
/**
* 直播间及主播
*/
LIVE,
/**
* 直播间
*/
LIVE_ROOM,
/**
* 主播
*/
LIVE_USER,
/**
* 专栏
*/
ARTICLE,
/**
* 话题
*/
TOPIC,
/**
* 用户
*/
USER {
override val value = "bili_user"
},
/**
* 相簿
*/
PHOTO
;
open val value = name.lowercase()
}
@Serializable
data class SearchResult<T : Entry>(
@SerialName("numPages")
val pages: Int,
@SerialName("numResults")
val total: Int,
@SerialName("page")
val page: Int,
@SerialName("pagesize")
val size: Int,
@SerialName("result")
val result: List<T> = emptyList()
)
@Serializable
data class SearchUser(
@SerialName("fans")
val fans: Int,
@SerialName("gender")
val gender: Int,
@SerialName("is_live")
@Serializable(NumberToBooleanSerializer::class)
val isLive: Boolean,
@SerialName("is_upuser")
@Serializable(NumberToBooleanSerializer::class)
val isUpper: Boolean,
@SerialName("level")
override val level: Int,
@SerialName("mid")
override val mid: Long,
@SerialName("room_id")
val roomId: Long,
@SerialName("type")
val type: String,
@SerialName("uname")
override val name: String,
@SerialName("upic")
override val face: String,
@SerialName("usign")
override val sign: String,
@SerialName("verify_info")
val verify: String,
@SerialName("videos")
val videos: Int
) : UserInfo {
override val live: String get() = "https://live.bilibili.com/${roomId}"
}
@Serializable
data class SearchSeason(
@SerialName("cover")
override val cover: String,
@SerialName("cv")
val cv: String,
@SerialName("desc")
val description: String,
@SerialName("ep_size")
val size: Int,
@SerialName("eps")
val episodes: List<SearchSeasonEpisode>? = null,
@SerialName("is_avid")
val isAvid: Boolean,
@SerialName("is_follow")
@Serializable(NumberToBooleanSerializer::class)
val isFollow: Boolean,
@SerialName("is_selection")
@Serializable(NumberToBooleanSerializer::class)
val isSelection: Boolean,
@SerialName("media_id")
override val mediaId: Long,
@SerialName("media_score")
override val rating: SearchSeasonRating? = null,
@SerialName("pubtime")
val published: Long,
@SerialName("season_id")
override val seasonId: Long,
@SerialName("season_type")
val seasonType: Int,
@SerialName("season_type_name")
override val type: String,
@SerialName("selection_style")
val selectionStyle: String,
@SerialName("staff")
val staff: String,
@SerialName("styles")
val styles: String,
@SerialName("title")
override val title: String,
@SerialName("url")
override val share: String,
@SerialName("new")
override val new: NewEpisode? = null
) : Media
@Serializable
data class SearchSeasonRating(
@SerialName("user_count")
override val count: Long,
@SerialName("score")
override val score: Double
) : Rating
@Serializable
data class SearchSeasonEpisode(
@SerialName("cover")
override val cover: String,
@SerialName("from")
val from: String = "",
@SerialName("id")
override val episodeId: Long,
@SerialName("is_premiere")
@Serializable(NumberToBooleanSerializer::class)
val isPremiere: Boolean = false,
@SerialName("long_title")
override val title: String,
@SerialName("url")
override val share: String = "",
@SerialName("title")
override val index: String,
) : Episode | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Search.kt | 4081549195 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import com.blr19c.falowp.bot.bili.plugins.bili.api.timestamp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import java.time.OffsetDateTime
import java.time.format.DateTimeParseException
sealed interface Live : Entry, Owner, WithDateTime {
val roomId: Long
val title: String
val cover: String
val online: Long
val liveStatus: Boolean
val link: String
val start: OffsetDateTime?
override val datetime: OffsetDateTime get() = start!!
override val uname: String
override val uid: Long
val share: String get() = link.substringBefore('?')
}
@Serializable
data class BiliRoomInfo(
@SerialName("encrypted")
val encrypted: Boolean,
@SerialName("hidden_till")
@Serializable(NumberToBooleanSerializer::class)
val hiddenTill: Boolean,
@SerialName("is_hidden")
val isHidden: Boolean,
@SerialName("is_locked")
val isLocked: Boolean,
@SerialName("is_portrait")
val isPortrait: Boolean,
@SerialName("is_sp")
@Serializable(NumberToBooleanSerializer::class)
val isSmartPhone: Boolean,
@SerialName("live_status")
val status: Int,// 0 未开播 1 开播中 2 轮播中
@SerialName("live_time")
val liveTime: Long,
@SerialName("lock_till")
@Serializable(NumberToBooleanSerializer::class)
val lockTill: Boolean,
@SerialName("pwd_verified")
val passwordVerified: Boolean,
@SerialName("room_id")
val roomId: Long,
@SerialName("short_id")
val shortId: Int,
@SerialName("uid")
val uid: Long
) : Entry {
val datetime: OffsetDateTime get() = timestamp(liveTime)
}
@Serializable
data class BiliRoomSimple(
@SerialName("cover")
override val cover: String,
@SerialName("liveStatus")
@Serializable(NumberToBooleanSerializer::class)
override val liveStatus: Boolean,
@SerialName("online")
override val online: Long = 0,
@SerialName("online_hidden")
@Serializable(NumberToBooleanSerializer::class)
val onlineHidden: Boolean = false,
@SerialName("roomStatus")
@Serializable(NumberToBooleanSerializer::class)
val roomStatus: Boolean,
@SerialName("roomid")
override val roomId: Long,
@SerialName("roundStatus")
@Serializable(NumberToBooleanSerializer::class)
val roundStatus: Boolean,
@SerialName("title")
override val title: String,
@SerialName("url")
override val link: String
) : Live {
@Transient
override var start: OffsetDateTime? = null
@Transient
override var uname: String = ""
@Transient
override var uid: Long = 0
}
@Serializable
data class BiliRoundPlayVideo(
@SerialName("aid")
val aid: Long,
@SerialName("bvid")
val bvid: String? = null,
@SerialName("bvid_url")
val link: String? = null,
@SerialName("cid")
val cid: Long,
@SerialName("pid")
val pid: Long,
@SerialName("play_time")
val time: Long,
@SerialName("play_url")
val url: String? = null,
@SerialName("sequence")
val sequence: Int,
@SerialName("title")
val title: String
)
@Serializable
data class BiliLiveOff(
@SerialName("recommend")
val recommends: List<LiveRecommend>,
@SerialName("record_list")
val records: List<LiveRecord>,
@SerialName("tips")
val tips: String
)
@Serializable
data class LiveRecommend(
@SerialName("cover")
override val cover: String,
@SerialName("face")
override val face: String,
@SerialName("flag")
val flag: Int,
@SerialName("is_auto_play")
@Serializable(NumberToBooleanSerializer::class)
val isAutoPlay: Boolean,
@SerialName("link")
override val link: String,
@SerialName("online")
override val online: Long = 0,
@SerialName("roomid")
override val roomId: Long,
@SerialName("title")
override val title: String,
@SerialName("uid")
override val uid: Long,
@SerialName("uname")
override val uname: String,
@SerialName("liveStatus")
@Serializable(NumberToBooleanSerializer::class)
override val liveStatus: Boolean = true,
) : Live {
override val start: OffsetDateTime? get() = null
}
@Serializable
data class LiveRecord(
@SerialName("bvid")
val bvid: String,
@SerialName("cover")
val cover: String,
@SerialName("is_sticky")
@Serializable(NumberToBooleanSerializer::class)
val isSticky: Boolean,
@SerialName("rid")
val roomId: String,
@SerialName("start_time")
val startTime: String,
@SerialName("title")
val title: String,
@SerialName("uid")
override val uid: Long,
@SerialName("uname")
override val uname: String
) : Owner
@Serializable
data class RoomInfo(
@SerialName("area_id")
val areaId: Int,
@SerialName("area_name")
val areaName: String,
@SerialName("background")
val background: String,
@SerialName("cover")
override val cover: String,
@SerialName("description")
val description: String,
@SerialName("hidden_status")
val hiddenStatus: Int,
@SerialName("hidden_time")
val hiddenTime: Long,
@SerialName("is_studio")
val isStudio: Boolean,
@SerialName("keyframe")
val keyframe: String,
@SerialName("live_screen_type")
val liveScreenType: Int,
@SerialName("live_start_time")
val liveStartTime: Long,
@SerialName("live_status")
@Serializable(NumberToBooleanSerializer::class)
override val liveStatus: Boolean,
@SerialName("lock_status")
val lockStatus: Int,
@SerialName("lock_time")
val lockTime: Long,
@SerialName("on_voice_join")
val onVoiceJoin: Int,
@SerialName("online")
override val online: Long,
@SerialName("parent_area_id")
val parentAreaId: Int,
@SerialName("parent_area_name")
val parentAreaName: String,
@SerialName("pk_status")
val pkStatus: Int,
@SerialName("room_id")
override val roomId: Long,
@SerialName("room_type")
val roomType: Map<String, Int>,
@SerialName("short_id")
val shortId: Int,
@SerialName("special_type")
val specialType: Int,
@SerialName("tags")
val tags: String,
@SerialName("title")
override val title: String,
@SerialName("uid")
override val uid: Long,
@SerialName("up_session")
val upSession: String
) : Live {
override val start: OffsetDateTime get() = timestamp(sec = liveStartTime)
override val datetime: OffsetDateTime get() = timestamp(sec = liveStartTime)
override val link: String get() = if (shortId == 0) "https://space.bilibili.com/${uid}" else "https://live.bilibili.com/${shortId}"
override val share: String get() = "https://live.bilibili.com/${roomId}"
override val uname: String get() = upSession
}
@Serializable
data class AnchorInfo(
@SerialName("base_info")
val baseInfo: BaseInfo
) {
@Serializable
data class BaseInfo(
@SerialName("face")
val face: String,
@SerialName("gender")
val gender: String,
@SerialName("uname")
val uname: String
)
}
@Serializable
data class BiliLiveInfo(
@SerialName("room_info")
val roomInfo: RoomInfo,
@SerialName("anchor_info")
val anchorInfo: AnchorInfo
) : Live by roomInfo {
override val face get() = anchorInfo.baseInfo.face
override val uname get() = anchorInfo.baseInfo.uname
}
@Serializable
data class SearchLiveRoom(
@SerialName("area")
val area: Int,
@SerialName("attentions")
val attentions: Int,
@SerialName("cate_name")
val cateName: String,
@SerialName("cover")
override val cover: String,
@SerialName("hit_columns")
val hitColumns: List<String>,
@SerialName("is_live_room_inline")
@Serializable(NumberToBooleanSerializer::class)
val isLiveRoomInline: Boolean,
@SerialName("live_status")
@Serializable(NumberToBooleanSerializer::class)
override val liveStatus: Boolean,
@SerialName("live_time")
val liveTime: String,
@SerialName("online")
override val online: Long = 0,
@SerialName("rank_index")
val rankIndex: Int,
@SerialName("rank_offset")
val rankOffset: Int,
@SerialName("rank_score")
val rankScore: Int,
@SerialName("roomid")
override val roomId: Long,
@SerialName("short_id")
val shortId: Int,
@SerialName("tags")
val tags: String,
@SerialName("title")
override val title: String,
@SerialName("type")
val type: String = "",
@SerialName("uface")
override val face: String,
@SerialName("uid")
override val uid: Long,
@SerialName("uname")
override val uname: String,
@SerialName("user_cover")
val userCover: String
) : Live {
override val link: String get() = if (shortId == 0) "https://space.bilibili.com/${uid}" else "https://live.bilibili.com/${shortId}"
override val start: OffsetDateTime? by lazy {
try {
OffsetDateTime.parse(liveTime)
} catch (_: DateTimeParseException) {
null
}
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Live.kt | 2617533932 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import com.blr19c.falowp.bot.bili.plugins.bili.api.timestamp
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.OffsetDateTime
sealed interface Episode : Entry {
val cover: String
val index: String
val title: String
val episodeId: Long
val share: String
}
sealed interface Season {
val cover: String
val seasonId: Long
val title: String
val type: String
val link get() = "https://www.bilibili.com/bangumi/play/ss${seasonId}"
}
sealed interface Media : Season, Entry {
val mediaId: Long
val share: String
val new: NewEpisode?
val rating: Rating?
}
sealed interface Rating : Entry {
val count: Long
val score: Double
}
sealed interface NewEpisode {
val id: Long
val index: String
val show: String
}
@Serializable
data class BiliSectionMedia(
@SerialName("media")
val media: SeasonMedia
)
@Serializable
data class SeasonMedia(
@SerialName("cover")
override val cover: String,
@SerialName("media_id")
override val mediaId: Long,
@SerialName("new_ep")
override val new: MediaNewEpisode? = null,
@SerialName("rating")
override val rating: SeasonRating? = null,
@SerialName("season_id")
override val seasonId: Long,
@SerialName("share_url")
override val share: String,
@SerialName("title")
override val title: String,
@SerialName("type_name")
override val type: String
) : Media
@Serializable
data class MediaNewEpisode(
@SerialName("id")
override val id: Long,
@SerialName("index")
override val index: String,
@SerialName("index_show")
override val show: String
) : NewEpisode
@Serializable
data class SeasonRating(
@SerialName("count")
override val count: Long,
@SerialName("score")
override val score: Double
) : Rating
@Serializable
data class BiliSeasonSection(
@SerialName("main_section")
val mainSection: SeasonSection,
@SerialName("section")
val section: List<SeasonSection>
)
@Serializable
data class SeasonSection(
@SerialName("episodes")
val episodes: List<SeasonEpisode>,
@SerialName("id")
val id: Long,
@SerialName("title")
val title: String,
@SerialName("type")
val type: Int
) : Entry
@Serializable
data class SeasonEpisode(
@SerialName("aid")
val aid: Long,
@SerialName("bvid")
val bvid: String? = null,
@SerialName("cover")
override val cover: String,
@SerialName("from")
val from: String = "",
@SerialName("id")
override val episodeId: Long,
@SerialName("is_premiere")
@Serializable(NumberToBooleanSerializer::class)
val isPremiere: Boolean = false,
@SerialName("long_title")
override val title: String,
@SerialName("share_url")
override val share: String,
@SerialName("title")
override val index: String,
@Contextual
@SerialName("pub_time")
val published: Long? = null
) : Episode {
val datetime: OffsetDateTime? get() = if (published == null) null else timestamp(published)
}
@Serializable
data class SeasonTimeline(
@SerialName("bgmcount")
override val index: String,
@SerialName("cover")
override val cover: String,
@SerialName("danmaku_count")
val danmaku: Int,
@SerialName("ep_id")
override val episodeId: Long,
@SerialName("favorites")
val favorites: Int,
@SerialName("is_finish")
@Serializable(NumberToBooleanSerializer::class)
val isFinish: Boolean,
@SerialName("lastupdate")
val last: Long,
@SerialName("new")
val new: Boolean,
@SerialName("play_count")
val play: Int,
@SerialName("season_id")
override val seasonId: Long,
@SerialName("season_status")
val seasonStatus: Int,
@SerialName("square_cover")
val squareCover: String,
@SerialName("title")
override val title: String,
@SerialName("type")
override val type: String = "番剧",
@SerialName("viewRank")
val viewRank: Int,
@SerialName("weekday")
val weekday: Int,
) : Season, Episode, WithDateTime {
override val share: String get() = "https://www.bilibili.com/bangumi/play/ep${episodeId}"
override val datetime: OffsetDateTime get() = timestamp(last)
}
@Serializable
data class BiliSeasonInfo(
@SerialName("cover")
override val cover: String,
@SerialName("episodes")
val episodes: List<SeasonEpisode>,
@SerialName("evaluate")
val evaluate: String,
@SerialName("link")
override val link: String,
@SerialName("media_id")
override val mediaId: Long,
@SerialName("new_ep")
override val new: SeasonNewEpisode? = null,
@SerialName("rating")
override val rating: SeasonRating? = null,
@SerialName("season_id")
override val seasonId: Long,
@SerialName("share_url")
override val share: String,
@SerialName("subtitle")
val subtitle: String,
@SerialName("title")
override val title: String,
@SerialName("total")
val total: Long,
@SerialName("up_info")
val upper: UpperSimple? = null
) : Media {
override val type: String get() = episodes.first().from.uppercase()
}
@Serializable
data class UpperSimple(
@SerialName("avatar")
val avatar: String,
@SerialName("mid")
val mid: Long,
@SerialName("uname")
override val uname: String = ""
) : Owner {
override val uid: Long get() = mid
override val face: String get() = avatar
}
@Serializable
data class SeasonNewEpisode(
@SerialName("id")
override val id: Long,
@SerialName("title")
override val index: String,
@SerialName("desc")
override val show: String
) : NewEpisode | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Season.kt | 1054898321 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import com.blr19c.falowp.bot.bili.plugins.bili.api.BiliClient
import com.blr19c.falowp.bot.bili.plugins.bili.api.dynamictime
import com.blr19c.falowp.bot.bili.plugins.bili.api.timestamp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.Transient
import java.time.Duration
import java.time.OffsetDateTime
internal inline fun <reified T : Entry> DynamicCard.decode(): T {
if (decode == null) {
val entry = try {
BiliClient.Json.decodeFromString<T>(card)
} catch (cause: SerializationException) {
throw IllegalArgumentException("card: ${detail.id}", cause)
}
decode = when (entry) {
is DynamicReply -> entry.copy(detail = detail.origin ?: entry.describe(), display = display)
is DynamicText -> entry.copy(emoji = display?.emoji)
is DynamicPicture -> entry.copy(emoji = display?.emoji)
is DynamicSketch -> entry.copy(emoji = display?.emoji)
is DynamicVideo -> entry.copy(id = detail.bvid ?: "av${entry.aid}")
is DynamicLiveRoom -> entry.copy(uname = profile.user.uname)
else -> entry
}
}
return decode as T
}
sealed interface DynamicCard : Entry, WithDateTime {
val card: String
val detail: DynamicDescribe
val display: DynamicDisplay?
val profile: UserProfile
override val datetime: OffsetDateTime
var decode: Entry?
fun images(): List<String> = when (detail.type) {
in DynamicType.DYNAMIC_TYPE_DRAW.typeMap -> decode<DynamicPicture>().detail.pictures.map { it.source }
else -> emptyList()
}
fun username(): String = when (detail.type) {
in DynamicType.DYNAMIC_TYPE_PGC.typeMap -> decode<DynamicEpisode>().season.title
else -> profile.user.uname
}
fun uid() = when (detail.type) {
in DynamicType.DYNAMIC_TYPE_PGC.typeMap -> decode<DynamicEpisode>().season.seasonId
else -> profile.user.uid
}
}
sealed interface DynamicEmojiContent : Entry {
val emoji: EmojiInfo?
val content: String
}
@Serializable
data class BiliDynamicList(
@SerialName("cards")
val dynamics: List<DynamicInfo> = emptyList(),
@SerialName("has_more")
@Serializable(NumberToBooleanSerializer::class)
val more: Boolean,
@SerialName("next_offset")
val next: Long
)
@Serializable
data class BiliDynamicInfo(
@SerialName("card")
val dynamic: DynamicInfo,
)
@Serializable
data class BiliSpaceDynamicInfo(
@SerialName("items")
val items: List<SpaceDynamicInfo>,
)
enum class DynamicType(vararg pairs: Pair<Int, String>) {
DYNAMIC_TYPE_NONE(
0x0000_0000 to "动态被删除",
0x0000_0400 to "动态被删除"
),
DYNAMIC_TYPE_FORWARD(
0x0000_0001 to "转发动态"
),
DYNAMIC_TYPE_DRAW(
0x0000_0002 to "动态"
),
DYNAMIC_TYPE_WORD(
0x0000_0004 to "动态"
),
DYNAMIC_TYPE_AV(
0x0000_0008 to "投稿视频"
),
DYNAMIC_TYPE_ARTICLE(
0x0000_0040 to "专栏"
),
DYNAMIC_TYPE_MUSIC(
0x0000_0100 to "音频"
),
DYNAMIC_TYPE_PGC(
0x0000_0200 to "番剧",
0x0000_1001 to "番剧",
0x0000_1002 to "电影",
0x0000_1003 to "电视剧",
0x0000_1004 to "国创",
0x0000_1005 to "纪录片"
),
DYNAMIC_TYPE_COMMON_SQUARE(
0x0000_0800 to "活动"
),
DYNAMIC_TYPE_COMMON_VERTICAL(
0x0000_0801 to "2049"
),
DYNAMIC_TYPE_LIVE(
0x0000_1068 to "直播"
),
DYNAMIC_TYPE_COURSES_SEASON(
0x0000_10D1 to "4305"
),
DYNAMIC_TYPE_MEDIALIST(
0x0000_10CC to "收藏"
),
DYNAMIC_TYPE_APPLET(
0x0000_10CE to "4305"
),
DYNAMIC_TYPE_LIVE_RCMD(
0x0000_10D4 to "房间"
),
DYNAMIC_TYPE_UGC_SEASON(
0x0000_10D6 to "合集"
),
DYNAMIC_TYPE_SUBSCRIPTION_NEW(
0x0000_10D7 to "4311"
)
;
val typeMap: Map<Int, String> = pairs.toMap()
companion object {
@JvmStatic
@JvmName("valueById")
operator fun invoke(id: Int): DynamicType {
for (value in entries) {
if (value.typeMap[id] != null) return value
}
throw IllegalArgumentException("$id for DynamicType")
}
}
}
@Serializable
data class DynamicDescribe(
@SerialName("bvid")
val bvid: String? = null,
@SerialName("comment")
val comment: Int = 0,
@SerialName("dynamic_id")
val id: Long = 0,
@SerialName("is_liked")
@Serializable(NumberToBooleanSerializer::class)
val isLiked: Boolean = false,
@SerialName("like")
val like: Long = 0,
@SerialName("origin")
val origin: DynamicDescribe? = null,
@SerialName("orig_dy_id")
val originDynamicId: Long? = null,
@SerialName("orig_type")
val originType: Int? = null,
@SerialName("previous")
val previous: DynamicDescribe? = null,
@SerialName("pre_dy_id")
val previousDynamicId: Long? = null,
@SerialName("repost")
val repost: Long = 0,
@SerialName("timestamp")
val timestamp: Long = 0,
@SerialName("type")
val type: Int = 0,
@SerialName("uid")
val uid: Long = 0,
@SerialName("user_profile")
val profile: UserProfile = UserProfile(),
@SerialName("view")
val view: Long = 0
) {
companion object {
val Empty = DynamicDescribe()
}
}
@Serializable
data class EmojiInfo(
@SerialName("emoji_details")
val details: List<EmojiDetail> = emptyList()
)
@Serializable
data class CardInfo(
@SerialName("add_on_card_show_type")
val type: Int,
@SerialName("vote_card")
val vote: String = ""
)
@Serializable
data class DynamicDisplay(
@SerialName("emoji_info")
val emoji: EmojiInfo = EmojiInfo(),
@SerialName("origin")
val origin: DynamicDisplay? = null,
@SerialName("add_on_card_info")
val infos: List<CardInfo> = emptyList()
)
@Serializable
data class DynamicInfo(
@SerialName("card")
override val card: String,
@SerialName("desc")
override val detail: DynamicDescribe,
@SerialName("display")
override val display: DynamicDisplay? = null
) : DynamicCard, Entry {
val link get() = "https://t.bilibili.com/${detail.id}"
val h5 get() = "https://t.bilibili.com/h5/dynamic/detail/${detail.id}"
@Transient
override var decode: Entry? = null
override val profile: UserProfile get() = detail.profile
override val datetime: OffsetDateTime get() = timestamp(detail.timestamp)
}
@Serializable
data class SpaceDynamicInfo(
@SerialName("id_str")
val id: String,
@SerialName("type")
val type: String
)
@Serializable
data class DynamicArticle(
@SerialName("act_id")
val actId: Int,
@SerialName("apply_time")
val apply: String,
@SerialName("author")
val author: ArticleAuthor,
@SerialName("banner_url")
val banner: String,
@SerialName("categories")
val categories: List<ArticleCategory>? = null,
@SerialName("category")
val category: ArticleCategory,
@SerialName("check_time")
val check: String,
@SerialName("cover_avid")
val avid: Long = 0,
@SerialName("ctime")
val created: Long,
@SerialName("id")
override val id: Long,
@SerialName("image_urls")
override val images: List<String>,
@SerialName("is_like")
val isLike: Boolean,
@SerialName("list")
val list: ArticleList?,
@SerialName("media")
val media: ArticleMedia,
@SerialName("origin_image_urls")
val originImageUrls: List<String>,
@SerialName("original")
val original: Int,
@SerialName("publish_time")
override val published: Long,
@SerialName("reprint")
val reprint: Int,
@SerialName("state")
val state: Int,
@SerialName("stats")
override val status: ArticleStatus,
@SerialName("summary")
override val summary: String,
@SerialName("template_id")
val templateId: Int,
@SerialName("title")
override val title: String,
@SerialName("words")
val words: Int
) : Article
@Serializable
data class DynamicEpisode(
@SerialName("apiSeasonInfo")
val season: SeasonInfo,
@SerialName("bullet_count")
val bullet: Long,
@SerialName("cover")
override val cover: String,
@SerialName("episode_id")
override val episodeId: Long,
@SerialName("index")
override val index: String,
@SerialName("index_title")
override val title: String,
@SerialName("new_desc")
val description: String,
@SerialName("online_finish")
val onlineFinish: Int,
@SerialName("play_count")
val play: Long,
@SerialName("reply_count")
val reply: Long,
@SerialName("url")
override val share: String
) : Episode
@Serializable
data class SeasonInfo(
@SerialName("cover")
override val cover: String,
@SerialName("is_finish")
@Serializable(NumberToBooleanSerializer::class)
val isFinish: Boolean,
@SerialName("season_id")
override val seasonId: Long,
@SerialName("title")
override val title: String,
@SerialName("total_count")
val total: Long,
@SerialName("ts")
val timestamp: Long,
@SerialName("type_name")
override val type: String
) : Season
@Serializable
data class DynamicLive(
@SerialName("background")
val background: String,
@SerialName("cover")
override val cover: String,
@SerialName("face")
override val face: String,
@SerialName("link")
override val link: String,
@SerialName("live_status")
@Serializable(NumberToBooleanSerializer::class)
override val liveStatus: Boolean,
@SerialName("lock_status")
val lockStatus: String,
@SerialName("on_flag")
val onFlag: Int,
@SerialName("online")
override val online: Long = 0,
@SerialName("roomid")
override val roomId: Long,
@SerialName("round_status")
@Serializable(NumberToBooleanSerializer::class)
val roundStatus: Boolean,
@SerialName("short_id")
val shortId: Int,
@SerialName("tags")
val tags: String,
@SerialName("title")
override val title: String,
@SerialName("uid")
override val uid: Long,
@SerialName("uname")
override val uname: String,
@SerialName("user_cover")
val avatar: String,
@SerialName("verify")
val verify: String,
) : Live {
override val start: OffsetDateTime? get() = null
}
@Serializable
data class DynamicLiveRoom(
@SerialName("live_play_info")
val play: LiveRoomInfo,
@SerialName("live_record_info")
val record: LiveRecord?,
@SerialName("style")
val style: Int,
@SerialName("type")
val type: Int,
@SerialName("uname")
override val uname: String = ""
) : Live by play
@Serializable
data class LiveRoomInfo(
@SerialName("area_id")
val areaId: Int,
@SerialName("area_name")
val areaName: String,
@SerialName("cover")
override val cover: String,
@SerialName("link")
override val link: String,
@SerialName("live_id")
val liveId: Long,
@SerialName("live_screen_type")
val liveScreenType: Int,
@SerialName("live_start_time")
val liveStartTime: Long,
@SerialName("live_status")
@Serializable(NumberToBooleanSerializer::class)
override val liveStatus: Boolean,
@SerialName("online")
override val online: Long,
@SerialName("parent_area_id")
val parentAreaId: Int,
@SerialName("parent_area_name")
val parentAreaName: String,
@SerialName("play_type")
val playType: Int,
@SerialName("room_id")
override val roomId: Long,
@SerialName("room_type")
val roomType: Int,
@SerialName("title")
override val title: String,
@SerialName("uid")
override val uid: Long,
@SerialName("watched_show")
val watchedShow: String
) : Live {
override val start: OffsetDateTime get() = timestamp(liveStartTime)
override val uname: String get() = title
}
@Serializable
data class DynamicMusic(
@SerialName("author")
val author: String,
@SerialName("cover")
val cover: String,
@SerialName("ctime")
val created: Long,
@SerialName("id")
val id: Long,
@SerialName("intro")
val intro: String,
@SerialName("playCnt")
val play: Long,
@SerialName("replyCnt")
val reply: Long,
@SerialName("schema")
val schema: String,
@SerialName("title")
val title: String,
@SerialName("typeInfo")
val type: String,
@SerialName("upId")
val upId: Long,
@SerialName("upper")
val upper: String,
@SerialName("upperAvatar")
val avatar: String
) : Entry, Owner, WithDateTime {
val link get() = "https://www.bilibili.com/audio/au$id"
override val uid: Long get() = upId
override val uname: String get() = author
override val face: String get() = author
override val datetime: OffsetDateTime get() = timestamp(created / 1_000)
}
@Serializable
data class DynamicPicture(
@SerialName("item")
val detail: DynamicPictureDetail,
@SerialName("user")
val user: UserSimple,
@Transient
override val emoji: EmojiInfo? = null
) : DynamicEmojiContent {
override val content: String get() = detail.description
}
@Serializable
data class DynamicPictureDetail(
@SerialName("category")
val category: String,
@SerialName("description")
val description: String,
@SerialName("id")
val id: Long,
@SerialName("is_fav")
@Serializable(NumberToBooleanSerializer::class)
val isFavourite: Boolean,
@SerialName("pictures")
val pictures: List<DynamicPictureInfo>,
@SerialName("reply")
val reply: Long,
@SerialName("title")
val title: String,
@SerialName("upload_time")
val uploaded: Long
)
@Serializable
data class DynamicPictureInfo(
@SerialName("img_height")
val height: Int,
@SerialName("img_size")
val size: Double? = null,
@SerialName("img_src")
val source: String,
@SerialName("img_width")
val width: Int
)
@Serializable
data class DynamicReply(
@SerialName("item")
val item: DynamicReplyDetail,
@SerialName("origin")
override val card: String = "null",
@SerialName("origin_user")
val originUser: UserProfile = UserProfile(),
@SerialName("user")
val user: UserSimple,
@Transient
override val detail: DynamicDescribe = DynamicDescribe.Empty,
@Transient
override val display: DynamicDisplay? = null
) : DynamicCard, DynamicEmojiContent {
@Transient
override var decode: Entry? = null
override val emoji: EmojiInfo? get() = display?.emoji
override val content get() = item.content
override val profile: UserProfile get() = originUser
override val datetime: OffsetDateTime get() = timestamp(detail.timestamp)
internal fun describe() = DynamicDescribe.Empty.copy(
id = item.id,
type = item.type,
uid = item.uid,
timestamp = if (item.timestamp != 0L) item.timestamp else dynamictime(id = item.id),
profile = originUser
)
}
@Serializable
data class DynamicReplyDetail(
@SerialName("at_uids")
val atUsers: List<Long> = emptyList(),
@SerialName("content")
val content: String,
@SerialName("orig_dy_id")
val id: Long,
@SerialName("orig_type")
val type: Int,
@SerialName("reply")
val reply: Long,
@SerialName("timestamp")
val timestamp: Long = 0,
@SerialName("uid")
val uid: Long
)
@Serializable
data class DynamicSketch(
@SerialName("rid")
val rid: Long,
@SerialName("sketch")
val detail: DynamicSketchDetail,
@SerialName("user")
val user: UserSimple,
@SerialName("vest")
val vest: DynamicSketchVest,
@Transient
override val emoji: EmojiInfo? = null
) : Entry, DynamicEmojiContent {
val title get() = detail.title
val link get() = detail.target
val cover get() = detail.cover
override val content get() = vest.content
}
@Serializable
data class DynamicSketchDetail(
@SerialName("cover_url")
val cover: String,
@SerialName("desc_text")
val description: String,
@SerialName("sketch_id")
val sketchId: Long,
@SerialName("target_url")
val target: String,
@SerialName("title")
val title: String
)
@Serializable
data class DynamicSketchVest(
@SerialName("content")
val content: String,
@SerialName("uid")
val uid: Long
)
@Serializable
data class DynamicText(
@SerialName("item")
val detail: DynamicTextDetail,
@SerialName("user")
val user: UserSimple,
@Transient
override val emoji: EmojiInfo? = null
) : DynamicEmojiContent {
override val content: String get() = detail.content
}
@Serializable
data class DynamicTextDetail(
@SerialName("at_uids")
val atUsers: List<Long> = emptyList(),
@SerialName("content")
val content: String,
@SerialName("reply")
val reply: Long,
@SerialName("uid")
val uid: Long
)
@Serializable
data class DynamicVideo(
@SerialName("aid")
val aid: Long,
@SerialName("bvid")
override val id: String = "",
@SerialName("cid")
val cid: Int,
@SerialName("copyright")
val copyright: Int,
@SerialName("ctime")
override val created: Long,
@SerialName("desc")
override val description: String,
@SerialName("dimension")
val dimension: VideoDimension,
@SerialName("duration")
val duration: Long,
@SerialName("dynamic")
val dynamic: String = "",
@SerialName("jump_url")
val jumpUrl: String,
@SerialName("owner")
val owner: VideoOwner,
@SerialName("pic")
override val cover: String,
@SerialName("pubdate")
val pubdate: Long,
@SerialName("stat")
override val status: VideoStatus,
@SerialName("tid")
override val tid: Int,
@SerialName("title")
override val title: String,
@SerialName("tname")
override val type: String,
@SerialName("videos")
val videos: Int,
@SerialName("season_id")
override val seasonId: Long? = null,
@SerialName("rights")
val rights: VideoRights
) : Video {
override val uid: Long get() = owner.mid
override val uname: String get() = owner.name
override val author: String get() = owner.name
override val mid: Long get() = owner.mid
override val length: String by lazy {
with(Duration.ofSeconds(duration)) { "%02d:%02d".format(toMinutes(), toSecondsPart()) }
}
override val isPay: Boolean get() = rights.pay || rights.ugcPay
override val isUnionVideo: Boolean get() = rights.isCooperation
override val isSteinsGate: Boolean get() = rights.isSteinGate
override val isLivePlayback: Boolean get() = false
}
@Serializable
data class DynamicMediaList(
@SerialName("cover")
val cover: String,
@SerialName("cover_type")
val coverType: Int,
@SerialName("fid")
val fid: Long,
@SerialName("id")
val id: Long,
@SerialName("intro")
val intro: String = "",
@SerialName("media_count")
val count: Int,
@SerialName("mid")
val mid: Long,
@SerialName("sharable")
val sharable: Boolean,
@SerialName("title")
val title: String,
@SerialName("type")
val type: Int,
@SerialName("upper")
val upper: VideoOwner
) : Entry, Owner by upper {
val link get() = "https://www.bilibili.com/medialist/detail/ml${id}"
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Dynamic.kt | 1937642750 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import com.blr19c.falowp.bot.bili.plugins.bili.api.timestamp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.Duration
import java.time.OffsetDateTime
sealed interface Video : Entry, Owner, WithDateTime {
val title: String
val author: String
val description: String
val mid: Long
val created: Long
val length: String
val id: String
val cover: String
val seasonId: Long?
val status: VideoStatus?
val tid: Int
val type: String
val isPay: Boolean
val isUnionVideo: Boolean
val isSteinsGate: Boolean
val isLivePlayback: Boolean
val link get() = "https://www.bilibili.com/video/${id}"
override val datetime: OffsetDateTime get() = timestamp(created)
}
@Serializable
data class BiliVideoInfo(
@SerialName("aid")
val aid: Long,
@SerialName("bvid")
override val id: String,
@SerialName("cid")
val cid: Long? = null,
@SerialName("copyright")
val copyright: Int,
@SerialName("ctime")
override val created: Long,
@SerialName("desc")
override val description: String,
@SerialName("dimension")
val dimension: VideoDimension,
@SerialName("duration")
val duration: Long,
@SerialName("dynamic")
val dynamic: String = "",
@SerialName("owner")
val owner: VideoOwner,
@SerialName("pages")
val pages: List<VideoPage> = emptyList(),
@SerialName("pic")
override val cover: String,
@SerialName("pubdate")
val pubdate: Long,
@SerialName("redirect_url")
val redirect: String? = null,
@SerialName("season_id")
override val seasonId: Long? = null,
@SerialName("staff")
val staff: List<VideoStaff> = emptyList(),
@SerialName("stat")
override val status: VideoStatus,
@SerialName("subtitle")
val subtitle: VideoSubtitle? = null,
@SerialName("tid")
override val tid: Int,
@SerialName("title")
override val title: String,
@SerialName("tname")
override val type: String,
@SerialName("videos")
val videos: Int,
@SerialName("rights")
val rights: VideoRights
) : Video {
override val uid: Long get() = owner.mid
override val uname: String get() = owner.name
override val author: String get() = owner.name
override val mid get() = owner.mid
override val length: String by lazy {
with(Duration.ofSeconds(duration)) { "%02d:%02d".format(toMinutes(), toSecondsPart()) }
}
override val isPay: Boolean get() = rights.pay || rights.ugcPay
override val isUnionVideo: Boolean get() = rights.isCooperation
override val isSteinsGate: Boolean get() = rights.isSteinGate
override val isLivePlayback: Boolean get() = false
}
/**
* 视频总结信息
*/
@Serializable
data class BiliVideoAiSummary(
@SerialName("model_result")
val modelResult: BiliVideoAiSummaryInfo,
) {
fun support(): Boolean {
return modelResult.outline.isNotEmpty()
}
}
@Serializable
data class BiliVideoAiSummaryInfo(
@SerialName("result_type")
val resultType: String,
@SerialName("summary")
val summary: String,
@SerialName("outline")
private val _outline: List<BiliVideoAiSummaryOutline>?
) {
val outline: List<BiliVideoAiSummaryOutline>
get() {
return _outline ?: emptyList()
}
}
@Serializable
data class BiliVideoAiSummaryOutline(
@SerialName("title")
val title: String,
@SerialName("part_outline")
val part: List<BiliVideoAiSummaryOutlinePart>
)
@Serializable
data class BiliVideoAiSummaryOutlinePart(
@SerialName("timestamp")
val timestamp: Long,
@SerialName("content")
val content: String
)
@Serializable
data class BiliSearchResult(
@SerialName("list")
val list: VideoInfoList,
@SerialName("page")
val page: VideoSearchPage
)
@Serializable
data class VideoTypeInfo(
@SerialName("count")
val count: Int,
@SerialName("name")
val name: String,
@SerialName("tid")
val tid: Long
)
@Serializable
data class VideoInfoList(
@SerialName("tlist")
val types: Map<Int, VideoTypeInfo>? = null,
@SerialName("vlist")
val videos: List<VideoSimple>
) {
init {
videos.forEach { it.types = types }
}
}
@Serializable
data class VideoSearchPage(
@SerialName("count")
val count: Int,
@SerialName("pn")
val num: Int,
@SerialName("ps")
val size: Int
)
@Serializable
data class VideoSubtitle(
@SerialName("allow_submit")
val allowSubmit: Boolean,
@SerialName("list")
val list: List<VideoSubtitleItem>
)
@Serializable
data class VideoSubtitleItem(
@SerialName("author_mid")
val mid: Long? = null,
@SerialName("author")
val author: VideoSubtitleAuthor? = null,
@SerialName("id")
val id: Long,
@SerialName("lan")
val language: String,
@SerialName("lan_doc")
val languageDocument: String,
@SerialName("is_lock")
val isLock: Boolean,
@SerialName("subtitle_url")
val subtitleUrl: String
)
@Serializable
data class VideoSubtitleAuthor(
@SerialName("mid")
val mid: Long,
@SerialName("name")
val name: String,
@SerialName("sex")
val sex: String,
@SerialName("face")
override val face: String,
@SerialName("sign")
val sign: String,
@SerialName("rank")
val rank: Int,
@SerialName("birthday")
val birthday: Int,
@SerialName("is_fake_account")
@Serializable(NumberToBooleanSerializer::class)
val isFakeAccount: Boolean,
@SerialName("is_deleted")
@Serializable(NumberToBooleanSerializer::class)
val isDeleted: Boolean
) : Owner {
override val uid: Long get() = mid
override val uname: String get() = name
}
@Serializable
data class VideoStatus(
@SerialName("coin")
val coin: Long,
@SerialName("danmaku")
val danmaku: Long,
@SerialName("dislike")
@Serializable(NumberToBooleanSerializer::class)
val dislike: Boolean,
@SerialName("favorite")
val favorite: Long,
@SerialName("his_rank")
@Serializable(NumberToBooleanSerializer::class)
val hisRank: Boolean,
@SerialName("like")
val like: Long,
@SerialName("now_rank")
val nowRank: Int,
@SerialName("reply")
val reply: Long,
@SerialName("share")
val share: Long,
@SerialName("view")
val view: Long
) : Entry
@Serializable
data class VideoStaff(
@SerialName("face")
override val face: String,
@SerialName("follower")
val follower: Int,
@SerialName("mid")
val mid: Long,
@SerialName("name")
val name: String,
@SerialName("official")
val official: UserOfficial,
@SerialName("title")
val title: String
) : Owner {
override val uid: Long get() = mid
override val uname: String get() = name
}
@Serializable
data class VideoSimple(
@SerialName("aid")
val aid: Long,
@SerialName("author")
override val author: String,
@SerialName("bvid")
override val id: String,
@SerialName("comment")
val comment: Long,
@SerialName("copyright")
val copyright: String,
@SerialName("created")
override val created: Long,
@SerialName("description")
override val description: String,
@SerialName("hide_click")
val hideClick: Boolean,
@SerialName("is_pay")
@Serializable(NumberToBooleanSerializer::class)
override val isPay: Boolean,
@SerialName("is_union_video")
@Serializable(NumberToBooleanSerializer::class)
override val isUnionVideo: Boolean,
@SerialName("is_steins_gate")
@Serializable(NumberToBooleanSerializer::class)
override val isSteinsGate: Boolean,
@SerialName("is_live_playback")
@Serializable(NumberToBooleanSerializer::class)
override val isLivePlayback: Boolean,
@SerialName("length")
override val length: String,
@SerialName("mid")
override val mid: Long,
@SerialName("pic")
override val cover: String,
@SerialName("play")
val play: Long,
@SerialName("review")
val review: Int,
@SerialName("subtitle")
val subtitle: String,
@SerialName("title")
override val title: String,
@SerialName("typeid")
override val tid: Int,
@SerialName("video_review")
val videoReview: Int,
@SerialName("season_id")
override val seasonId: Long? = null,
@SerialName("stat")
override val status: VideoStatus? = null
) : Video {
internal var types: Map<Int, VideoTypeInfo>? = null
override val type: String get() = types?.get(tid)?.name ?: throw NoSuchElementException("video type: $tid")
override val uid: Long get() = mid
override val uname: String get() = author
}
@Serializable
data class VideoPage(
@SerialName("cid")
val cid: Int,
@SerialName("dimension")
val dimension: VideoDimension,
@SerialName("duration")
val duration: Int,
@SerialName("from")
val from: String,
@SerialName("page")
val page: Int,
@SerialName("part")
val part: String,
@SerialName("vid")
val bvid: String,
@SerialName("weblink")
val weblink: String
)
@Serializable
data class VideoOwner(
@SerialName("face")
override val face: String? = null,
@SerialName("mid")
val mid: Long,
@SerialName("name")
val name: String = "",
) : Owner {
override val uid: Long get() = mid
override val uname: String get() = name
}
@Serializable
data class VideoDimension(
@SerialName("height")
val height: Int,
@SerialName("rotate")
val rotate: Int,
@SerialName("width")
val width: Int
)
@Serializable
data class VideoRights(
@SerialName("autoplay")
@Serializable(NumberToBooleanSerializer::class)
val autoplay: Boolean = false,
@SerialName("bp")
@Serializable(NumberToBooleanSerializer::class)
val bp: Boolean = false,
@SerialName("clean_mode")
@Serializable(NumberToBooleanSerializer::class)
val cleanMode: Boolean = false,
@SerialName("download")
@Serializable(NumberToBooleanSerializer::class)
val download: Boolean = false,
@SerialName("elec")
@Serializable(NumberToBooleanSerializer::class)
val charge: Boolean = false,
@SerialName("hd5")
@Serializable(NumberToBooleanSerializer::class)
val hd5: Boolean = false,
@SerialName("is_360")
@Serializable(NumberToBooleanSerializer::class)
val is360: Boolean = false,
@SerialName("is_cooperation")
@Serializable(NumberToBooleanSerializer::class)
val isCooperation: Boolean = false,
@SerialName("is_stein_gate")
@Serializable(NumberToBooleanSerializer::class)
val isSteinGate: Boolean = false,
@SerialName("movie")
@Serializable(NumberToBooleanSerializer::class)
val movie: Boolean = false,
@SerialName("no_background")
@Serializable(NumberToBooleanSerializer::class)
val noBackground: Boolean = true,
@SerialName("no_reprint")
@Serializable(NumberToBooleanSerializer::class)
val noReprint: Boolean = true,
@SerialName("no_share")
@Serializable(NumberToBooleanSerializer::class)
val noShare: Boolean = true,
@SerialName("pay")
@Serializable(NumberToBooleanSerializer::class)
val pay: Boolean = false,
@SerialName("ugc_pay")
@Serializable(NumberToBooleanSerializer::class)
val ugcPay: Boolean = false,
@SerialName("ugc_pay_preview")
@Serializable(NumberToBooleanSerializer::class)
val ugcPayPreview: Boolean = false
) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Video.kt | 4261865007 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import com.blr19c.falowp.bot.bili.plugins.bili.api.timestamp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.OffsetDateTime
sealed interface Article : Entry, WithDateTime {
val id: Long
val images: List<String>
val title: String
val published: Long
val summary: String get() = ""
val status: ArticleStatus? get() = null
val link get() = "https://www.bilibili.com/read/cv$id"
override val datetime: OffsetDateTime get() = timestamp(published)
}
@Serializable
data class BiliArticleList(
@SerialName("last")
val last: ArticleSimple,
@SerialName("list")
val list: ArticleList? = null,
@SerialName("next")
val next: ArticleSimple? = null,
@SerialName("now")
val now: Long,
@SerialName("total")
val total: Long
)
@Serializable
data class BiliArticleView(
@SerialName("attention")
val attention: Boolean,
@SerialName("author_name")
val authorName: String,
@SerialName("banner_url")
val bannerUrl: String,
@SerialName("coin")
val coin: Long,
@SerialName("favorite")
val favorite: Boolean,
@SerialName("image_urls")
val imageUrls: List<String>,
@SerialName("in_list")
val inList: Boolean,
@SerialName("is_author")
val isAuthor: Boolean,
@SerialName("like")
@Serializable(NumberToBooleanSerializer::class)
val like: Boolean,
@SerialName("mid")
val mid: Long,
@SerialName("next")
val next: Long,
@SerialName("origin_image_urls")
override val images: List<String>,
@SerialName("pre")
val pre: Long,
@SerialName("share_channels")
val shareChannels: List<ShareChannel>,
@SerialName("shareable")
val shareable: Boolean,
@SerialName("show_later_watch")
val showLaterWatch: Boolean,
@SerialName("show_small_window")
val showSmallWindow: Boolean,
@SerialName("stats")
override val status: ArticleStatus,
@SerialName("title")
override val title: String,
@SerialName("id")
override val id: Long = 0,
@SerialName("publish_time")
override val published: Long = 0,
) : Article, Owner {
override val uid: Long get() = mid
override val uname: String get() = authorName
@Serializable
data class ShareChannel(
@SerialName("name")
val name: String,
@SerialName("picture")
val picture: String,
@SerialName("share_channel")
val shareChannel: String
)
}
@Serializable
data class ArticleAuthor(
@SerialName("face")
override val face: String,
@SerialName("mid")
val mid: Long,
@SerialName("name")
val name: String,
@SerialName("nameplate")
val nameplate: UserNameplate,
@SerialName("official_verify")
val official: UserOfficial
) : Owner {
override val uid: Long get() = mid
override val uname: String get() = name
}
@Serializable
data class ArticleStatus(
@SerialName("coin")
val coin: Long = 0,
@SerialName("dislike")
@Serializable(NumberToBooleanSerializer::class)
val dislike: Boolean = false,
@SerialName("dynamic")
val dynamic: Long = 0,
@SerialName("favorite")
val favorite: Long = 0,
@SerialName("like")
val like: Long = 0,
@SerialName("reply")
val reply: Long = 0,
@SerialName("share")
val share: Long = 0,
@SerialName("view")
val view: Long = 0
) : Entry
@Serializable
data class ArticleSimple(
@SerialName("categories")
val categories: List<ArticleCategory>? = null,
@SerialName("category")
val category: ArticleCategory,
@SerialName("id")
override val id: Long,
@SerialName("image_urls")
override val images: List<String>,
@SerialName("publish_time")
override val published: Long,
@SerialName("summary")
override val summary: String,
@SerialName("title")
override val title: String,
@SerialName("words")
val words: Int
) : Article
@Serializable
data class ArticleMedia(
@SerialName("area")
val area: String,
@SerialName("cover")
val cover: String,
@SerialName("media_id")
val mediaId: Long,
@SerialName("score")
val score: Int,
@SerialName("season_id")
val seasonId: Long,
@SerialName("spoiler")
val spoiler: Int,
@SerialName("title")
val title: String,
@SerialName("type_id")
val typeId: Int,
@SerialName("type_name")
val type: String
)
@Serializable
data class ArticleList(
@SerialName("apply_time")
val apply: String,
@SerialName("articles_count")
val count: Int,
@SerialName("check_time")
val checked: String,
@SerialName("ctime")
val created: Long,
@SerialName("id")
val id: Long,
@SerialName("image_url")
val image: String,
@SerialName("mid")
val mid: Long,
@SerialName("name")
val name: String,
@SerialName("publish_time")
val published: Long,
@SerialName("read")
val read: Int,
@SerialName("reason")
val reason: String,
@SerialName("state")
val state: Int,
@SerialName("summary")
val summary: String,
@SerialName("update_time")
val updated: Long,
@SerialName("words")
val words: Int
) : Owner {
override val uid: Long get() = mid
override val uname: String get() = name
}
@Serializable
data class ArticleCategory(
@SerialName("id")
val id: Long,
@SerialName("name")
val name: String,
@SerialName("parent_id")
val parentId: Long
) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Article.kt | 987339310 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class WbiImages(
@SerialName("img_url")
val imgUrl: String = "",
@SerialName("sub_url")
val subUrl: String = ""
) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/WbiImages.kt | 1264251117 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Qrcode(
@SerialName("url")
val url: String,
@SerialName("qrcode_key")
val key: String
)
@Serializable
data class QrcodeStatus(
@SerialName("url")
val url: String,
@SerialName("refresh_token")
val refreshToken: String,
@SerialName("timestamp")
val timestamp: Long,
@SerialName("code")
val code: Int,
@SerialName("message")
val message: String,
)
@Serializable
data class LoginSso(
@SerialName("sso")
val sso: List<String>
) | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Login.kt | 1617014054 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
internal object NumberToBooleanSerializer : KSerializer<Boolean> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor(this::class.qualifiedName!!, PrimitiveKind.INT)
override fun serialize(encoder: Encoder, value: Boolean) = encoder.encodeInt(if (value) 1 else 0)
override fun deserialize(decoder: Decoder): Boolean = decoder.decodeInt() != 0
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/NumberToBooleanSerializer.kt | 2194974015 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import java.time.OffsetDateTime
interface WithDateTime {
val datetime: OffsetDateTime?
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/WithDateTime.kt | 2862089338 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class EmotePanel(
@SerialName("all_packages")
val all: List<EmoteItem>,
@SerialName("user_panel_packages")
val user: List<EmoteItem>
)
@Serializable
data class EmotePackage(
@SerialName("packages")
val packages: List<EmoteItem>
)
@Serializable
data class EmoteItem(
@SerialName("emote")
val emote: List<EmojiDetail>,
@SerialName("id")
val id: Int,
@SerialName("mtime")
val mtime: Long,
@SerialName("text")
val text: String,
@SerialName("type")
val type: Int,
@SerialName("url")
val url: String
)
@Serializable
data class EmojiDetail(
@SerialName("id")
val id: Int,
@SerialName("mtime")
val mtime: Long,
@SerialName("package_id")
val packageId: Int,
@SerialName("text")
val text: String,
@SerialName("type")
val type: Int,
@SerialName("url")
val url: String
)
@Serializable
@Suppress("EnumEntryName")
enum class EmoteBusiness { reply, dynamic } | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Emote.kt | 88746931 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import com.blr19c.falowp.bot.bili.plugins.bili.api.timestamp
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.OffsetDateTime
interface Owner {
val face: String? get() = null
val uid: Long
val uname: String
}
sealed interface UserInfo : Entry, Owner {
val name: String
val level: Int
val sign: String
val live: String
override val face: String
val mid: Long
override val uid: Long get() = mid
override val uname: String get() = name
}
@Serializable
data class BiliUserInfo(
@SerialName("birthday")
val birthday: String,
@SerialName("coins")
val coins: Long,
@SerialName("face")
override val face: String,
@SerialName("fans_badge")
val fansBadge: Boolean,
@SerialName("is_followed")
val isFollowed: Boolean,
@SerialName("jointime")
val joined: Long,
@SerialName("level")
override val level: Int,
@SerialName("live_room")
val liveRoom: BiliRoomSimple? = null,
@SerialName("mid")
override val mid: Long,
@SerialName("moral")
val moral: Int,
@SerialName("name")
override val name: String,
@SerialName("nameplate")
val nameplate: UserNameplate,
@SerialName("official")
val official: UserOfficial,
@SerialName("rank")
val rank: Int,
@SerialName("sex")
val sex: String,
@SerialName("sign")
override val sign: String,
@SerialName("top_photo")
val topPhoto: String,
) : UserInfo {
override val live: String get() = liveRoom?.link ?: "未开通直播间"
init {
liveRoom?.uid = mid
liveRoom?.uname = name
}
}
@Serializable
data class UserNameplate(
@SerialName("condition")
val condition: String,
@SerialName("image")
val image: String,
@SerialName("image_small")
val imageSmall: String,
@SerialName("level")
val level: String,
@SerialName("name")
val name: String,
@SerialName("nid")
val nid: Long
)
@Serializable
data class UserProfile(
@SerialName("info")
val user: UserSimple = UserSimple(),
@SerialName("rank")
val rank: String? = null,
@SerialName("sign")
val sign: String? = null
)
@Serializable
data class UserOfficial(
@SerialName("desc")
val description: String,
@SerialName("role")
val role: Int = 0,
@SerialName("title")
val title: String = "",
@SerialName("type")
val type: Int
)
@Serializable
data class UserSimple(
@SerialName("face")
override val face: String? = null,
@SerialName("head_url")
val head: String? = null,
@SerialName("uid")
override val uid: Long = 0,
@SerialName("uname")
override val uname: String = ""
) : Owner
@Serializable
data class UserMultiple(
@SerialName("card")
val card: Card
) {
@Serializable
data class Card(
@SerialName("fans")
val fans: Long,
@SerialName("official_verify")
val officialVerify: UserOfficial,
@SerialName("rank")
val rank: String,
@SerialName("regtime")
val registered: Long,
@SerialName("uid")
val uid: Long
) : WithDateTime {
override val datetime: OffsetDateTime get() = timestamp(registered)
}
} | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/User.kt | 2689282920 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
@Serializable
data class TempData(
@SerialName("code")
val code: Int,
@SerialName("data")
val data: JsonElement? = null,
@SerialName("result")
val result: JsonElement? = null,
@SerialName("message")
val message: String,
@SerialName("ttl")
val ttl: Int? = null,
@SerialName("msg")
val msg: String? = null
)
| falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/TempData.kt | 1271873717 |
package com.blr19c.falowp.bot.bili.plugins.bili.api.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
@Serializable
data class GarbSuit(
@SerialName("fan_user")
val fanUser: FanUser,
@SerialName("item")
val item: GarbSuitItem,
@SerialName("suit_items")
val items: Map<String, List<GarbSuitItem>>
)
@Serializable
data class FanUser(
@SerialName("avatar")
val avatar: String,
@SerialName("mid")
val mid: Long,
@SerialName("nickname")
val nickname: String
) : Owner {
override val face: String get() = avatar
override val uid: Long get() = mid
override val uname: String get() = nickname
}
@Serializable
data class GarbSuitItem(
@SerialName("item_id")
val itemId: Int,
@SerialName("name")
val name: String,
@SerialName("properties")
val properties: JsonObject,
@SerialName("sale_left_time")
val saleLeftTime: Int,
@SerialName("sale_surplus")
val saleSurplus: Int,
@SerialName("sale_time_end")
val saleTimeEnd: Int,
@SerialName("state")
val state: String,
@SerialName("suit_item_id")
val suitItemId: Int,
@SerialName("tab_id")
val tabId: Int,
@SerialName("items")
val items: List<GarbSuitItem>? = null
)
val GarbSuit.emoji get() = items["emoji_package"].orEmpty()
val GarbSuitItem.image get() = (properties["image"] as JsonPrimitive).content | falowp-bot-plugins/falowp-bot-plugin-bili/src/main/kotlin/com/blr19c/falowp/bot/bili/plugins/bili/api/data/Suit.kt | 3966141789 |
package com.blr19c.falowp.bot.auth.plugins.auth
import com.blr19c.falowp.bot.auth.plugins.hook.NoAuthorizationHook
import com.blr19c.falowp.bot.system.api.SendMessage
import com.blr19c.falowp.bot.system.listener.hooks.MessagePluginExecutionHook
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Listener.Hook.Companion.beforeHook
import com.blr19c.falowp.bot.system.plugin.hook.withPluginHook
/**
* 权限
*/
@Plugin(
name = "权限",
tag = "权限",
desc = "权限",
hidden = true
)
class Auth {
private val auth = beforeHook<MessagePluginExecutionHook> { (receiveMessage, register) ->
val botApi = this.botApi()
if ((register.match.auth?.code ?: Int.MIN_VALUE) > receiveMessage.sender.auth.code) {
withPluginHook(botApi, NoAuthorizationHook(MessagePluginExecutionHook(receiveMessage, register))) {
botApi.sendReply(SendMessage.builder("你还没有权限操作此功能").build())
}
return@beforeHook this.terminate()
}
}
init {
auth.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-auth/src/main/kotlin/com/blr19c/falowp/bot/auth/plugins/auth/Auth.kt | 3001673707 |
package com.blr19c.falowp.bot.auth.plugins.ban
import com.blr19c.falowp.bot.auth.plugins.ban.database.BanInfo
import com.blr19c.falowp.bot.auth.plugins.ban.database.BanInfo.sourceId
import com.blr19c.falowp.bot.auth.plugins.ban.database.BanInfo.userId
import com.blr19c.falowp.bot.system.api.ApiAuth
import com.blr19c.falowp.bot.system.listener.hooks.ReceiveMessageHook
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Listener.Hook.Companion.beforeHook
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.message
import io.ktor.util.collections.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insertIgnore
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
/**
* 禁用用户
*/
@Plugin(name = "禁用用户", tag = "权限", desc = "ban @禁用的人 unban@解禁的人")
class Ban {
private val banSet by lazy {
val concurrentSet = ConcurrentSet<String>()
concurrentSet.addAll(
transaction {
BanInfo.selectAll().map { it[userId] + it[sourceId] }.toSet()
}
)
concurrentSet
}
private val ban = message(Regex("ban"), auth = ApiAuth.ADMINISTRATOR) {
val banList = transaction {
val banList = mutableListOf<String>()
for (user in [email protected]) {
if (user.auth == ApiAuth.ADMINISTRATOR) continue
BanInfo.insertIgnore {
it[userId] = user.id
it[sourceId] = receiveMessage.source.id
}
banList.addLast(user.nickname)
banSet.add(user.id + receiveMessage.source.id)
}
banList
}
if (banList.isNotEmpty()) {
this.sendReply("已禁用用户:${banList.joinToString(",")}", reference = true)
}
}
private val unban = message(Regex("unban"), auth = ApiAuth.ADMINISTRATOR) {
val unbanList = transaction {
val unbanList = mutableListOf<String>()
for (user in [email protected]) {
BanInfo.deleteWhere {
(userId eq user.id).and(sourceId eq receiveMessage.source.id)
}
unbanList.addLast(user.nickname)
banSet.remove(user.id + receiveMessage.source.id)
}
unbanList
}
if (unbanList.isNotEmpty()) {
this.sendReply("已解禁用户:${unbanList.joinToString(",")}", reference = true)
}
}
private val banHook = beforeHook<ReceiveMessageHook>(order = Int.MIN_VALUE) { (receiveMessage) ->
if (banSet.contains(receiveMessage.sender.id + receiveMessage.source.id)) this.terminate()
}
init {
ban.register()
unban.register()
banHook.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-auth/src/main/kotlin/com/blr19c/falowp/bot/auth/plugins/ban/Ban.kt | 2990441138 |
package com.blr19c.falowp.bot.auth.plugins.ban.database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.transactions.transaction
/**
* 禁用用户
*/
object BanInfo : Table("ban_info") {
val id = integer("id").autoIncrement()
/**
* 用户id
*/
val userId = varchar("user_id", 64)
/**
* 来源id
*/
val sourceId = varchar("source_id", 128)
override val primaryKey = PrimaryKey(id, name = "pk_ban_info_id")
init {
transaction {
uniqueIndex(userId, sourceId)
SchemaUtils.create(BanInfo)
}
}
} | falowp-bot-plugins/falowp-bot-plugin-auth/src/main/kotlin/com/blr19c/falowp/bot/auth/plugins/ban/database/BanInfo.kt | 3261865175 |
package com.blr19c.falowp.bot.auth.plugins.hook
import com.blr19c.falowp.bot.system.listener.hooks.MessagePluginExecutionHook
import com.blr19c.falowp.bot.system.plugin.Plugin
/**
* 无权限
*/
data class NoAuthorizationHook(val messagePluginExecutionHook: MessagePluginExecutionHook) : Plugin.Listener.Hook | falowp-bot-plugins/falowp-bot-plugin-auth/src/main/kotlin/com/blr19c/falowp/bot/auth/plugins/hook/NoAuthorizationHook.kt | 3476406151 |
package com.blr19c.falowp.bot.repeat.plugins.repeat
import com.blr19c.falowp.bot.system.api.*
import com.blr19c.falowp.bot.system.listener.events.SendMessageEvent
import com.blr19c.falowp.bot.system.plugin.MessagePluginRegisterMatch
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Listener.Event.Companion.eventListener
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.queueMessage
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.random.Random
/**
* 复读机
*/
@Plugin(
name = "复读机",
tag = "聊天",
desc = "和大家一起复读"
)
class Repeater {
private val mutex: Mutex = Mutex()
private val executor = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val historyMessage = LinkedHashMap<String, RepeaterData>()
private fun equalsContent(content1: ReceiveMessage.Content, content2: ReceiveMessage.Content) = runBlocking {
val image1 = content1.image.map { it.toSummary() }.toList()
val image2 = content2.image.map { it.toSummary() }.toList()
content1.at.map { it.id }.toList() == content2.at.map { it.id }.toList()
&& content1.message == content2.message
&& image1 == image2
}
private fun buildReplyMessage(content: ReceiveMessage.Content): SendMessageChain {
if (Random.nextDouble(0.0, 1.0) < 0.8) {
val message = if (content.message.contains("打断施法"))
"打断!".plus(content.message) else content.message
return SendMessage.builder()
.at(content.at.map { it.id })
.image(content.image.map { it.info })
.text(message)
.build()
}
val replyMessage = "打断施法"
val interruptMessage = if (content.message.contains(replyMessage))
"打断!".plus(content.message) else replyMessage.plus("!")
return SendMessage.builder(interruptMessage).build()
}
private suspend fun addMessage(botApi: BotApi, originalMessage: RepeaterData, sourceId: String) = mutex.withLock {
val repeaterData = historyMessage.compute(sourceId) { _, oldRepeaterData ->
var newRepeaterData = originalMessage
oldRepeaterData ?: return@compute newRepeaterData
if (!equalsContent(newRepeaterData.content, oldRepeaterData.content)) {
return@compute newRepeaterData
}
newRepeaterData = oldRepeaterData.copy(count = oldRepeaterData.count + 1)
if (newRepeaterData.count < 0) {
newRepeaterData = oldRepeaterData.copy(repeat = true)
}
if (newRepeaterData.count >= 3) {
newRepeaterData = newRepeaterData.copy(count = Int.MIN_VALUE)
}
newRepeaterData
} ?: return
if (repeaterData.count < 0 && !repeaterData.repeat) {
botApi.sendReply(buildReplyMessage(repeaterData.content))
}
}
private val repeater = queueMessage(
MessagePluginRegisterMatch.allMatch(),
terminateEvent = false, onSuccess = {}, onOverFlow = {}
) {
executor.launch {
addMessage(this@queueMessage, RepeaterData(receiveMessage.content), receiveMessage.source.id)
}
}
private val sendMessageEvent = eventListener<SendMessageEvent> { (sendMessageList, _, forward) ->
if (forward || this.receiveMessage.source.id.isBlank()) return@eventListener
for (sendMessageChain in sendMessageList) {
val atList = sendMessageChain.messageList.filterIsInstance<AtSendMessage>()
.map { ReceiveMessage.User.empty().copy(id = it.at) }
.toList()
val imageList = sendMessageChain.messageList.filterIsInstance<ImageSendMessage>()
.map { it.image }
.toList()
val text = sendMessageChain.messageList.filterIsInstance<TextSendMessage>().joinToString { it.content }
val content = ReceiveMessage.Content(text, atList, imageList, emptyList()) { null }
addMessage(this, RepeaterData(content, repeat = true), this.receiveMessage.source.id)
}
}
init {
repeater.register()
sendMessageEvent.register()
}
data class RepeaterData(val content: ReceiveMessage.Content, val count: Int = 1, val repeat: Boolean = false)
} | falowp-bot-plugins/falowp-bot-plugin-repeat/src/main/kotlin/com/blr19c/falowp/bot/repeat/plugins/repeat/Repeater.kt | 2975941480 |
package com.blr19c.falowp.bot.user.vo
import com.blr19c.falowp.bot.system.api.ApiAuth
import com.blr19c.falowp.bot.system.expand.ImageUrl
import java.math.BigDecimal
/**
* 机器人用户信息
*/
data class BotUserVo(
val id: Int,
/**
* 用户id
*/
val userId: String,
/**
* 昵称
*/
val nickname: String,
/**
* 头像url
*/
val avatar: ImageUrl,
/**
* 权限
*/
val auth: ApiAuth,
/**
* 好感度
*/
val impression: BigDecimal,
/**
* 金币
*/
val coins: BigDecimal,
/**
* 来源id
*/
val sourceId: String,
/**
* 来源类型
*/
val sourceType: String
) | falowp-bot-plugins/falowp-bot-plugin-user/src/main/kotlin/com/blr19c/falowp/bot/user/vo/BotUserVo.kt | 934214323 |
package com.blr19c.falowp.bot.user.database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.transactions.transaction
/**
* 机器人用户
*/
object BotUser : Table("bot_user") {
val id = integer("id").autoIncrement()
/**
* 用户id
*/
val userId = varchar("user_id", 64).index()
/**
* 昵称
*/
val nickname = varchar("nickname", 128)
/**
* 头像url
*/
val avatar = varchar("avatar", 256)
/**
* 权限
*/
val auth = varchar("auth", 32)
/**
* 好感度
*/
val impression = decimal("impression", 10, 2)
/**
* 金币 签到记录
*/
val coins = decimal("coins", 10, 2)
/**
* 来源id
*/
val sourceId = varchar("source_id", 128).index()
/**
* 来源类型
*/
val sourceType = varchar("source_type", 16)
override val primaryKey = PrimaryKey(id, name = "pk_bot_user_id")
init {
transaction {
uniqueIndex(userId, sourceId)
SchemaUtils.create(BotUser)
}
}
}
| falowp-bot-plugins/falowp-bot-plugin-user/src/main/kotlin/com/blr19c/falowp/bot/user/database/BotUser.kt | 1060043077 |
package com.blr19c.falowp.bot.user.plugins.user
import com.blr19c.falowp.bot.system.api.SendMessage
import com.blr19c.falowp.bot.system.json.Json
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Message.message
import com.blr19c.falowp.bot.system.readPluginResource
import com.blr19c.falowp.bot.system.web.htmlToImageBase64
import com.blr19c.falowp.bot.user.database.BotUser
import com.blr19c.falowp.bot.user.vo.BotUserVo
import org.jetbrains.exposed.sql.SortOrder
import org.jsoup.Jsoup
/**
* 排行榜
*/
@Plugin(
name = "金币/好感度排行",
desc = """
<p>金币排行</p>
<p>好感度排行</p>
"""
)
class Ranking {
private val coinsRanking = message(Regex("金币排行")) {
val list = queryBySourceId(this.receiveMessage.source.id) {
it.orderBy(BotUser.coins, order = SortOrder.DESC).take(7)
}
val replyImgBase64 = build(list, "coinsRanking.html", "#coinsRankingDiv") {
it.coins.toPlainString()
}
this.sendReply(SendMessage.builder().image(replyImgBase64).build())
}
private val impressionRanking = message(Regex("好感度排行")) {
val list = queryBySourceId(this.receiveMessage.source.id) {
it.orderBy(BotUser.impression, order = SortOrder.DESC).take(7)
}
val replyImgBase64 = build(list, "impressionRanking.html", "#impressionRankingDiv") {
it.impression.toPlainString()
}
this.sendReply(SendMessage.builder().image(replyImgBase64).build())
}
private suspend fun build(
list: List<BotUserVo>,
htmlFile: String,
querySelector: String,
block: (BotUserVo) -> String
): String {
val impressionList = list.map { block.invoke(it) }
val nameList = list.map { it.nickname }
val html = readPluginResource(htmlFile) { inputStream ->
inputStream.bufferedReader().use { Jsoup.parse(it.readText()) }
}
html.select("#labels").`val`(Json.toJsonString(nameList))
html.select("#data").`val`(Json.toJsonString(impressionList))
return htmlToImageBase64(html.html(), querySelector)
}
init {
coinsRanking.register()
impressionRanking.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-user/src/main/kotlin/com/blr19c/falowp/bot/user/plugins/user/Ranking.kt | 1992457945 |
package com.blr19c.falowp.bot.user.plugins.user
import com.blr19c.falowp.bot.system.api.BotApi
import com.blr19c.falowp.bot.system.api.ReceiveMessage
import com.blr19c.falowp.bot.system.listener.hooks.ReceiveMessageHook
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Listener.Hook.Companion.beforeHook
import com.blr19c.falowp.bot.user.database.BotUser
import com.blr19c.falowp.bot.user.database.BotUser.sourceId
import com.blr19c.falowp.bot.user.database.BotUser.userId
import com.blr19c.falowp.bot.user.vo.BotUserVo
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.insertIgnore
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import java.math.BigDecimal
/**
* 通过hook增加用户信息
*/
@Plugin(name = "用户信息", hidden = true)
class BotUserHook {
private val userInfoHook = beforeHook<ReceiveMessageHook> { (receiveMessage) ->
val botApi = this.botApi()
//当前人
val currentUser = botApi.currentUserOrNull()
botApi.createUser(currentUser, receiveMessage.sender)
//被at的人
for (user in receiveMessage.content.at) {
val atUser = queryByUserId(user.id, receiveMessage.source.id)
botApi.createUser(atUser, user)
}
}
private suspend fun BotApi.createUser(botUser: BotUserVo?, user: ReceiveMessage.User) {
val avatarUrl = user.avatar.toUrl()
if (botUser == null) {
transaction {
BotUser.insertIgnore {
it[userId] = user.id
it[nickname] = user.nickname
it[avatar] = avatarUrl
it[auth] = user.auth.name
it[impression] = BigDecimal.ZERO
it[coins] = BigDecimal.ZERO
it[sourceId] = receiveMessage.source.id
it[sourceType] = receiveMessage.source.type.name
}
}
} else {
transaction {
BotUser.update({ (userId eq user.id).and(sourceId eq receiveMessage.source.id) }) {
it[nickname] = user.nickname
it[avatar] = avatarUrl
it[auth] = user.auth.name
}
}
}
}
init {
userInfoHook.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-user/src/main/kotlin/com/blr19c/falowp/bot/user/plugins/user/BotUserHook.kt | 3728391772 |
package com.blr19c.falowp.bot.user.plugins.user
import com.blr19c.falowp.bot.system.api.ApiAuth
import com.blr19c.falowp.bot.system.api.BotApi
import com.blr19c.falowp.bot.system.expand.ImageUrl
import com.blr19c.falowp.bot.user.database.BotUser
import com.blr19c.falowp.bot.user.vo.BotUserVo
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.plus
import org.jetbrains.exposed.sql.transactions.transaction
import java.math.BigDecimal
/**
* 当前用户
*/
fun BotApi.currentUser(): BotUserVo {
return currentUserOrNull()!!
}
/**
* 当前用户
*/
fun BotApi.currentUserOrNull(): BotUserVo? {
return queryByUserId(receiveMessage.sender.id, receiveMessage.source.id)
}
/**
* 根据userId查询用户
*/
fun queryByUserId(userId: String, sourceId: String): BotUserVo? {
return transaction {
BotUser.selectAll()
.where {
val user = BotUser.userId eq userId
val source = BotUser.sourceId eq sourceId
user and source
}
.singleOrNull()
?.let { convertVo(it) }
}
}
/**
* 根据来源id获取用户
*/
fun queryBySourceId(sourceId: String, block: (Query) -> List<ResultRow> = { it.toList() }): List<BotUserVo> {
return transaction {
BotUser.selectAll()
.where { BotUser.sourceId eq sourceId }
.let { block.invoke(it) }
.map { convertVo(it) }
}
}
/**
* 增加金币
*/
fun BotUserVo.incrementCoins(coins: BigDecimal) {
transaction {
BotUser.update({ BotUser.id eq [email protected] }) {
it.update(BotUser.coins, BotUser.coins + coins)
}
}
}
/**
* 减少金币
*/
fun BotUserVo.decrementCoins(coins: BigDecimal) {
incrementCoins(-coins)
}
/**
* 增加好感度
*/
fun BotUserVo.incrementImpression(impression: BigDecimal) {
transaction {
BotUser.update({ BotUser.id eq [email protected] }) {
it.update(BotUser.impression, BotUser.impression + impression)
}
}
}
/**
* 减少好感度
*/
fun BotUserVo.decrementImpression(impression: BigDecimal) {
incrementImpression(-impression)
}
private fun convertVo(resultRow: ResultRow): BotUserVo {
return BotUserVo(
resultRow[BotUser.id],
resultRow[BotUser.userId],
resultRow[BotUser.nickname],
ImageUrl(resultRow[BotUser.avatar]),
ApiAuth.valueOf(resultRow[BotUser.auth]),
resultRow[BotUser.impression],
resultRow[BotUser.coins],
resultRow[BotUser.sourceId],
resultRow[BotUser.sourceType]
)
} | falowp-bot-plugins/falowp-bot-plugin-user/src/main/kotlin/com/blr19c/falowp/bot/user/plugins/user/BotUserOption.kt | 2234505772 |
package com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.vo
/**
* 词云消息记录
*/
data class WordcloudTextInfoVo(
val id: Int,
/**
* 发送的消息
*/
val text: String,
/**
* 用户id
*/
val userId: String,
/**
* 来源id
*/
val sourceId: String,
/**
* 来源类型
*/
val sourceType: String,
)
| falowp-bot-plugins/falowp-bot-plugin-wordcloud/src/main/kotlin/com/blr19c/falowp/bot/wordcloud/plugins/wordcloud/vo/WordcloudTextInfoVo.kt | 1403772085 |
package com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.database
import com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.vo.WordcloudTextInfoVo
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.javatime.date
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import java.time.LocalDate
/**
* 词云消息记录
*/
object WordcloudTextInfo : Table("word_cloud_text_info") {
val id = integer("id").autoIncrement()
/**
* 发送的消息
*/
val text = text("text")
/**
* 用户id
*/
val userId = varchar("user_id", 64)
/**
* 来源id
*/
val sourceId = varchar("source_id", 128).index()
/**
* 来源类型
*/
val sourceType = varchar("source_type", 16)
/**
* 创建时间
*/
val createDate = date("create_date").index()
override val primaryKey = PrimaryKey(id, name = "pk_bot_user_id")
init {
transaction {
SchemaUtils.create(WordcloudTextInfo)
}
}
fun queryAllSourceId(createDate: LocalDate): List<String> = transaction {
return@transaction WordcloudTextInfo.select(sourceId)
.where { WordcloudTextInfo.createDate eq createDate }
.groupBy(sourceId)
.distinctBy { it[sourceId] }
.map { it[sourceId] }
.toList()
}
fun queryBySourceId(sourceId: String, createDate: LocalDate): List<WordcloudTextInfoVo> = transaction {
return@transaction WordcloudTextInfo.selectAll()
.where { (WordcloudTextInfo.sourceId eq sourceId).and(WordcloudTextInfo.createDate eq createDate) }
.map {
WordcloudTextInfoVo(
it[WordcloudTextInfo.id],
it[text],
it[userId],
it[WordcloudTextInfo.sourceId],
it[sourceType]
)
}.toList()
}
}
| falowp-bot-plugins/falowp-bot-plugin-wordcloud/src/main/kotlin/com/blr19c/falowp/bot/wordcloud/plugins/wordcloud/database/WordcloudTextInfo.kt | 2658831980 |
package com.blr19c.falowp.bot.wordcloud.plugins.wordcloud
import com.blr19c.falowp.bot.system.api.*
import com.blr19c.falowp.bot.system.json.Json
import com.blr19c.falowp.bot.system.listener.events.GreetingEvent
import com.blr19c.falowp.bot.system.listener.events.SendMessageEvent
import com.blr19c.falowp.bot.system.listener.hooks.ReceiveMessageHook
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Listener.Event.Companion.eventListener
import com.blr19c.falowp.bot.system.plugin.Plugin.Listener.Hook.Companion.beforeHook
import com.blr19c.falowp.bot.system.plugin.hook.withPluginHook
import com.blr19c.falowp.bot.system.pluginConfigListProperty
import com.blr19c.falowp.bot.system.readPluginResource
import com.blr19c.falowp.bot.system.web.htmlToImageBase64
import com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.database.WordcloudTextInfo
import com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.event.WordcloudEvent
import com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.hook.WordcloudSegmentHook
import com.hankcs.hanlp.HanLP
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import org.jsoup.Jsoup
import java.time.LocalDate
/**
* 词云
*/
@Plugin(name = "词云", desc = "在晚安事件时生成今日词云")
class Wordcloud {
private val executor = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val greetingEvent = eventListener<GreetingEvent> { (_, goodNight) ->
if (!goodNight) return@eventListener
this.publishEvent(WordcloudEvent())
}
private val wordcloud = eventListener<WordcloudEvent> {
this.generateWordcloud(it.date)
}
private val receiveMessage = beforeHook<ReceiveMessageHook> { (receiveMessage) ->
if (receiveMessage.content.message.isBlank()) {
return@beforeHook
}
executor.launch {
addMessage(
receiveMessage.content.message,
receiveMessage.sender.id,
receiveMessage.source.id,
receiveMessage.source.type
)
}
}
private val sendMessage = eventListener<SendMessageEvent> { (sendMessage) ->
for (textSendMessage in sendMessage.filterIsInstance<TextSendMessage>()) {
if ([email protected]()) continue
if ([email protected]()) continue
if (textSendMessage.content.isBlank()) continue
addMessage(
textSendMessage.content,
[email protected],
[email protected],
[email protected]
)
}
}
private suspend fun BotApi.generateWordcloud(date: LocalDate) {
val html = readPluginResource("wordcloud.html") { inputStream ->
inputStream.bufferedReader().use { Jsoup.parse(it.readText()) }
}
for (sourceId in WordcloudTextInfo.queryAllSourceId(date)) {
val segmentCountMap = mutableMapOf<String, Int>()
lateinit var sourceType: String
for (wordcloudTextInfoVo in WordcloudTextInfo.queryBySourceId(sourceId, date)) {
sourceType = wordcloudTextInfoVo.sourceType
HanLP.segment(wordcloudTextInfoVo.text)
.map { it.word.replace(Regex("[\\pP\\p{Punct}]"), "") }
.filter { it.isNotBlank() }
.forEach { segmentCountMap.compute(it) { _, v -> v?.plus(1) ?: 1 } }
}
if (segmentCountMap.isEmpty()) continue
withPluginHook(this, WordcloudSegmentHook(segmentCountMap)) {
val blockWords = pluginConfigListProperty("blockWords")
blockWords.forEach { segmentCountMap.remove(it) }
}
val wordCloudData = Json.toJsonString(segmentCountMap.toList().map { listOf(it.first, it.second) }.toList())
html.select("#wordCloudData").`val`(wordCloudData)
val image = htmlToImageBase64(html.html(), "#canvas")
this.send(sourceId, sourceType, SendMessage.builder("今日词云").image(image).build())
}
}
private fun addMessage(text: String, userId: String, sourceId: String, sourceType: SourceTypeEnum) {
transaction {
WordcloudTextInfo.insert {
it[WordcloudTextInfo.text] = text
it[WordcloudTextInfo.userId] = userId
it[WordcloudTextInfo.sourceId] = sourceId
it[WordcloudTextInfo.sourceType] = sourceType.name
it[createDate] = LocalDate.now()
}
}
}
private suspend fun BotApi.send(
sourceId: String,
sourceType: String,
sendMessageChain: SendMessageChain
) {
if (sourceType == SourceTypeEnum.PRIVATE.name) {
this.sendPrivate(sendMessageChain, sourceId = sourceId)
}
if (sourceType == SourceTypeEnum.GROUP.name) {
this.sendGroup(sendMessageChain, sourceId = sourceId)
}
}
init {
greetingEvent.register()
wordcloud.register()
receiveMessage.register()
sendMessage.register()
}
} | falowp-bot-plugins/falowp-bot-plugin-wordcloud/src/main/kotlin/com/blr19c/falowp/bot/wordcloud/plugins/wordcloud/Wordcloud.kt | 3835177036 |
package com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.event
import com.blr19c.falowp.bot.system.plugin.Plugin
import java.time.LocalDate
/**
* 发送词云事件
*
* @param date 日期
*/
data class WordcloudEvent(val date: LocalDate = LocalDate.now()) : Plugin.Listener.Event
| falowp-bot-plugins/falowp-bot-plugin-wordcloud/src/main/kotlin/com/blr19c/falowp/bot/wordcloud/plugins/wordcloud/event/WordcloudEvent.kt | 2525842547 |
package com.blr19c.falowp.bot.wordcloud.plugins.wordcloud.hook
import com.blr19c.falowp.bot.system.plugin.Plugin
/**
* 词云分词钩子
*
* @param segmentCountMap 分词内容
*/
data class WordcloudSegmentHook(val segmentCountMap: MutableMap<String, Int>) : Plugin.Listener.Hook
| falowp-bot-plugins/falowp-bot-plugin-wordcloud/src/main/kotlin/com/blr19c/falowp/bot/wordcloud/plugins/wordcloud/hook/WordcloudSegmentHook.kt | 708451449 |
package com.blr19c.falowp.bot.idle.plugins.idle
import com.blr19c.falowp.bot.system.api.SendMessage
import com.blr19c.falowp.bot.system.plugin.Plugin
import com.blr19c.falowp.bot.system.plugin.Plugin.Task.cronScheduling
import com.blr19c.falowp.bot.system.systemConfigProperty
import com.blr19c.falowp.bot.system.web.webclient
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.utils.io.jvm.javaio.*
import net.fortuna.ical4j.data.CalendarBuilder
import net.fortuna.ical4j.model.*
import net.fortuna.ical4j.model.component.VEvent
import net.fortuna.ical4j.model.property.DtEnd
import net.fortuna.ical4j.model.property.Summary
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.temporal.Temporal
import java.time.temporal.TemporalAdjusters
@Plugin(
name = "摸鱼",
tag = "聊天",
desc = "每天10点推送"
)
class Idle {
private val idle = cronScheduling("0 0 10 * * ?") {
val inputStream =
webclient().get("https://www.shuyz.com/githubfiles/china-holiday-calender/master/holidayCal.ics")
.bodyAsChannel().toInputStream()
val calendar = CalendarBuilder().build(inputStream)
val now = LocalDate.now()
val holidayLines = mutableListOf<String>()
for (closestHoliday in getClosestHolidays(calendar, now)) {
val startDate = closestHoliday.getStartDateTime()!!
val endDate = closestHoliday.getEndDateTime()!!
val summary = closestHoliday.summary.get().value
val distanceSummary = ChronoUnit.DAYS.between(now, startDate)
val sumSummaryDay = ChronoUnit.DAYS.between(startDate, endDate) + 1
val line = "距离【$summary】还有: ${distanceSummary}天-共${sumSummaryDay}天"
holidayLines.add(line)
}
val todayDate = DateTimeFormatter.ofPattern("yyyy年MM月dd日").format(now)
val todayWeek = DateTimeFormatter.ofPattern("EEEE").format(now)
val todayLine = """今天是${todayDate},${todayWeek}。"""
val title = """【${systemConfigProperty("nickname")}摸鱼办】提醒您:"""
val myLine = "摸鱼人!即使今天是开工第${now.dayOfYear}天,也一定不要忘记摸鱼哦!"
val body1 =
"""$todayLine $myLine 有事没事起身去茶水间,去厕所,去廊道走走,别总在工位上坐着,钱是老板的,但健康是自己的。"""
val lastBetween = ChronoUnit.DAYS.between(now, now.with(TemporalAdjusters.lastDayOfMonth()))
val payWagesLast = """离【月底发工资】:${lastBetween}天"""
val payWages05 = """离【05号发工资】:${betweenPayday(5)}"""
val payWages10 = """离【10号发工资】:${betweenPayday(10)}"""
val payWages15 = """离【15号发工资】:${betweenPayday(15)}"""
val payWages20 = """离【20号发工资】:${betweenPayday(20)}"""
val payWages25 = """离【25号发工资】:${betweenPayday(25)}"""
val week = """距离【双休】还有:${betweenWeek()}"""
val lineList =
listOf(
title,
body1,
payWagesLast,
payWages05,
payWages10,
payWages15,
payWages20,
payWages25,
week,
holidayLines.joinToString("\n")
)
val line = lineList.joinToString("\n")
this.sendAllGroup(SendMessage.builder(line).build())
}
/**
* 获取最近的发薪
*/
private fun betweenPayday(dayOfMonth: Int): String {
val now = LocalDate.now()
var payday: LocalDate = LocalDate.of(now.year, now.month, dayOfMonth)
if (now.dayOfMonth > dayOfMonth) {
payday = payday.plusMonths(1)
}
val between = ChronoUnit.DAYS.between(now, payday)
return if (between == 0.toLong()) "就在今天!!" else between.toString().plus("天")
}
/**
* 获取最近的双休
*/
private fun betweenWeek(): String {
val now = LocalDate.now()
val current = now.dayOfWeek
if (DayOfWeek.SATURDAY == current || DayOfWeek.SUNDAY == current) {
return "就在今天!!"
}
val between = ChronoUnit.DAYS.between(now, now.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)))
return between.toString().plus("天")
}
/**
* 获取最近的假期
*/
private fun getClosestHolidays(calendar: Calendar, currentDate: LocalDate): List<VEvent> {
val allHolidays = calendar.getComponents<VEvent>(Component.VEVENT)
val map = mutableMapOf<String, VEvent>()
var lastSummaryComment: String? = null
var lastHoliday: VEvent? = null
for (holiday in allHolidays
.filter { it.getEndDateTime() != null }
.filter { it.getStartDateTime() != null }
.filter { it.getStartDateTime()!!.isAfter(currentDate) }
.sortedBy { it.getEndDateTime() }) {
val summarySplit = holiday.summary.get().value.split(" ")
if (summarySplit.size < 2) continue
if (summarySplit[1] == "补班") continue
val summaryComment = summarySplit[0] + summarySplit[1]
if (lastSummaryComment == null) {
lastSummaryComment = summaryComment
var propertyList: ContentCollection<Property> = holiday!!.propertyList
propertyList = propertyList.remove(holiday.getProperty<Summary>(Property.SUMMARY).get())
propertyList = propertyList.add(Summary(lastSummaryComment))
lastHoliday = VEvent(propertyList as PropertyList)
map[summaryComment] = lastHoliday
continue
}
if (lastSummaryComment == summaryComment) {
var propertyList: ContentCollection<Property> = lastHoliday!!.propertyList
propertyList = propertyList.remove(lastHoliday.getProperty<DtEnd<Temporal>>(Property.DTEND).get())
propertyList = propertyList.add(holiday.getProperty<DtEnd<Temporal>>(Property.DTEND).get())
lastHoliday = VEvent(propertyList as PropertyList)
map[summaryComment] = lastHoliday
continue
}
if (map.size == 2) {
break
}
lastSummaryComment = null
}
return map.values.toList()
}
private fun DateTimePropertyAccessor.getStartDateTime(): LocalDate? {
val startDate = this.getDateTimeStart<Temporal>().orElse(null)?.date ?: return null
if (startDate is LocalDateTime) {
return startDate.toLocalDate()
}
return LocalDate.from(startDate)
}
private fun DateTimePropertyAccessor.getEndDateTime(): LocalDate? {
val endDate = this.getDateTimeEnd<Temporal>().orElse(null)?.date ?: return null
if (endDate is LocalDateTime) {
return endDate.toLocalDate()
}
return LocalDate.from(endDate)
}
init {
idle.register()
}
}
| falowp-bot-plugins/falowp-bot-plugin-idle/src/main/kotlin/com/blr19c/falowp/bot/idle/plugins/idle/Idle.kt | 2048044456 |
package lista
import java.time.LocalDate
fun main() {
print("Digite seu ano de nascimento: ")
val anoNascimento = readln().toInt()
val idade = calculaIdade(anoNascimento)
println("Sua idade atual é: $idade")
}
fun calculaIdade(anoNascimento: Int): Int {
val anoAtual = LocalDate.now().year
val idade = anoAtual - anoNascimento
return idade
}
| lista-exercicios-kotlin/src/lista/Ex03.kt | 3479659840 |
package lista
fun main() {
for (n in 1..10){
println("Tabuada do $n".uppercase())
for (i in 1..10){
println("$n x $i = ${n * i}")
}
println()
}
} | lista-exercicios-kotlin/src/lista/Ex17.kt | 1972404082 |
/*
ler denominador
ler numerador
enquanto denominadior for 0
da erro
repetir pergunta ("Digite o denominador: ")
ler donominador teclado
divisao = nume / deno
prit
*/
package lista
fun main() {
print("Digite o numerador: ")
val numerador = readln().toDouble()
val denominador = lerDenominador()
val divisao = numerador / denominador
println(divisao)
}
fun lerDenominador(): Double {
print("Digite o denominador: ")
var denominador = readln().toDouble()
while (denominador == 0.0) {
println("Número inválido para a divisão! ")
print("Digite o denominador: ")
denominador = readln().toDouble()
}
return denominador
} | lista-exercicios-kotlin/src/lista/Ex07.kt | 2840054590 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.