├── gradle.properties ├── settings.gradle.kts ├── .github ├── afdian.jpg └── workflows │ └── test.yml ├── src ├── test │ ├── resources │ │ └── META-INF │ │ │ └── services │ │ │ ├── org.slf4j.spi.SLF4JServiceProvider │ │ │ └── net.mamoe.mirai.console.plugin.jvm.JvmPlugin │ ├── kotlin │ │ └── xyz │ │ │ └── cssxsh │ │ │ └── mirai │ │ │ ├── hibernate │ │ │ └── entry │ │ │ │ ├── H2Test.kt │ │ │ │ ├── MySqlTest.kt │ │ │ │ ├── MariaDBTest.kt │ │ │ │ ├── PostgreSqlTest.kt │ │ │ │ ├── SqliteTest.kt │ │ │ │ ├── MSSqlTest.kt │ │ │ │ └── DatabaseTest.kt │ │ │ └── test │ │ │ └── MiraiHibernatePluginTest.kt │ └── java │ │ └── xyz │ │ └── cssxsh │ │ └── mirai │ │ └── test │ │ ├── entry │ │ ├── Work.java │ │ └── User.java │ │ └── MiraiHibernateDemo.java └── main │ ├── resources │ └── META-INF │ │ └── services │ │ ├── net.mamoe.mirai.console.plugin.jvm.JvmPlugin │ │ └── xyz.cssxsh.mirai.spi.ComparableService │ └── kotlin │ └── xyz │ └── cssxsh │ ├── mirai │ └── hibernate │ │ ├── entry │ │ ├── FaceTagRecord.kt │ │ ├── RecalledKind.kt │ │ ├── GroupRecord.kt │ │ ├── BotRecord.kt │ │ ├── FriendIndex.kt │ │ ├── GroupMemberIndex.kt │ │ ├── FriendRecord.kt │ │ ├── NudgeRecord.kt │ │ ├── GroupMemberRecord.kt │ │ ├── FaceRecord.kt │ │ └── MessageRecord.kt │ │ ├── MiraiH2.kt │ │ ├── spi │ │ └── MiraiHibernateSourceHandler.kt │ │ ├── MiraiHibernateLoader.kt │ │ ├── MiraiHibernatePlugin.kt │ │ ├── MiraiHibernateUtils.kt │ │ ├── MiraiHibernateConfiguration.kt │ │ └── MiraiHibernateRecorder.kt │ └── hibernate │ ├── MacroSQLFunction.kt │ └── Criteria.kt ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── example ├── sqlite.hibernate.properties ├── h2.hibernate.properties ├── postgresql.hibernate.properties ├── update_message_record.sql ├── mysql.hibernate.properties ├── mariadb.hibernate.properties ├── sqlserver.hibernate.properties ├── h2.web.md └── h2.web.cmd ├── CHANGELOG.md ├── .gitignore ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "mirai-hibernate-plugin" -------------------------------------------------------------------------------- /.github/afdian.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cssxsh/mirai-hibernate-plugin/HEAD/.github/afdian.jpg -------------------------------------------------------------------------------- /src/test/resources/META-INF/services/org.slf4j.spi.SLF4JServiceProvider: -------------------------------------------------------------------------------- 1 | org.slf4j.simple.SimpleServiceProvider -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/net.mamoe.mirai.console.plugin.jvm.JvmPlugin: -------------------------------------------------------------------------------- 1 | xyz.cssxsh.mirai.hibernate.MiraiHibernatePlugin -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cssxsh/mirai-hibernate-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/xyz.cssxsh.mirai.spi.ComparableService: -------------------------------------------------------------------------------- 1 | xyz.cssxsh.mirai.hibernate.spi.MiraiHibernateSourceHandler -------------------------------------------------------------------------------- /src/test/resources/META-INF/services/net.mamoe.mirai.console.plugin.jvm.JvmPlugin: -------------------------------------------------------------------------------- 1 | xyz.cssxsh.mirai.test.MiraiHibernatePluginTest 2 | xyz.cssxsh.mirai.test.MiraiHibernateDemo -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/H2Test.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import java.io.File 4 | 5 | class H2Test : DatabaseTest() { 6 | init { 7 | configuration.apply { 8 | File("./example/h2.hibernate.properties").inputStream().use(properties::load) 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /example/sqlite.hibernate.properties: -------------------------------------------------------------------------------- 1 | hibernate.connection.url=jdbc:sqlite:file:./data/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/record.sqlite 2 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 3 | hibernate.connection.isolation=1 4 | hibernate.hbm2ddl.auto=update 5 | hibernate-connection-autocommit=true -------------------------------------------------------------------------------- /example/h2.hibernate.properties: -------------------------------------------------------------------------------- 1 | hibernate.connection.url=jdbc:h2:file:./data/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/record.h2;AUTO_SERVER=TRUE 2 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 3 | hibernate.connection.isolation=1 4 | hibernate.hbm2ddl.auto=update 5 | hibernate-connection-autocommit=true -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/MySqlTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import java.io.File 4 | 5 | class MySqlTest : DatabaseTest() { 6 | init { 7 | configuration.apply { 8 | File("./example/mysql.hibernate.properties").inputStream().use(properties::load) 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/MariaDBTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import java.io.File 4 | 5 | class MariaDBTest : DatabaseTest() { 6 | init { 7 | configuration.apply { 8 | File("./example/mariadb.hibernate.properties").inputStream().use(properties::load) 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/PostgreSqlTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import java.io.File 4 | 5 | class PostgreSqlTest : DatabaseTest() { 6 | init { 7 | configuration.apply { 8 | File("./example/postgresql.hibernate.properties").inputStream().use(properties::load) 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /example/postgresql.hibernate.properties: -------------------------------------------------------------------------------- 1 | hibernate.connection.url=jdbc:postgresql://localhost:5432/mirai?autoReconnect=true 2 | hibernate.connection.username=postgres 3 | hibernate.connection.password=root 4 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 5 | hibernate.connection.isolation=1 6 | hibernate.hbm2ddl.auto=update 7 | hibernate.autoReconnect=true -------------------------------------------------------------------------------- /example/update_message_record.sql: -------------------------------------------------------------------------------- 1 | UPDATE `message_record` SET 2 | recall = 1 3 | WHERE ids = null or ids = ''; 4 | 5 | UPDATE `message_record` SET 6 | recall = 2 7 | WHERE recall = target_id; 8 | 9 | UPDATE `message_record` SET 10 | recall = 3 11 | WHERE recall > 12345; 12 | 13 | ALTER TABLE `message_record` 14 | CHANGE COLUMN `recall` `recall` TINYINT(4) NOT NULL DEFAULT 0 AFTER `kind`; -------------------------------------------------------------------------------- /example/mysql.hibernate.properties: -------------------------------------------------------------------------------- 1 | hibernate.connection.url=jdbc:mysql://localhost:3306/mirai?autoReconnect=true 2 | hibernate.connection.CharSet=utf8mb4 3 | hibernate.connection.useUnicode=true 4 | hibernate.connection.username=root 5 | hibernate.connection.password=root 6 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 7 | hibernate.connection.isolation=1 8 | hibernate.hbm2ddl.auto=update 9 | hibernate.autoReconnect=true -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/SqliteTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import org.junit.jupiter.api.condition.* 4 | import java.io.File 5 | 6 | @DisabledIfEnvironmentVariable(named = "CI", matches = "true") 7 | class SqliteTest : DatabaseTest() { 8 | init { 9 | configuration.apply { 10 | File("./example/sqlite.hibernate.properties").inputStream().use(properties::load) 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /example/mariadb.hibernate.properties: -------------------------------------------------------------------------------- 1 | hibernate.connection.url=jdbc:mariadb://localhost:3306/mirai?autoReconnect=true&allowPublicKeyRetrieval=true 2 | hibernate.connection.CharSet=utf8mb4 3 | hibernate.connection.useUnicode=true 4 | hibernate.connection.username=root 5 | hibernate.connection.password=root 6 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 7 | hibernate.connection.isolation=1 8 | hibernate.hbm2ddl.auto=update 9 | hibernate.autoReconnect=true -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/MSSqlTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import java.io.File 4 | 5 | class MSSqlTest : DatabaseTest() { 6 | init { 7 | configuration.apply { 8 | File("./example/sqlserver.hibernate.properties").inputStream().use(properties::load) 9 | 10 | if (System.getenv("CI") == "true") { 11 | setProperty("hibernate.connection.password", System.getenv("SQLCMDPASSWORD")) 12 | } 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /example/sqlserver.hibernate.properties: -------------------------------------------------------------------------------- 1 | # https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url 2 | hibernate.connection.url=jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databaseName=mirai;encrypt=true;trustServerCertificate=true 3 | hibernate.connection.username=sa 4 | hibernate.connection.password=root 5 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 6 | hibernate.connection.isolation=1 7 | hibernate.hbm2ddl.auto=update 8 | hibernate.autoReconnect=true 9 | hibernate.globally_quoted_identifiers=true -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/FaceTagRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | 6 | /** 7 | * 表情包标签记录 8 | * @param id 记录自增ID 9 | * @param md5 图片MD5, 同时用作外键关联 10 | * @param tag 标签 11 | */ 12 | @Entity 13 | @Table(name = "face_tag_record") 14 | @Serializable 15 | public data class FaceTagRecord( 16 | @Id 17 | @Column(name = "id", nullable = false, updatable = false) 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | val id: Long = 0, 20 | @Column(name = "md5", nullable = false, updatable = false, length = 32) 21 | public val md5: String, 22 | @Column(name = "tag", nullable = false, updatable = false, columnDefinition = "text") 23 | public val tag: String 24 | ) : java.io.Serializable -------------------------------------------------------------------------------- /src/test/java/xyz/cssxsh/mirai/test/entry/Work.java: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.test.entry; 2 | 3 | import jakarta.persistence.*; 4 | 5 | @Entity 6 | @Table(name = "work") 7 | public class Work { 8 | private Long pid; 9 | private String content; 10 | 11 | private User user; 12 | 13 | @Id 14 | public Long getPid() { 15 | return pid; 16 | } 17 | 18 | public void setPid(Long pid) { 19 | this.pid = pid; 20 | } 21 | 22 | public String getContent() { 23 | return content; 24 | } 25 | 26 | public void setContent(String content) { 27 | this.content = content; 28 | } 29 | 30 | @ManyToOne 31 | public User getUser() { 32 | return user; 33 | } 34 | 35 | public void setUser(User user) { 36 | this.user = user; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/xyz/cssxsh/mirai/test/entry/User.java: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.test.entry; 2 | 3 | import jakarta.persistence.*; 4 | 5 | import java.util.List; 6 | 7 | @Entity 8 | @Table(name = "user") 9 | public class User { 10 | @Id 11 | private Long id; 12 | 13 | private String name; 14 | 15 | @OneToMany(mappedBy = "user") 16 | private List works; 17 | 18 | public void setId(Long id) { 19 | this.id = id; 20 | } 21 | 22 | public Long getId() { 23 | return id; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | public List getWorks() { 34 | return works; 35 | } 36 | 37 | public void setWorks(List works) { this.works = works;} 38 | } 39 | -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/RecalledKind.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import kotlinx.serialization.* 4 | import kotlinx.serialization.descriptors.* 5 | import kotlinx.serialization.encoding.* 6 | 7 | /** 8 | * 撤回类型 9 | * @since 2.7 10 | */ 11 | public enum class RecalledKind { 12 | NONE, SEND_FAIL, SELF, ADMIN; 13 | 14 | public companion object Serializer : KSerializer { 15 | 16 | override val descriptor: SerialDescriptor = 17 | PrimitiveSerialDescriptor(this::class.qualifiedName!!, PrimitiveKind.INT) 18 | 19 | override fun deserialize(decoder: Decoder): RecalledKind { 20 | val index = decoder.decodeInt() 21 | return values().getOrNull(index) ?: SEND_FAIL 22 | } 23 | 24 | override fun serialize(encoder: Encoder, value: RecalledKind) { 25 | encoder.encodeInt(value.ordinal) 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /example/h2.web.md: -------------------------------------------------------------------------------- 1 | # 使用 WEB 管理 H2 中的数据 2 | 3 | ## 开启兼容模式 4 | 5 | > 如果你需要运行 Mirai 插件的同时在线编辑数据 6 | 7 | 编辑文件 `hibernate.properties` 的 `hibernate.connection.url`, 8 | 在 `hibernate.h2` 后面加上 `;AUTO_SERVER=TRUE` 9 | 10 | ## SHELL 启动WEB网页 11 | 12 | > 你可以使用成品启动脚本 [h2.web.cmd](h2.web.cmd) 13 | 14 | ```shell 15 | java -jar .\plugin-libraries\com\h2database\h2\2.1.214\h2-2.1.214.jar 16 | ``` 17 | 18 | **JDBC URL** 填上面提到的 `hibernate.connection.url` 的值 19 | `jdbc:h2:./data/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/hibernate.h2;AUTO_SERVER=TRUE` 20 | 21 | ## JAVA 启动WEB网页 22 | 23 | ```java 24 | import org.h2.tools.Console; 25 | 26 | public class H2Web { 27 | public static void run() { 28 | Console console = new Console(); 29 | // start 30 | console.runTool("-url", "jdbc:h2:./data/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/hibernate.h2;AUTO_SERVER=TRUE"); 31 | // stop 32 | console.shutdown(); 33 | } 34 | } 35 | ``` -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/hibernate/MacroSQLFunction.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.hibernate 2 | 3 | import org.hibernate.dialect.function.* 4 | import org.hibernate.query.ReturnableType 5 | import org.hibernate.sql.ast.SqlAstTranslator 6 | import org.hibernate.sql.ast.spi.SqlAppender 7 | import org.hibernate.sql.ast.tree.SqlAstNode 8 | import org.hibernate.type.* 9 | 10 | /** 11 | * 宏函数,通过构造宏来实现自定义的函数方法. 12 | * @param type 返回值类型,无返回值可以填 null, 13 | * @param macro 表达式构造 lambda 14 | * @since 2.3.3 15 | * @see addRandFunction 16 | * @see addDiceFunction 17 | */ 18 | public class MacroSQLFunction( 19 | type: BasicTypeReference<*>? = null, 20 | private val macro: SqlAppender.(List, SqlAstTranslator<*>) -> Unit 21 | ) : StandardSQLFunction("macro", false, type) { 22 | 23 | override fun render( 24 | sqlAppender: SqlAppender, 25 | sqlAstArguments: List, 26 | returnType: ReturnableType<*>, 27 | translator: SqlAstTranslator<*> 28 | ) { 29 | macro.invoke(sqlAppender, sqlAstArguments, translator) 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/GroupRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import net.mamoe.mirai.contact.* 6 | 7 | /** 8 | * 群记录 9 | * @param group 群ID 10 | * @param name 名字 11 | * @param owner 群主 12 | * @param disable 已封禁 13 | * @since 2.6.0 14 | */ 15 | @Entity 16 | @Table(name = "group_record") 17 | @Serializable 18 | public data class GroupRecord( 19 | @Id 20 | @Column(name = "group_id", nullable = false, updatable = false) 21 | val group: Long, 22 | @Column(name = "name", nullable = false) 23 | val name: String, 24 | @Column(name = "owner", nullable = false) 25 | val owner: Long, 26 | @Column(name = "disable", nullable = false) 27 | val disable: Boolean = false 28 | ) : java.io.Serializable { 29 | 30 | public companion object { 31 | /** 32 | * From Group Implement 33 | */ 34 | public fun fromImpl(group: Group): GroupRecord = GroupRecord( 35 | group = group.id, 36 | name = group.name, 37 | owner = group.owner.id 38 | ) 39 | } 40 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 2.9.0 (24/09/11) 2 | 3 | 1. update: h2 2.3.232 4 | 2. update: sqlite-jdbc 3.46.1.0 5 | 3. update: postgresql 42.7.4 6 | 4. update: mssql-jdbc 12.8.1.jre1 7 | 5. feat: MiraiH2 8 | 9 | ## 2.8.2 (24/08/11) 10 | 11 | 1. update: hibernate-platform 6.6.0.Final 12 | 2. update: h2 2.3.230 13 | 3. update: sqlite-jdbc 3.46.0.1 14 | 4. update: mysql-connector-j 9.0.0 15 | 5. update: mariadb-java-client 3.4.1 16 | 6. update: mssql-jdbc 12.8.0.jre11 17 | 18 | ## 2.8.1 (24/04/27) 19 | 20 | 1. update: hibernate-orm 6.4.8.Final 21 | 2. update: ci 22 | 3. update: jdbc driver 23 | 24 | ## 2.8.0 (24/01/23) 25 | 26 | 1. update: dependency 27 | 2. fix: face record tags 28 | 3. fix: face_tag_record foreignKey 29 | 4. fix: epoch second 30 | 5. feat: handle database file backup 31 | 32 | ## 2.7.1 (23/03/05) 33 | 34 | 1. fix: nudge record 35 | 36 | ## 2.7.0 (23/03/05) 37 | 38 | 1. feat: RecalledKind 39 | 2. feat: MariaDB 40 | 41 | ## 2.7.0-RC (23/02/24) 42 | 43 | 1. feat `backup`/`restore` 支持 44 | 2. update: `hibernate` version 6.1.7.Final 45 | 3. feat: `MessageRecord.name` 46 | 4. fix: recall info 47 | 5. update: `org.xerial:sqlite-jdbc` version 3.41.0.0 48 | 6. update: `org.postgresql:postgresql` version 42.5.4 -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/BotRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import net.mamoe.mirai.* 6 | import java.time.* 7 | 8 | /** 9 | * 机器人记录 10 | * @param bot Bot ID 11 | * @param name 名字 12 | * @param init 启用时间戳 13 | * @param latest 最晚(登录/下线)时间戳 14 | * @since 2.6.0 15 | */ 16 | @Entity 17 | @Table(name = "bot_record") 18 | @Serializable 19 | public data class BotRecord( 20 | @Id 21 | @Column(name = "bot_id", nullable = false, updatable = false) 22 | val bot: Long, 23 | @Column(name = "name", nullable = false) 24 | val name: String, 25 | @Column(name = "init_time", nullable = false, updatable = false) 26 | val init: Long, 27 | @Column(name = "latest", nullable = false) 28 | val latest: Long 29 | ) : java.io.Serializable { 30 | 31 | public companion object { 32 | /** 33 | * From Bot Implement 34 | */ 35 | public fun fromImpl(bot: Bot): BotRecord = BotRecord( 36 | bot = bot.id, 37 | name = bot.nick, 38 | init = Instant.now().epochSecond, 39 | latest = Instant.now().epochSecond 40 | ) 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/FriendIndex.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import kotlinx.serialization.descriptors.* 6 | import kotlinx.serialization.encoding.* 7 | 8 | /** 9 | * 好友索引 10 | * @param bot 机器人ID 11 | * @param uid 好友ID 12 | * @since 2.5.0 13 | */ 14 | @Embeddable 15 | @Serializable(FriendIndex.Companion::class) 16 | public data class FriendIndex( 17 | @Column(name = "bot", nullable = false, updatable = false) 18 | val bot: Long, 19 | @Column(name = "uid", nullable = false, updatable = false) 20 | val uid: Long 21 | ) : java.io.Serializable { 22 | internal companion object : KSerializer { 23 | override val descriptor: SerialDescriptor = 24 | PrimitiveSerialDescriptor(FriendIndex::class.qualifiedName!!, PrimitiveKind.STRING) 25 | 26 | override fun deserialize(decoder: Decoder): FriendIndex { 27 | val uuid = decoder.decodeString() 28 | val (bot, uid) = uuid.split(".") 29 | return FriendIndex( 30 | bot = bot.toLong(), 31 | uid = uid.toLong() 32 | ) 33 | } 34 | 35 | override fun serialize(encoder: Encoder, value: FriendIndex) { 36 | encoder.encodeString("${value.bot}.${value.uid}") 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/GroupMemberIndex.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import kotlinx.serialization.descriptors.* 6 | import kotlinx.serialization.encoding.* 7 | 8 | /** 9 | * 群成员索引 10 | * @param group 群ID 11 | * @param uid 好友ID 12 | * @since 2.5.0 13 | */ 14 | @Embeddable 15 | @Serializable(GroupMemberIndex.Companion::class) 16 | public data class GroupMemberIndex( 17 | @Column(name = "group_id", nullable = false, updatable = false) 18 | val group: Long, 19 | @Column(name = "uid", nullable = false, updatable = false) 20 | val uid: Long 21 | ) : java.io.Serializable { 22 | internal companion object : KSerializer { 23 | override val descriptor: SerialDescriptor = 24 | PrimitiveSerialDescriptor(FriendIndex::class.qualifiedName!!, PrimitiveKind.STRING) 25 | 26 | override fun deserialize(decoder: Decoder): GroupMemberIndex { 27 | val uuid = decoder.decodeString() 28 | val (bot, uid) = uuid.split(".") 29 | return GroupMemberIndex( 30 | group = bot.toLong(), 31 | uid = uid.toLong() 32 | ) 33 | } 34 | 35 | override fun serialize(encoder: Encoder, value: GroupMemberIndex) { 36 | encoder.encodeString("${value.group}.${value.uid}") 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /example/h2.web.cmd: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal 3 | set JAVA_BINARY="java" 4 | if exist "java" set JAVA_BINARY=".\java\bin\java.exe" 5 | if exist "java-home" set JAVA_BINARY=".\java-home\bin\java.exe" 6 | if exist "jdk-17.0.7+7" set JAVA_BINARY=".\jdk-17.0.7+7\bin\java.exe" 7 | if exist "jdk-17.0.7+7-jre" set JAVA_BINARY=".\jdk-17.0.7+7-jre\bin\java.exe" 8 | if exist "jdk-17.0.8+7" set JAVA_BINARY=".\jdk-17.0.8+7\bin\java.exe" 9 | if exist "jdk-17.0.8+7-jre" set JAVA_BINARY=".\jdk-17.0.8+7-jre\bin\java.exe" 10 | 11 | set H2_JAR="h2-2.2.222.jar" 12 | if exist ".\plugin-libraries\com\h2database\h2\2.1.214\h2-2.1.214.jar" set H2_JAR=".\plugin-libraries\com\h2database\h2\2.1.214\h2-2.1.214.jar" 13 | if exist ".\plugin-libraries\com\h2database\h2\2.2.222\h2-2.2.222.jar" set H2_JAR=".\plugin-libraries\com\h2database\h2\2.2.222\h2-2.2.222.jar" 14 | if exist ".\plugin-libraries\com\h2database\h2\2.2.224\h2-2.2.224.jar" set H2_JAR=".\plugin-libraries\com\h2database\h2\2.2.224\h2-2.2.224.jar" 15 | if exist ".\plugin-libraries\com\h2database\h2\2.3.230\h2-2.3.230.jar" set H2_JAR=".\plugin-libraries\com\h2database\h2\2.3.230\h2-2.3.230.jar" 16 | if exist ".\plugin-libraries\com\h2database\h2\2.3.232\h2-2.3.232.jar" set H2_JAR=".\plugin-libraries\com\h2database\h2\2.3.232\h2-2.3.232.jar" 17 | 18 | %JAVA_BINARY% -version 19 | %JAVA_BINARY% -jar %H2_JAR% -url jdbc:h2:./data/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/hibernate.h2;AUTO_SERVER=TRUE %* 20 | 21 | set EL=%ERRORLEVEL% 22 | if %EL% NEQ 0 ( 23 | echo Process exited with %EL% 24 | pause 25 | ) -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiH2.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate 2 | 3 | import kotlinx.coroutines.* 4 | import net.mamoe.mirai.console.events.* 5 | import net.mamoe.mirai.event.* 6 | import net.mamoe.mirai.utils.* 7 | import org.h2.jdbc.* 8 | import org.h2.server.web.* 9 | import org.h2.tools.* 10 | import org.hibernate.* 11 | import java.sql.* 12 | import kotlin.coroutines.* 13 | 14 | /** 15 | * H2 相关操作 16 | * @since 2.9.0 17 | */ 18 | public object MiraiH2 : SimpleListenerHost() { 19 | 20 | override fun handleException(context: CoroutineContext, exception: Throwable) { 21 | when (exception) { 22 | is ExceptionInEventHandlerException -> { 23 | logger.warning({ "Exception in H2" }, exception.cause) 24 | } 25 | else -> { 26 | logger.warning({ "Exception in H2" }, exception) 27 | } 28 | } 29 | } 30 | 31 | private val web = WebServer() 32 | 33 | /** 34 | * 创建一个 H2 网络会话 35 | * @return URL 36 | * @exception SQLException 37 | */ 38 | public fun url(session: Session): String { 39 | return session.doReturningWork { wrapper -> 40 | val connection = wrapper.unwrap(JdbcConnection::class.java) 41 | web.addSession(connection) 42 | } 43 | } 44 | 45 | @EventHandler 46 | internal fun ConsoleEvent.handle() { 47 | if (this !is StartupEvent) return 48 | web.init("-webPort", System.getProperty("h2.web.port", "0")) 49 | web.start() 50 | launch { 51 | web.listen() 52 | } 53 | 54 | launch { 55 | while (web.isRunning(false).not()) { 56 | delay(timeMillis = 10_000) 57 | } 58 | val url = try { 59 | factory.fromSession { url(session = it) } 60 | } catch (_: SQLException) { 61 | return@launch 62 | } 63 | logger.info(message = "h2database editor $url") 64 | if (System.getProperty("h2.web.browser", "false").toBoolean()) { 65 | Server.openBrowser(url) 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/spi/MiraiHibernateSourceHandler.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.spi 2 | 3 | import net.mamoe.mirai.contact.* 4 | import net.mamoe.mirai.event.events.* 5 | import net.mamoe.mirai.message.data.* 6 | import xyz.cssxsh.mirai.hibernate.* 7 | import xyz.cssxsh.mirai.spi.* 8 | import kotlin.streams.asSequence 9 | 10 | /** 11 | * 为 mirai-administrator 实现的消息记录 12 | * @see xyz.cssxsh.mirai.admin.from 13 | * @see xyz.cssxsh.mirai.admin.quote 14 | * @see xyz.cssxsh.mirai.admin.target 15 | */ 16 | public class MiraiHibernateSourceHandler : MessageSourceHandler { 17 | override val id: String = "hibernate-recorder" 18 | override val level: Int by lazy { System.getProperty("xyz.cssxsh.mirai.hibernate.recorder", "10").toInt() } 19 | 20 | @Deprecated(message = "兼容性实现", replaceWith = ReplaceWith("null")) 21 | override fun find(contact: Contact?, event: MessageEvent?): MessageSource? { 22 | return when { 23 | contact is Member -> from(member = contact) 24 | contact != null -> target(contact = contact) 25 | event != null -> quote(event = event) 26 | else -> null 27 | } 28 | } 29 | 30 | override fun from(member: Member): MessageSource? { 31 | return MiraiHibernateRecorder[member].use { stream -> 32 | stream.asSequence().find { !it.recall }?.toMessageSource() 33 | } 34 | } 35 | 36 | override fun target(contact: Contact): MessageSource? { 37 | return MiraiHibernateRecorder[contact].use { stream -> 38 | stream.asSequence().find { !it.recall && it.bot == it.fromId }?.toMessageSource() 39 | } 40 | } 41 | 42 | override fun quote(event: MessageEvent): MessageSource? { 43 | val quote = event.message.findIsInstance() 44 | return if (quote != null) { 45 | MiraiHibernateRecorder[quote.source].find { !it.recall }?.toMessageSource() 46 | } else { 47 | MiraiHibernateRecorder[event.subject].use { stream -> 48 | stream.asSequence().find { !it.recall && it.fromId != event.sender.id }?.toMessageSource() 49 | } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/test/MiraiHibernatePluginTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.test 2 | 3 | import net.mamoe.mirai.console.plugin.jvm.* 4 | import net.mamoe.mirai.event.* 5 | import org.hibernate.* 6 | import xyz.cssxsh.mirai.hibernate.* 7 | 8 | object MiraiHibernatePluginTest : KotlinPlugin( 9 | JvmPluginDescription( 10 | id = "xyz.cssxsh.mirai.plugin.mirai-hibernate-text", 11 | name = "mirai-hibernate-test", 12 | version = "0.0.0" 13 | ) { 14 | dependsOn("xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin", false) 15 | } 16 | ) { 17 | 18 | private lateinit var factory: SessionFactory 19 | 20 | override fun onEnable() { 21 | factory = MiraiHibernateConfiguration(plugin = this).buildSessionFactory() 22 | val metadata = factory.fromSession { session -> 23 | session.doReturningWork { connection -> connection.metaData } 24 | } 25 | 26 | println(metadata.driverName) 27 | 28 | // MiraiHibernateRecorder 的使用 29 | globalEventChannel().subscribeMessages { 30 | startsWith("record") { 31 | // 返回一个流,请记得关闭这个流 32 | MiraiHibernateRecorder[subject].use { steam -> 33 | steam.forEach { record -> 34 | // 转化成消息链 35 | record.toMessageChain() 36 | 37 | // 转化消息引用 38 | // 这里的 originalMessage 来自 上面的 toMessageChain 39 | record.toMessageSource().originalMessage 40 | } 41 | } 42 | 43 | // 返回一个列表,第 2,3 参数是 开始时刻和结束时间 44 | MiraiHibernateRecorder[subject, 16000000, 160000001].forEach { record -> 45 | // 转化成消息链 46 | record.toMessageChain() 47 | // 转化消息引用 48 | // 这里的 originalMessage 来自 上面的 toMessageChain 49 | record.toMessageSource().originalMessage 50 | } 51 | } 52 | } 53 | 54 | // MiraiH2 的使用 55 | val url = factory.fromSession { session -> 56 | MiraiH2.url(session = session) 57 | } 58 | 59 | println(url) 60 | } 61 | 62 | override fun onDisable() { 63 | factory.close() 64 | } 65 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # User-specific stuff 2 | .idea/ 3 | 4 | *.iml 5 | *.ipr 6 | *.iws 7 | 8 | # IntelliJ 9 | out/ 10 | # mpeltonen/sbt-idea plugin 11 | .idea_modules/ 12 | 13 | # JIRA plugin 14 | atlassian-ide-plugin.xml 15 | 16 | # Compiled class file 17 | *.class 18 | 19 | # Log file 20 | *.log 21 | 22 | # BlueJ files 23 | *.ctxt 24 | 25 | # Package Files # 26 | *.jar 27 | *.war 28 | *.nar 29 | *.ear 30 | *.zip 31 | *.tar.gz 32 | *.rar 33 | 34 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 35 | hs_err_pid* 36 | 37 | *~ 38 | 39 | # temporary files which can be created if a process still has a handle open of a deleted file 40 | .fuse_hidden* 41 | 42 | # KDE directory preferences 43 | .directory 44 | 45 | # Linux trash folder which might appear on any partition or disk 46 | .Trash-* 47 | 48 | # .nfs files are created when an open file is removed but is still being accessed 49 | .nfs* 50 | 51 | # General 52 | .DS_Store 53 | .AppleDouble 54 | .LSOverride 55 | 56 | # Icon must end with two \r 57 | Icon 58 | 59 | # Thumbnails 60 | ._* 61 | 62 | # Files that might appear in the root of a volume 63 | .DocumentRevisions-V100 64 | .fseventsd 65 | .Spotlight-V100 66 | .TemporaryItems 67 | .Trashes 68 | .VolumeIcon.icns 69 | .com.apple.timemachine.donotpresent 70 | 71 | # Directories potentially created on remote AFP share 72 | .AppleDB 73 | .AppleDesktop 74 | Network Trash Folder 75 | Temporary Items 76 | .apdisk 77 | 78 | # Windows thumbnail cache files 79 | Thumbs.db 80 | Thumbs.db:encryptable 81 | ehthumbs.db 82 | ehthumbs_vista.db 83 | 84 | # Dump file 85 | *.stackdump 86 | 87 | # Folder config file 88 | [Dd]esktop.ini 89 | 90 | # Recycle Bin used on file shares 91 | $RECYCLE.BIN/ 92 | 93 | # Windows Installer files 94 | *.cab 95 | *.msi 96 | *.msix 97 | *.msm 98 | *.msp 99 | 100 | # Windows shortcuts 101 | *.lnk 102 | 103 | .gradle 104 | build/ 105 | 106 | # Ignore Gradle GUI config 107 | gradle-app.setting 108 | 109 | # Cache of project 110 | .gradletasknamecache 111 | 112 | **/build/ 113 | 114 | # Common working directory 115 | run/ 116 | 117 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 118 | !gradle-wrapper.jar 119 | 120 | # Local Test Launch point 121 | debug-sandbox 122 | 123 | # test data 124 | data 125 | -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/FriendRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import net.mamoe.mirai.contact.* 6 | import net.mamoe.mirai.event.events.* 7 | import java.time.* 8 | 9 | /** 10 | * 好友记录 11 | * @param uuid 好友索引 12 | * @param remark 备注 13 | * @param category 好友分组 14 | * @param added 添加时间戳 15 | * @param deleted 删除时间戳 16 | * @since 2.5.0 17 | */ 18 | @Entity 19 | @Table(name = "friend_record") 20 | @Serializable 21 | public data class FriendRecord( 22 | @EmbeddedId 23 | val uuid: FriendIndex, 24 | @Column(name = "remark", nullable = false) 25 | val remark: String, 26 | @Column(name = "category", nullable = false) 27 | val category: String, 28 | @Column(name = "added", nullable = false, updatable = false) 29 | val added: Long, 30 | @Column(name = "deleted", nullable = false) 31 | val deleted: Long 32 | ) : java.io.Serializable { 33 | 34 | public companion object { 35 | /** 36 | * From Friend Event 37 | */ 38 | public fun fromEvent(event: FriendEvent): FriendRecord = FriendRecord( 39 | uuid = FriendIndex(bot = event.bot.id, uid = event.friend.id), 40 | remark = event.friend.remarkOrNick, 41 | category = try { 42 | event.friend.friendGroup.name 43 | } catch (_: NoSuchMethodError) { 44 | "我的好友" 45 | } catch (_: NullPointerException) { 46 | "我的好友" 47 | }, 48 | added = if (event is FriendAddEvent) Instant.now().epochSecond else Instant.MIN.epochSecond, 49 | deleted = if (event is FriendDeleteEvent) Instant.now().epochSecond else Instant.MAX.epochSecond, 50 | ) 51 | 52 | /** 53 | * From Friend Implement 54 | */ 55 | public fun fromImpl(friend: Friend): FriendRecord = FriendRecord( 56 | uuid = FriendIndex(bot = friend.bot.id, uid = friend.id), 57 | remark = friend.remarkOrNick, 58 | category = try { 59 | friend.friendGroup.name 60 | } catch (_: NoSuchMethodError) { 61 | "我的好友" 62 | } catch (_: NullPointerException) { 63 | "我的好友" 64 | }, 65 | added = Instant.MIN.epochSecond, 66 | deleted = Instant.MAX.epochSecond, 67 | ) 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/NudgeRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import net.mamoe.mirai.contact.* 6 | import net.mamoe.mirai.event.events.* 7 | import net.mamoe.mirai.message.data.* 8 | 9 | /** 10 | * 戳一戳记录 11 | * @param id 记录自增ID 12 | * @param bot 机器人ID 13 | * @param time Unix时间戳,秒单位 14 | * @param fromId 起始用户ID 15 | * @param targetId 目标用户ID 16 | * @param kind 消息类型 17 | * @param subject 会话所在ID 18 | * @param action 戳一戳 `行为` 19 | * @param suffix 戳一戳 `后缀` 20 | * @param recalled 撤销者 21 | * @property recall 已撤销 22 | */ 23 | @Entity 24 | @Table(name = "nudge_record") 25 | @Serializable 26 | public data class NudgeRecord( 27 | @Id 28 | @Column(name = "id", nullable = false, updatable = false) 29 | @GeneratedValue(strategy = GenerationType.IDENTITY) 30 | val id: Long = 0, 31 | @Column(name = "bot", nullable = false, updatable = false) 32 | val bot: Long, 33 | @Column(name = "time", nullable = false, updatable = false) 34 | val time: Int, 35 | @Column(name = "from_id", nullable = false, updatable = false) 36 | val fromId: Long, 37 | @Column(name = "target_id", nullable = false, updatable = false) 38 | val targetId: Long, 39 | @Column(name = "kind", nullable = false, updatable = false) 40 | @Enumerated(value = EnumType.ORDINAL) 41 | val kind: MessageSourceKind, 42 | @Column(name = "subject", nullable = false, updatable = false) 43 | val subject: Long, 44 | @Column(name = "action", nullable = false, updatable = false) 45 | val action: String, 46 | @Column(name = "suffix", nullable = false, updatable = false) 47 | val suffix: String, 48 | @Column(name = "recall", nullable = false) 49 | @Serializable(RecalledKind.Serializer::class) 50 | @Enumerated(value = EnumType.ORDINAL) 51 | @org.hibernate.annotations.ColumnDefault("0") 52 | val recalled: RecalledKind = RecalledKind.NONE 53 | ) : java.io.Serializable { 54 | public constructor(event: NudgeEvent, time: Int = (System.currentTimeMillis() / 1000).toInt()) : this( 55 | bot = event.bot.id, 56 | time = time, 57 | fromId = event.from.id, 58 | targetId = event.target.id, 59 | kind = when (event.subject) { 60 | is Group -> MessageSourceKind.GROUP 61 | is Friend -> MessageSourceKind.FRIEND 62 | is Member -> MessageSourceKind.TEMP 63 | is Stranger -> MessageSourceKind.STRANGER 64 | else -> throw NoSuchElementException("Nudge kind with ${event.subject}") 65 | }, 66 | subject = event.subject.id, 67 | action = event.action, 68 | suffix = event.suffix 69 | ) 70 | 71 | @get:jakarta.persistence.Transient 72 | public val recall: Boolean get() = recalled != RecalledKind.NONE 73 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/GroupMemberRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import net.mamoe.mirai.contact.* 6 | import net.mamoe.mirai.event.events.* 7 | import java.time.* 8 | 9 | /** 10 | * 群成员记录 11 | * @param uuid 好友索引 12 | * @param permission 权限 13 | * @param name 名字 14 | * @param title 头衔 15 | * @param joined 加入时间戳 16 | * @param last 最后发言时间戳 17 | * @param active 活跃度 18 | * @param exited 退出时间戳 19 | * @since 2.5.0 20 | */ 21 | @Entity 22 | @Table(name = "group_member_record") 23 | @Serializable 24 | public data class GroupMemberRecord( 25 | @EmbeddedId 26 | val uuid: GroupMemberIndex, 27 | @Column(name = "permission", nullable = false) 28 | @Enumerated(value = EnumType.ORDINAL) 29 | val permission: MemberPermission = MemberPermission.MEMBER, 30 | @Column(name = "name", nullable = false) 31 | val name: String, 32 | @Column(name = "title", nullable = false) 33 | val title: String, 34 | @Column(name = "joined", nullable = false, updatable = false) 35 | val joined: Long, 36 | @Column(name = "last", nullable = false) 37 | val last: Long, 38 | @Column(name = "active", nullable = false) 39 | val active: Int, 40 | @Column(name = "exited", nullable = false) 41 | val exited: Long 42 | ) : java.io.Serializable { 43 | 44 | public companion object { 45 | /** 46 | * From Group Member Event 47 | */ 48 | public fun fromEvent(event: GroupMemberEvent): GroupMemberRecord = GroupMemberRecord( 49 | uuid = GroupMemberIndex(group = event.group.id, uid = event.member.id), 50 | permission = event.member.permission, 51 | name = (event.member as NormalMember).nameCardOrNick, 52 | title = (event.member as NormalMember).specialTitle, 53 | joined = (event.member as NormalMember).joinTimestamp.toLong(), 54 | last = (event.member as NormalMember).lastSpeakTimestamp.toLong(), 55 | active = try { 56 | event.member.active.temperature 57 | } catch (_: NoSuchMethodError) { 58 | 0 59 | }, 60 | exited = when (event) { 61 | is MemberLeaveEvent -> Instant.now().epochSecond 62 | else -> Instant.MAX.epochSecond 63 | } 64 | ) 65 | 66 | /** 67 | * From Normal Member Implement 68 | */ 69 | public fun fromImpl(member: NormalMember): GroupMemberRecord = GroupMemberRecord( 70 | uuid = GroupMemberIndex(group = member.group.id, uid = member.id), 71 | permission = member.permission, 72 | name = member.nameCardOrNick, 73 | title = member.specialTitle, 74 | joined = member.joinTimestamp.toLong(), 75 | last = member.lastSpeakTimestamp.toLong(), 76 | active = try { 77 | member.active.temperature 78 | } catch (_: NoSuchMethodError) { 79 | 0 80 | }, 81 | exited = Instant.MAX.epochSecond 82 | ) 83 | } 84 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateLoader.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate 2 | 3 | import net.mamoe.mirai.console.plugin.* 4 | import net.mamoe.mirai.console.plugin.jvm.* 5 | import java.io.* 6 | import java.sql.* 7 | 8 | /** 9 | * 加载和配置 Hibernate 10 | */ 11 | public interface MiraiHibernateLoader { 12 | /** 13 | * 是否自动扫描已标记注解的类 14 | */ 15 | public val autoScan: Boolean 16 | 17 | /** 18 | * 自动扫描 的 起始包 19 | */ 20 | public val packageName: String 21 | 22 | /** 23 | * 自动扫描 的 类加载器 24 | */ 25 | public val classLoader: ClassLoader 26 | 27 | /** 28 | * 文件 29 | */ 30 | public val configuration: File 31 | 32 | /** 33 | * 默认配置 34 | */ 35 | public val default: String 36 | 37 | public companion object { 38 | /** 39 | * 根据 [plugin] 创建 MiraiHibernateLoader 40 | * @see Impl 41 | */ 42 | @JvmStatic 43 | public operator fun invoke(plugin: JvmPlugin): MiraiHibernateLoader = Impl(plugin = plugin) 44 | 45 | private fun PluginFileExtensions.path(filename: String): String { 46 | return try { 47 | resolveDataFile(filename).toURI().schemeSpecificPart 48 | .removePrefix(File(".").normalize().toURI().schemeSpecificPart) 49 | .prependIndent("./") 50 | } catch (_: Exception) { 51 | filename 52 | } 53 | } 54 | } 55 | 56 | /** 57 | * 简单的实现 58 | */ 59 | public data class Impl( 60 | override val autoScan: Boolean, 61 | override val packageName: String, 62 | override val classLoader: ClassLoader, 63 | override val configuration: File, 64 | override val default: String 65 | ) : MiraiHibernateLoader { 66 | public constructor(plugin: PluginFileExtensions) : this( 67 | autoScan = true, 68 | packageName = with(plugin::class.java) { 69 | val packagePath = packageName.replace('.', '/') 70 | for (name in listOf("entry", "entity", "entities", "model", "models", "bean", "beans", "dto")) { 71 | classLoader.getResource("$packagePath/$name") ?: continue 72 | return@with "$packageName.$name" 73 | } 74 | packageName 75 | }, 76 | classLoader = plugin::class.java.classLoader, 77 | configuration = plugin.configFolder.resolve("hibernate.properties"), 78 | default = """ 79 | hibernate.connection.url=jdbc:h2:file:${plugin.path("hibernate.h2")} 80 | hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider 81 | hibernate.hikari.connectionTimeout=180000 82 | hibernate.connection.isolation=${Connection.TRANSACTION_READ_UNCOMMITTED} 83 | hibernate.hbm2ddl.auto=update 84 | hibernate-connection-autocommit=${true} 85 | hibernate.connection.show_sql=${false} 86 | hibernate.autoReconnect=${true} 87 | """.trimIndent() 88 | ) 89 | } 90 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/FaceRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.coroutines.* 5 | import kotlinx.serialization.* 6 | import kotlinx.serialization.json.* 7 | import net.mamoe.mirai.internal.message.data.* 8 | import net.mamoe.mirai.internal.message.image.* 9 | import net.mamoe.mirai.message.* 10 | import net.mamoe.mirai.message.data.* 11 | import net.mamoe.mirai.message.data.Image.Key.queryUrl 12 | import net.mamoe.mirai.utils.* 13 | 14 | /** 15 | * 表情包记录 16 | * @param md5 图片MD5, 同时用作ID 17 | * @param code 消息内容,JSON序列 18 | * @param content 图片代替文本 19 | * @param url 图片URL 20 | * @param height 图片高 21 | * @param width 图片宽 22 | * @param disable 禁用 23 | */ 24 | @Entity 25 | @Table(name = "face_record") 26 | @Serializable 27 | public data class FaceRecord( 28 | @Id 29 | @Column(name = "md5", nullable = false, updatable = false, length = 32) 30 | public val md5: String, 31 | @Column(name = "code", nullable = false, columnDefinition = "text") 32 | public val code: String, 33 | @Column(name = "content", nullable = false) 34 | public val content: String, 35 | @Column(name = "url", nullable = false) 36 | public val url: String, 37 | @Column(name = "height", nullable = false) 38 | public val height: Int, 39 | @Column(name = "width", nullable = false) 40 | public val width: Int, 41 | @Column(name = "disable", nullable = false, updatable = false) 42 | public val disable: Boolean = false 43 | ) : java.io.Serializable { 44 | 45 | /** 46 | * 表情包标签记录集 47 | * @see md5 48 | */ 49 | @OneToMany(orphanRemoval = true) 50 | @JoinColumn( 51 | name = "md5", 52 | referencedColumnName = "md5", 53 | updatable = false, 54 | foreignKey = ForeignKey(ConstraintMode.NO_CONSTRAINT) 55 | ) 56 | @kotlinx.serialization.Transient 57 | public val tags: List = emptyList() 58 | 59 | /** 60 | * [FaceRecord.code] 解码 61 | * @see code 62 | */ 63 | public fun toMessageContent(): MessageContent = json.decodeFromString(serializer, code) 64 | 65 | public companion object { 66 | private val json = Json { 67 | serializersModule = MessageSerializers.serializersModule 68 | ignoreUnknownKeys = true 69 | } 70 | private val serializer = PolymorphicSerializer(MessageContent::class) 71 | 72 | /** 73 | * from [OnlineImage.isEmoji] 74 | */ 75 | public fun fromImage(image: Image): FaceRecord { 76 | return FaceRecord( 77 | md5 = image.md5.toUHexString("").lowercase(), 78 | code = json.encodeToString(serializer, image), 79 | content = image.contentToString(), 80 | height = image.height, 81 | width = image.width, 82 | url = runBlocking { image.queryUrl() } 83 | ) 84 | } 85 | 86 | /** 87 | * from [MarketFaceImpl] 88 | */ 89 | @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") 90 | public fun fromMarketFace(face: MarketFace): FaceRecord { 91 | val delegate = try { 92 | (face as MarketFaceImpl).delegate 93 | } catch (_: Throwable) { 94 | face::class.java.getDeclaredField("delegate") 95 | .get(face).cast() 96 | } 97 | val md5 = delegate.faceId.toUHexString("").lowercase() 98 | val size = if (delegate.tabId < 10_0000) 200 else 300 99 | val url = when (delegate.subType) { 100 | 1 -> "https://gxh.vip.qq.com/club/item/parcel/item/${md5.substring(0, 2)}/$md5/raw${size}.gif" 101 | 2 -> "https://gxh.vip.qq.com/club/item/parcel/item/${md5.substring(0, 2)}/$md5/raw${size}.png" 102 | 3 -> "https://gxh.vip.qq.com/club/item/parcel/item/${md5.substring(0, 2)}/$md5/raw${size}.gif" 103 | else -> "https://gxh.vip.qq.com/club/item/parcel/item/${md5.substring(0, 2)}/$md5/${size}x${size}.png" 104 | } 105 | return FaceRecord( 106 | md5 = md5, 107 | code = json.encodeToString(serializer, face), 108 | height = delegate.imageHeight, 109 | width = delegate.imageWidth, 110 | content = face.name, 111 | url = url 112 | ) 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernatePlugin.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate 2 | 3 | import kotlinx.coroutines.* 4 | import net.mamoe.mirai.console.extension.* 5 | import net.mamoe.mirai.console.plugin.* 6 | import net.mamoe.mirai.console.plugin.jvm.* 7 | import net.mamoe.mirai.event.* 8 | import net.mamoe.mirai.utils.* 9 | import xyz.cssxsh.hibernate.* 10 | import java.util.* 11 | 12 | @PublishedApi 13 | internal object MiraiHibernatePlugin : KotlinPlugin( 14 | JvmPluginDescription( 15 | id = "xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin", 16 | name = "mirai-hibernate-plugin", 17 | version = "2.9.0" 18 | ) { 19 | author("cssxsh") 20 | 21 | dependsOn("xyz.cssxsh.mirai.plugin.mirai-administrator", ">= 1.1.0", true) 22 | } 23 | ) { 24 | 25 | override fun PluginComponentStorage.onLoad() { 26 | checkPlatform(folder = dataFolder) 27 | jvmPluginClasspath.runCatching { 28 | downloadAndAddToPath( 29 | classLoader = pluginSharedLibrariesClassLoader, 30 | dependencies = listOf(mssql()) 31 | ) 32 | }.onFailure { cause -> 33 | logger.warning({ "添加 MSSQL 驱动失败" }, cause) 34 | } 35 | ServiceLoader.load(java.sql.Driver::class.java, jvmPluginClasspath.pluginClassLoader) 36 | .forEach { driver -> 37 | logger.info { "Driver: ${driver::class.java.name} Version ${driver.majorVersion}.${driver.minorVersion}" } 38 | } 39 | } 40 | 41 | override fun onEnable() { 42 | 43 | val configuration = MiraiHibernateConfiguration(plugin = this) 44 | 45 | with(configuration) { 46 | val url = getProperty("hibernate.connection.url").orEmpty() 47 | if (url.startsWith("jdbc:sqlite")) { 48 | logger.error { "Sqlite 不支持并发, 将替换为 H2Database" } 49 | setProperty("hibernate.connection.url", url.replace("sqlite", "h2")) 50 | setProperty("hibernate.connection.driver_class", "org.h2.Driver") 51 | setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect") 52 | setProperty("hibernate.hikari.minimumIdle", "10") 53 | setProperty("hibernate.hikari.maximumPoolSize", "10") 54 | } 55 | } 56 | 57 | try { 58 | factory = configuration.buildSessionFactory() 59 | } catch (exception: Exception) { 60 | if ("Unsupported database file version" in exception.message.orEmpty()) { 61 | val current = System.currentTimeMillis() 62 | resolveDataFile("hibernate.h2.mv.db") 63 | .renameTo(resolveDataFile("backup.$current.h2.mv.db")) 64 | resolveDataFile("hibernate.h2.trace.db") 65 | .renameTo(resolveDataFile("backup.$current.h2.trace.db")) 66 | throw RuntimeException("本地文件和数据库版本不匹配,已备份,请重新启动", exception) 67 | } 68 | if ("password" in exception.message.orEmpty()) { 69 | throw RuntimeException( 70 | "配置错误:\n ${configuration.loader.configuration.toPath().toUri()}\"", 71 | exception 72 | ) 73 | } 74 | throw exception 75 | } 76 | 77 | val metadata = factory.fromSession { it.getDatabaseMetaData() } 78 | 79 | logger.info { "Database ${metadata.url} by ${metadata.driverName}." } 80 | logger.info { "如果你想使用其他类型的数据库,请自行修改:\n ${configuration.loader.configuration.toPath().toUri()}" } 81 | 82 | val backup = resolveConfigFile("hibernate.backup.properties") 83 | if (backup.exists()) { 84 | logger.info("发现备份配置,开始载入备份") 85 | launch { 86 | val properties = Properties() 87 | backup.inputStream().use(properties::load) 88 | configuration.restore(properties) 89 | } 90 | } 91 | 92 | for (plugin in PluginManager.plugins) { 93 | if (plugin !is JvmPlugin) continue 94 | when (plugin.description.id) { 95 | "net.mamoe.mirai-api-http" -> { 96 | logger.info { "如果要使用 mirai-hibernate-plugin 为 mirai-api-http 提供消息持久化, 请安装 https://github.com/cssxsh/mirai-hibernate-http " } 97 | } 98 | "com.github.yyuueexxiinngg.onebot" -> continue 99 | else -> continue 100 | } 101 | } 102 | 103 | MiraiH2.registerTo(globalEventChannel()) 104 | MiraiHibernateRecorder.registerTo(globalEventChannel()) 105 | } 106 | 107 | override fun onDisable() { 108 | MiraiHibernateRecorder.cancel() 109 | MiraiH2.cancel() 110 | factory.close() 111 | } 112 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Mirai Hibernate Plugin](https://github.com/cssxsh/mirai-hibernate-plugin) 2 | 3 | > Mirai Hibernate 前置插件 4 | 5 | [Mirai Console](https://github.com/mamoe/mirai-console) 的前置插件,用于 Hibernate ORM 框架的初始化 6 | 7 | [![maven-central](https://img.shields.io/maven-central/v/xyz.cssxsh.mirai/mirai-hibernate-plugin)](https://search.maven.org/artifact/xyz.cssxsh.mirai/mirai-hibernate-plugin) 8 | [![Database Test](https://github.com/cssxsh/mirai-hibernate-plugin/actions/workflows/test.yml/badge.svg)](https://github.com/cssxsh/mirai-hibernate-plugin/actions/workflows/test.yml) 9 | [![Codacy Badge](https://app.codacy.com/project/badge/Grade/f82572fd42324ce19df9d1639250127d)](https://www.codacy.com/gh/cssxsh/mirai-hibernate-plugin/dashboard?utm_source=github.com&utm_medium=referral&utm_content=cssxsh/mirai-hibernate-plugin&utm_campaign=Badge_Grade) 10 | 11 | 插件自带聊天记录器 [MiraiHibernateRecorder](src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateLoader.kt), 12 | 会记录 `群聊/私聊` 的内容到数据库方便其他插件使用,默认是 `h2database` 数据库(since `2.2.0+`) 13 | 14 | 每个插件都有应有独立的数据库配置在其配置文件目录 `config/.../hibernate.properties` 15 | 例如,聊天记录器数据库配置在 `config/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/hibernate.properties` 16 | 17 | ## 数据库支持 18 | 19 | 本插件打包了以下版本的数据库驱动和连接池 20 | 21 | * `com.mysql:mysql-connector-j:9.0.0` - [mysql.hibernate.properties](example/mysql.hibernate.properties) 22 | * `org.mariadb.jdbc:mariadb-java-client:3.4.1` - [mariadb.hibernate.properties](example/mariadb.hibernate.properties) 23 | * `org.xerial:sqlite-jdbc:3.46.0.1` - [sqlite.hibernate.properties](example/sqlite.hibernate.properties) 24 | * `org.postgresql:postgresql:42.7.3` - [postgresql.hibernate.properties](example/postgresql.hibernate.properties) 25 | * `com.h2database:h2:2.3.230` - [h2.hibernate.properties](example/h2.hibernate.properties) 26 | * `com.microsoft.sqlserver:mssql-jdbc:12.8.0.jre11` - [sqlserver.hibernate.properties](example/sqlserver.hibernate.properties) 27 | * `com.zaxxer:HikariCP:5.0.1` 28 | 29 | 需要其他数据库驱动或连接池支持,请添加 `plugin-shared-libraries` 依赖,有2种方法 30 | 31 | 1. 将 **Jar包** 放到 `plugin-shared-libraries` 目录中一同被 `mirai-console` 加载 32 | 33 | 2. 在 `plugin-shared-libraries/libraries.txt` 中添加 maven 引用, 34 | 例如 `com.oracle.database.jdbc:ojdbc11:21.8.0.0` 35 | 36 | ## 在 Mirai Console Plugin 项目中引用 37 | 38 | ```kotlin 39 | repositories { 40 | mavenCentral() 41 | } 42 | 43 | dependencies { 44 | compileOnly("xyz.cssxsh.mirai:mirai-hibernate-plugin:${version}") 45 | } 46 | 47 | // hibernate 6 和 HikariCP 5 需要 jdk11 48 | mirai { 49 | jvmTarget = JavaVersion.VERSION_11 50 | } 51 | ``` 52 | 53 | ## 在 Mirai Core Jvm 项目中引用 54 | 55 | ```kotlin 56 | repositories { 57 | mavenCentral() 58 | } 59 | 60 | dependencies { 61 | implementation("xyz.cssxsh.mirai:mirai-hibernate-plugin:${version}") 62 | } 63 | ``` 64 | 需要手动对 `xyz.cssxsh.mirai.hibernate.factory` 进行初始化,和对 `MiraiHibernateRecorder` 进行注册 65 | 66 | **Maven 项目请根据上面的 maven-central 指向的链接查询相关配置方法** 67 | 68 | ## 在 mirai-api-http 中引用 69 | 70 | 使用本插件作为 mirai-api-http 的消息源需要额外的拓展插件 71 | 72 | ## 一些方法和类说明 73 | 74 | * [MiraiHibernateConfiguration](src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateConfiguration.kt) 75 | 配置的,对应于 `JvmPlugin` 的 `SessionFactory` 76 | 默认将会读取(生成)在 `config` 目录下的 `hibernate.properties` 作为配置文件 77 | 并且自动扫描加载当前插件的 `entry` 类包中被 `jakarta.persistence.Entity` 标记的实体类 78 | 79 | * [MiraiHibernateRecorder](src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateRecorder.kt) 80 | 是本插件自带的消息记录器,通过对 `MessageEvent` 和 `MessagePostSendEvent` 记录,保存消息历史到数据库 81 | 82 | * [CriteriaBuilder.rand](src/main/kotlin/xyz/cssxsh/hibernate/Criteria.kt) 83 | `MiraiHibernateConfiguration` 中会对 Sqlite / PostgreSql 的 `random` 进行别名注册为 `rand` 统一SQL语句的中的随机函数名 84 | 85 | * [CriteriaBuilder.dice](src/main/kotlin/xyz/cssxsh/hibernate/Criteria.kt) 86 | `MiraiHibernateConfiguration` 中会注册名为 `dice` 的宏,用于随机取行 87 | 88 | ### 示例代码 89 | 90 | * [kotlin](src/test/kotlin/xyz/cssxsh/mirai/test/MiraiHibernatePluginTest.kt) 91 | * [java](src/test/java/xyz/cssxsh/mirai/test/MiraiHibernateDemo.java) 92 | 93 | ## 安装 94 | 95 | ### MCL 指令安装 96 | 97 | **请确认 mcl.jar 的版本是 2.1.0+** 98 | `./mcl --update-package xyz.cssxsh.mirai:mirai-hibernate-plugin --channel maven-stable --type plugins` 99 | 100 | ### 手动安装 101 | 102 | 1. 从 [Releases](https://github.com/cssxsh/mirai-hibernate-plugin/releases) 或者 [Maven](https://repo1.maven.org/maven2/xyz/cssxsh/mirai/mirai-hibernate-plugin/) 下载 `mirai2.jar` 103 | 2. 将其放入 `plugins` 文件夹中 104 | 105 | ### 聊天数据迁移 106 | 107 | 1. 将原 `config/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin/hibernate.properties` 改名备份为 `hibernate.backup.properties` 108 | 2. 按照 [example](example) 中的例子写一份新的 `hibernate.properties` 109 | 3. 重启 `mirai-console` 110 | 111 | ## [爱发电](https://afdian.net/@cssxsh) 112 | 113 | ![afdian](.github/afdian.jpg) -------------------------------------------------------------------------------- /src/test/java/xyz/cssxsh/mirai/test/MiraiHibernateDemo.java: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.test; 2 | 3 | import net.mamoe.mirai.Bot; 4 | import net.mamoe.mirai.console.plugin.jvm.JavaPlugin; 5 | import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescriptionBuilder; 6 | import net.mamoe.mirai.message.data.MessageChain; 7 | import net.mamoe.mirai.message.data.MessageSource; 8 | import org.hibernate.SessionFactory; 9 | import xyz.cssxsh.mirai.hibernate.MiraiH2; 10 | import xyz.cssxsh.mirai.hibernate.MiraiHibernateConfiguration; 11 | import xyz.cssxsh.mirai.hibernate.MiraiHibernateRecorder; 12 | import xyz.cssxsh.mirai.hibernate.entry.MessageRecord; 13 | import xyz.cssxsh.mirai.test.entry.User; 14 | import xyz.cssxsh.mirai.test.entry.Work; 15 | 16 | public class MiraiHibernateDemo extends JavaPlugin { 17 | public MiraiHibernateDemo() { 18 | super(new JvmPluginDescriptionBuilder("xyz.cssxsh.mirai.plugin.mirai-hibernate-demo", "0.0.0") 19 | .dependsOn("xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin", false) 20 | .build()); 21 | } 22 | 23 | private SessionFactory factory; 24 | 25 | @Override 26 | public void onEnable() { 27 | // MiraiHibernateConfiguration 会自动扫描 entry, entity, entities, model, models, bean, beans, dto 的包类 28 | // 只会扫描一个包,先发现先扫 29 | var configuration = new MiraiHibernateConfiguration(this); 30 | // 如果你的实体包没被扫描,可以手动指定包扫描 31 | configuration.scan("xyz.cssxsh.mirai.test.entry"); 32 | // 或者用 Hibernate 原生的方法手动加类 33 | configuration.addAnnotatedClass(User.class); 34 | 35 | // buildSessionFactory 时会自动建表 36 | factory = configuration.buildSessionFactory(); 37 | 38 | // 用这个方法能安全关闭 Session 不需要额外写 try catch 39 | var u = factory.fromSession((session) -> { 40 | // 查找 41 | return session.find(User.class, 1L); 42 | }); 43 | 44 | 45 | // 用这个方法能安全关闭 Transaction 不需要额外写 try catch 46 | // fromTransaction 在 fromSession 的基础上套了一层 事务(Transaction) 47 | // 当有数据变更时,必须套着事务 48 | factory.fromTransaction((session) -> { 49 | // 插入 50 | var user = new User(); 51 | user.setId(1L); 52 | user.setName("name"); 53 | session.persist(user); 54 | 55 | // 修改 56 | user.setName("new name"); 57 | session.merge(user); 58 | 59 | // 删除 60 | session.remove(user); 61 | 62 | // 原生sql 查询 63 | session.createNativeQuery("select * from user", User.class) 64 | .list(); 65 | 66 | // hql 查询(格式像是 sql 混杂 java) 67 | String hql = "from User s where s.name = :name"; 68 | session.createQuery(hql, User.class) 69 | .setParameter("name", "...") 70 | .list(); 71 | 72 | String hql2 = "from Work w where w.user.name = :name"; 73 | session.createQuery(hql2, Work.class) 74 | .setParameter("name", "...") 75 | .list(); 76 | 77 | // criteria 查询(纯 java 代码的方式构造 sql)我推荐这种,不过用起来比较复杂 78 | var builder = session.getCriteriaBuilder(); 79 | 80 | var query = builder.createQuery(User.class); 81 | var root = query.from(User.class); 82 | query.select(root); 83 | query.where(builder.between(root.get("id"), 0L, 1000L)); 84 | 85 | var list = session.createQuery(query) 86 | .list(); 87 | 88 | var query2 = builder.createQuery(Work.class); 89 | var root2 = query.from(Work.class); 90 | query2.select(root2); 91 | query2.where(builder.between(root2.get("user").get("id"), 0L, 1000L)); 92 | 93 | var list2 = session.createQuery(query) 94 | .list(); 95 | 96 | return 0; 97 | }); 98 | 99 | // MiraiHibernateRecorder 的使用 100 | // 返回一个流,请记得关闭这个流 101 | try (var steam = MiraiHibernateRecorder.INSTANCE.get(Bot.findInstance(123456))) { 102 | MessageRecord record = steam.findFirst().get(); 103 | // 转化成消息链 104 | MessageChain message = record.toMessageChain(); 105 | // 转化消息引用 106 | // 这里的 originalMessage 来自 上面的 toMessageChain 107 | MessageSource source = record.toMessageSource(); 108 | 109 | } catch (Exception e) { 110 | // 111 | } 112 | 113 | // 返回一个列表,第 2,3 参数是 开始时刻和结束时间 114 | var list = MiraiHibernateRecorder.INSTANCE.get(Bot.getInstance(123456), 1600000, 1600001); 115 | for (MessageRecord record : list) { 116 | record.toMessageSource(); 117 | // or 118 | record.toMessageChain(); 119 | } 120 | 121 | // 创建一个 网页会话,访问 h2 数据库 122 | var url = factory.fromSession(MiraiH2.INSTANCE::url); 123 | } 124 | 125 | @Override 126 | public void onDisable() { 127 | factory.close(); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/hibernate/Criteria.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.hibernate 2 | 3 | import jakarta.persistence.criteria.* 4 | import org.hibernate.* 5 | import org.hibernate.cfg.* 6 | import org.hibernate.dialect.function.* 7 | import org.hibernate.query.* 8 | import org.hibernate.sql.ast.* 9 | import org.hibernate.type.* 10 | import java.sql.* 11 | 12 | /** 13 | * rand 函数 14 | * @see Configuration.addRandFunction 15 | */ 16 | public fun CriteriaBuilder.rand(): Expression = function("rand", Double::class.java) 17 | 18 | /** 19 | * dice 函数 20 | * @param model 模,应为正整数 21 | * @return 随机生成 [0, model) 范围的数 22 | * @since 2.3.3 23 | * @see Configuration.addRandFunction 24 | */ 25 | public fun CriteriaBuilder.dice(model: Expression): Expression = function("dice", Long::class.java, model) 26 | 27 | /** 28 | * Sqlite / PostgreSQL 添加 rand 函数别名 29 | * 30 | * 通过 `hibernate.connection.url` 判断数据库类型,然后添加对应的函数别名 31 | * @since 2.3.3 32 | * @see CriteriaBuilder.rand 33 | */ 34 | public fun Configuration.addRandFunction() { 35 | // MySql rand 0 ~ 1 36 | // Sqlite random -9223372036854775808 ~ +9223372036854775807 37 | // PostgreSQL random 0 ~ 1 38 | // H2 rand 0 ~ 1 39 | // SqlServer rand 0 ~ 1 40 | val url = getProperty("hibernate.connection.url") ?: throw IllegalStateException("url is empty") 41 | when { 42 | url.startsWith("jdbc:sqlite") -> { 43 | addSqlFunction("rand", MacroSQLFunction(StandardBasicTypes.DOUBLE) { _, _ -> 44 | appendSql("((RANDOM() + 9223372036854775808) / 2.0 / 9223372036854775808)") 45 | }) 46 | } 47 | url.startsWith("jdbc:postgresql") -> { 48 | addSqlFunction("rand", StandardSQLFunction("random", StandardBasicTypes.DOUBLE)) 49 | } 50 | } 51 | } 52 | 53 | /** 54 | * 添加 dice 函数 55 | * 56 | * 通过 `hibernate.connection.url` 判断数据库类型,然后添加对应的函数别名 57 | * 58 | * @see CriteriaBuilder.dice 59 | */ 60 | public fun Configuration.addDiceFunction() { 61 | // MySql rand 0 ~ 1 62 | // Sqlite random -9223372036854775808 ~ +9223372036854775807 63 | // PostgreSQL random 0 ~ 1 64 | // H2 rand 0 ~ 1 65 | // SqlServer rand 0 ~ 1 66 | val url = getProperty("hibernate.connection.url") ?: throw IllegalStateException("url is empty") 67 | when { 68 | url.startsWith("jdbc:sqlite") -> { 69 | addSqlFunction("dice", MacroSQLFunction(StandardBasicTypes.LONG) { args, translator -> 70 | val (model) = args 71 | appendSql("ABS(RANDOM() % ") 72 | translator.render(model, SqlAstNodeRenderingMode.DEFAULT) 73 | appendSql(")") 74 | }) 75 | } 76 | url.startsWith("jdbc:postgresql") -> { 77 | addSqlFunction("dice", MacroSQLFunction(StandardBasicTypes.LONG) { args, translator -> 78 | val (model) = args 79 | appendSql("FLOOR(") 80 | translator.render(model, SqlAstNodeRenderingMode.DEFAULT) 81 | appendSql(" * RANDOM())") 82 | }) 83 | } 84 | else -> { 85 | addSqlFunction("dice", MacroSQLFunction(StandardBasicTypes.LONG) { args, translator -> 86 | val (model) = args 87 | appendSql("FLOOR(") 88 | translator.render(model, SqlAstNodeRenderingMode.DEFAULT) 89 | appendSql(" * RAND())") 90 | }) 91 | } 92 | } 93 | } 94 | 95 | /** 96 | * 构造一个 Criteria 查询 97 | */ 98 | public inline fun Session.withCriteria(block: CriteriaBuilder.(query: CriteriaQuery) -> Unit): Query = 99 | createQuery(with(criteriaBuilder) { createQuery(T::class.java).also { block(it) } }) 100 | 101 | /** 102 | * 构造一个 Criteria 查询 103 | */ 104 | public inline fun Session.withCriteriaUpdate(block: CriteriaBuilder.(query: CriteriaUpdate) -> Unit): MutationQuery = 105 | createMutationQuery(with(criteriaBuilder) { createCriteriaUpdate(T::class.java).also { block(it) } }) 106 | 107 | /** 108 | * 构造一个 Criteria 查询 109 | */ 110 | public inline fun Session.withCriteriaDelete(block: CriteriaBuilder.(query: CriteriaDelete) -> Unit): MutationQuery = 111 | createMutationQuery(with(criteriaBuilder) { createCriteriaDelete(T::class.java).also { block(it) } }) 112 | 113 | /** 114 | * 获得 Root 115 | */ 116 | public inline fun AbstractQuery<*>.from(): Root = from(X::class.java) 117 | 118 | /** 119 | * 获得 Root 120 | */ 121 | public inline fun CriteriaUpdate.from(): Root = from(T::class.java) 122 | 123 | /** 124 | * 获得 Root 125 | */ 126 | public inline fun CriteriaDelete.from(): Root = from(T::class.java) 127 | 128 | /** 129 | * 获得 Subquery 130 | */ 131 | public inline fun CommonAbstractCriteria.subquery(): Subquery = subquery(T::class.java) 132 | 133 | /** 134 | * 获取会话的 [DatabaseMetaData] 135 | */ 136 | public fun Session.getDatabaseMetaData(): DatabaseMetaData = doReturningWork { connection -> connection.metaData } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateUtils.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate 2 | 3 | import net.mamoe.mirai.contact.* 4 | import net.mamoe.mirai.message.data.* 5 | import net.mamoe.mirai.utils.* 6 | import org.hibernate.* 7 | import org.hibernate.dialect.Dialect 8 | import org.sqlite.SQLiteJDBCLoader 9 | import xyz.cssxsh.hibernate.* 10 | import xyz.cssxsh.mirai.hibernate.entry.* 11 | import java.io.File 12 | import java.net.URL 13 | 14 | internal val logger by lazy { 15 | try { 16 | MiraiHibernatePlugin.logger 17 | } catch (_: ExceptionInInitializerError) { 18 | MiraiLogger.Factory.create(MiraiHibernateRecorder::class) 19 | } 20 | } 21 | 22 | private const val SQLITE_JNI = 23 | "https://raw.githubusercontent.com/xerial/sqlite-jdbc/master/src/main/resources/org/sqlite/native/Linux-Android/aarch64/libsqlitejdbc.so" 24 | 25 | /** 26 | * 检查当前平台,并修正问题 27 | * @see SQLiteJDBCLoader 28 | */ 29 | public fun checkPlatform(folder: File) { 30 | // Termux 31 | System.getenv("TERMUX_VERSION")?.let { version -> 32 | logger.info { "change platform: Linux-Android/aarch64, for termux $version" } 33 | System.setProperty("org.sqlite.lib.path", folder.path) 34 | val lib = folder.resolve("libsqlitejdbc.so") 35 | if (lib.exists().not()) { 36 | val url = SQLiteJDBCLoader::class.java.classLoader 37 | .getResource("org/sqlite/native/Linux-Android/aarch64/libsqlitejdbc.so") 38 | ?: URL(SQLITE_JNI) 39 | 40 | lib.writeBytes(url.readBytes()) 41 | } 42 | SQLiteJDBCLoader.initialize() 43 | } 44 | } 45 | 46 | /** 47 | * 获取所有 [Dialect] 48 | * @see Dialect 49 | */ 50 | public fun dialects(): Set> { 51 | return org.reflections.Reflections("org.hibernate.dialect", "org.hibernate.community.dialect") 52 | .getSubTypesOf(Dialect::class.java) 53 | } 54 | 55 | /** 56 | * 获取 MSSQL 驱动 artifact id 57 | */ 58 | @PublishedApi 59 | internal fun mssql(): String { 60 | val java = System.getProperty("java.version") 61 | // val version = System.getProperty("xyz.cssxsh.mirai.hibernate.mssql.version", "11.2.3") 62 | return when { 63 | java.startsWith("17") -> "com.microsoft.sqlserver:mssql-jdbc:12.8.1.jre11" 64 | java.startsWith("11") -> "com.microsoft.sqlserver:mssql-jdbc:12.8.1.jre11" 65 | java.startsWith("8") -> "com.microsoft.sqlserver:mssql-jdbc:12.8.1.jre8" 66 | else -> "com.microsoft.sqlserver:mssql-jdbc:12.8.0.jre11" 67 | } 68 | } 69 | 70 | /** 71 | * 插件的 SessionFactory 72 | */ 73 | public lateinit var factory: SessionFactory 74 | internal set 75 | 76 | /** 77 | * 将消息记录打包为转发消息 78 | * @param subject 上下文 79 | * @see ForwardMessage 80 | */ 81 | public fun List.toForwardMessage(subject: Contact): ForwardMessage { 82 | return buildForwardMessage(subject) { 83 | for (record in this@toForwardMessage) { 84 | record.fromId named record.name(subject) at record.time says record.toMessageChain() 85 | } 86 | } 87 | } 88 | 89 | /** 90 | * 将消息记录打包为转发消息 91 | * @param subject 上下文 92 | * @see ForwardMessage 93 | */ 94 | public fun Sequence.toForwardMessage(subject: Contact): ForwardMessage { 95 | return buildForwardMessage(subject) { 96 | for (record in this@toForwardMessage) { 97 | record.fromId named record.name(subject) at record.time says record.toMessageChain() 98 | } 99 | } 100 | } 101 | 102 | /** 103 | * 随机得到一个表情包记录 104 | * @see factory 105 | */ 106 | public fun FaceRecord.Companion.random(): FaceRecord { 107 | return factory.fromSession { session -> 108 | val count = session.withCriteria { query -> 109 | val record = query.from() 110 | query.select(count(record)) 111 | }.uniqueResult().toInt() 112 | logger.debug { "face record count $count" } 113 | session.withCriteria { query -> 114 | val record = query.from() 115 | query.select(record) 116 | .where(not(record.get("disable"))) 117 | .orderBy(desc(record.get("md5"))) 118 | }.setFirstResult((0 until count).random()).setMaxResults(1).uniqueResult() 119 | } 120 | } 121 | 122 | /** 123 | * 禁用指定 [md5] 的 表情包记录 124 | * @see FaceRecord.md5 125 | */ 126 | public fun FaceRecord.Companion.disable(md5: String): FaceRecord { 127 | return factory.fromTransaction { session -> 128 | val result = session.withCriteriaUpdate { query -> 129 | val root = query.from() 130 | query.where(equal(root.get("md5"), md5)) 131 | .set(root.get("disable"), true) 132 | }.executeUpdate() 133 | 134 | check(result > 0) { "FaceRecord(${md5}).disable 修改失败" } 135 | 136 | session.get(FaceRecord::class.java, md5) 137 | } 138 | } 139 | 140 | /** 141 | * 通过 [tag] 获取表情包记录 142 | * @see FaceTagRecord.tag 143 | */ 144 | public fun FaceRecord.Companion.match(tag: String): List { 145 | return factory.fromSession { session -> 146 | session.withCriteria { query -> 147 | val root = query.from() 148 | val join = root.joinList("tags") 149 | query.select(root) 150 | .where(equal(join.get("tag"), tag)) 151 | }.list() 152 | } 153 | } 154 | 155 | /** 156 | * 通过 [md5] 获取表情包标签记录 157 | * @see FaceTagRecord.md5 158 | */ 159 | public operator fun FaceTagRecord.Companion.get(md5: String): List { 160 | return factory.fromSession { session -> 161 | session.withCriteria { query -> 162 | val root = query.from() 163 | query.select(root) 164 | .where(equal(root.get("md5"), md5)) 165 | }.list() 166 | } 167 | } 168 | 169 | /** 170 | * 通过 [md5] 设置表情包标签记录 171 | * @see FaceTagRecord.md5 172 | */ 173 | public operator fun FaceTagRecord.Companion.set(md5: String, tag: String): List { 174 | return factory.fromTransaction { session -> 175 | session.persist(FaceTagRecord(md5 = md5, tag = tag)) 176 | 177 | session.withCriteria { query -> 178 | val root = query.from() 179 | query.select(root) 180 | .where(equal(root.get("md5"), md5)) 181 | }.list() 182 | } 183 | } 184 | 185 | /** 186 | * 通过 [md5] 移除表情包标签记录 187 | * @see FaceTagRecord.md5 188 | */ 189 | public fun FaceTagRecord.Companion.remove(md5: String, tag: String): List { 190 | return factory.fromTransaction { session -> 191 | session.withCriteriaDelete { query -> 192 | val root = query.from() 193 | query.where( 194 | equal(root.get("md5"), md5), 195 | equal(root.get("tag"), tag) 196 | ) 197 | }.executeUpdate() 198 | 199 | session.withCriteria { query -> 200 | val root = query.from() 201 | query.select(root) 202 | .where(equal(root.get("md5"), md5)) 203 | }.list() 204 | } 205 | } -------------------------------------------------------------------------------- /src/test/kotlin/xyz/cssxsh/mirai/hibernate/entry/DatabaseTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import kotlinx.serialization.json.* 6 | import net.mamoe.mirai.contact.* 7 | import net.mamoe.mirai.message.data.* 8 | import net.mamoe.mirai.utils.* 9 | import org.hibernate.SessionFactory 10 | import org.hibernate.cfg.Configuration 11 | import org.junit.jupiter.api.* 12 | import xyz.cssxsh.hibernate.* 13 | import java.io.File 14 | import java.util.ServiceLoader 15 | import kotlin.random.Random 16 | 17 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 18 | abstract class DatabaseTest { 19 | 20 | protected val logger: MiraiLogger = MiraiLogger.Factory.create(this::class.java) 21 | 22 | init { 23 | ServiceLoader.load(java.sql.Driver::class.java) 24 | .forEach { driver -> 25 | logger.info { "Driver: ${driver::class.java.name} Version ${driver.majorVersion}.${driver.minorVersion}" } 26 | } 27 | } 28 | 29 | protected val configuration = Configuration().apply { 30 | val reflections = org.reflections.Reflections("xyz.cssxsh.mirai.hibernate.entry") 31 | val query = org.reflections.scanners.Scanners.TypesAnnotated 32 | .of(Entity::class.java, Embeddable::class.java, MappedSuperclass::class.java) 33 | .asClass() 34 | query.apply(reflections.store).forEach { clazz -> 35 | addAnnotatedClass(clazz) 36 | } 37 | 38 | setProperty("hibernate.show_sql", "true") 39 | } 40 | 41 | protected val factory: SessionFactory by lazy { 42 | File("./data/xyz.cssxsh.mirai.plugin.mirai-hibernate-plugin").mkdirs() 43 | configuration.addRandFunction() 44 | configuration.addDiceFunction() 45 | configuration.buildSessionFactory() 46 | } 47 | 48 | @BeforeAll 49 | fun insert() { 50 | val random = Random(seed = System.currentTimeMillis()) 51 | factory.fromTransaction { session -> 52 | repeat(100) { index -> 53 | val md5 = random.nextBytes(16).toUHexString("") 54 | val face = FaceRecord( 55 | md5 = md5, 56 | code = "{}", 57 | content = "$index", 58 | url = "https://127.0.0.1/$index", 59 | height = index, 60 | width = index 61 | ) 62 | 63 | session.persist(face) 64 | 65 | val message = MessageRecord( 66 | bot = index * 10L, 67 | fromId = index * 100L, 68 | targetId = index * 1000L, 69 | ids = "$index", 70 | internalIds = "$index", 71 | time = (System.currentTimeMillis() / 1000).toInt(), 72 | kind = MessageSourceKind.values().random(), 73 | code = md5 74 | ) 75 | 76 | session.persist(message) 77 | 78 | val friend = FriendRecord( 79 | uuid = FriendIndex( 80 | bot = random.nextLong(0, Long.MAX_VALUE), 81 | uid = random.nextLong(0, Long.MAX_VALUE) 82 | ), 83 | remark = "好友", 84 | category = "我的好友", 85 | added = random.nextLong(), 86 | deleted = Long.MAX_VALUE 87 | ) 88 | 89 | session.persist(friend) 90 | 91 | val member = GroupMemberRecord( 92 | uuid = GroupMemberIndex( 93 | group = random.nextLong(0, Long.MAX_VALUE), 94 | uid = random.nextLong(0, Long.MAX_VALUE) 95 | ), 96 | permission = MemberPermission.values().random(), 97 | name = "...", 98 | title = "😁", 99 | joined = random.nextLong(), 100 | last = System.currentTimeMillis(), 101 | active = index, 102 | exited = Long.MAX_VALUE 103 | ) 104 | 105 | session.persist(member) 106 | } 107 | } 108 | } 109 | 110 | @Test 111 | fun backup() { 112 | factory.fromSession { session -> 113 | session.withCriteria { query -> 114 | val root = query.from() 115 | query.select(root) 116 | }.list() 117 | session.withCriteria { query -> 118 | val root = query.from() 119 | query.select(root) 120 | }.list() 121 | } 122 | } 123 | 124 | @Test 125 | fun rand() { 126 | val num = factory.fromSession { session -> 127 | session.withCriteria { query -> 128 | query.select(rand()) 129 | }.uniqueResult() 130 | } 131 | logger.info("rand $num") 132 | Assertions.assertTrue(num >= 0.0, "< 0.0") 133 | Assertions.assertTrue(num <= 1.0, "> 1.0") 134 | 135 | val list = factory.fromSession { session -> 136 | session.withCriteria { query -> 137 | val record = query.from() 138 | query.select(record) 139 | .orderBy(asc(rand())) 140 | }.setMaxResults(3).list() 141 | } 142 | Assertions.assertEquals(list.size, 3) 143 | } 144 | 145 | @Test 146 | fun dice() { 147 | val num = factory.fromSession { session -> 148 | session.withCriteria { query -> 149 | query.select(dice(literal(1000))) 150 | }.uniqueResult() 151 | } 152 | logger.info("dice $num") 153 | Assertions.assertTrue(num >= 0, "< 0") 154 | Assertions.assertTrue(num <= 1000, "> 1000") 155 | 156 | val list = factory.fromSession { session -> 157 | session.withCriteria { query -> 158 | val record = query.from() 159 | val id = record.get("id") 160 | val max = query.subquery().apply { 161 | select(max(from().get("id"))) 162 | } 163 | 164 | query.select(record) 165 | .where( 166 | ge(id, dice(max)) 167 | ) 168 | }.setMaxResults(3).list() 169 | } 170 | Assertions.assertEquals(list.size, 3) 171 | } 172 | 173 | @Test 174 | fun join() { 175 | factory.inSession { session -> 176 | val face = session.withCriteria { query -> 177 | val root = query.from() 178 | query.select(root) 179 | }.setMaxResults(1).uniqueResult() 180 | 181 | session.transaction.begin() 182 | session.merge(FaceTagRecord(md5 = face.md5, tag = "test")) 183 | session.transaction.commit() 184 | 185 | logger.info(face.tags.toString()) 186 | 187 | session.transaction.begin() 188 | session.merge(face.copy(disable = true)) 189 | session.transaction.commit() 190 | } 191 | } 192 | 193 | @AfterAll 194 | fun close() { 195 | factory.close() 196 | } 197 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateConfiguration.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate 2 | 3 | import jakarta.persistence.* 4 | import net.mamoe.mirai.console.plugin.jvm.* 5 | import org.hibernate.* 6 | import org.hibernate.boot.registry.* 7 | import org.hibernate.cfg.* 8 | import xyz.cssxsh.hibernate.* 9 | import java.sql.* 10 | import java.util.* 11 | import kotlin.streams.* 12 | 13 | /** 14 | * 适用于插件的 Hibernate [Configuration] 15 | * @param loader 加载器,定义一些加载行为 16 | * @see [Configuration.addRandFunction] 17 | */ 18 | public class MiraiHibernateConfiguration(@PublishedApi internal val loader: MiraiHibernateLoader) : 19 | Configuration( 20 | BootstrapServiceRegistryBuilder() 21 | .applyClassLoader(loader.classLoader) 22 | .build() 23 | ) { 24 | public constructor(plugin: JvmPlugin) : this(loader = MiraiHibernateLoader(plugin = plugin)) 25 | 26 | init { 27 | // 载入文件 28 | loader.configuration.apply { if (exists().not()) writeText(loader.default) }.inputStream().use(properties::load) 29 | if (loader.autoScan) scan(packageName = loader.packageName) 30 | default() 31 | } 32 | 33 | /** 34 | * 扫描指定包名下的 实体类 (被 Entity, Embeddable, MappedSuperclass 标记的类) 35 | * @see MiraiHibernateLoader.autoScan 36 | * @see MiraiHibernateLoader.packageName 37 | * @see jakarta.persistence.Entity 38 | * @see jakarta.persistence.Embeddable 39 | * @see jakarta.persistence.MappedSuperclass 40 | */ 41 | public fun scan(packageName: String) { 42 | val reflections = org.reflections.Reflections( 43 | org.reflections.util.ConfigurationBuilder() 44 | .forPackage(packageName, loader.classLoader) 45 | .addClassLoaders(loader.classLoader) 46 | ) 47 | val query = org.reflections.scanners.Scanners.TypesAnnotated 48 | .of(Entity::class.java, Embeddable::class.java, MappedSuperclass::class.java) 49 | .asClass(loader.classLoader) 50 | query.apply(reflections.store).forEach { clazz -> 51 | addAnnotatedClass(clazz) 52 | } 53 | } 54 | 55 | private fun setPropertyIfAbsent(propertyName: String, value: String) { 56 | if (propertyName !in properties) { 57 | properties.setProperty(propertyName, value) 58 | } 59 | } 60 | 61 | /** 62 | * @see org.hibernate.dialect.MySQLDialect 63 | * @see org.hibernate.dialect.MariaDBDialect 64 | * @see org.hibernate.dialect.H2Dialect 65 | * @see org.hibernate.dialect.PostgreSQLDialect 66 | * @see org.hibernate.dialect.SQLServerDialect 67 | * @see org.hibernate.dialect.OracleDialect 68 | * @see org.hibernate.community.dialect.SQLiteDialect 69 | */ 70 | private fun Configuration.default() { 71 | // 设置默认数据库连接池 72 | setPropertyIfAbsent("hibernate.connection.provider_class", "org.hibernate.hikaricp.internal.HikariCPConnectionProvider") 73 | // 设置默认事务隔离级别 74 | setPropertyIfAbsent("hibernate.connection.isolation", "${Connection.TRANSACTION_READ_UNCOMMITTED}") 75 | // 设置 rand 别名 76 | addRandFunction() 77 | // 设置 dice 宏 78 | addDiceFunction() 79 | val url = getProperty("hibernate.connection.url") ?: throw NoSuchElementException("jdbc url no found!") 80 | when { 81 | url.startsWith("jdbc:h2") -> { 82 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.dialect.H2Dialect") 83 | // XXX auto upgrade 2.1 to 2.2 84 | try { 85 | DriverManager.getConnection(url, properties).close() 86 | } catch (cause: org.h2.jdbc.JdbcSQLNonTransientConnectionException) { 87 | try { 88 | println("try upgrade h2database file") 89 | org.h2.tools.Upgrade.upgrade(url, properties, 214) 90 | } catch (suppressed: Throwable) { 91 | cause.addSuppressed(suppressed) 92 | cause.printStackTrace() 93 | } 94 | } 95 | } 96 | url.startsWith("jdbc:sqlite") -> { 97 | // SQLite 是单文件数据库,最好只有一个连接 98 | setPropertyIfAbsent("hibernate.hikari.minimumIdle", "1") 99 | setPropertyIfAbsent("hibernate.hikari.maximumPoolSize", "1") 100 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.community.dialect.SQLiteDialect") 101 | } 102 | url.startsWith("jdbc:mysql") -> { 103 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.dialect.MySQLDialect") 104 | } 105 | url.startsWith("jdbc:mariadb") -> { 106 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect") 107 | } 108 | url.startsWith("jdbc:postgresql") -> { 109 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect") 110 | } 111 | url.startsWith("jdbc:sqlserver") -> { 112 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect") 113 | setPropertyIfAbsent("hibernate.globally_quoted_identifiers", "true") 114 | } 115 | url.startsWith("jdbc:oracle") -> { 116 | // setPropertyIfAbsent("hibernate.dialect", "org.hibernate.dialect.OracleDialect") 117 | } 118 | } 119 | } 120 | 121 | /** 122 | * 数据库还原 123 | * @since 2.7.0 124 | */ 125 | public fun restore(properties: Properties) { 126 | val another = another(properties = properties) 127 | 128 | buildSessionFactory().use { target -> 129 | val entities = target.metamodel.entities 130 | another.buildSessionFactory().use { source -> 131 | for (entity in entities) { 132 | transfer(source, target, entity.javaType, 4096) 133 | } 134 | } 135 | } 136 | } 137 | 138 | /** 139 | * 数据库备份 140 | * @since 2.7.0 141 | */ 142 | public fun backup(properties: Properties) { 143 | val another = another(properties = properties) 144 | 145 | buildSessionFactory().use { source -> 146 | val entities = source.metamodel.entities 147 | another.buildSessionFactory().use { target -> 148 | for (entity in entities) { 149 | transfer(source, target, entity.javaType, 4096) 150 | } 151 | } 152 | } 153 | } 154 | 155 | @PublishedApi 156 | internal fun another(properties: Properties): Configuration { 157 | require(properties.getProperty("hibernate.connection.url") != getProperty("hibernate.connection.url")) { 158 | "Both database url are the same!" 159 | } 160 | val another = Configuration( 161 | BootstrapServiceRegistryBuilder() 162 | .applyClassLoader(loader.classLoader) 163 | .build() 164 | ) 165 | another.addProperties(properties) 166 | another.default() 167 | buildSessionFactory().use { target -> 168 | for (managedType in target.metamodel.managedTypes) { 169 | another.addAnnotatedClass(managedType.javaType) 170 | } 171 | } 172 | return another 173 | } 174 | 175 | @PublishedApi 176 | internal fun transfer(source: SessionFactory, target: SessionFactory, entity: Class<*>, chunked: Int) { 177 | source.fromSession { session -> 178 | val query = session.criteriaBuilder.createQuery(entity) 179 | query.from(entity) 180 | session.createQuery(query).stream() 181 | .asSequence().chunked(chunked) 182 | .forEach { list -> 183 | target.fromTransaction { list.forEach(it::merge) } 184 | } 185 | } 186 | } 187 | } -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Database Test 2 | on: 3 | push: 4 | paths-ignore: 5 | - '**/*.md' 6 | pull_request: 7 | paths-ignore: 8 | - '**/*.md' 9 | 10 | jobs: 11 | windows: 12 | runs-on: windows-latest 13 | steps: 14 | 15 | - name: Start MSSQL 16 | run: | 17 | choco install sql-server-express --no-progress -y 18 | sc qc 'MSSQL$SQLEXPRESS' 19 | 20 | # https://learn.microsoft.com/en-us/sql/powershell/how-to-enable-tcp-sqlps 21 | - name: Enable the TCP protocol on MSSQL$SQLEXPRESS 22 | run: | 23 | [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SqlWmiManagement') 24 | $ManagedComputer = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer' 25 | $ManagedComputer 26 | $ServerInstance = $ManagedComputer.ServerInstances['SQLEXPRESS'] 27 | $Tcp = $ServerInstance.ServerProtocols['Tcp'] 28 | $Tcp.IsEnabled = $True 29 | $IP4 = $Tcp.IPAddresses['IP4'] 30 | $IP4.IPAddressProperties['Enabled'].Value = $True 31 | $IP4.IPAddressProperties['TcpPort'].Value = '1433' 32 | $IPAll = $Tcp.IPAddresses['IPALL'] 33 | $IPAll.IPAddressProperties['TcpPort'].Value = '1433' 34 | $Tcp.Alter() 35 | $Tcp.Refresh() 36 | $Tcp 37 | $Np = $ServerInstance.ServerProtocols['Np'] 38 | $Np.IsEnabled = $True 39 | $Np.Alter() 40 | $Np.Refresh() 41 | $Np 42 | sqlcmd -S '.\SQLEXPRESS' -Q "ALTER LOGIN [sa] WITH PASSWORD = '$Env:COMPUTERNAME'" 43 | sqlcmd -S '.\SQLEXPRESS' -Q "ALTER LOGIN [sa] ENABLE" 44 | Get-ItemProperty -Path 'HKLM:\Software\Microsoft\Microsoft SQL Server\MSSQL*\MSSQLServer\' 45 | Set-ItemProperty -Path 'HKLM:\Software\Microsoft\Microsoft SQL Server\MSSQL*\MSSQLServer\' -Name LoginMode -Value 2 46 | Restart-Service -Name 'MSSQL$SQLEXPRESS' 47 | echo "SQLCMDPASSWORD=$Env:COMPUTERNAME" >> $Env:GITHUB_ENV 48 | 49 | - name: Start PostgreSQL 50 | run: | 51 | sc config postgresql-x64-14 start= demand 52 | sc start postgresql-x64-14 53 | 54 | - name: Start MySQL 55 | run: | 56 | mysqld --initialize-insecure 57 | mysqld --install 58 | sc start MySQL 59 | 60 | - name: Checkout 61 | uses: actions/checkout@v4 62 | 63 | - name: Setup JDK 11 64 | uses: actions/setup-java@v4 65 | with: 66 | distribution: 'adopt' 67 | java-version: '11' 68 | 69 | - name: chmod -R 777 * 70 | run: chmod -R 777 * 71 | 72 | - name: Init gradle project 73 | run: ./gradlew clean --scan 74 | 75 | - name: Create Database and Account 76 | run: | 77 | & $Env:PGBIN/createdb -U postgres mirai 78 | mysqladmin -uroot create mirai 79 | mysqladmin -uroot password root 80 | sqlcmd -S tcp:localhost\SQLEXPRESS,1433 -Q "CREATE DATABASE mirai" -U sa 81 | 82 | - name: Assemble 83 | run: ./gradlew assemble --scan 84 | 85 | - name: SqliteTest 86 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.SqliteTest" --scan --info 87 | 88 | - name: H2Test 89 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.H2Test" --scan --info 90 | 91 | - name: MariaDBTest 92 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MariaDBTest" --scan --info 93 | 94 | - name: MySqlTest 95 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MySqlTest" --scan --info 96 | 97 | - name: PostgreSqlTest 98 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.PostgreSqlTest" --scan --info 99 | 100 | - name: MSSqlTest 101 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MSSqlTest" --scan --info 102 | 103 | macos: 104 | runs-on: macos-latest 105 | steps: 106 | 107 | - name: Start PostgreSQL 108 | run: | 109 | brew install postgresql 110 | brew info postgresql 111 | brew services start postgresql -v 112 | 113 | - name: Start MySQL 114 | run: | 115 | brew install mysql 116 | brew info mysql 117 | brew services start mysql -v 118 | 119 | - name: Checkout 120 | uses: actions/checkout@v4 121 | 122 | - name: Setup JDK 11 123 | uses: actions/setup-java@v4 124 | with: 125 | distribution: 'adopt' 126 | java-version: '11' 127 | 128 | - name: chmod -R 777 * 129 | run: chmod -R 777 * 130 | 131 | - name: Init gradle project 132 | run: ./gradlew clean --scan 133 | 134 | - name: Set Database User 135 | run: | 136 | createuser -U runner -s postgres 137 | createdb mirai 138 | psql -c "ALTER USER postgres PASSWORD 'root';" 139 | mysqladmin -uroot create mirai 140 | mysqladmin -uroot password root 141 | env: 142 | PGUSER: postgres 143 | PGDATABASE: postgres 144 | 145 | - name: Assemble 146 | run: ./gradlew assemble --scan 147 | 148 | - name: SqliteTest 149 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.SqliteTest" --scan --info 150 | 151 | - name: H2Test 152 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.H2Test" --scan --info 153 | 154 | - name: MariaDBTest 155 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MariaDBTest" --scan --info 156 | 157 | - name: MySqlTest 158 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MySqlTest" --scan --info 159 | 160 | - name: PostgreSqlTest 161 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.PostgreSqlTest" --scan --info 162 | 163 | linux: 164 | runs-on: ubuntu-latest 165 | steps: 166 | 167 | - name: Start PostgreSql 168 | run: | 169 | sudo systemctl start postgresql 170 | sudo -u postgres createdb mirai 171 | sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'root';" 172 | 173 | - name: Start MySQL 174 | run: | 175 | sudo systemctl start mysql.service 176 | mysqladmin -u root -proot create mirai 177 | 178 | - name: Checkout 179 | uses: actions/checkout@v4 180 | 181 | - name: Setup JDK 11 182 | uses: actions/setup-java@v4 183 | with: 184 | distribution: 'adopt' 185 | java-version: '11' 186 | 187 | - name: chmod -R 777 * 188 | run: chmod -R 777 * 189 | 190 | - name: Init gradle project 191 | run: ./gradlew clean --scan 192 | 193 | - name: Assemble 194 | run: ./gradlew assemble --scan 195 | 196 | - name: SqliteTest 197 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.SqliteTest" --scan --info 198 | 199 | - name: H2Test 200 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.H2Test" --scan --info 201 | 202 | - name: MariaDBTest 203 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MariaDBTest" --scan --info 204 | 205 | - name: MySqlTest 206 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.MySqlTest" --scan --info 207 | 208 | - name: PostgreSqlTest 209 | run: ./gradlew test --tests "xyz.cssxsh.mirai.hibernate.entry.PostgreSqlTest" --scan --info 210 | 211 | build: 212 | needs: [ windows, macos, linux ] 213 | runs-on: ubuntu-latest 214 | steps: 215 | - name: Checkout 216 | uses: actions/checkout@v4 217 | 218 | - name: Setup JDK 11 219 | uses: actions/setup-java@v4 220 | with: 221 | distribution: 'adopt' 222 | java-version: '11' 223 | 224 | - name: chmod -R 777 * 225 | run: chmod -R 777 * 226 | 227 | - name: Build Plugin 228 | run: ./gradlew buildPlugin 229 | 230 | - name: Upload 231 | uses: actions/upload-artifact@v4 232 | with: 233 | name: build-${{ github.run_id }} 234 | path: build/mirai/* -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/entry/MessageRecord.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate.entry 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.serialization.* 5 | import net.mamoe.mirai.* 6 | import net.mamoe.mirai.contact.* 7 | import net.mamoe.mirai.message.code.* 8 | import net.mamoe.mirai.message.data.* 9 | import net.mamoe.mirai.utils.* 10 | import xyz.cssxsh.hibernate.* 11 | import xyz.cssxsh.mirai.hibernate.* 12 | 13 | /** 14 | * 戳一戳记录 15 | * @param id 记录自增ID 16 | * @param bot 机器人ID 17 | * @param fromId 起始用户ID 18 | * @param targetId 目标用户ID 19 | * @param ids 消息ID 20 | * @param internalIds 消息SEQ 21 | * @param time Unix时间戳,秒单位 22 | * @param kind 消息类型 23 | * @param code 消息内容,JSON序列化 24 | * @param recalled 撤销者 25 | * @property recall 已撤销 26 | */ 27 | @Entity 28 | @Table(name = "message_record", indexes = [Index(columnList = "from_id"), Index(columnList = "target_id")]) 29 | @Serializable 30 | public data class MessageRecord( 31 | @Id 32 | @Column(name = "id", nullable = false, updatable = false) 33 | @GeneratedValue(strategy = GenerationType.IDENTITY) 34 | val id: Long = 0, 35 | @Column(name = "bot", nullable = false, updatable = false) 36 | val bot: Long, 37 | @Column(name = "from_id", nullable = false, updatable = false) 38 | val fromId: Long, 39 | @Column(name = "target_id", nullable = false, updatable = false) 40 | val targetId: Long, 41 | @Column(name = "ids", nullable = true, updatable = false) 42 | val ids: String?, 43 | @Column(name = "internal_ids", nullable = true, updatable = false) 44 | val internalIds: String?, 45 | @Column(name = "time", nullable = false, updatable = false) 46 | val time: Int, 47 | @Column(name = "kind", nullable = false, updatable = false) 48 | @Enumerated(value = EnumType.ORDINAL) 49 | val kind: MessageSourceKind, 50 | @Column(name = "code", nullable = false, updatable = false, columnDefinition = "text") 51 | val code: String, 52 | @Column(name = "recall", nullable = false, updatable = true) 53 | @Enumerated(value = EnumType.ORDINAL) 54 | @Serializable(RecalledKind.Serializer::class) 55 | @org.hibernate.annotations.ColumnDefault("0") 56 | val recalled: RecalledKind = RecalledKind.NONE 57 | ) : java.io.Serializable { 58 | /** 59 | * [MessageSource.originalMessage] 来自 [MessageRecord.code] 的解码 60 | */ 61 | public fun toMessageSource(): MessageSource { 62 | return Mirai.buildMessageSource(bot, kind) { 63 | fromId = this@MessageRecord.fromId 64 | targetId = this@MessageRecord.targetId 65 | ids = this@MessageRecord.ids.toIntArray() 66 | internalIds = this@MessageRecord.internalIds.toIntArray() 67 | time = this@MessageRecord.time 68 | messages(messages = toMessageChain()) 69 | } 70 | } 71 | 72 | /** 73 | * 从 [MessageRecord.code] 解码 74 | */ 75 | public fun toMessageChain(): MessageChain { 76 | return try { 77 | MessageChain.deserializeFromJsonString(code) 78 | } catch (cause: SerializationException) { 79 | try { 80 | MiraiCode.deserializeMiraiCode(code) 81 | } catch (_: Throwable) { 82 | throw cause 83 | } 84 | } 85 | } 86 | 87 | /** 88 | * 获取消息记录对应发送人名称 89 | * @param subject 上下文 90 | * @since 2.7 91 | */ 92 | @JvmOverloads 93 | public fun name(subject: Contact? = null): String { 94 | when (recalled) { 95 | RecalledKind.NONE -> Unit 96 | RecalledKind.SEND_FAIL -> return "send-fail" 97 | RecalledKind.SELF -> return "self-recalled" 98 | RecalledKind.ADMIN -> return "admin-recalled" 99 | } 100 | val context = subject ?: when (kind) { 101 | MessageSourceKind.GROUP -> Bot.getInstanceOrNull(qq = bot)?.getGroup(id = targetId) 102 | MessageSourceKind.FRIEND -> Bot.getInstanceOrNull(qq = bot)?.getFriend(id = targetId) 103 | MessageSourceKind.TEMP -> Bot.getInstanceOrNull(qq = bot)?.getFriend(id = targetId) 104 | MessageSourceKind.STRANGER -> Bot.getInstanceOrNull(qq = bot)?.getStranger(id = targetId) 105 | } 106 | val sender = when (context) { 107 | is Group -> if (fromId == bot) context.botAsMember else context[fromId] 108 | is Friend -> if (fromId == bot) context.bot else context 109 | is Stranger -> if (fromId == bot) context.bot else context 110 | null -> if (fromId == bot) Bot.getInstanceOrNull(qq = bot) else null 111 | else -> null 112 | } 113 | return sender?.nameCardOrNick ?: runCatching(::remark).getOrNull() ?: "$fromId" 114 | } 115 | 116 | private fun remark(): String? { 117 | return when (kind) { 118 | MessageSourceKind.GROUP -> factory.fromSession { session -> 119 | val record = session.withCriteria { query -> 120 | val root = query.from() 121 | val index = root.get("uuid") 122 | query.select(root) 123 | .where( 124 | equal(index, GroupMemberIndex(targetId, fromId)) 125 | ) 126 | }.singleResultOrNull 127 | record?.name 128 | } 129 | MessageSourceKind.FRIEND -> factory.fromSession { session -> 130 | val record = session.withCriteria { query -> 131 | val root = query.from() 132 | val index = root.get("uuid") 133 | query.select(root) 134 | .where( 135 | equal(index, FriendIndex(bot, fromId)) 136 | ) 137 | }.singleResultOrNull 138 | record?.remark 139 | } 140 | MessageSourceKind.TEMP -> factory.fromSession { session -> 141 | val record = session.withCriteria { query -> 142 | val root = query.from() 143 | val index = root.get("uuid") 144 | val uid = index.get("uid") 145 | query.select(root) 146 | .where( 147 | equal(uid, targetId) 148 | ) 149 | }.singleResultOrNull 150 | record?.name 151 | } 152 | MessageSourceKind.STRANGER -> null 153 | } 154 | } 155 | 156 | @get:jakarta.persistence.Transient 157 | public val recall: Boolean get() = recalled != RecalledKind.NONE 158 | 159 | public companion object { 160 | /** 161 | * From Success Send Message 162 | */ 163 | public fun fromSuccess(source: MessageSource, message: MessageChain): MessageRecord = MessageRecord( 164 | bot = source.botId, 165 | fromId = source.fromId, 166 | targetId = source.targetId, 167 | time = source.time, 168 | ids = source.ids.joinToString(","), 169 | internalIds = source.internalIds.joinToString(","), 170 | kind = source.kind, 171 | code = with(MessageChain) { 172 | message.serializeToJsonString() 173 | } 174 | ) 175 | 176 | /** 177 | * From Failure Send Message 178 | */ 179 | public fun fromFailure(target: Contact, message: MessageChain): MessageRecord = MessageRecord( 180 | bot = target.bot.id, 181 | fromId = target.bot.id, 182 | targetId = target.id, 183 | time = 0, 184 | ids = null, 185 | internalIds = null, 186 | kind = when (target) { 187 | is Group -> MessageSourceKind.GROUP 188 | is Friend -> MessageSourceKind.FRIEND 189 | is Member -> MessageSourceKind.TEMP 190 | is Stranger -> MessageSourceKind.STRANGER 191 | else -> throw NoSuchElementException("Unknown message kind with $target") 192 | }, 193 | code = with(MessageChain) { 194 | message.serializeToJsonString() 195 | }, 196 | recalled = RecalledKind.SEND_FAIL 197 | ) 198 | 199 | private fun String?.toIntArray(): IntArray { 200 | return if (isNullOrEmpty()) { 201 | IntArray(0) 202 | } else { 203 | split(',').mapToIntArray { it.toInt() } 204 | } 205 | } 206 | } 207 | } -------------------------------------------------------------------------------- /src/main/kotlin/xyz/cssxsh/mirai/hibernate/MiraiHibernateRecorder.kt: -------------------------------------------------------------------------------- 1 | package xyz.cssxsh.mirai.hibernate 2 | 3 | import jakarta.persistence.* 4 | import kotlinx.coroutines.* 5 | import net.mamoe.mirai.* 6 | import net.mamoe.mirai.contact.* 7 | import net.mamoe.mirai.event.* 8 | import net.mamoe.mirai.event.events.* 9 | import net.mamoe.mirai.internal.message.* 10 | import net.mamoe.mirai.message.data.* 11 | import net.mamoe.mirai.utils.* 12 | import xyz.cssxsh.hibernate.* 13 | import xyz.cssxsh.mirai.hibernate.entry.* 14 | import java.sql.* 15 | import java.io.* 16 | import java.util.* 17 | import java.util.stream.* 18 | import kotlin.coroutines.* 19 | 20 | /** 21 | * 消息记录器 记录机器人发送、接受和撤销的消息 22 | * @see MessageRecord 23 | * @see MessageEvent 24 | * @see MessagePostSendEvent 25 | * @see MessageRecallEvent 26 | * @see NudgeEvent 27 | */ 28 | public object MiraiHibernateRecorder : SimpleListenerHost() { 29 | 30 | private fun E.merge(): E = factory.fromTransaction { session -> session.merge(this@merge) } 31 | 32 | @EventHandler(priority = EventPriority.HIGHEST) 33 | internal fun MessageEvent.record() { 34 | launch { 35 | val message = message.asSequence().filterNot { it is MessageSource }.toMessageChain() 36 | val source = if (this@record is MessageSyncEvent) { 37 | source.copyAmend { 38 | fromId = bot.id 39 | targetId = subject.id 40 | } 41 | } else { 42 | source 43 | } 44 | MessageRecord.fromSuccess(source = source, message = message).merge() 45 | } 46 | launch { 47 | for (item in message) { 48 | when { 49 | item is Image && item.isEmoji -> FaceRecord.fromImage(image = item).merge() 50 | item is MarketFace && item !is Dice -> FaceRecord.fromMarketFace(face = item).merge() 51 | } 52 | } 53 | } 54 | } 55 | 56 | @Suppress("INVISIBLE_MEMBER") 57 | @EventHandler(priority = EventPriority.HIGHEST) 58 | internal fun MessagePostSendEvent<*>.record() { 59 | launch { 60 | val source = source 61 | val message = with(LightMessageRefiner) { message.dropMiraiInternalFlags() } 62 | if (source != null) { 63 | MessageRecord.fromSuccess(source = source, message = message).merge() 64 | } else { 65 | MessageRecord.fromFailure(target = target, message = message).merge() 66 | } 67 | } 68 | } 69 | 70 | @EventHandler(priority = EventPriority.HIGHEST) 71 | internal fun MessageRecallEvent.record() { 72 | val kind = when (this) { 73 | is MessageRecallEvent.FriendRecall -> { 74 | RecalledKind.SELF 75 | } 76 | is MessageRecallEvent.GroupRecall -> { 77 | if ((operator?.id ?: bot.id) != authorId) RecalledKind.ADMIN else RecalledKind.SELF 78 | } 79 | } 80 | launch { 81 | val targets = get(this@record) 82 | if (targets.isEmpty()) { 83 | logger.warning { "No found origin message for ${this@record}" } 84 | } 85 | for (record in targets) { 86 | record.copy(recalled = kind).merge() 87 | } 88 | } 89 | } 90 | 91 | @EventHandler(priority = EventPriority.HIGHEST) 92 | internal fun NudgeEvent.record() { 93 | launch { 94 | NudgeRecord(event = this@record).merge() 95 | } 96 | } 97 | 98 | @EventHandler(priority = EventPriority.HIGHEST) 99 | internal fun BotOnlineEvent.record() { 100 | launch { 101 | factory.fromTransaction { session -> 102 | session.merge(BotRecord.fromImpl(bot)) 103 | for (friend in bot.friends) { 104 | session.merge(FriendRecord.fromImpl(friend = friend)) 105 | } 106 | for (group in bot.groups) { 107 | session.merge(GroupMemberRecord.fromImpl(member = group.botAsMember)) 108 | for (member in group.members) { 109 | session.merge(GroupMemberRecord.fromImpl(member = member)) 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | @EventHandler(priority = EventPriority.HIGHEST) 117 | internal fun BotOfflineEvent.record() { 118 | if (reconnect) return 119 | launch { 120 | BotRecord.fromImpl(bot).merge() 121 | } 122 | } 123 | 124 | @EventHandler(priority = EventPriority.HIGHEST) 125 | internal fun BotNickChangedEvent.record() { 126 | launch { 127 | BotRecord.fromImpl(bot).merge() 128 | } 129 | } 130 | 131 | @EventHandler(priority = EventPriority.HIGHEST) 132 | internal fun FriendEvent.record() { 133 | if (this is MessageEvent && ignore.add(friend.id).not()) return 134 | launch { 135 | FriendRecord.fromEvent(event = this@record).merge() 136 | } 137 | } 138 | 139 | @EventHandler(priority = EventPriority.HIGHEST) 140 | internal fun GroupMemberEvent.record() { 141 | if (member !is NormalMember) return 142 | if (this is MessageEvent && ignore.add(member.id).not()) return 143 | launch { 144 | GroupMemberRecord.fromEvent(event = this@record).merge() 145 | } 146 | } 147 | 148 | @EventHandler(priority = EventPriority.HIGHEST) 149 | internal fun GroupEvent.record() { 150 | if (this is MessageEvent && ignore.add(group.id).not()) return 151 | launch { 152 | GroupRecord.fromImpl(group = group).merge() 153 | } 154 | } 155 | 156 | private val ignore: MutableSet = Collections.newSetFromMap(WeakHashMap()) 157 | 158 | private inline fun Throwable.unwrap(): T? { 159 | var current = this 160 | while (true) { 161 | if (current is T) return current 162 | current = current.cause ?: break 163 | } 164 | return null 165 | } 166 | 167 | override fun handleException(context: CoroutineContext, exception: Throwable) { 168 | when (val cause = exception.unwrap() ?: exception.unwrap() ?: exception) { 169 | is SQLIntegrityConstraintViolationException -> 170 | logger.debug({ "SQLIntegrityConstraintViolationException in Recorder" }, cause) 171 | is SQLException -> { 172 | logger.warning({ "SQLException in Recorder" }, cause) 173 | } 174 | is PersistenceException -> { 175 | logger.warning({ "PersistenceException in Recorder" }, cause) 176 | } 177 | is CancellationException -> { 178 | // ignore ... 179 | } 180 | is ExceptionInEventHandlerException -> { 181 | logger.warning({ "Exception in Recorder" }, cause.cause) 182 | } 183 | else -> { 184 | logger.warning({ "Exception in Recorder" }, exception) 185 | } 186 | } 187 | } 188 | 189 | /** 190 | * 通过 [md5] 获取表情包记录 191 | * @see FaceRecord.md5 192 | */ 193 | public fun face(md5: String): FaceRecord? { 194 | return factory.fromSession { session -> 195 | session.get(FaceRecord::class.java, md5) 196 | } 197 | } 198 | 199 | /** 200 | * 与 [event] 对应的记录 201 | * @see [MessageRecord.code] 202 | */ 203 | public operator fun get(event: MessageRecallEvent): List { 204 | return factory.fromSession { session -> 205 | session.withCriteria { query -> 206 | val record = query.from() 207 | query.select(record) 208 | .where( 209 | equal( 210 | record.get("kind"), when (event) { 211 | is MessageRecallEvent.FriendRecall -> MessageSourceKind.FRIEND 212 | is MessageRecallEvent.GroupRecall -> MessageSourceKind.GROUP 213 | } 214 | ), 215 | equal(record.get("fromId"), event.authorId), 216 | equal( 217 | record.get("targetId"), when (event) { 218 | is MessageRecallEvent.FriendRecall -> event.bot.id 219 | is MessageRecallEvent.GroupRecall -> event.group.id 220 | } 221 | ), 222 | equal(record.get("ids"), event.messageIds.joinToString()), 223 | equal(record.get("time"), event.messageTime) 224 | ) 225 | .orderBy(asc(abs(diff(record.get("bot"), event.bot.id)))) 226 | }.list() 227 | } 228 | } 229 | 230 | /** 231 | * 与 [source] 对应的记录 232 | * @see [MessageRecord.code] 233 | */ 234 | public operator fun get(source: MessageSource): List { 235 | return factory.fromSession { session -> 236 | session.withCriteria { query -> 237 | val record = query.from() 238 | query.select(record) 239 | .where( 240 | equal(record.get("kind"), source.kind), 241 | equal(record.get("fromId"), source.fromId), 242 | equal(record.get("targetId"), source.targetId), 243 | equal(record.get("ids"), source.ids.joinToString()), 244 | equal(record.get("time"), source.time) 245 | ) 246 | .orderBy(asc(abs(diff(record.get("bot"), source.botId)))) 247 | }.list() 248 | } 249 | } 250 | 251 | /** 252 | * [bot] 发送的 或 [bot] 收到 的消息 253 | * @param start 开始时间 254 | * @param end 结束时间 255 | */ 256 | public operator fun get(bot: Bot, start: Int, end: Int): List { 257 | return factory.fromSession { session -> 258 | session.withCriteria { query -> 259 | val record = query.from() 260 | query.select(record) 261 | .where( 262 | between(record.get("time"), start, end), 263 | equal(record.get("bot"), bot.id) 264 | ) 265 | .orderBy(desc(record.get("time"))) 266 | }.list() 267 | } 268 | } 269 | 270 | /** 271 | * [bot] 发送的 或 [bot] 收到 的消息 272 | */ 273 | public operator fun get(bot: Bot): Stream { 274 | val session = factory.openSession() 275 | return try { 276 | session.withCriteria { query -> 277 | val record = query.from() 278 | query.select(record) 279 | .where(equal(record.get("bot"), bot.id)) 280 | .orderBy(desc(record.get("time"))) 281 | }.stream().onClose { session.close() } 282 | } catch (cause: Throwable) { 283 | session.close() 284 | throw cause 285 | } 286 | } 287 | 288 | /** 289 | * 发送到群 [group] 或 从 [group] 收到 消息 290 | * @param start 开始时间 291 | * @param end 结束时间 292 | */ 293 | public operator fun get(group: Group, start: Int, end: Int): List { 294 | return factory.fromSession { session -> 295 | session.withCriteria { query -> 296 | val record = query.from() 297 | query.select(record) 298 | .where( 299 | equal(record.get("bot"), group.bot.id), 300 | between(record.get("time"), start, end), 301 | equal(record.get("kind"), MessageSourceKind.GROUP), 302 | equal(record.get("targetId"), group.id) 303 | ) 304 | .orderBy(desc(record.get("time"))) 305 | }.list() 306 | } 307 | } 308 | 309 | /** 310 | * 发送到群 [group] 或 从 [group] 收到 消息 311 | */ 312 | public operator fun get(group: Group): Stream { 313 | val session = factory.openSession() 314 | return try { 315 | session.withCriteria { query -> 316 | val record = query.from() 317 | query.select(record) 318 | .where( 319 | equal(record.get("bot"), group.bot.id), 320 | equal(record.get("kind"), MessageSourceKind.GROUP), 321 | equal(record.get("targetId"), group.id) 322 | ) 323 | .orderBy(desc(record.get("time"))) 324 | }.stream().onClose { session.close() } 325 | } catch (cause: Throwable) { 326 | session.close() 327 | throw cause 328 | } 329 | } 330 | 331 | /** 332 | * 发送到群 [friend] 或 从 [friend] 收到 的消息 333 | * @param start 开始时间 334 | * @param end 结束时间 335 | */ 336 | public operator fun get(friend: Friend, start: Int, end: Int): List { 337 | return factory.fromSession { session -> 338 | session.withCriteria { query -> 339 | val record = query.from() 340 | query.select(record) 341 | .where( 342 | equal(record.get("bot"), friend.bot.id), 343 | between(record.get("time"), start, end), 344 | equal(record.get("kind"), MessageSourceKind.FRIEND), 345 | or( 346 | equal(record.get("fromId"), friend.id), 347 | equal(record.get("targetId"), friend.id) 348 | ) 349 | ) 350 | .orderBy(desc(record.get("time"))) 351 | }.list() 352 | } 353 | } 354 | 355 | /** 356 | * 发送到群 [friend] 或 从 [friend] 收到 的消息 357 | */ 358 | public operator fun get(friend: Friend): Stream { 359 | val session = factory.openSession() 360 | return try { 361 | session.withCriteria { query -> 362 | val record = query.from() 363 | query.select(record) 364 | .where( 365 | equal(record.get("bot"), friend.bot.id), 366 | equal(record.get("kind"), MessageSourceKind.FRIEND), 367 | or( 368 | equal(record.get("fromId"), friend.id), 369 | equal(record.get("targetId"), friend.id) 370 | ) 371 | ) 372 | .orderBy(desc(record.get("time"))) 373 | }.stream().onClose { session.close() } 374 | } catch (cause: Throwable) { 375 | session.close() 376 | throw cause 377 | } 378 | } 379 | 380 | /** 381 | * [member] 发送的消息 382 | * @param start 开始时间 383 | * @param end 结束时间 384 | */ 385 | public operator fun get(member: Member, start: Int, end: Int): List { 386 | return factory.fromSession { session -> 387 | session.withCriteria { query -> 388 | val record = query.from() 389 | query.select(record) 390 | .where( 391 | equal(record.get("bot"), member.bot.id), 392 | between(record.get("time"), start, end), 393 | equal(record.get("kind"), MessageSourceKind.GROUP), 394 | equal(record.get("fromId"), member.id), 395 | equal(record.get("targetId"), member.group.id) 396 | ) 397 | .orderBy(desc(record.get("time"))) 398 | }.list() 399 | } 400 | } 401 | 402 | /** 403 | * [member] 发送的消息 404 | */ 405 | public operator fun get(member: Member): Stream { 406 | val session = factory.openSession() 407 | return try { 408 | session.withCriteria { query -> 409 | val record = query.from() 410 | query.select(record) 411 | .where( 412 | equal(record.get("bot"), member.bot.id), 413 | equal(record.get("kind"), MessageSourceKind.GROUP), 414 | equal(record.get("fromId"), member.id), 415 | equal(record.get("targetId"), member.group.id) 416 | ) 417 | .orderBy(desc(record.get("time"))) 418 | }.stream().onClose { session.close() } 419 | } catch (cause: Throwable) { 420 | session.close() 421 | throw cause 422 | } 423 | } 424 | 425 | /** 426 | * 发送到群 [stranger] 或 从 [stranger] 收到 的消息 427 | * @param start 开始时间 428 | * @param end 结束时间 429 | */ 430 | public operator fun get(stranger: Stranger, start: Int, end: Int): List { 431 | return factory.fromSession { session -> 432 | session.withCriteria { query -> 433 | val record = query.from() 434 | query.select(record) 435 | .where( 436 | equal(record.get("bot"), stranger.bot.id), 437 | between(record.get("time"), start, end), 438 | equal(record.get("kind"), MessageSourceKind.STRANGER), 439 | or( 440 | equal(record.get("fromId"), stranger.id), 441 | equal(record.get("targetId"), stranger.id) 442 | ) 443 | ) 444 | .orderBy(desc(record.get("time"))) 445 | }.list() 446 | } 447 | } 448 | 449 | /** 450 | * 发送到群 [stranger] 或 从 [stranger] 收到 的消息 451 | */ 452 | public operator fun get(stranger: Stranger): Stream { 453 | val session = factory.openSession() 454 | return try { 455 | session.withCriteria { query -> 456 | val record = query.from() 457 | query.select(record) 458 | .where( 459 | equal(record.get("bot"), stranger.bot.id), 460 | equal(record.get("kind"), MessageSourceKind.STRANGER), 461 | or( 462 | equal(record.get("fromId"), stranger.id), 463 | equal(record.get("targetId"), stranger.id) 464 | ) 465 | ) 466 | .orderBy(desc(record.get("time"))) 467 | }.stream().onClose { session.close() } 468 | } catch (cause: Throwable) { 469 | session.close() 470 | throw cause 471 | } 472 | } 473 | 474 | /** 475 | * 发送到群 [contact] 或 从 [contact] 收到 的消息 476 | * @param start 开始时间 477 | * @param end 结束时间 478 | */ 479 | public operator fun get(contact: Contact, start: Int, end: Int): List { 480 | return when (contact) { 481 | is Bot -> get(bot = contact, start = start, end = end) 482 | is Group -> get(group = contact, start = start, end = end) 483 | is Friend -> get(friend = contact, start = start, end = end) 484 | is Member -> get(member = contact, start = start, end = end) 485 | is Stranger -> get(stranger = contact, start = start, end = end) 486 | else -> throw IllegalStateException("不支持查询的联系人 $contact") 487 | } 488 | } 489 | 490 | /** 491 | * 发送到群 [contact] 或 从 [contact] 收到 的消息 492 | */ 493 | public operator fun get(contact: Contact): Stream { 494 | return when (contact) { 495 | is Bot -> get(bot = contact) 496 | is Group -> get(group = contact) 497 | is Friend -> get(friend = contact) 498 | is Member -> get(member = contact) 499 | is Stranger -> get(stranger = contact) 500 | else -> throw IllegalStateException("不支持查询的联系人 $contact") 501 | } 502 | } 503 | 504 | /** 505 | * 种类为 [kind] 的消息 506 | * @param start 开始时间 507 | * @param end 结束时间 508 | */ 509 | public operator fun get(kind: MessageSourceKind, start: Int, end: Int): List { 510 | return factory.fromSession { session -> 511 | session.withCriteria { query -> 512 | val record = query.from() 513 | query.select(record) 514 | .where( 515 | between(record.get("time"), start, end), 516 | equal(record.get("kind"), kind) 517 | ) 518 | .orderBy(desc(record.get("time"))) 519 | }.list() 520 | } 521 | } 522 | 523 | /** 524 | * 种类为 [kind] 的消息 525 | */ 526 | public operator fun get(kind: MessageSourceKind): Stream { 527 | val session = factory.openSession() 528 | return try { 529 | session.withCriteria { query -> 530 | val record = query.from() 531 | query.select(record) 532 | .where( 533 | equal(record.get("kind"), kind) 534 | ) 535 | .orderBy(desc(record.get("time"))) 536 | }.stream().onClose { session.close() } 537 | } catch (cause: Throwable) { 538 | session.close() 539 | throw cause 540 | } 541 | } 542 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to mirai it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) mirai the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to mirai the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, mirai and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | mirai a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to mirai, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise mirai, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------