From 620aeb939843823667fffb31be8971c091b4f0f3 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 7 Jul 2020 10:08:49 +0800 Subject: [PATCH 01/46] extends Event --- .../src/main/kotlin/io/github/wechaty/StateEnum.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/StateEnum.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/StateEnum.kt index fb54b6f..798027a 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/StateEnum.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/StateEnum.kt @@ -1,7 +1,7 @@ package io.github.wechaty -enum class StateEnum { +import io.github.wechaty.eventEmitter.Event +enum class StateEnum: Event { PENDING,ON,OFF; - -} \ No newline at end of file +} From db8081981df7c5dc4dba5978779c1f78b3bff5e0 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 7 Jul 2020 10:32:29 +0800 Subject: [PATCH 02/46] add some demo update pom.xml add onLougout event --- wechaty/pom.xml | 9 +++- .../java/io/github/wechaty/ContatcDemo.java | 40 +++++++++++++++ .../java/io/github/wechaty/FindRoomDemo.java | 32 ++++++++++++ .../java/io/github/wechaty/MetionDemo.java | 30 ++++++++++++ .../io/github/wechaty/MiniProgramDemo.java | 26 ++++++++++ .../main/java/io/github/wechaty/RoomDemo.java | 35 +++++++++++++ .../java/io/github/wechaty/SimpleExample.java | 49 +++++++++++++++++++ .../main/java/io/github/wechaty/Token.java | 5 ++ .../main/kotlin/io/github/wechaty/Wechaty.kt | 13 ++++- 9 files changed, 236 insertions(+), 3 deletions(-) create mode 100644 wechaty/src/main/java/io/github/wechaty/ContatcDemo.java create mode 100644 wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java create mode 100644 wechaty/src/main/java/io/github/wechaty/MetionDemo.java create mode 100644 wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java create mode 100644 wechaty/src/main/java/io/github/wechaty/RoomDemo.java create mode 100644 wechaty/src/main/java/io/github/wechaty/SimpleExample.java create mode 100644 wechaty/src/main/java/io/github/wechaty/Token.java diff --git a/wechaty/pom.xml b/wechaty/pom.xml index 728e0d1..8072d65 100644 --- a/wechaty/pom.xml +++ b/wechaty/pom.xml @@ -16,13 +16,17 @@ - io.github.wechaty wechaty-puppet ${project.version} - + + + io.github.wechaty + wechaty-puppet-hostie + ${project.version} + io.github.wechaty wechaty-puppet-mock @@ -107,6 +111,7 @@ junit test + org.reflections reflections diff --git a/wechaty/src/main/java/io/github/wechaty/ContatcDemo.java b/wechaty/src/main/java/io/github/wechaty/ContatcDemo.java new file mode 100644 index 0000000..af11d65 --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/ContatcDemo.java @@ -0,0 +1,40 @@ +package io.github.wechaty; + +import io.github.wechaty.schemas.ContactQueryFilter; +import io.github.wechaty.user.Contact; +import io.github.wechaty.user.Room; +import io.github.wechaty.user.manager.ContactManager; +import io.github.wechaty.user.manager.MessageManager; +import io.github.wechaty.utils.QrcodeUtils; + +import java.util.List; + +public class ContatcDemo { + public static void main(String[] args) { + Wechaty bot = Wechaty.instance(Token.token) + .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) + .onLogin(user -> System.out.println("User logined :" + user.name())) + .onMessage(message -> { + String text = message.text(); + Contact from = message.from(); + Contact to = message.to(); + Room room = message.room(); + System.out.println("收到来自" + from.name() + "的消息:" + text); + + if (text.contains("find")) { + from.say("请输入联系人名字:"); + } + else { + ContactQueryFilter queryFilter = new ContactQueryFilter(); + queryFilter.setName("犀利豆"); + ContactManager contactManager = new ContactManager(to.getWechaty()); + Contact contact = contactManager.find(queryFilter); + // 如果查询参数为空,那么就查询全部 + contactManager.findAll(new ContactQueryFilter()); + assert contact != null; + System.out.println(contact.name()); + } + }) + .start(true); + } +} diff --git a/wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java b/wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java new file mode 100644 index 0000000..c61957b --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java @@ -0,0 +1,32 @@ +package io.github.wechaty; + +import com.sun.xml.internal.ws.encoding.policy.MtomPolicyMapConfigurator; +import io.github.wechaty.schemas.ContactQueryFilter; +import io.github.wechaty.schemas.RoomQueryFilter; +import io.github.wechaty.user.Contact; +import io.github.wechaty.user.Room; +import io.github.wechaty.user.manager.ContactManager; +import io.github.wechaty.user.manager.RoomManager; +import io.github.wechaty.utils.QrcodeUtils; + +import java.util.List; + +public class FindRoomDemo { + public static void main(String[] args) { + Wechaty bot = Wechaty.instance(Token.token) + .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) + .onLogin(user -> System.out.println("User logined :" + user.name())) + .onMessage(message -> { + String text = message.text(); + Contact from = message.from(); + Contact to = message.to(); + Room room = message.room(); + System.out.println("接收到了消息" + text); + }) + .onLogout((contactId, reason) -> { + System.out.println("用户id为:" + contactId); + System.out.println("理由为:" + reason); + }) + .start(true); + } +} diff --git a/wechaty/src/main/java/io/github/wechaty/MetionDemo.java b/wechaty/src/main/java/io/github/wechaty/MetionDemo.java new file mode 100644 index 0000000..f7cd1c6 --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/MetionDemo.java @@ -0,0 +1,30 @@ +package io.github.wechaty; + +import io.github.wechaty.filebox.FileBox; +import io.github.wechaty.user.Contact; +import io.github.wechaty.user.Room; +import io.github.wechaty.user.UrlLink; +import io.github.wechaty.utils.QrcodeUtils; + +import java.util.List; + +public class MetionDemo { + public static void main(String[] args) { + Wechaty bot = Wechaty.instance(Token.token) + .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) + .onLogin(user -> System.out.println("User logined :" + user.name())) + .onMessage(message -> { + String text = message.text(); + Contact from = message.from(); + Room room = message.room(); + System.out.println(message.text()); + System.out.println("收到来自" + from.name() + "的消息:" + text); + + List contacts = message.mentionList(); + for (Contact contact : contacts) { + System.out.println(contact.name()); + } + }) + .start(true); + } +} diff --git a/wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java b/wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java new file mode 100644 index 0000000..78b3219 --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java @@ -0,0 +1,26 @@ +package io.github.wechaty; + +import io.github.wechaty.schemas.ContactQueryFilter; +import io.github.wechaty.user.Contact; +import io.github.wechaty.user.MiniProgram; +import io.github.wechaty.user.Room; +import io.github.wechaty.user.manager.ContactManager; +import io.github.wechaty.utils.QrcodeUtils; + +public class MiniProgramDemo { + public static void main(String[] args) { + Wechaty bot = Wechaty.instance(Token.token) + .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) + .onLogin(user -> System.out.println("User logined :" + user.name())) + .onMessage(message -> { + String text = message.text(); + Contact from = message.from(); + Contact to = message.to(); + Room room = message.room(); + System.out.println("收到来自" + from.name() + "的消息:" + text); + + from.say(MiniProgram.Companion.create()); + }) + .start(true); + } +} diff --git a/wechaty/src/main/java/io/github/wechaty/RoomDemo.java b/wechaty/src/main/java/io/github/wechaty/RoomDemo.java new file mode 100644 index 0000000..4315e4f --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/RoomDemo.java @@ -0,0 +1,35 @@ +package io.github.wechaty; + +import io.github.wechaty.schemas.ContactQueryFilter; +import io.github.wechaty.user.Contact; +import io.github.wechaty.user.Room; +import io.github.wechaty.user.manager.ContactManager; +import io.github.wechaty.user.manager.RoomManager; +import io.github.wechaty.utils.QrcodeUtils; + +public class RoomDemo { + public static void main(String[] args) { + Wechaty bot = Wechaty.instance(Token.token) + .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) + .onLogin(user -> System.out.println("User logined :" + user.name())) + .onMessage(message -> { + String text = message.text(); + Contact from = message.from(); + Contact to = message.to(); + Room room = message.room(); + System.out.println("收到来自" + from.name() + "的消息:" + text); + + ContactQueryFilter queryFilter = new ContactQueryFilter(); + queryFilter.setName("Friday BOT"); + ContactManager contactManager = new ContactManager(to.getWechaty()); + Contact contact = contactManager.find(queryFilter); + + if (contact != null) { + room.add(contact); + System.out.println(contact.name()); + room.say("已邀请" + contact.name() + "加入群聊"); + } + }) + .start(true); + } +} diff --git a/wechaty/src/main/java/io/github/wechaty/SimpleExample.java b/wechaty/src/main/java/io/github/wechaty/SimpleExample.java new file mode 100644 index 0000000..5b5c9f9 --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/SimpleExample.java @@ -0,0 +1,49 @@ +package io.github.wechaty; + +import io.github.wechaty.filebox.FileBox; +import io.github.wechaty.user.Contact; +import io.github.wechaty.user.Room; +import io.github.wechaty.user.UrlLink; +import io.github.wechaty.user.UrlLinkKt; +import io.github.wechaty.utils.QrcodeUtils; + +import java.util.List; + +public class SimpleExample { + public static void main(String[] args) { + + Wechaty bot = Wechaty.instance(Token.token) + .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) + .onLogin(user -> System.out.println("User logined :" + user.name())) + .onMessage(message -> { + Contact to = message.to(); + String text = message.text(); + Contact from = message.from(); + Room room = message.room(); + UrlLink urlLink = UrlLink.Companion.create("https://wechaty.js.org/v/zh/api"); + System.out.println(message.text()); + System.out.println("收到来自" + from.name() + "的消息:" + text); + if (text.contains("ding")) { + if (room != null) { + room.say("nihao" + from.name()); + } else { + System.out.println("现在是单对单聊天"); + // 向from说话 + from.say("nihaosdasd"); + from.say(urlLink); + from.say(FileBox.fromUrl("https://upload-images.jianshu.io/upload_images/13859386-effeaff79bda02fd.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240/format/webp", "images.jpg", null)); + to.say("woyehao"); + } + } + + else { + System.out.println("不包含ding"); + } + }) + .onLogout((contactId, reason) -> { + System.out.println("用户id为:" + contactId); + System.out.println("理由为" + contactId); + }) + .start(true); + } +} diff --git a/wechaty/src/main/java/io/github/wechaty/Token.java b/wechaty/src/main/java/io/github/wechaty/Token.java new file mode 100644 index 0000000..de9d121 --- /dev/null +++ b/wechaty/src/main/java/io/github/wechaty/Token.java @@ -0,0 +1,5 @@ +package io.github.wechaty; + +public class Token { + static final String token = "puppet_padplus_0d01102884cd1233"; +} diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index 442c037..58fe007 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -80,6 +80,9 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : return on(EventEnum.LOGIN,listener) } + fun onLogout(listener: LogoutListener): Wechaty { + return on(EventEnum.LOGOUT, listener) + } fun onScan(listener: ScanListener):Wechaty{ return on(EventEnum.SCAN,listener); } @@ -122,6 +125,14 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : return this } + private fun on(event: Event, listener: LogoutListener): Wechaty { + super.on(event, object : Listener { + override fun handler(vararg any: Any) { + listener.handler(any[0] as String, any[1] as String) + } + }) + return this + } private fun on(event: Event, listener: DongListener):Wechaty { return this } @@ -248,7 +259,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : override fun handler(payload: EventLogoutPayload) { val contact = contactManager.loadSelf(payload.contactId) contact.ready() - emit(EventEnum.LOGOUT, contact, payload.data) + emit(EventEnum.LOGOUT, contact.id, payload.data) } }) } From 83cb4b55d760755186ae2169b89f58eb7e271829 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 7 Jul 2020 12:30:33 +0800 Subject: [PATCH 03/46] add StorageBackend implements --- .../wechaty/memorycard/backend/StorageFile.kt | 93 +++++++++++++++++++ .../wechaty/memorycard/backend/StorageNop.kt | 67 +++++++++++++ .../wechaty/memorycard/backend/StorageObs.kt | 66 +++++++++++++ .../wechaty/memorycard/backend/StorageS3.kt | 67 +++++++++++++ 4 files changed, 293 insertions(+) create mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt create mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt create mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt create mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt new file mode 100644 index 0000000..3190930 --- /dev/null +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -0,0 +1,93 @@ +package io.github.wechaty.io.github.wechaty.memorycard.backend + +import io.github.wechaty.io.github.wechaty.status.StateSwitch +import io.github.wechaty.memorycard.MemoryCardPayload +import io.github.wechaty.memorycard.StorageBackend +import io.github.wechaty.memorycard.StorageBackendOptions +import io.github.wechaty.memorycard.StorageFileOptions +import io.github.wechaty.utils.JsonUtils +import org.apache.commons.io.FileUtils +import org.apache.commons.io.FilenameUtils +import org.apache.commons.lang3.StringUtils +import org.slf4j.LoggerFactory +import java.io.File +import java.lang.Exception +import kotlin.math.abs + +class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { + + private var absFileName:String + + init { + + log.info("StorageFile, constructor(%s, ...)", name) + + options.type = "file" + options = options as StorageFileOptions + + val file = File(name) + + if(file.isAbsolute) { + this.absFileName = name + } + else { + this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) + } + + if(!StringUtils.endsWith(this.absFileName,".memory-card.json")) { + this.absFileName += ".memory-card.json" + } + + } + + override fun load(): MemoryCardPayload { + log.info("StorageFile, load() from %s", this.absFileName) + + val file = File(absFileName) + if(!file.exists()){ + return MemoryCardPayload() + } + val text = FileUtils.readFileToString(file, "UTF-8") + var payload = MemoryCardPayload() + try { + payload = JsonUtils.readValue(text); + } + catch (e: Exception) { + log.error("MemoryCard, load() exception: %s", e) + } + return payload + + } + + override fun save(payload: MemoryCardPayload) { + log.info("StorageFile, save() to %s", this.absFileName) + val text = JsonUtils.write(payload) + val file = File(absFileName) + FileUtils.write(file,text,"UTF-8") + + } + + override fun destory() { + log.info("StorageFile, destoay()") + + val file = File(absFileName) + if (file.exists()) { + FileUtils.deleteQuietly(file) + } + } + + override fun toString(): String { + return "${this.name}<${this.absFileName}>" + } + companion object { + private val log = LoggerFactory.getLogger(StorageFile::class.java) + } +} + + + +fun main(){ + + StorageFile("test", StorageFileOptions()) + +} diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt new file mode 100644 index 0000000..85a5876 --- /dev/null +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt @@ -0,0 +1,67 @@ +package io.github.wechaty.io.github.wechaty.memorycard.backend + +import io.github.wechaty.memorycard.MemoryCardPayload +import io.github.wechaty.memorycard.StorageBackend +import io.github.wechaty.memorycard.StorageBackendOptions +import io.github.wechaty.memorycard.StorageFileOptions +import io.github.wechaty.utils.JsonUtils +import org.apache.commons.io.FileUtils +import org.apache.commons.io.FilenameUtils +import org.apache.commons.lang3.StringUtils +import org.slf4j.LoggerFactory +import java.io.File + +class StorageNop(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { + + private var absFileName:String + + init { + options.type = "file" + options = options as StorageFileOptions + val file = File(name) + if(file.isAbsolute){ + this.absFileName = name + }else{ + this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) + } + + if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ + this.absFileName += ".memory-card.json" + } + + } + + override fun save(payload: MemoryCardPayload) { + val text = JsonUtils.write(payload) + val file = File(absFileName) + FileUtils.write(file,text,"UTF-8") + + } + + override fun load(): MemoryCardPayload { + val file = File(absFileName) + if(!file.exists()){ + return MemoryCardPayload() + } + val text = FileUtils.readFileToString(file, "UTF-8") + return JsonUtils.readValue(text); + + } + + override fun destory() { + TODO("Not yet implemented") + } + + companion object { + private val log = LoggerFactory.getLogger(StorageNop::class.java) + } + +} + + + +fun main(){ + + StorageFile("test", StorageFileOptions()) + +} diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt new file mode 100644 index 0000000..b3dca40 --- /dev/null +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -0,0 +1,66 @@ +package io.github.wechaty.io.github.wechaty.memorycard.backend + +import io.github.wechaty.memorycard.MemoryCardPayload +import io.github.wechaty.memorycard.StorageBackend +import io.github.wechaty.memorycard.StorageBackendOptions +import io.github.wechaty.memorycard.StorageFileOptions +import io.github.wechaty.utils.JsonUtils +import org.apache.commons.io.FileUtils +import org.apache.commons.io.FilenameUtils +import org.apache.commons.lang3.StringUtils +import org.slf4j.LoggerFactory +import java.io.File + +class StorageObs(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { + + private var absFileName:String + + init { + options.type = "file" + options = options as StorageFileOptions + val file = File(name) + if(file.isAbsolute){ + this.absFileName = name + }else{ + this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) + } + + if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ + this.absFileName += ".memory-card.json" + } + + } + + override fun save(payload: MemoryCardPayload) { + val text = JsonUtils.write(payload) + val file = File(absFileName) + FileUtils.write(file,text,"UTF-8") + + } + + override fun load(): MemoryCardPayload { + val file = File(absFileName) + if(!file.exists()){ + return MemoryCardPayload() + } + val text = FileUtils.readFileToString(file, "UTF-8") + return JsonUtils.readValue(text); + + } + + override fun destory() { + TODO("Not yet implemented") + } + + companion object { + private val log = LoggerFactory.getLogger(StorageObs::class.java) + } +} + + + +fun main(){ + + StorageFile("test", StorageFileOptions()) + +} diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt new file mode 100644 index 0000000..1d7a2cf --- /dev/null +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -0,0 +1,67 @@ +package io.github.wechaty.io.github.wechaty.memorycard.backend + +import io.github.wechaty.memorycard.MemoryCardPayload +import io.github.wechaty.memorycard.StorageBackend +import io.github.wechaty.memorycard.StorageBackendOptions +import io.github.wechaty.memorycard.StorageFileOptions +import io.github.wechaty.utils.JsonUtils +import org.apache.commons.io.FileUtils +import org.apache.commons.io.FilenameUtils +import org.apache.commons.lang3.StringUtils +import org.slf4j.LoggerFactory +import java.io.File + +class StorageS3(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { + + private var absFileName:String + + init { + options.type = "file" + options = options as StorageFileOptions + val file = File(name) + if(file.isAbsolute){ + this.absFileName = name + }else{ + this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) + } + + if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ + this.absFileName += ".memory-card.json" + } + + } + + override fun save(payload: MemoryCardPayload) { + val text = JsonUtils.write(payload) + val file = File(absFileName) + FileUtils.write(file,text,"UTF-8") + + } + + override fun load(): MemoryCardPayload { + val file = File(absFileName) + if(!file.exists()){ + return MemoryCardPayload() + } + val text = FileUtils.readFileToString(file, "UTF-8") + return JsonUtils.readValue(text); + + } + + override fun destory() { + TODO("Not yet implemented") + } + + companion object { + private val log = LoggerFactory.getLogger(StorageS3::class.java) + } + +} + + + +fun main(){ + + StorageFile("test", StorageFileOptions()) + +} From f9543faeb62f9d578d6b40bbdf91a586cb1074ae Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 7 Jul 2020 12:30:59 +0800 Subject: [PATCH 04/46] add MemoryCard.kt --- .../github/wechaty/memorycard/MemoryCard.kt | 281 ++++++++++++------ .../wechaty/memorycard/StorageOptions.kt | 68 +++-- .../wechaty/memorycard/StrorageBackend.kt | 77 +++-- 3 files changed, 268 insertions(+), 158 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index e6864fd..c988441 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -1,89 +1,192 @@ -//package io.github.wechaty.memorycard -// -//import org.slf4j.LoggerFactory -//import java.util.concurrent.Future -// -//class MemoryCard{ -// -// private var name:String? = null -// protected var parent:MemoryCard? = null -// protected var payload:MemoryCardPayload ? = null -// protected var storage:StorageBackend? = null -// protected val multiplexNameList = mutableListOf() -// -// private var options:MemoryCardOptions -// -// constructor(name: String?=null,options:MemoryCardOptions? = null){ -// -// val _optiones:MemoryCardOptions = options ?: MemoryCardOptions() -// -// if(name != null){ -// if(options != null) { -// _optiones.name = name -// } -// } -// this.options = _optiones -// this.name = _optiones.name -// -// (_optiones.multiplex != null).let { -// this.parent = _optiones.multiplex!!.parent -// this.payload = this.parent!!.payload -// this.multiplexNameList.addAll(parent!!.multiplexNameList) -// this.multiplexNameList.add(_optiones.multiplex!!.name) -// this.storage = null -// } -// -// (_optiones.multiplex == null).let { -// this.payload = null -// this.multiplexNameList.clear() -// } -// } -// -// private fun getStore():StorageBackend?{ -// log.debug("getStorage() for storage type: %s'",this.options) -// -// return StorageBackend.getStorage( -// this.options.name!!, -// this.options.storageOptions -// ) -// } -// -// fun load(){ -// this.payload = this.storage!!.load() -// } -// -// fun save(){ -// this.storage!!.save(this.payload!!) -// } -// -// companion object{ -// private val log = LoggerFactory.getLogger(MemoryCard::class.java) -// -// fun multiplex(memory:MemoryCard,name:String):MemoryCard{ -// return MemoryCard() -// } -// } -// -// -//} -// -//class MemoryCardPayload{ -// val map:Map = HashMap() -//} -// -//data class Multiplex( -// val parent:MemoryCard, -// val name:String -//) -// -//class MemoryCardOptions{ -// -// var name:String? = null -// var storageOptions:StorageBackendOptions? = null -// var multiplex:Multiplex? = null -// -//} -// -// -// -// +package io.github.wechaty.memorycard + +import io.github.wechaty.utils.JsonUtils +import org.slf4j.LoggerFactory +import java.lang.Exception +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Future + +const val NAMESPACE_MULTIPLEX_SEPRATOR = "\r" +const val NAMESPACE_KEY_SEPRATOR = "\n" + +val NAMESPACE_MULTIPLEX_SEPRATOR_REGEX = Regex(NAMESPACE_MULTIPLEX_SEPRATOR) +val NAMESPACE_KEY_SEPRATOR_REGEX = Regex(NAMESPACE_KEY_SEPRATOR) + +class MemoryCard { + + private var name:String? = null + protected var parent:MemoryCard? = null + protected var payload:MemoryCardPayload ? = null + protected var storage:StorageBackend? = null + protected val multiplexNameList = mutableListOf() + + private var options:MemoryCardOptions + + constructor(name: String?=null,options:MemoryCardOptions? = null){ + + val _optiones:MemoryCardOptions = options ?: MemoryCardOptions() + + if(name != null){ + if(options != null) { + _optiones.name = name + } + } + this.options = _optiones + this.name = _optiones.name + + (_optiones.multiplex != null).let { + this.parent = _optiones.multiplex!!.parent + this.payload = this.parent!!.payload + this.multiplexNameList.addAll(parent!!.multiplexNameList) + this.multiplexNameList.add(_optiones.multiplex!!.name) + this.storage = null + } + + (_optiones.multiplex == null).let { + this.payload = null + this.multiplexNameList.clear() + } + } + + private fun getStore():StorageBackend?{ + log.debug("getStorage() for storage type: %s'",this.options) + + return StorageBackend.getStorage( + this.options.name!!, + this.options.storageOptions + ) + } + + fun load() { + this.payload = this.storage!!.load() + } + + fun save() { + this.storage!!.save(this.payload!!) + } + + fun destory(): Future { + log.info("MemoryCard, destroy() storage: %s", this.storage ?: "N/A") + if (this.isMultiplex()) { + throw Exception("can not destroy on a multiplexed memory") + } + + if (this.payload != null) { + this.destory() + this.storage = null + } + this.payload = null + return CompletableFuture.completedFuture(null) + } + + + fun size(): Future { + log.info("MemoryCard, <%s> size", this.multiplexPath()) + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + + var count: Int + if (this.isMultiplex()) { + count = this.payload!!.map.keys + .filter { key -> this.isMultiplexKey(key) } + .size + } + else { + count = this.payload!!.map.size + } + + return CompletableFuture.completedFuture(count) + } + + + fun isMultiplex (): Boolean { + return this.multiplexNameList.size > 0 + } + + protected fun multiplexPath(): String { + return this.multiplexNameList.joinToString("/") + } + + protected fun multiplexNamespace(): String { + if (!this.isMultiplex()) { + throw Exception("not a multiplex memory") + } + + val namespace = NAMESPACE_MULTIPLEX_SEPRATOR + + this.multiplexNameList.joinToString(NAMESPACE_MULTIPLEX_SEPRATOR) + return namespace + } + protected fun isMultiplexKey (key: String): Boolean { + + if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.matches(key) + && NAMESPACE_KEY_SEPRATOR_REGEX.matches(key)) { + + val namespace = this.multiplexNamespace() + return key.startsWith(namespace) + } + return false + } + + protected fun resolveKey (name: String): String { + + if (this.isMultiplex()) { + val namespace = this.multiplexNamespace() + return namespace + NAMESPACE_KEY_SEPRATOR + name + } + else { + return name + } + } + companion object{ + private val log = LoggerFactory.getLogger(MemoryCard::class.java) + val VERSION = "0.0.0" + fun multiplex(memory:MemoryCard,name:String):MemoryCard{ + return MemoryCard() + } + + fun fromJSON(text: String): MemoryCard { + log.info("MemoryCard, fromJSON(...)") + var jsonObj: MemoryCardJsonObject + jsonObj = JsonUtils.readValue(text) + val card = MemoryCard(jsonObj.options.name, jsonObj.options) + card.payload = jsonObj.payload + return MemoryCard() + } + + fun fromJSON(obj: MemoryCardJsonObject): MemoryCard { + log.info("MemoryCard, fromJSON(...)") + val card = MemoryCard(obj.options.name, obj.options) + card.payload = obj.payload + + return card + } + } + + +} + +class MemoryCardPayload{ + val map: Map = HashMap() +} + +data class Multiplex( + val parent: MemoryCard, + val name: String +) + +class MemoryCardOptions{ + + var name:String? = null + var storageOptions:StorageBackendOptions? = null + var multiplex:Multiplex? = null +} + +data class MemoryCardJsonObject( + val payload: MemoryCardPayload, + val options: MemoryCardOptions +) + + + + diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt index f2d32a8..75cc22b 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt @@ -1,30 +1,38 @@ -//package io.github.wechaty.memorycard -// -//sealed class StorageBackendOptions{ -// var type:String?=null -//} -// -//data class StorageS3Options( -// val accessKeyId:String, -// val secretAccessKey:String, -// val region:String, -// val bucket:String -//):StorageBackendOptions() -// -// -//data class StorageObsOptions( -// val accessKeyId:String, -// val secretAccessKey:String, -// val server:String, -// val bucket:String -//):StorageBackendOptions() -// -//class StorageNopOptions: StorageBackendOptions() { -// var placeholder: String? = null -//} -// -//typealias StorageFileOptions = StorageNopOptions -// -//val BACKEND_DICT = mapOf( -// "file" to StorageFile::class -//) +package io.github.wechaty.memorycard + +import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile +import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageNop +import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageObs +import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageS3 + +sealed class StorageBackendOptions { + var type: String? = null +} + +data class StorageS3Options( + val accessKeyId:String, + val secretAccessKey:String, + val region:String, + val bucket:String +):StorageBackendOptions() + + +data class StorageObsOptions( + val accessKeyId:String, + val secretAccessKey:String, + val server:String, + val bucket:String +):StorageBackendOptions() + +class StorageNopOptions: StorageBackendOptions() { + var placeholder: String? = null +} + +typealias StorageFileOptions = StorageNopOptions + +val BACKEND_DICT = mapOf( + "file" to StorageFile::class, + "s3" to StorageS3::class, + "nop" to StorageNop::class, + "obs" to StorageObs::class +) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt index 6879ab5..597fa98 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt @@ -1,39 +1,38 @@ -//package io.github.wechaty.memorycard -// -//import org.slf4j.LoggerFactory -//import kotlin.reflect.full.createInstance -//import kotlin.reflect.full.primaryConstructor -// -//abstract class StorageBackend(name: String, option: StorageBackendOptions) { -// -// init { -// log.debug("constructor({}, { type: {} })",name,option) -// } -// -// abstract fun save(payload: MemoryCardPayload) -// abstract fun load():MemoryCardPayload -// abstract fun destory() -// -// companion object{ -// private val log = LoggerFactory.getLogger(StorageBackend::class.java) -// -// fun getStorage(name: String,options: StorageBackendOptions?):StorageBackend{ -// -// var _options = options -// -// if(options == null) { -// _options = StorageFileOptions() -// _options.type = "file" -// } -// -// if(_options?.type == null || _options.type !in BACKEND_DICT.keys){ -// throw Exception("backed unknown : ${_options?.type}") -// } -// -// -// } -// -// } -// -//} -// +package io.github.wechaty.memorycard + +import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile +import io.github.wechaty.utils.JsonUtils +import org.slf4j.LoggerFactory + +abstract class StorageBackend(name: String, option: StorageBackendOptions) { + + init { + log.debug("constructor({}, { type: {} })", name, option) + } + + abstract fun save(payload: MemoryCardPayload) + abstract fun load():MemoryCardPayload + abstract fun destory() + + companion object{ + private val log = LoggerFactory.getLogger(StorageBackend::class.java) + + fun getStorage(name: String,options: StorageBackendOptions?): StorageBackend { + log.info("getStorage', name: %s, options: %s", name, options?.let { JsonUtils.write(it) }) + + var _options = options + + if(options == null) { + _options = StorageFileOptions() + _options.type = "file" + } + + if(_options?.type == null || _options.type!! !in BACKEND_DICT.keys){ + throw Exception("backed unknown : ${_options?.type}") + } + return StorageFile(name, _options) + } + } + +} + From 8312cb2e23f6221fc1e69eb410bb69318e7b0948 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 7 Jul 2020 13:28:25 +0800 Subject: [PATCH 05/46] add MemoryCard.kt method like load save, delete --- .../github/wechaty/memorycard/MemoryCard.kt | 141 +++++++++++++++++- 1 file changed, 134 insertions(+), 7 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index c988441..626a5a5 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory import java.lang.Exception import java.util.concurrent.CompletableFuture import java.util.concurrent.Future +import kotlin.math.abs const val NAMESPACE_MULTIPLEX_SEPRATOR = "\r" const val NAMESPACE_KEY_SEPRATOR = "\n" @@ -22,7 +23,8 @@ class MemoryCard { private var options:MemoryCardOptions - constructor(name: String?=null,options:MemoryCardOptions? = null){ + constructor(name: String? = null,options:MemoryCardOptions? = null){ + log.info("MemoryCard, constructor(%s)", options?.let { JsonUtils.write(it) }) val _optiones:MemoryCardOptions = options ?: MemoryCardOptions() @@ -37,32 +39,77 @@ class MemoryCard { (_optiones.multiplex != null).let { this.parent = _optiones.multiplex!!.parent this.payload = this.parent!!.payload + this.multiplexNameList.addAll(parent!!.multiplexNameList) this.multiplexNameList.add(_optiones.multiplex!!.name) + this.storage = null } (_optiones.multiplex == null).let { this.payload = null this.multiplexNameList.clear() + this.storage = getStore() } } - private fun getStore():StorageBackend?{ - log.debug("getStorage() for storage type: %s'",this.options) + private fun getStore(): StorageBackend?{ + log.debug("getStorage() for storage type: %s", + if (this.options != null && this.options.storageOptions != null && this.options.storageOptions!!.type != null) + this.options + else + "N/A" + ) + + if (this.options == null) { + return null + } return StorageBackend.getStorage( this.options.name!!, this.options.storageOptions ) } - fun load() { - this.payload = this.storage!!.load() + fun load(): Future { + log.info("MemoryCard, load() from storage: %s", this.storage ?: "N/A") + if (this.isMultiplex()) { + log.info("MemoryCard, load() should not be called on a multiplex MemoryCard. NOOP") + return CompletableFuture.completedFuture(null) + } + if (this.payload == null) { + throw Exception("memory had already loaded before.") + } + + if (this.storage != null) { + this.payload = this.storage!!.load() + } + else { + log.info("MemoryCard, load() no storage") + this.payload = MemoryCardPayload() + } + return CompletableFuture.completedFuture(null) } - fun save() { + fun save(): Future { + if (this.isMultiplex()) { + if (this.parent == null) { + throw Exception("multiplex memory no parent") + } + } + this.parent!!.save() + + log.info("MemoryCard, <%s>%s save() to %s",this.name ?: "", this.multiplexPath(), this.storage ?: "N/A") + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + + if (this.storage == null) { + log.info("MemoryCard, save() no storage, NOOP") + } + this.storage!!.save(this.payload!!) + return CompletableFuture.completedFuture(null) } fun destory(): Future { @@ -138,6 +185,86 @@ class MemoryCard { return name } } + + fun get(name: String): CompletableFuture? { + log.info("MemoryCard, <%s> get(%s)", this.multiplexPath(), name) + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + + val key = this.resolveKey(name) + return CompletableFuture.supplyAsync { + this.payload!!.map.get(key) + } + } + + fun set(name: String, data: T): Future { + log.info("MemoryCard, <%s> set(%s, %s)", this.multiplexPath(), name, data) + + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + + val key = this.resolveKey(name) + this.payload!!.map[key] = data as Any + return CompletableFuture.completedFuture(null) + } + + fun clear(): Future { + log.info("MemoryCard, <%s> clear()", this.multiplexPath()) + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + if (this.isMultiplex()) { + val keys = this.payload!!.map.keys + for (key in keys) { + this.payload!!.map.remove(key) + } + } + else { + this.payload = MemoryCardPayload() + } + return CompletableFuture.completedFuture(null) + } + + fun delete(name: String): Future { + + log.info("MemoryCard, <%s> delete(%s)", this.multiplexPath(), name) + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + + val key = this.resolveKey(name) + this.payload!!.map.remove(key) + return CompletableFuture.completedFuture(null) + } + + fun has(key: String): Future { + log.info("MemoryCard, <%s> has (%s)", this.multiplexPath(), key) + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + val absoluteKey = this.resolveKey(key) + return CompletableFuture.supplyAsync { + this.payload!!.map.containsKey(absoluteKey) + } + } + + + override fun toString(): String { + var mpString = "" + if (this.multiplexNameList.size > 0) { + mpString = this.multiplexNameList + .map { mpName -> "multiplex(${mpName})" } + .joinToString("") + } + var name = "" + if (this.options != null && this.options.name != null) { + name = this.options.name.toString() + } + + return "MemoryCard<${name}>${mpString}" + } companion object{ private val log = LoggerFactory.getLogger(MemoryCard::class.java) val VERSION = "0.0.0" @@ -167,7 +294,7 @@ class MemoryCard { } class MemoryCardPayload{ - val map: Map = HashMap() + val map = mutableMapOf() } data class Multiplex( From 7854172f3689a3ae479ec2adea9824ff8a2a854e Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 7 Jul 2020 13:28:52 +0800 Subject: [PATCH 06/46] add StateSwitch.kt method like on,off --- .../io/github/wechaty/status/StateSwitch.kt | 54 ++++++++++++++++--- 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index f3aa3f8..5a64df9 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -2,6 +2,7 @@ package io.github.wechaty.io.github.wechaty.status import io.github.wechaty.StateEnum import io.github.wechaty.eventEmitter.EventEmitter +import io.github.wechaty.eventEmitter.Listener import io.github.wechaty.io.github.wechaty.schemas.EventEnum import org.slf4j.LoggerFactory import java.util.concurrent.CompletableFuture @@ -36,22 +37,61 @@ class StateSwitch:EventEmitter(){ } } - fun on(state: StateEnum):StateEnum{ + fun on(state: StateEnum):StateEnum { val on = on() - log.debug("statusSwitch $name on ${state.name} <- $on") + log.debug("statusSwitch $name on ${state.name} <- ${on}") onoff = true pending = (state == StateEnum.PENDING) - emit(EventEnum.ON,state.name) - TODO() + emit(EventEnum.ON, state.name) + return on } - fun on():StateEnum{ - TODO() + fun on(): StateEnum { + val on = + if (this.onoff == true) + if (this.pending == true) + StateEnum.PENDING + else + StateEnum.ON + else + StateEnum.OFF + log.info("StateSwitch, <%s> on() is %s", this.name, on) + return on } - companion object{ + fun off(state: StateEnum) { + log.info("StateSwitch, <%s> off(%s) <- (%s)", this.name, state, this.off()) + this.onoff = false + this.pending = (state == StateEnum.PENDING) + this.emit(StateEnum.OFF, state) + +// if (this.onResolver == null) { +// +// } + } + + fun off(): StateEnum { + val off = + if (!this.onoff) + if (this.pending) + StateEnum.PENDING + else + StateEnum.ON + else + StateEnum.OFF + log.info("StateSwitch, <%s> off() is %s", this.name, off) + return off + } + + fun addEventListener(type: StateEnum, listener: Listener) { + super.addListener(type, listener) + } + fun removeEventListener(type: StateEnum, listener: Listener) { + super.removeListener(type, listener) + } + companion object { private val log = LoggerFactory.getLogger(StateSwitch::class.java) } From 3f09b5ecdb29a3dbcb5cb7a350e847d49e2b6d20 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Wed, 8 Jul 2020 19:52:14 +0800 Subject: [PATCH 07/46] update StorageNop.kt StorageObs.kt StorageS3.kt --- .../github/wechaty/memorycard/MemoryCard.kt | 32 ++++++++++ .../github/wechaty/memorycard/StorageFile.kt | 58 ------------------- .../wechaty/memorycard/backend/StorageFile.kt | 15 +++-- .../wechaty/memorycard/backend/StorageNop.kt | 51 +++++----------- .../wechaty/memorycard/backend/StorageObs.kt | 45 ++++++-------- .../wechaty/memorycard/backend/StorageS3.kt | 58 +++++++++++-------- 6 files changed, 110 insertions(+), 149 deletions(-) delete mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageFile.kt diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 626a5a5..5102ac7 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -241,16 +241,48 @@ class MemoryCard { fun has(key: String): Future { log.info("MemoryCard, <%s> has (%s)", this.multiplexPath(), key) + if (this.payload == null) { throw Exception("no payload, please call load() first.") } + val absoluteKey = this.resolveKey(key) return CompletableFuture.supplyAsync { this.payload!!.map.containsKey(absoluteKey) } } + fun keys(): MutableSet { + log.info("MemoryCard, <%s> keys()", this.multiplexPath()) + + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + var result = mutableSetOf() + for (key in this.payload!!.map.keys) { + if (this.isMultiplex()) { + if (this.isMultiplexKey(key)) { + val namespace = this.multiplexNamespace() + val mpKey = key.substring(namespace.length + 1) + result.add(mpKey) + } + continue + } + result.add(key) + } + return result + } + + + fun values(): MutableCollection { + log.info("MemoryCard, <%s> values()", this.multiplexPath()) + + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + return this.payload!!.map.values + } override fun toString(): String { var mpString = "" if (this.multiplexNameList.size > 0) { diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageFile.kt deleted file mode 100644 index f4647a8..0000000 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageFile.kt +++ /dev/null @@ -1,58 +0,0 @@ -//package io.github.wechaty.memorycard -// -//import io.github.wechaty.utils.JsonUtils -//import org.apache.commons.io.FileUtils -//import org.apache.commons.io.FilenameUtils -//import org.apache.commons.lang3.StringUtils -//import java.io.File -// -//class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { -// -// private var absFileName:String -// -// init { -// options.type = "file" -// options = options as StorageFileOptions -// val file = File(name) -// if(file.isAbsolute){ -// this.absFileName = name -// }else{ -// this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) -// } -// -// if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ -// this.absFileName += ".memory-card.json" -// } -// -// } -// -// override fun save(payload: MemoryCardPayload) { -// val text = JsonUtils.write(payload) -// val file = File(absFileName) -// FileUtils.write(file,text,"UTF-8") -// -// } -// -// override fun load(): MemoryCardPayload { -// val file = File(absFileName) -// if(!file.exists()){ -// return MemoryCardPayload() -// } -// val text = FileUtils.readFileToString(file, "UTF-8") -// return JsonUtils.readValue(text); -// -// } -// -// override fun destory() { -// TODO("Not yet implemented") -// } -// -//} -// -// -// -//fun main(){ -// -// StorageFile("test",StorageFileOptions()) -// -//} diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index 3190930..45e0bb7 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -14,9 +14,9 @@ import java.io.File import java.lang.Exception import kotlin.math.abs -class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { +class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name, options) { - private var absFileName:String + private var absFileName: String init { @@ -61,10 +61,11 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag override fun save(payload: MemoryCardPayload) { log.info("StorageFile, save() to %s", this.absFileName) + val text = JsonUtils.write(payload) val file = File(absFileName) - FileUtils.write(file,text,"UTF-8") + FileUtils.write(file,text,"UTF-8") } override fun destory() { @@ -72,7 +73,13 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag val file = File(absFileName) if (file.exists()) { - FileUtils.deleteQuietly(file) + val deleteQuietly = FileUtils.deleteQuietly(file) + if (deleteQuietly) { + log.info("destory() ${this.absFileName} success") + } + else { + log.warn("destory() ${this.absFileName} failed") + } } } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt index 85a5876..801806e 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt @@ -1,9 +1,6 @@ package io.github.wechaty.io.github.wechaty.memorycard.backend -import io.github.wechaty.memorycard.MemoryCardPayload -import io.github.wechaty.memorycard.StorageBackend -import io.github.wechaty.memorycard.StorageBackendOptions -import io.github.wechaty.memorycard.StorageFileOptions +import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils @@ -13,43 +10,27 @@ import java.io.File class StorageNop(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private var absFileName:String - init { - options.type = "file" - options = options as StorageFileOptions - val file = File(name) - if(file.isAbsolute){ - this.absFileName = name - }else{ - this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) - } - - if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ - this.absFileName += ".memory-card.json" - } + log.info("StorageNop, constructor(%s, ...)", name) + options.type = "nop" + options = options as StorageNopOptions + } + override fun load(): MemoryCardPayload { + log.info("StorageNop, load()") + return MemoryCardPayload() } override fun save(payload: MemoryCardPayload) { - val text = JsonUtils.write(payload) - val file = File(absFileName) - FileUtils.write(file,text,"UTF-8") - + log.info("StorageNop, save()") } - override fun load(): MemoryCardPayload { - val file = File(absFileName) - if(!file.exists()){ - return MemoryCardPayload() - } - val text = FileUtils.readFileToString(file, "UTF-8") - return JsonUtils.readValue(text); - + override fun destory() { + log.info("StorageNop, destroy()") } - override fun destory() { - TODO("Not yet implemented") + override fun toString(): String { + return "${this.name} " } companion object { @@ -60,8 +41,6 @@ class StorageNop(val name: String, var options: StorageBackendOptions) : Storage -fun main(){ - - StorageFile("test", StorageFileOptions()) - +fun main() { + StorageFile("test", StorageNopOptions()) } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index b3dca40..2501754 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -1,9 +1,11 @@ package io.github.wechaty.io.github.wechaty.memorycard.backend -import io.github.wechaty.memorycard.MemoryCardPayload -import io.github.wechaty.memorycard.StorageBackend -import io.github.wechaty.memorycard.StorageBackendOptions -import io.github.wechaty.memorycard.StorageFileOptions +import com.amazonaws.auth.AWSStaticCredentialsProvider +import com.amazonaws.auth.BasicAWSCredentials +import com.amazonaws.regions.Regions +import com.amazonaws.services.s3.AmazonS3 +import com.amazonaws.services.s3.AmazonS3ClientBuilder +import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils @@ -13,45 +15,36 @@ import java.io.File class StorageObs(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private var absFileName:String + private lateinit var s3: AmazonS3 init { - options.type = "file" - options = options as StorageFileOptions - val file = File(name) - if(file.isAbsolute){ - this.absFileName = name - }else{ - this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) - } - - if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ - this.absFileName += ".memory-card.json" - } + + log.info("StorageS3, constructor()") + options.type = "s3" + options = options as StorageS3Options + val basicAWSCredentials = BasicAWSCredentials((options as StorageS3Options).accessKeyId, (options as StorageS3Options).secretAccessKey) + this.s3 = AmazonS3ClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(basicAWSCredentials)) + .withRegion(Regions.DEFAULT_REGION).build() } override fun save(payload: MemoryCardPayload) { - val text = JsonUtils.write(payload) - val file = File(absFileName) - FileUtils.write(file,text,"UTF-8") } override fun load(): MemoryCardPayload { - val file = File(absFileName) - if(!file.exists()){ - return MemoryCardPayload() - } - val text = FileUtils.readFileToString(file, "UTF-8") - return JsonUtils.readValue(text); + return MemoryCardPayload() } override fun destory() { TODO("Not yet implemented") } + override fun toString(): String { + return "${this.name}<${this.name}>" + } + companion object { private val log = LoggerFactory.getLogger(StorageObs::class.java) } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 1d7a2cf..9f8207b 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -1,9 +1,11 @@ package io.github.wechaty.io.github.wechaty.memorycard.backend -import io.github.wechaty.memorycard.MemoryCardPayload -import io.github.wechaty.memorycard.StorageBackend -import io.github.wechaty.memorycard.StorageBackendOptions -import io.github.wechaty.memorycard.StorageFileOptions +import com.amazonaws.auth.AWSStaticCredentialsProvider +import com.amazonaws.auth.BasicAWSCredentials +import com.amazonaws.regions.Regions +import com.amazonaws.services.s3.AmazonS3 +import com.amazonaws.services.s3.AmazonS3ClientBuilder +import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils @@ -13,45 +15,51 @@ import java.io.File class StorageS3(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private var absFileName:String + private lateinit var s3: AmazonS3 init { - options.type = "file" - options = options as StorageFileOptions - val file = File(name) - if(file.isAbsolute){ - this.absFileName = name - }else{ - this.absFileName = FilenameUtils.concat(System.getProperty("user.dir"),name) - } - if(!StringUtils.endsWith(this.absFileName,".memory-card.json")){ - this.absFileName += ".memory-card.json" - } + log.info("StorageS3, constructor()") + options.type = "s3" + options = options as StorageS3Options + val basicAWSCredentials = BasicAWSCredentials((options as StorageS3Options).accessKeyId, (options as StorageS3Options).secretAccessKey) + this.s3 = AmazonS3ClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(basicAWSCredentials)) + .withRegion((options as StorageS3Options).region).build() } override fun save(payload: MemoryCardPayload) { - val text = JsonUtils.write(payload) - val file = File(absFileName) - FileUtils.write(file,text,"UTF-8") + log.info("StorageS3, save()") + val options = this.options as StorageS3Options + + this.s3.putObject(JsonUtils.write(payload), options.bucket, this.name) } override fun load(): MemoryCardPayload { - val file = File(absFileName) - if(!file.exists()){ + log.info("StorageS3, load()") + + val options = this.options as StorageS3Options + val result = this.s3.getObject(options.bucket, this.name) + if (result==null || result.objectContent == null) { return MemoryCardPayload() } - val text = FileUtils.readFileToString(file, "UTF-8") - return JsonUtils.readValue(text); - + // 这里还有问题 + return MemoryCardPayload() } override fun destory() { - TODO("Not yet implemented") + log.info("StorageS3, destory()") + + val options = this.options as StorageS3Options + this.s3.deleteObject(options.bucket, this.name) + } + + override fun toString(): String { + return "${this.name}<${this.name}>" } + companion object { private val log = LoggerFactory.getLogger(StorageS3::class.java) } From db363cea7bdb682e530b614a6ca42b41cc712686 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Wed, 8 Jul 2020 21:43:20 +0800 Subject: [PATCH 08/46] =?UTF-8?q?=E7=AE=80=E5=8C=96json=E5=AD=98=E5=82=A8?= =?UTF-8?q?=E5=BD=A2=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/github/wechaty/memorycard/MemoryCard.kt | 2 +- .../io/github/wechaty/memorycard/StorageOptions.kt | 12 ++++++------ .../github/wechaty/memorycard/backend/StorageFile.kt | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 5102ac7..8c5ea9f 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -326,7 +326,7 @@ class MemoryCard { } class MemoryCardPayload{ - val map = mutableMapOf() + var map = mutableMapOf() } data class Multiplex( diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt index 75cc22b..973b539 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt @@ -9,6 +9,12 @@ sealed class StorageBackendOptions { var type: String? = null } +class StorageNopOptions: StorageBackendOptions() { + var placeholder: String? = null +} + +typealias StorageFileOptions = StorageNopOptions + data class StorageS3Options( val accessKeyId:String, val secretAccessKey:String, @@ -24,12 +30,6 @@ data class StorageObsOptions( val bucket:String ):StorageBackendOptions() -class StorageNopOptions: StorageBackendOptions() { - var placeholder: String? = null -} - -typealias StorageFileOptions = StorageNopOptions - val BACKEND_DICT = mapOf( "file" to StorageFile::class, "s3" to StorageS3::class, diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index 45e0bb7..9eb1b50 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -14,6 +14,8 @@ import java.io.File import java.lang.Exception import kotlin.math.abs +// 本身是不存储数据的 +// 存储了持久化的文件名和选项 class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name, options) { private var absFileName: String @@ -50,21 +52,19 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag val text = FileUtils.readFileToString(file, "UTF-8") var payload = MemoryCardPayload() try { - payload = JsonUtils.readValue(text); + payload.map = JsonUtils.readValue(text); } catch (e: Exception) { log.error("MemoryCard, load() exception: %s", e) } return payload - } override fun save(payload: MemoryCardPayload) { log.info("StorageFile, save() to %s", this.absFileName) - val text = JsonUtils.write(payload) + val text = JsonUtils.write(payload.map) val file = File(absFileName) - FileUtils.write(file,text,"UTF-8") } From 50d9131b8ff5b04b9a13ee9361377d45667c1dce Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 9 Jul 2020 22:17:04 +0800 Subject: [PATCH 09/46] update StorageObs.kt and MemoryCard.kt --- .../github/wechaty/memorycard/MemoryCard.kt | 93 ++++++++++++------ .../wechaty/memorycard/backend/StorageNop.kt | 4 +- .../wechaty/memorycard/backend/StorageObs.kt | 95 +++++++++++++++---- .../wechaty/memorycard/backend/StorageS3.kt | 38 +++++--- 4 files changed, 169 insertions(+), 61 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 8c5ea9f..4c99632 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -13,6 +13,7 @@ const val NAMESPACE_KEY_SEPRATOR = "\n" val NAMESPACE_MULTIPLEX_SEPRATOR_REGEX = Regex(NAMESPACE_MULTIPLEX_SEPRATOR) val NAMESPACE_KEY_SEPRATOR_REGEX = Regex(NAMESPACE_KEY_SEPRATOR) +// 名字可以由options传入也可以直接传入 class MemoryCard { private var name:String? = null @@ -21,39 +22,45 @@ class MemoryCard { protected var storage:StorageBackend? = null protected val multiplexNameList = mutableListOf() + // 是否是multiplex,用哪个存储后端,memorycard名字是什么 private var options:MemoryCardOptions - constructor(name: String? = null,options:MemoryCardOptions? = null){ + // name和options里面的name有可能同时为空 + constructor(name: String? = null, options: MemoryCardOptions? = null) { log.info("MemoryCard, constructor(%s)", options?.let { JsonUtils.write(it) }) - - val _optiones:MemoryCardOptions = options ?: MemoryCardOptions() - - if(name != null){ - if(options != null) { - _optiones.name = name - } + val _options: MemoryCardOptions = options ?: MemoryCardOptions() + if(name != null) { + _options.name = name } - this.options = _optiones - this.name = _optiones.name - - (_optiones.multiplex != null).let { - this.parent = _optiones.multiplex!!.parent + else if (_options.name != null) { + this.name = _options.name + } + else { + this.name = "default" + _options.name = "default" + } + this.options = _options + // let不能这么用 +// false.let { +// println(1) +// } + if (_options.multiplex != null) { + this.parent = _options.multiplex!!.parent this.payload = this.parent!!.payload this.multiplexNameList.addAll(parent!!.multiplexNameList) - this.multiplexNameList.add(_optiones.multiplex!!.name) + this.multiplexNameList.add(_options.multiplex!!.name) this.storage = null } - - (_optiones.multiplex == null).let { + else { this.payload = null this.multiplexNameList.clear() this.storage = getStore() } } - private fun getStore(): StorageBackend?{ + private fun getStore(): StorageBackend? { log.debug("getStorage() for storage type: %s", if (this.options != null && this.options.storageOptions != null && this.options.storageOptions!!.type != null) @@ -65,6 +72,8 @@ class MemoryCard { if (this.options == null) { return null } + + // 默认得到一个file的后端 return StorageBackend.getStorage( this.options.name!!, this.options.storageOptions @@ -77,7 +86,7 @@ class MemoryCard { log.info("MemoryCard, load() should not be called on a multiplex MemoryCard. NOOP") return CompletableFuture.completedFuture(null) } - if (this.payload == null) { + if (this.payload != null) { throw Exception("memory had already loaded before.") } @@ -96,8 +105,9 @@ class MemoryCard { if (this.parent == null) { throw Exception("multiplex memory no parent") } + this.parent!!.save() } - this.parent!!.save() + log.info("MemoryCard, <%s>%s save() to %s",this.name ?: "", this.multiplexPath(), this.storage ?: "N/A") if (this.payload == null) { @@ -106,6 +116,7 @@ class MemoryCard { if (this.storage == null) { log.info("MemoryCard, save() no storage, NOOP") + return CompletableFuture.completedFuture(null) } this.storage!!.save(this.payload!!) @@ -118,8 +129,10 @@ class MemoryCard { throw Exception("can not destroy on a multiplexed memory") } - if (this.payload != null) { - this.destory() +// this.clear() + + if (this.storage != null) { + this.storage!!.destory() this.storage = null } this.payload = null @@ -212,6 +225,7 @@ class MemoryCard { fun clear(): Future { log.info("MemoryCard, <%s> clear()", this.multiplexPath()) + if (this.payload == null) { throw Exception("no payload, please call load() first.") } @@ -228,7 +242,6 @@ class MemoryCard { } fun delete(name: String): Future { - log.info("MemoryCard, <%s> delete(%s)", this.multiplexPath(), name) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -239,6 +252,16 @@ class MemoryCard { return CompletableFuture.completedFuture(null) } + fun entries(): MutableSet> { + log.info("MemoryCard, <%s> *entries()", this.multiplexPath()) + + if (this.payload == null) { + throw Exception("no payload, please call load() first.") + } + + return this.payload!!.map.entries + } + fun has(key: String): Future { log.info("MemoryCard, <%s> has (%s)", this.multiplexPath(), key) @@ -283,6 +306,14 @@ class MemoryCard { return this.payload!!.map.values } + + fun multiplex (name: String): MemoryCard { + log.info("MemoryCard, multiplex(%s)", name) + + // FIXME: as any ? + return multiplex(this, name) + } + override fun toString(): String { var mpString = "" if (this.multiplexNameList.size > 0) { @@ -300,8 +331,12 @@ class MemoryCard { companion object{ private val log = LoggerFactory.getLogger(MemoryCard::class.java) val VERSION = "0.0.0" - fun multiplex(memory:MemoryCard,name:String):MemoryCard{ - return MemoryCard() + + fun multiplex(memory: MemoryCard, name: String): MemoryCard{ + log.info("MemoryCard, static multiplex(%s, %s)", memory, name) + memory.options.multiplex = Multiplex(name = name, parent = memory) + val mpMemory = MemoryCard(options = memory.options) + return mpMemory } fun fromJSON(text: String): MemoryCard { @@ -334,12 +369,11 @@ data class Multiplex( val name: String ) -class MemoryCardOptions{ - - var name:String? = null - var storageOptions:StorageBackendOptions? = null +data class MemoryCardOptions( + var name: String? = null, + var storageOptions:StorageBackendOptions? = null, var multiplex:Multiplex? = null -} +) data class MemoryCardJsonObject( val payload: MemoryCardPayload, @@ -349,3 +383,4 @@ data class MemoryCardJsonObject( + diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt index 801806e..5d32409 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt @@ -36,11 +36,11 @@ class StorageNop(val name: String, var options: StorageBackendOptions) : Storage companion object { private val log = LoggerFactory.getLogger(StorageNop::class.java) } - } fun main() { - StorageFile("test", StorageNopOptions()) + var storageNop = StorageNop("test", StorageNopOptions()) + println(storageNop) } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index 2501754..f9e4718 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -5,46 +5,93 @@ import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.regions.Regions import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.AmazonS3ClientBuilder +import com.obs.services.ObsClient import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream import java.io.File +// 使用华为的云存储服务 class StorageObs(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private lateinit var s3: AmazonS3 + private lateinit var obs: ObsClient init { - - log.info("StorageS3, constructor()") - options.type = "s3" - options = options as StorageS3Options - val basicAWSCredentials = BasicAWSCredentials((options as StorageS3Options).accessKeyId, (options as StorageS3Options).secretAccessKey) - this.s3 = AmazonS3ClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(basicAWSCredentials)) - .withRegion(Regions.DEFAULT_REGION).build() - + log.info("StorageObs, constructor()") + options.type = "obs" + options = options as StorageObsOptions + var _options = options as StorageObsOptions + this.obs = ObsClient(_options.accessKeyId, _options.secretAccessKey, _options.server) } override fun save(payload: MemoryCardPayload) { - + log.info("StorageObs, save()") + this.putObject(payload) } override fun load(): MemoryCardPayload { - - return MemoryCardPayload() + log.info("StorageObs, load()") + val card = this.getObject() + if (card == null) { + return MemoryCardPayload() + } + + log.info("press", card) + return card } override fun destory() { - TODO("Not yet implemented") + log.info("StorageObs, destroy()") + this.deleteObject() } override fun toString(): String { return "${this.name}<${this.name}>" } + private fun putObject(payload: MemoryCardPayload) { + val options = this.options as StorageObsOptions + val putObject = this.obs.putObject(options.bucket, this.name, ByteArrayInputStream(JsonUtils.write(payload.map).toByteArray())) + // 还需要处理异常 + if (putObject.statusCode >= 300) { + throw Exception("obs putObject error") + } + } + + private fun getObject(): MemoryCardPayload { + val options = this.options as StorageObsOptions + val obsObject = this.obs.getObject(options.bucket, this.name) + val input = obsObject.objectContent + var byte = ByteArray(1024) + val bos = ByteArrayOutputStream() + var len = 0; + while (true) { + len = input.read(byte) + if (len != -1) { + bos.write(byte, 0, len) + } + else { + break + } + } + var card = MemoryCardPayload() + card.map = JsonUtils.readValue(String(bos.toByteArray())) + return card + } + + private fun deleteObject() { + val options = this.options as StorageObsOptions + val deleteObject = this.obs.deleteObject(options.bucket, this.name) + if (deleteObject.statusCode >= 300) { + throw Exception("obs deleteObject error") + } + } + companion object { private val log = LoggerFactory.getLogger(StorageObs::class.java) } @@ -53,7 +100,23 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage fun main(){ - - StorageFile("test", StorageFileOptions()) - + val storageObsOptions = StorageObsOptions("D5RKYDQRCRYICGP65H2R", "K0Va8jn8kWBK8jzdmC4QC2vvqsgF5Epz1iWhZOOp", + "obs.cn-north-4.myhuaweicloud.com", "cybersa") + + val storageObs = StorageObs("objectname", storageObsOptions) + val load = storageObs.load() + println(load.map) + load.map.forEach { t, u -> print(t + ":" + u) } + storageObs.destory() + +// var obsClient = ObsClient("D5RKYDQRCRYICGP65H2R", "K0Va8jn8kWBK8jzdmC4QC2vvqsgF5Epz1iWhZOOp", +// "obs.cn-north-4.myhuaweicloud.com") +// var map = mutableMapOf() +// map.put("a", "nihsdasd") +// obsClient.putObject("cybersa", "objectname", ByteArrayInputStream(JsonUtils.write(map).toByteArray())) +// val obsObject = obsClient.getObject("cybersa", "objectname") +// var byte = ByteArray(1024) +// var len = obsObject.objectContent.read(byte) +// println(String(byte, 0 , len)) +// obsClient.close() } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 9f8207b..4e0df85 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -2,29 +2,25 @@ package io.github.wechaty.io.github.wechaty.memorycard.backend import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials -import com.amazonaws.regions.Regions import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.AmazonS3ClientBuilder import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils -import org.apache.commons.io.FileUtils -import org.apache.commons.io.FilenameUtils -import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory -import java.io.File class StorageS3(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { private lateinit var s3: AmazonS3 init { - log.info("StorageS3, constructor()") options.type = "s3" options = options as StorageS3Options - val basicAWSCredentials = BasicAWSCredentials((options as StorageS3Options).accessKeyId, (options as StorageS3Options).secretAccessKey) + var _options = options as StorageS3Options + + val basicAWSCredentials = BasicAWSCredentials(_options.accessKeyId, _options.secretAccessKey) this.s3 = AmazonS3ClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(basicAWSCredentials)) - .withRegion((options as StorageS3Options).region).build() + .withRegion(_options.region).build() } @@ -32,7 +28,7 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB log.info("StorageS3, save()") val options = this.options as StorageS3Options - this.s3.putObject(JsonUtils.write(payload), options.bucket, this.name) + this.s3.putObject(JsonUtils.write(payload.map), options.bucket, this.name) } @@ -45,12 +41,27 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB return MemoryCardPayload() } // 这里还有问题 - return MemoryCardPayload() + val objectContent = result.objectContent + var payloadMap = StringBuffer() + var readBuf = ByteArray(1024) + var readLen = 0 + while (true) { + readLen = objectContent.read(readBuf) + if (readLen > 0) { + payloadMap.append(String(readBuf, 0, readLen)) + } + else { + break + } + } + + var payload = MemoryCardPayload() + payload.map = JsonUtils.readValue(payloadMap.toString()) + return payload } override fun destory() { log.info("StorageS3, destory()") - val options = this.options as StorageS3Options this.s3.deleteObject(options.bucket, this.name) } @@ -66,10 +77,9 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB } - - fun main(){ - StorageFile("test", StorageFileOptions()) + val storageS3 = StorageS3("test", StorageS3Options("1", "1", "2", "3")) + val load = storageS3.load() } From 96bb05f3aeca2fc8540774fd789a6d68245ede1e Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 9 Jul 2020 22:17:46 +0800 Subject: [PATCH 10/46] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8E=E4=B8=BA?= =?UTF-8?q?=E4=BA=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet/pom.xml | 16 +++++ .../io/github/wechaty/utils/JsonUtils.kt | 3 +- .../MemoryCardTest.kt | 71 +++++++++++++++++++ 3 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt diff --git a/wechaty-puppet/pom.xml b/wechaty-puppet/pom.xml index c78acd0..7fe2e93 100644 --- a/wechaty-puppet/pom.xml +++ b/wechaty-puppet/pom.xml @@ -40,6 +40,11 @@ commons-lang3 + + com.amazonaws + aws-java-sdk-s3 + 1.11.636 + @@ -105,7 +110,18 @@ okhttp + + + com.huaweicloud + esdk-obs-java + 3.19.7 + + + junit + junit + test + diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/utils/JsonUtils.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/utils/JsonUtils.kt index 70bd984..a775dc0 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/utils/JsonUtils.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/utils/JsonUtils.kt @@ -15,11 +15,10 @@ object JsonUtils { return mapper.readValue(json) } - fun write(input:Any):String{ + fun write(input:Any):String { return mapper.writeValueAsString(input) } - } diff --git a/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt b/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt new file mode 100644 index 0000000..6f37d95 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt @@ -0,0 +1,71 @@ +package io.github.wechaty.io.github.wechaty.memorycard.test + +import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile +import io.github.wechaty.memorycard.* +import org.junit.Before +import org.junit.Test + + +class MemoryCardTest { + + lateinit var memoryCard: MemoryCard + + @Before + fun setUp() { + memoryCard = MemoryCard("test") + } + @Test + fun testCreate() { + + this.memoryCard.load() + this.memoryCard.values().forEach { + println(it) + } + this.memoryCard.destory() + } + + @Test + fun testLoad() { + this.memoryCard.load() + this.memoryCard.set("a", "b") + this.memoryCard.save() + } + + @Test + fun testSave() { + var card = MemoryCard() + card.load() + card.set("a", "你好") +// println(card.get("a")?.get()) + card.keys().forEach { + println(it) + } + card.save() + } + @Test + fun testDestory() { + } + + @Test + fun testMultiplex() { + memoryCard.load() + // 这里的name是前缀的名字 + // \rparent\nson + val multiplex = Multiplex(this.memoryCard, "parent") + val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) + println(memoryCardOptions) + // 用debug模式会有问题 + // 如果一个memory是multiple的,那么它自身就不会保存,只会保存一个父类的 + var son = MemoryCard(options = memoryCardOptions) + son.load() + + son.set("son", "b") + son.set("nihao", "asdasd") + println(son.get("son")?.get()) + son.delete("nihao") + println(son.has("nihao").get()) + println(son.has("son").get()) + son.save() + } + +} From 62cfbd5af998689d5635958ea367dda0e13e26b6 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 9 Jul 2020 22:23:59 +0800 Subject: [PATCH 11/46] add some onXXX Event --- .../main/kotlin/io/github/wechaty/Wechaty.kt | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index 58fe007..ea75d4a 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -86,6 +86,9 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : fun onScan(listener: ScanListener):Wechaty{ return on(EventEnum.SCAN,listener); } + fun onFriendship(listener: FriendshipListener): Wechaty { + return on(EventEnum.FRIENDSHIP, listener) + } fun onRoomJoin(listener: RoomJoinListener):Wechaty { return on(EventEnum.ROOM_JOIN,listener) @@ -99,10 +102,16 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : return on(EventEnum.ROOM_TOPIC,listener) } + fun onRoomInvite(listener: RoomInviteListener): Wechaty { + return on(EventEnum.ROOM_INVITE, listener) + } fun onMessage(listener: MessageListener):Wechaty{ return on(EventEnum.MESSAGE,listener) } + fun onError(listener: ErrorListener): Wechaty { + return on(EventEnum.ERROR, listener) + } fun use(vararg plugins: WechatyPlugin):Wechaty{ plugins.forEach { it(this) @@ -133,10 +142,19 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : }) return this } + private fun on(event: Event, listener: DongListener):Wechaty { return this } + private fun on(event: Event, listener: ErrorListener): Wechaty { + super.on(event, object : Listener { + override fun handler(vararg any: Any) { + listener.handler(any[0] as String) + } + }) + return this + } private fun on(event: Event, listener: ScanListener):Wechaty{ super.on(event, object : Listener { override fun handler(vararg any: Any) { @@ -154,7 +172,24 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : }) return this } + private fun on(event: Event, listener: FriendshipListener): Wechaty { + super.on(event, object : Listener { + override fun handler(vararg any: Any) { + listener.handler(any[0] as String) + } + }) + return this + } + private fun on(eventName: Event, listener: RoomInviteListener): Wechaty { + super.on(eventName, object : Listener { + override fun handler(vararg any: Any) { + // roomInvitationId + listener.handler(any[0] as String) + } + }) + return this + } private fun on(eventName: Event, listener: RoomJoinListener):Wechaty { super.on(eventName, object : Listener { override fun handler(vararg any: Any) { @@ -240,7 +275,8 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : override fun handler(payload: EventFriendshipPayload) { val friendship = friendship().load(payload.friendshipId) friendship.ready() - emit(EventEnum.FRIENDSHIP, friendship) +// emit(EventEnum.FRIENDSHIP, friendship) + emit(EventEnum.FRIENDSHIP, payload.friendshipId) } }) } @@ -349,7 +385,6 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : val changer = contactManager.loadSelf(payload.changerId) changer.ready() val date = Date(payload.timestamp * 1000) - emit(EventEnum.ROOM_TOPIC, room, payload.newTopic, payload.oldTopic, changer, date) room.emit(EventEnum.TOPIC, payload.newTopic, payload.oldTopic, changer, date) } From 8fd067c4de2dadac9d1857ed6a155322cf7d6a5a Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 11 Jul 2020 15:04:16 +0800 Subject: [PATCH 12/46] update contact --- .../java/io/github/wechaty/example/Main.java | 36 +++++++------------ 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/examples/src/main/java/io/github/wechaty/example/Main.java b/examples/src/main/java/io/github/wechaty/example/Main.java index 4a0f34e..d096cd7 100644 --- a/examples/src/main/java/io/github/wechaty/example/Main.java +++ b/examples/src/main/java/io/github/wechaty/example/Main.java @@ -2,6 +2,7 @@ import io.github.wechaty.Wechaty; +import io.github.wechaty.user.Contact; import io.github.wechaty.user.Room; import io.github.wechaty.utils.QrcodeUtils; import okhttp3.OkHttpClient; @@ -16,37 +17,24 @@ public class Main { public static void main(String[] args){ Wechaty bot = Wechaty.instance("your_token") - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println(user)) + .onScan((qrcode, statusScanStatus, data) -> { + System.out.println(QrcodeUtils.getQr(qrcode)); + System.out.println("Online Image: https://wechaty.github.io/qrcode/" + qrcode); + }) + .onLogin(user -> System.out.println(user.name() + "login")) .onMessage(message -> { Room room = message.room(); String text = message.text(); - if (StringUtils.equals(text, "#ding")) { + Contact from = message.from(); + if (StringUtils.equals(text, "ding")) { if (room != null) { room.say("dong"); } + else { + // say something to from contact + from.say("hello:" + from.name()); + } } }).start(true); - -// } - -// Room room = bot.room(); -// -// RoomQueryFilter roomQueryFilter = new RoomQueryFilter(); -// -// roomQueryFilter.setTopic("ChatOps - Donut"); -// -// Future> all = room.findAll(roomQueryFilter); -// -// List rooms = all.get(); -// -// Room room1 = rooms.get(0); -// -// FileBox fileBox = FileBox.fromFile("dong.jpg", "dong.jpg"); -// -// room1.say(fileBox).get(); - } - - } From 203fcedfc65d90e1a0bdd4bee79496c809174f9d Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 11 Jul 2020 15:05:14 +0800 Subject: [PATCH 13/46] update format --- wechaty/pom.xml | 2 -- .../src/main/kotlin/io/github/wechaty/user/Contact.kt | 4 +++- .../main/kotlin/io/github/wechaty/user/MiniProgram.kt | 3 +-- .../src/main/kotlin/io/github/wechaty/user/UrlLink.kt | 11 ++++++++--- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/wechaty/pom.xml b/wechaty/pom.xml index 8072d65..34f8921 100644 --- a/wechaty/pom.xml +++ b/wechaty/pom.xml @@ -90,8 +90,6 @@ okhttp - - org.hamcrest hamcrest-core diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index e49fe43..b7556f6 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -115,7 +115,9 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) } open fun avatar(): Future { - TODO() + log.info("Contact, avatar()") + val contactAvatar = this.puppet.getContactAvatar(this.id) + return contactAvatar } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt index c5217cb..afc5fc2 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt @@ -38,8 +38,7 @@ class MiniProgram(var payload: MiniProgramPayload) { fun create():MiniProgram{ val payload = MiniProgramPayload() return MiniProgram(payload); - } } -} \ No newline at end of file +} diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/UrlLink.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/UrlLink.kt index 1024566..ff7d99d 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/UrlLink.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/UrlLink.kt @@ -69,7 +69,6 @@ class UrlLink(val payload:UrlLinkPayload) { return UrlLink(payload) -// } } @@ -79,7 +78,13 @@ class UrlLink(val payload:UrlLinkPayload) { fun main(){ val create = UrlLink.create("https://xilidou.com") - +// val bilibili = UrlLink.create("https://www.bilibili.com/") +// val image = UrlLink.create("https://img.xilidou.com/img/java-wechaty.png") println(create) - +// println(bilibili) +// print(image) + val urlLink = UrlLinkPayload("Nihao", "https://www.bilibili.com/") + urlLink.thumbnailUrl = "https://xilidou.com/images/avatar.jpg" + urlLink.description = "犀利豆的博客" + print(urlLink) } From 10c8c7d1611278d35e2412e51cc53908e4c4c571 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 11 Jul 2020 15:06:11 +0800 Subject: [PATCH 14/46] =?UTF-8?q?=E5=AE=8C=E5=96=84obs=E5=90=8E=E7=AB=AF?= =?UTF-8?q?=E5=92=8Cmemory=20card=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/github/wechaty/memorycard/MemoryCard.kt | 10 +++++++--- .../wechaty/memorycard/backend/StorageObs.kt | 16 ++++++++++++---- .../wechaty/memorycard/backend/StorageS3.kt | 8 +++++--- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 4c99632..4fd95d1 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -1,10 +1,15 @@ package io.github.wechaty.memorycard import io.github.wechaty.utils.JsonUtils +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import org.slf4j.LoggerFactory import java.lang.Exception +import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.CompletableFuture import java.util.concurrent.Future +import javax.xml.bind.JAXBElement import kotlin.math.abs const val NAMESPACE_MULTIPLEX_SEPRATOR = "\r" @@ -32,6 +37,7 @@ class MemoryCard { if(name != null) { _options.name = name } + else if (_options.name != null) { this.name = _options.name } @@ -79,7 +85,6 @@ class MemoryCard { this.options.storageOptions ) } - fun load(): Future { log.info("MemoryCard, load() from storage: %s", this.storage ?: "N/A") if (this.isMultiplex()) { @@ -108,7 +113,6 @@ class MemoryCard { this.parent!!.save() } - log.info("MemoryCard, <%s>%s save() to %s",this.name ?: "", this.multiplexPath(), this.storage ?: "N/A") if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -199,7 +203,7 @@ class MemoryCard { } } - fun get(name: String): CompletableFuture? { + fun get(name: String): CompletableFuture? { log.info("MemoryCard, <%s> get(%s)", this.multiplexPath(), name) if (this.payload == null) { throw Exception("no payload, please call load() first.") diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index f9e4718..6b2e381 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -66,6 +66,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage private fun getObject(): MemoryCardPayload { val options = this.options as StorageObsOptions val obsObject = this.obs.getObject(options.bucket, this.name) + println(obsObject) val input = obsObject.objectContent var byte = ByteArray(1024) val bos = ByteArrayOutputStream() @@ -79,6 +80,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage break } } + input.close() var card = MemoryCardPayload() card.map = JsonUtils.readValue(String(bos.toByteArray())) return card @@ -104,10 +106,16 @@ fun main(){ "obs.cn-north-4.myhuaweicloud.com", "cybersa") val storageObs = StorageObs("objectname", storageObsOptions) - val load = storageObs.load() - println(load.map) - load.map.forEach { t, u -> print(t + ":" + u) } - storageObs.destory() + var memory = MemoryCardPayload() + var address = Address("福州", "付件") + var person = Person("sda", 13, address) + memory.map.put("person", person) + storageObs.save(memory) + +// val load = storageObs.load() +// println(load.map) +// load.map.forEach { t, u -> print(t + ":" + u) } +// storageObs.destory() // var obsClient = ObsClient("D5RKYDQRCRYICGP65H2R", "K0Va8jn8kWBK8jzdmC4QC2vvqsgF5Epz1iWhZOOp", // "obs.cn-north-4.myhuaweicloud.com") diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 4e0df85..4f2d5e1 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -37,11 +37,12 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB val options = this.options as StorageS3Options val result = this.s3.getObject(options.bucket, this.name) - if (result==null || result.objectContent == null) { + if (result == null || result.objectContent == null) { return MemoryCardPayload() } // 这里还有问题 val objectContent = result.objectContent + var payloadMap = StringBuffer() var readBuf = ByteArray(1024) var readLen = 0 @@ -79,7 +80,8 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB fun main(){ - val storageS3 = StorageS3("test", StorageS3Options("1", "1", "2", "3")) - val load = storageS3.load() +// val storageS3 = StorageS3("test", StorageS3Options("1", "1", "2", "3")) +// val load = storageS3.load() + var function: () -> Unit = {} } From 4d202d9857bf0a851b3f8f4fc1d018c8ed40802a Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 11 Jul 2020 15:07:07 +0800 Subject: [PATCH 15/46] add conurrent dependency --- wechaty-puppet/pom.xml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/wechaty-puppet/pom.xml b/wechaty-puppet/pom.xml index 7fe2e93..25b0c6b 100644 --- a/wechaty-puppet/pom.xml +++ b/wechaty-puppet/pom.xml @@ -21,7 +21,11 @@ org.jetbrains.kotlin kotlin-stdlib - + + org.jetbrains.kotlinx + kotlinx-coroutines-core + 1.3.7 + com.github.ben-manes.caffeine From bb44289b717fc02dd2b589607c7e8ed2749c6129 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 14 Jul 2020 19:12:34 +0800 Subject: [PATCH 16/46] update some format --- .../github/wechaty/memorycard/MemoryCard.kt | 54 +++++++++---------- .../wechaty/memorycard/StorageOptions.kt | 4 +- .../wechaty/memorycard/backend/StorageFile.kt | 25 ++++++--- 3 files changed, 46 insertions(+), 37 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 4fd95d1..5ee46ac 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -1,9 +1,7 @@ package io.github.wechaty.memorycard import io.github.wechaty.utils.JsonUtils -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.async -import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.* import org.slf4j.LoggerFactory import java.lang.Exception import java.util.concurrent.ArrayBlockingQueue @@ -32,8 +30,9 @@ class MemoryCard { // name和options里面的name有可能同时为空 constructor(name: String? = null, options: MemoryCardOptions? = null) { - log.info("MemoryCard, constructor(%s)", options?.let { JsonUtils.write(it) }) val _options: MemoryCardOptions = options ?: MemoryCardOptions() + log.info("MemoryCard, constructor({})", JsonUtils.write(_options)) + if(name != null) { _options.name = name } @@ -42,14 +41,12 @@ class MemoryCard { this.name = _options.name } else { + // 如果没有给名字就用一个default作为名字 this.name = "default" _options.name = "default" } this.options = _options - // let不能这么用 -// false.let { -// println(1) -// } + if (_options.multiplex != null) { this.parent = _options.multiplex!!.parent this.payload = this.parent!!.payload @@ -68,7 +65,7 @@ class MemoryCard { private fun getStore(): StorageBackend? { - log.debug("getStorage() for storage type: %s", + log.debug("getStorage() for storage type: {}", if (this.options != null && this.options.storageOptions != null && this.options.storageOptions!!.type != null) this.options else @@ -85,8 +82,10 @@ class MemoryCard { this.options.storageOptions ) } + + fun load(): Future { - log.info("MemoryCard, load() from storage: %s", this.storage ?: "N/A") + log.info("MemoryCard, load() from storage: {}", this.storage ?: "N/A") if (this.isMultiplex()) { log.info("MemoryCard, load() should not be called on a multiplex MemoryCard. NOOP") return CompletableFuture.completedFuture(null) @@ -99,7 +98,7 @@ class MemoryCard { this.payload = this.storage!!.load() } else { - log.info("MemoryCard, load() no storage") + log.info("MemoryCard, load() no storagebackend") this.payload = MemoryCardPayload() } return CompletableFuture.completedFuture(null) @@ -113,7 +112,7 @@ class MemoryCard { this.parent!!.save() } - log.info("MemoryCard, <%s>%s save() to %s",this.name ?: "", this.multiplexPath(), this.storage ?: "N/A") + log.info("MemoryCard, <{}>{} save() to {}",this.name ?: "", this.multiplexPath(), this.storage ?: "N/A") if (this.payload == null) { throw Exception("no payload, please call load() first.") } @@ -128,12 +127,12 @@ class MemoryCard { } fun destory(): Future { - log.info("MemoryCard, destroy() storage: %s", this.storage ?: "N/A") + log.info("MemoryCard, destroy() storage: {}", this.storage ?: "N/A") if (this.isMultiplex()) { throw Exception("can not destroy on a multiplexed memory") } -// this.clear() + // this.clear() if (this.storage != null) { this.storage!!.destory() @@ -145,7 +144,7 @@ class MemoryCard { fun size(): Future { - log.info("MemoryCard, <%s> size", this.multiplexPath()) + log.info("MemoryCard, <{}> size", this.multiplexPath()) if (this.payload == null) { throw Exception("no payload, please call load() first.") } @@ -177,11 +176,12 @@ class MemoryCard { throw Exception("not a multiplex memory") } + // \r + \n val namespace = NAMESPACE_MULTIPLEX_SEPRATOR + this.multiplexNameList.joinToString(NAMESPACE_MULTIPLEX_SEPRATOR) return namespace } - protected fun isMultiplexKey (key: String): Boolean { + protected fun isMultiplexKey(key: String): Boolean { if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.matches(key) && NAMESPACE_KEY_SEPRATOR_REGEX.matches(key)) { @@ -204,7 +204,7 @@ class MemoryCard { } fun get(name: String): CompletableFuture? { - log.info("MemoryCard, <%s> get(%s)", this.multiplexPath(), name) + log.info("MemoryCard, <{}> get({})", this.multiplexPath(), name) if (this.payload == null) { throw Exception("no payload, please call load() first.") } @@ -216,7 +216,7 @@ class MemoryCard { } fun set(name: String, data: T): Future { - log.info("MemoryCard, <%s> set(%s, %s)", this.multiplexPath(), name, data) + log.info("MemoryCard, <{}> set({}, {})", this.multiplexPath(), name, data) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -228,7 +228,7 @@ class MemoryCard { } fun clear(): Future { - log.info("MemoryCard, <%s> clear()", this.multiplexPath()) + log.info("MemoryCard, <{}> clear()", this.multiplexPath()) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -246,7 +246,7 @@ class MemoryCard { } fun delete(name: String): Future { - log.info("MemoryCard, <%s> delete(%s)", this.multiplexPath(), name) + log.info("MemoryCard, <{}> delete({})", this.multiplexPath(), name) if (this.payload == null) { throw Exception("no payload, please call load() first.") } @@ -257,7 +257,7 @@ class MemoryCard { } fun entries(): MutableSet> { - log.info("MemoryCard, <%s> *entries()", this.multiplexPath()) + log.info("MemoryCard, <{}> *entries()", this.multiplexPath()) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -267,7 +267,7 @@ class MemoryCard { } fun has(key: String): Future { - log.info("MemoryCard, <%s> has (%s)", this.multiplexPath(), key) + log.info("MemoryCard, <{}> has ({})", this.multiplexPath(), key) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -280,7 +280,7 @@ class MemoryCard { } fun keys(): MutableSet { - log.info("MemoryCard, <%s> keys()", this.multiplexPath()) + log.info("MemoryCard, <{}> keys()", this.multiplexPath()) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -302,7 +302,7 @@ class MemoryCard { fun values(): MutableCollection { - log.info("MemoryCard, <%s> values()", this.multiplexPath()) + log.info("MemoryCard, <{}> values()", this.multiplexPath()) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -312,7 +312,7 @@ class MemoryCard { } fun multiplex (name: String): MemoryCard { - log.info("MemoryCard, multiplex(%s)", name) + log.info("MemoryCard, multiplex({})", name) // FIXME: as any ? return multiplex(this, name) @@ -337,7 +337,7 @@ class MemoryCard { val VERSION = "0.0.0" fun multiplex(memory: MemoryCard, name: String): MemoryCard{ - log.info("MemoryCard, static multiplex(%s, %s)", memory, name) + log.info("MemoryCard, static multiplex({}, {})", memory, name) memory.options.multiplex = Multiplex(name = name, parent = memory) val mpMemory = MemoryCard(options = memory.options) return mpMemory @@ -360,8 +360,6 @@ class MemoryCard { return card } } - - } class MemoryCardPayload{ diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt index 973b539..e9dce5b 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt @@ -20,7 +20,7 @@ data class StorageS3Options( val secretAccessKey:String, val region:String, val bucket:String -):StorageBackendOptions() +): StorageBackendOptions() data class StorageObsOptions( @@ -28,7 +28,7 @@ data class StorageObsOptions( val secretAccessKey:String, val server:String, val bucket:String -):StorageBackendOptions() +): StorageBackendOptions() val BACKEND_DICT = mapOf( "file" to StorageFile::class, diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index 9eb1b50..ae478f9 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -11,11 +11,12 @@ import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import java.io.File +import java.io.IOException import java.lang.Exception import kotlin.math.abs // 本身是不存储数据的 -// 存储了持久化的文件名和选项 +// 存储了持久化的文件名和以及用什么方式存储 class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name, options) { private var absFileName: String @@ -49,7 +50,14 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag if(!file.exists()){ return MemoryCardPayload() } - val text = FileUtils.readFileToString(file, "UTF-8") + var text = "" + try { + text = FileUtils.readFileToString(file, "UTF-8") + } + catch (e: IOException) { + log.error("load() from file %s error %s", this.absFileName, e.toString()) + } + var payload = MemoryCardPayload() try { payload.map = JsonUtils.readValue(text); @@ -65,7 +73,12 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag val text = JsonUtils.write(payload.map) val file = File(absFileName) - FileUtils.write(file,text,"UTF-8") + try { + FileUtils.write(file,text,"UTF-8") + } + catch (e: IOException) { + log.error("MemoryCard, save() exception: %s", e) + } } override fun destory() { @@ -93,8 +106,6 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag -fun main(){ - - StorageFile("test", StorageFileOptions()) - +fun main() { + val storageFile = StorageFile("test", StorageFileOptions()) } From 0236b41d7575dc1d8562b5b25963c3d6bf444b39 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 16 Jul 2020 22:47:56 +0800 Subject: [PATCH 17/46] update Storage and StateSwitch --- wechaty-puppet/pom.xml | 9 - .../github/wechaty/memorycard/MemoryCard.kt | 2 +- .../wechaty/memorycard/backend/StorageObs.kt | 17 +- .../wechaty/memorycard/backend/StorageS3.kt | 1 + .../io/github/wechaty/status/StateSwitch.kt | 204 +++++++++++++++--- 5 files changed, 192 insertions(+), 41 deletions(-) diff --git a/wechaty-puppet/pom.xml b/wechaty-puppet/pom.xml index 25b0c6b..beedff5 100644 --- a/wechaty-puppet/pom.xml +++ b/wechaty-puppet/pom.xml @@ -49,15 +49,6 @@ aws-java-sdk-s3 1.11.636 - - - - - - - - - diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 5ee46ac..d76644c 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -83,7 +83,6 @@ class MemoryCard { ) } - fun load(): Future { log.info("MemoryCard, load() from storage: {}", this.storage ?: "N/A") if (this.isMultiplex()) { @@ -145,6 +144,7 @@ class MemoryCard { fun size(): Future { log.info("MemoryCard, <{}> size", this.multiplexPath()) + if (this.payload == null) { throw Exception("no payload, please call load() first.") } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index 6b2e381..0d91f38 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -48,6 +48,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage override fun destory() { log.info("StorageObs, destroy()") this.deleteObject() +// obs.close() } override fun toString(): String { @@ -66,7 +67,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage private fun getObject(): MemoryCardPayload { val options = this.options as StorageObsOptions val obsObject = this.obs.getObject(options.bucket, this.name) - println(obsObject) + val input = obsObject.objectContent var byte = ByteArray(1024) val bos = ByteArrayOutputStream() @@ -80,6 +81,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage break } } + input.close() var card = MemoryCardPayload() card.map = JsonUtils.readValue(String(bos.toByteArray())) @@ -105,12 +107,13 @@ fun main(){ val storageObsOptions = StorageObsOptions("D5RKYDQRCRYICGP65H2R", "K0Va8jn8kWBK8jzdmC4QC2vvqsgF5Epz1iWhZOOp", "obs.cn-north-4.myhuaweicloud.com", "cybersa") - val storageObs = StorageObs("objectname", storageObsOptions) - var memory = MemoryCardPayload() - var address = Address("福州", "付件") - var person = Person("sda", 13, address) - memory.map.put("person", person) - storageObs.save(memory) + val storageObs = StorageObs("notexist", storageObsOptions) + val load = storageObs.load() +// var memory = MemoryCardPayload() +// var address = Address("福州", "付件") +// var person = Person("sda", 13, address) +// memory.map.put("person", person) +// storageObs.save(memory) // val load = storageObs.load() // println(load.map) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 4f2d5e1..3670aa0 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -65,6 +65,7 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB log.info("StorageS3, destory()") val options = this.options as StorageS3Options this.s3.deleteObject(options.bucket, this.name) + this.s3.shutdown() } override fun toString(): String { diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index 5a64df9..35060d5 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -4,15 +4,17 @@ import io.github.wechaty.StateEnum import io.github.wechaty.eventEmitter.EventEmitter import io.github.wechaty.eventEmitter.Listener import io.github.wechaty.io.github.wechaty.schemas.EventEnum +import kotlinx.coroutines.* import org.slf4j.LoggerFactory +import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import java.util.concurrent.atomic.AtomicInteger -val COUNTER=AtomicInteger() - -class StateSwitch:EventEmitter(){ - +var COUNTER = AtomicInteger() +val nop: () -> Unit = {} +val resolver: suspend () -> Unit = {} +class StateSwitch: EventEmitter(){ @Volatile private var onoff:Boolean = false @@ -20,34 +22,77 @@ class StateSwitch:EventEmitter(){ @Volatile private var pending:Boolean = false + private lateinit var onPromise : suspend () -> Unit + private lateinit var offPromise : suspend () -> Unit - private lateinit var onPromise : Future - private lateinit var offPromise : Future - - private lateinit var onResolver : Function - private lateinit var offResolver : Function - + private lateinit var onResolver : () -> Unit + private lateinit var offResolver : () -> Unit private val name :String = "#${COUNTER.addAndGet(1)}" + private lateinit var onQueue: ArrayBlockingQueue<() -> Unit> + private lateinit var offQueue: ArrayBlockingQueue<() -> Unit> + init { - offPromise = CompletableFuture.completedFuture(null); - onPromise = CompletableFuture.runAsync{ - TODO() - } + log.info("StateSwitch, constructor(%s)", this.name) + + this.onoff = false + this.pending = false + onQueue = ArrayBlockingQueue(1) + offQueue = ArrayBlockingQueue(1) + this.offQueue.put(nop) + // 赋值但是不执行 +// runBlocking { +// onPromise = { +// onResolver = nop +// } +// onPromise() +// } + +// this.offPromise = resolver +// this.offResolver = nop + +// this.onResolver = nop +// this.offResolver = nop } - fun on(state: StateEnum):StateEnum { - val on = on() - log.debug("statusSwitch $name on ${state.name} <- ${on}") + // 传入on的状态只能是on或者说pending + fun on(state: StateEnum): StateEnum { + + log.debug("statusSwitch $name on ${state.name} <- ${this.on()}") + if (state == StateEnum.OFF) { + throw Exception("the parameter state shouldn't be off") + } onoff = true pending = (state == StateEnum.PENDING) emit(EventEnum.ON, state.name) - return on - } +// if (this.offResolver === nop) { +// runBlocking { +// offPromise = { +// offResolver = nop +// } +// offPromise() +// } +// +// } +// +// if (state == StateEnum.ON && this.onResolver !== nop) { +// this.onResolver() +//// this.onResolver = nop +// } + if (this.offQueue.isEmpty()) { + this.offQueue.put(nop) + } + + if (state == StateEnum.ON && this.onQueue.isEmpty()) { + this.onQueue.put(nop) + } + return this.on() + } + // get the current on state fun on(): StateEnum { val on = if (this.onoff == true) @@ -61,17 +106,37 @@ class StateSwitch:EventEmitter(){ return on } - fun off(state: StateEnum) { + fun off(state: StateEnum): StateEnum { log.info("StateSwitch, <%s> off(%s) <- (%s)", this.name, state, this.off()) + if (state == StateEnum.ON) { + throw Exception("the parameter state shouldn't be on") + } + this.onoff = false this.pending = (state == StateEnum.PENDING) this.emit(StateEnum.OFF, state) -// if (this.onResolver == null) { -// +// if (this.onResolver === nop) { +// runBlocking { +// onPromise = { +// onResolver = nop +// } +// onPromise() +// } +// } +// if (state == StateEnum.OFF && this.offResolver !== nop) { +// this.offResolver() +// this.offResolver = nop // } + if (this.onQueue.isEmpty()) { + this.onQueue.put(nop) + } + if (state == StateEnum.OFF && this.offQueue.isEmpty()) { + this.offQueue.put(nop) + } + return this.off() } - + // get the current off state fun off(): StateEnum { val off = if (!this.onoff) @@ -85,16 +150,107 @@ class StateSwitch:EventEmitter(){ return off } + /** + * @param state: 准备变为的状态 + * @param cross: 是否变换状态,默认可以 + */ + fun ready(state: StateEnum = StateEnum.ON, cross: Boolean = true) = runBlocking { + log.info("StateSwitch, <%s> ready(%s, %s)", name, state, cross) + + // 如果准备变换的状态为on + if (state == StateEnum.ON) { + // 如果当前状态为off,并且不允许变换状态 + if (onoff == false && cross == false) { + throw Exception("ready(on) but the state is off. call ready(on, true) to force crossWait") + } + // 当前状态为on + // 或者说当前状态为off, 但是允许变换状态 + // his.onPromise +// coroutineScope { +// val job = launch { onPromise } +// job.join() +// } + CoroutineScope(Dispatchers.Default).launch { + onQueue.take() + } + } + // 如果准备变为off + else if (state == StateEnum.OFF) { + // 但是当前状态为 on, 并且不允许变换状态 + if (onoff == true && cross == false) { + throw Exception("ready(off) but the state is on. call ready(off, true) to force crossWait") + } + // 当前状态为off,或者说当前状态为on, 但是允许变换状态 + // 执行状态改变时执行的函数 +// this.offPromise +// coroutineScope { +// val job = launch { offPromise } +// job.join() +// } + CoroutineScope(Dispatchers.Default).launch { + offQueue.take() + } + } + // 错误状态 + else { + throw Exception("should not go here. ${state} should be of type 'never'") + } + log.info("StateSwitch, <%s> ready(%s, %s) resolved.", name, state, cross) + } + fun addEventListener(type: StateEnum, listener: Listener) { super.addListener(type, listener) } + fun removeEventListener(type: StateEnum, listener: Listener) { super.removeListener(type, listener) } + companion object { private val log = LoggerFactory.getLogger(StateSwitch::class.java) } +} -} +fun main() { +// val function: () -> Unit = { println(1) } +// var queue: ArrayBlockingQueue<() -> Unit> = ArrayBlockingQueue(2) +// queue.offer { +// println(1) +// } +// +// queue.offer { +// println(2) +// } +// +// val poll = queue.poll() +// poll() +// queue.poll()() +// val poll1 = queue.poll() +// println(poll1) +// +// var function2: ()->Unit = {} +//// var function3: ()->Unit = {} +// var function3: ()->Unit = function2 +// function3 = { println(1)} +// println(function2 === function3) + val stateSwitch = StateSwitch() + println(stateSwitch.on()) + + stateSwitch.on(StateEnum.PENDING) + println(stateSwitch.on()) + stateSwitch.ready(StateEnum.ON) + println(stateSwitch.on()) + stateSwitch.on(StateEnum.ON) + println(stateSwitch.on()) + // ====================================== + stateSwitch.off(StateEnum.PENDING) + println(stateSwitch.off()) + + stateSwitch.ready(StateEnum.OFF) + println(stateSwitch.on()) + stateSwitch.off(StateEnum.OFF) + println(stateSwitch.on()) + +} From ab8ee966661b0bf49ec1319baae5db3887adaf30 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 16 Jul 2020 22:56:33 +0800 Subject: [PATCH 18/46] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8C=85=E5=90=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D=E9=94=99=E8=AF=AF,=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E9=98=BF=E9=87=8C=E4=BA=91oss=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet/pom.xml | 6 +- .../wechaty/memorycard/StorageOptions.kt | 16 +++- .../wechaty/memorycard/StrorageBackend.kt | 2 +- .../wechaty/memorycard/backend/StorageFile.kt | 2 +- .../wechaty/memorycard/backend/StorageNop.kt | 2 +- .../wechaty/memorycard/backend/StorageOSS.kt | 87 +++++++++++++++++++ .../wechaty/memorycard/backend/StorageObs.kt | 2 +- .../wechaty/memorycard/backend/StorageS3.kt | 3 +- 8 files changed, 109 insertions(+), 11 deletions(-) create mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt diff --git a/wechaty-puppet/pom.xml b/wechaty-puppet/pom.xml index beedff5..485f2ef 100644 --- a/wechaty-puppet/pom.xml +++ b/wechaty-puppet/pom.xml @@ -111,7 +111,11 @@ esdk-obs-java 3.19.7 - + + com.aliyun.oss + aliyun-sdk-oss + 3.10.2 + junit junit diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt index e9dce5b..efddd8d 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt @@ -1,9 +1,10 @@ package io.github.wechaty.memorycard -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageNop -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageObs -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageS3 +import io.github.wechaty.memorycard.backend.StorageFile +import io.github.wechaty.memorycard.backend.StorageNop +import io.github.wechaty.memorycard.backend.StorageObs +import io.github.wechaty.memorycard.backend.StorageS3 + sealed class StorageBackendOptions { var type: String? = null @@ -30,6 +31,13 @@ data class StorageObsOptions( val bucket:String ): StorageBackendOptions() +data class StorageOSSOptions( + val accessKeyId: String, + val secretAccessKey: String, + val endPoint: String, + val bucket: String +): StorageBackendOptions() + val BACKEND_DICT = mapOf( "file" to StorageFile::class, "s3" to StorageS3::class, diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt index 597fa98..a2036b4 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt @@ -1,6 +1,6 @@ package io.github.wechaty.memorycard -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile +import io.github.wechaty.memorycard.backend.StorageFile import io.github.wechaty.utils.JsonUtils import org.slf4j.LoggerFactory diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index ae478f9..de17c7a 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -1,4 +1,4 @@ -package io.github.wechaty.io.github.wechaty.memorycard.backend +package io.github.wechaty.memorycard.backend import io.github.wechaty.io.github.wechaty.status.StateSwitch import io.github.wechaty.memorycard.MemoryCardPayload diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt index 5d32409..ead9366 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt @@ -1,4 +1,4 @@ -package io.github.wechaty.io.github.wechaty.memorycard.backend +package io.github.wechaty.memorycard.backend import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt new file mode 100644 index 0000000..f46466b --- /dev/null +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt @@ -0,0 +1,87 @@ +package io.github.wechaty.memorycard.backend + +import com.aliyun.oss.OSSClient +import com.aliyun.oss.OSSClientBuilder +import io.github.wechaty.memorycard.* +import io.github.wechaty.utils.JsonUtils +import org.slf4j.LoggerFactory +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream + +// 使用华为的云存储服务 +class StorageOSS(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { + + private lateinit var oss: OSSClient + + init { + log.info("StorageOSS, constructor()") + options.type = "oss" + options = options as StorageOSSOptions + var _options = options as StorageOSSOptions + this.oss = OSSClientBuilder().build(_options.endPoint,_options.accessKeyId, _options.secretAccessKey) as OSSClient + } + + override fun save(payload: MemoryCardPayload) { + log.info("StorageOSS, save()") + this.putObject(payload) + } + + override fun load(): MemoryCardPayload { + log.info("StorageOSS, load()") + val card = this.getObject() + + log.info("press", card) + return card + } + + override fun destory() { + log.info("StorageOSS, destroy()") + this.deleteObject() + } + + override fun toString(): String { + return "${this.name}<${this.name}>" + } + + private fun putObject(payload: MemoryCardPayload) { + val options = this.options as StorageObsOptions + val putObject = this.oss.putObject(options.bucket, this.name, ByteArrayInputStream(JsonUtils.write(payload.map).toByteArray())) + // 还需要处理异常 + } + + private fun getObject(): MemoryCardPayload { + val options = this.options as StorageObsOptions + val obsObject = this.oss.getObject(options.bucket, this.name) + println(obsObject) + val input = obsObject.objectContent + var byte = ByteArray(1024) + val bos = ByteArrayOutputStream() + var len = 0; + while (true) { + len = input.read(byte) + if (len != -1) { + bos.write(byte, 0, len) + } + else { + break + } + } + input.close() + var card = MemoryCardPayload() + card.map = JsonUtils.readValue(String(bos.toByteArray())) + return card + } + + private fun deleteObject() { + val options = this.options as StorageObsOptions + val deleteObject = this.oss.deleteObject(options.bucket, this.name) + } + + companion object { + private val log = LoggerFactory.getLogger(StorageObs::class.java) + } +} + +fun main() { + +} diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index 0d91f38..be06258 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -1,4 +1,4 @@ -package io.github.wechaty.io.github.wechaty.memorycard.backend +package io.github.wechaty.memorycard.backend import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 3670aa0..f7b59c1 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -1,4 +1,4 @@ -package io.github.wechaty.io.github.wechaty.memorycard.backend +package io.github.wechaty.memorycard.backend import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials @@ -83,6 +83,5 @@ fun main(){ // val storageS3 = StorageS3("test", StorageS3Options("1", "1", "2", "3")) // val load = storageS3.load() - var function: () -> Unit = {} } From 1dc8f510f7c5acdf742ee9b56f7930a7bea8cd3f Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Fri, 17 Jul 2020 20:29:20 +0800 Subject: [PATCH 19/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0=E9=98=BF=E9=87=8C?= =?UTF-8?q?=E4=BA=91oss=E5=90=8E=E7=AB=AF=202.=20=E6=9A=82=E6=97=B6?= =?UTF-8?q?=E5=AE=8C=E6=88=90stateswitch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wechaty/memorycard/backend/StorageOSS.kt | 52 ++++++--- .../io/github/wechaty/status/StateSwitch.kt | 102 ++++++------------ 2 files changed, 72 insertions(+), 82 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt index f46466b..b1ccd52 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt @@ -2,6 +2,7 @@ package io.github.wechaty.memorycard.backend import com.aliyun.oss.OSSClient import com.aliyun.oss.OSSClientBuilder +import com.aliyun.oss.model.PutObjectRequest import io.github.wechaty.memorycard.* import io.github.wechaty.utils.JsonUtils import org.slf4j.LoggerFactory @@ -29,7 +30,6 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage override fun load(): MemoryCardPayload { log.info("StorageOSS, load()") val card = this.getObject() - log.info("press", card) return card } @@ -39,21 +39,23 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage this.deleteObject() } - override fun toString(): String { - return "${this.name}<${this.name}>" - } - private fun putObject(payload: MemoryCardPayload) { - val options = this.options as StorageObsOptions - val putObject = this.oss.putObject(options.bucket, this.name, ByteArrayInputStream(JsonUtils.write(payload.map).toByteArray())) - // 还需要处理异常 + val options = this.options as StorageOSSOptions + + val putObjectRequest = PutObjectRequest(options.bucket, this.name, ByteArrayInputStream(JsonUtils.write(payload.map).toByteArray())) + try { + this.oss.putObject(putObjectRequest) + } + catch (e: Exception) { + log.error("上传${this.name}错误") + } } private fun getObject(): MemoryCardPayload { - val options = this.options as StorageObsOptions - val obsObject = this.oss.getObject(options.bucket, this.name) - println(obsObject) - val input = obsObject.objectContent + val options = this.options as StorageOSSOptions + val ossObject = this.oss.getObject(options.bucket, this.name) + + val input = ossObject.objectContent var byte = ByteArray(1024) val bos = ByteArrayOutputStream() var len = 0; @@ -67,14 +69,29 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage } } input.close() + ossObject.close() var card = MemoryCardPayload() card.map = JsonUtils.readValue(String(bos.toByteArray())) return card } private fun deleteObject() { - val options = this.options as StorageObsOptions - val deleteObject = this.oss.deleteObject(options.bucket, this.name) + val options = this.options as StorageOSSOptions + try { + this.oss.deleteObject(options.bucket, this.name) + } + catch (e: Exception) { + log.error("删除${this.name}错误") + } + } + + fun shutdown() { + log.info("StorageOSS, shutdown()") + this.oss.shutdown() + } + + override fun toString(): String { + return "${this.name}<${this.name}>" } companion object { @@ -83,5 +100,10 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage } fun main() { - + val storageOSSOptions = StorageOSSOptions("LTAI4G2iSKd5m8aTZprdj133", "UT9ns4KvNdZkdMIIPEU87upQv2fsBp", + "oss-cn-beijing.aliyuncs.com", "cybersa") + val storageOSS = StorageOSS("objectkey", storageOSSOptions) + val load = storageOSS.load() +// load.map.put("a", "b") +// storageOSS.save(load) } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index 35060d5..c15af20 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger var COUNTER = AtomicInteger() val nop: () -> Unit = {} -val resolver: suspend () -> Unit = {} +val resolver: () -> Unit = {} class StateSwitch: EventEmitter(){ @Volatile @@ -40,24 +40,18 @@ class StateSwitch: EventEmitter(){ this.pending = false onQueue = ArrayBlockingQueue(1) offQueue = ArrayBlockingQueue(1) - this.offQueue.put(nop) - // 赋值但是不执行 + this.offQueue.put(resolver) + // runBlocking { // onPromise = { // onResolver = nop // } // onPromise() // } - -// this.offPromise = resolver -// this.offResolver = nop - -// this.onResolver = nop -// this.offResolver = nop } // 传入on的状态只能是on或者说pending - fun on(state: StateEnum): StateEnum { + fun on(state: StateEnum): String { log.debug("statusSwitch $name on ${state.name} <- ${this.on()}") @@ -68,6 +62,7 @@ class StateSwitch: EventEmitter(){ pending = (state == StateEnum.PENDING) emit(EventEnum.ON, state.name) + // if (this.offResolver === nop) { // runBlocking { // offPromise = { @@ -75,38 +70,33 @@ class StateSwitch: EventEmitter(){ // } // offPromise() // } -// -// } -// -// if (state == StateEnum.ON && this.onResolver !== nop) { -// this.onResolver() -//// this.onResolver = nop // } + if (this.offQueue.isEmpty()) { - this.offQueue.put(nop) + this.offQueue.put(resolver) } if (state == StateEnum.ON && this.onQueue.isEmpty()) { - this.onQueue.put(nop) + this.onQueue.put(resolver) } return this.on() } // get the current on state - fun on(): StateEnum { + fun on(): String { val on = if (this.onoff == true) if (this.pending == true) - StateEnum.PENDING + "pending" else - StateEnum.ON + "true" else - StateEnum.OFF + "false" log.info("StateSwitch, <%s> on() is %s", this.name, on) return on } - fun off(state: StateEnum): StateEnum { + fun off(state: StateEnum): String { log.info("StateSwitch, <%s> off(%s) <- (%s)", this.name, state, this.off()) if (state == StateEnum.ON) { throw Exception("the parameter state shouldn't be on") @@ -123,29 +113,25 @@ class StateSwitch: EventEmitter(){ // } // onPromise() // } -// } -// if (state == StateEnum.OFF && this.offResolver !== nop) { -// this.offResolver() -// this.offResolver = nop // } if (this.onQueue.isEmpty()) { - this.onQueue.put(nop) + this.onQueue.put(resolver) } if (state == StateEnum.OFF && this.offQueue.isEmpty()) { - this.offQueue.put(nop) + this.offQueue.put(resolver) } return this.off() } // get the current off state - fun off(): StateEnum { + fun off(): String { val off = if (!this.onoff) if (this.pending) - StateEnum.PENDING + "pending" else - StateEnum.ON + "true" else - StateEnum.OFF + "false" log.info("StateSwitch, <%s> off() is %s", this.name, off) return off } @@ -153,8 +139,9 @@ class StateSwitch: EventEmitter(){ /** * @param state: 准备变为的状态 * @param cross: 是否变换状态,默认可以 + * 好像可以去掉runblocking */ - fun ready(state: StateEnum = StateEnum.ON, cross: Boolean = true) = runBlocking { + fun ready(state: StateEnum = StateEnum.ON, cross: Boolean = true) { log.info("StateSwitch, <%s> ready(%s, %s)", name, state, cross) // 如果准备变换的状态为on @@ -172,6 +159,7 @@ class StateSwitch: EventEmitter(){ // } CoroutineScope(Dispatchers.Default).launch { onQueue.take() + println("on") } } // 如果准备变为off @@ -213,44 +201,24 @@ class StateSwitch: EventEmitter(){ fun main() { -// val function: () -> Unit = { println(1) } -// var queue: ArrayBlockingQueue<() -> Unit> = ArrayBlockingQueue(2) -// queue.offer { -// println(1) -// } -// -// queue.offer { -// println(2) -// } -// -// val poll = queue.poll() -// poll() -// queue.poll()() -// val poll1 = queue.poll() -// println(poll1) -// -// var function2: ()->Unit = {} -//// var function3: ()->Unit = {} -// var function3: ()->Unit = function2 -// function3 = { println(1)} -// println(function2 === function3) + val stateSwitch = StateSwitch() - println(stateSwitch.on()) + println("刚开始创建时:" + stateSwitch.on()) stateSwitch.on(StateEnum.PENDING) - println(stateSwitch.on()) + println("调用on(pending):" + stateSwitch.on()) stateSwitch.ready(StateEnum.ON) - println(stateSwitch.on()) + println("调用ready(on)之后:" + stateSwitch.on()) stateSwitch.on(StateEnum.ON) - println(stateSwitch.on()) + println("调用on(on):" + stateSwitch.on()) // ====================================== - stateSwitch.off(StateEnum.PENDING) - println(stateSwitch.off()) - - stateSwitch.ready(StateEnum.OFF) - println(stateSwitch.on()) - - stateSwitch.off(StateEnum.OFF) - println(stateSwitch.on()) +// stateSwitch.off(StateEnum.PENDING) +// println(stateSwitch.off()) +// +// stateSwitch.ready(StateEnum.OFF) +// println(stateSwitch.on()) +// +// stateSwitch.off(StateEnum.OFF) +// println(stateSwitch.on()) } From e47298cac57f8e252e9c842225684a8501921644 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 18 Jul 2020 18:55:36 +0800 Subject: [PATCH 20/46] =?UTF-8?q?1.=20=E5=AE=8C=E5=96=84=E9=98=BF=E9=87=8C?= =?UTF-8?q?=E4=BA=91oss=E5=90=8E=E7=AB=AF=202.=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E4=B8=80=E4=BA=9B=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/wechaty/memorycard/MemoryCard.kt | 2 +- .../wechaty/memorycard/StorageOptions.kt | 12 ++--- .../wechaty/memorycard/StrorageBackend.kt | 7 +-- .../wechaty/memorycard/backend/StorageFile.kt | 6 +-- .../wechaty/memorycard/backend/StorageNop.kt | 7 +-- .../wechaty/memorycard/backend/StorageOSS.kt | 33 ++++++++++---- .../wechaty/memorycard/backend/StorageObs.kt | 44 +++++++++++++------ .../wechaty/memorycard/backend/StorageS3.kt | 9 ++-- 8 files changed, 73 insertions(+), 47 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index d76644c..010f37e 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -149,7 +149,7 @@ class MemoryCard { throw Exception("no payload, please call load() first.") } - var count: Int + val count: Int if (this.isMultiplex()) { count = this.payload!!.map.keys .filter { key -> this.isMultiplexKey(key) } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt index efddd8d..8cb4043 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StorageOptions.kt @@ -1,18 +1,13 @@ package io.github.wechaty.memorycard -import io.github.wechaty.memorycard.backend.StorageFile -import io.github.wechaty.memorycard.backend.StorageNop -import io.github.wechaty.memorycard.backend.StorageObs -import io.github.wechaty.memorycard.backend.StorageS3 +import io.github.wechaty.memorycard.backend.* sealed class StorageBackendOptions { var type: String? = null } -class StorageNopOptions: StorageBackendOptions() { - var placeholder: String? = null -} +class StorageNopOptions: StorageBackendOptions() typealias StorageFileOptions = StorageNopOptions @@ -42,5 +37,6 @@ val BACKEND_DICT = mapOf( "file" to StorageFile::class, "s3" to StorageS3::class, "nop" to StorageNop::class, - "obs" to StorageObs::class + "obs" to StorageObs::class, + "oss" to StorageOSS::class ) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt index a2036b4..ed1020c 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/StrorageBackend.kt @@ -17,17 +17,18 @@ abstract class StorageBackend(name: String, option: StorageBackendOptions) { companion object{ private val log = LoggerFactory.getLogger(StorageBackend::class.java) - fun getStorage(name: String,options: StorageBackendOptions?): StorageBackend { - log.info("getStorage', name: %s, options: %s", name, options?.let { JsonUtils.write(it) }) + fun getStorage(name: String, options: StorageBackendOptions?): StorageBackend { + log.info("getStorage', name: {}, options: {}", name, options?.let { JsonUtils.write(it) }) var _options = options + // 如果没有传option参数,默认用file后端 if(options == null) { _options = StorageFileOptions() _options.type = "file" } - if(_options?.type == null || _options.type!! !in BACKEND_DICT.keys){ + if(_options?.type == null || _options.type!! !in BACKEND_DICT.keys) { throw Exception("backed unknown : ${_options?.type}") } return StorageFile(name, _options) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index de17c7a..6e6494a 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -1,6 +1,5 @@ package io.github.wechaty.memorycard.backend -import io.github.wechaty.io.github.wechaty.status.StateSwitch import io.github.wechaty.memorycard.MemoryCardPayload import io.github.wechaty.memorycard.StorageBackend import io.github.wechaty.memorycard.StorageBackendOptions @@ -13,7 +12,6 @@ import org.slf4j.LoggerFactory import java.io.File import java.io.IOException import java.lang.Exception -import kotlin.math.abs // 本身是不存储数据的 // 存储了持久化的文件名和以及用什么方式存储 @@ -58,9 +56,9 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag log.error("load() from file %s error %s", this.absFileName, e.toString()) } - var payload = MemoryCardPayload() + val payload = MemoryCardPayload() try { - payload.map = JsonUtils.readValue(text); + payload.map = JsonUtils.readValue(text) } catch (e: Exception) { log.error("MemoryCard, load() exception: %s", e) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt index ead9366..db1b20c 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageNop.kt @@ -1,12 +1,7 @@ package io.github.wechaty.memorycard.backend import io.github.wechaty.memorycard.* -import io.github.wechaty.utils.JsonUtils -import org.apache.commons.io.FileUtils -import org.apache.commons.io.FilenameUtils -import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory -import java.io.File class StorageNop(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { @@ -41,6 +36,6 @@ class StorageNop(val name: String, var options: StorageBackendOptions) : Storage fun main() { - var storageNop = StorageNop("test", StorageNopOptions()) + val storageNop = StorageNop("test", StorageNopOptions()) println(storageNop) } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt index b1ccd52..c7a146a 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt @@ -9,16 +9,16 @@ import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream -// 使用华为的云存储服务 +// 使用阿里的云存储服务 class StorageOSS(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private lateinit var oss: OSSClient + private var oss: OSSClient init { log.info("StorageOSS, constructor()") options.type = "oss" options = options as StorageOSSOptions - var _options = options as StorageOSSOptions + val _options = options as StorageOSSOptions this.oss = OSSClientBuilder().build(_options.endPoint,_options.accessKeyId, _options.secretAccessKey) as OSSClient } @@ -53,10 +53,18 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage private fun getObject(): MemoryCardPayload { val options = this.options as StorageOSSOptions - val ossObject = this.oss.getObject(options.bucket, this.name) - + val ossObject = try { + this.oss.getObject(options.bucket, this.name) + } + catch (e: Exception) { + log.error("获取文件${this.name}失败") + null + } + if (ossObject == null) { + return MemoryCardPayload() + } val input = ossObject.objectContent - var byte = ByteArray(1024) + val byte = ByteArray(1024) val bos = ByteArrayOutputStream() var len = 0; while (true) { @@ -70,7 +78,7 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage } input.close() ossObject.close() - var card = MemoryCardPayload() + val card = MemoryCardPayload() card.map = JsonUtils.readValue(String(bos.toByteArray())) return card } @@ -102,8 +110,15 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage fun main() { val storageOSSOptions = StorageOSSOptions("LTAI4G2iSKd5m8aTZprdj133", "UT9ns4KvNdZkdMIIPEU87upQv2fsBp", "oss-cn-beijing.aliyuncs.com", "cybersa") - val storageOSS = StorageOSS("objectkey", storageOSSOptions) - val load = storageOSS.load() + // 如果有后缀要带上完整的后缀 + val storageOSS = StorageOSS("PAT.jpg", storageOSSOptions) +// val load = storageOSS.load() + storageOSS.destory() +// load.map.forEach { t, u -> +// println("key:" + t + " value:" + u) +// } + // ok // load.map.put("a", "b") // storageOSS.save(load) + storageOSS.shutdown() } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index be06258..d063d3d 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -19,7 +19,7 @@ import java.io.File // 使用华为的云存储服务 class StorageObs(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private lateinit var obs: ObsClient + private var obs: ObsClient init { log.info("StorageObs, constructor()") @@ -37,10 +37,6 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage override fun load(): MemoryCardPayload { log.info("StorageObs, load()") val card = this.getObject() - if (card == null) { - return MemoryCardPayload() - } - log.info("press", card) return card } @@ -48,17 +44,11 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage override fun destory() { log.info("StorageObs, destroy()") this.deleteObject() -// obs.close() - } - - override fun toString(): String { - return "${this.name}<${this.name}>" } private fun putObject(payload: MemoryCardPayload) { val options = this.options as StorageObsOptions val putObject = this.obs.putObject(options.bucket, this.name, ByteArrayInputStream(JsonUtils.write(payload.map).toByteArray())) - // 还需要处理异常 if (putObject.statusCode >= 300) { throw Exception("obs putObject error") } @@ -66,8 +56,18 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage private fun getObject(): MemoryCardPayload { val options = this.options as StorageObsOptions - val obsObject = this.obs.getObject(options.bucket, this.name) + val obsObject = try { + this.obs.getObject(options.bucket, this.name) + } + catch (e: Exception) { + log.error("获取${name}错误") + null + } + + if (obsObject == null) { + return MemoryCardPayload() + } val input = obsObject.objectContent var byte = ByteArray(1024) val bos = ByteArrayOutputStream() @@ -83,6 +83,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage } input.close() + obs.close() var card = MemoryCardPayload() card.map = JsonUtils.readValue(String(bos.toByteArray())) return card @@ -90,11 +91,28 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage private fun deleteObject() { val options = this.options as StorageObsOptions - val deleteObject = this.obs.deleteObject(options.bucket, this.name) + val deleteObject = try { + this.obs.deleteObject(options.bucket, this.name) + } + catch (e: Exception) { + log.error("删除${name}错误") + null + } + if (deleteObject == null) { + throw Exception("obs deleteObject error") + } if (deleteObject.statusCode >= 300) { throw Exception("obs deleteObject error") } } + override fun toString(): String { + return "${this.name}<${this.name}>" + } + + fun shutdown() { + log.info("StorageObs, shutdown()") + this.obs.close() + } companion object { private val log = LoggerFactory.getLogger(StorageObs::class.java) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index f7b59c1..314c20a 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -10,13 +10,13 @@ import org.slf4j.LoggerFactory class StorageS3(val name: String, var options: StorageBackendOptions) : StorageBackend(name,options) { - private lateinit var s3: AmazonS3 + private var s3: AmazonS3 init { log.info("StorageS3, constructor()") options.type = "s3" options = options as StorageS3Options - var _options = options as StorageS3Options + val _options = options as StorageS3Options val basicAWSCredentials = BasicAWSCredentials(_options.accessKeyId, _options.secretAccessKey) this.s3 = AmazonS3ClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(basicAWSCredentials)) @@ -65,13 +65,16 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB log.info("StorageS3, destory()") val options = this.options as StorageS3Options this.s3.deleteObject(options.bucket, this.name) - this.s3.shutdown() } override fun toString(): String { return "${this.name}<${this.name}>" } + fun shutdown() { + log.info("StorageS3, shutdown()") + this.s3.shutdown() + } companion object { private val log = LoggerFactory.getLogger(StorageS3::class.java) From 6c5fce54d9a33531b6db7dc1352a2e1822668ad1 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 18 Jul 2020 23:16:28 +0800 Subject: [PATCH 21/46] =?UTF-8?q?1.=20=E8=AE=B2match=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=B8=BAcontainsMatchIn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/wechaty/memorycard/MemoryCard.kt | 57 +++++++++++++------ 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 010f37e..59f340d 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -83,6 +83,25 @@ class MemoryCard { ) } + suspend fun loadAsync() { + log.info("MemoryCard, load() from storage: {}", this.storage ?: "N/A") + if (this.isMultiplex()) { + log.info("MemoryCard, load() should not be called on a multiplex MemoryCard. NOOP") + return + } + if (this.payload != null) { + throw Exception("memory had already loaded before.") + } + + if (this.storage != null) { + this.payload = this.storage!!.load() + } + else { + log.info("MemoryCard, load() no storagebackend") + this.payload = MemoryCardPayload() + } + } + fun load(): Future { log.info("MemoryCard, load() from storage: {}", this.storage ?: "N/A") if (this.isMultiplex()) { @@ -176,15 +195,14 @@ class MemoryCard { throw Exception("not a multiplex memory") } - // \r + \n val namespace = NAMESPACE_MULTIPLEX_SEPRATOR + this.multiplexNameList.joinToString(NAMESPACE_MULTIPLEX_SEPRATOR) return namespace } protected fun isMultiplexKey(key: String): Boolean { - if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.matches(key) - && NAMESPACE_KEY_SEPRATOR_REGEX.matches(key)) { + if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.containsMatchIn(key) + && NAMESPACE_KEY_SEPRATOR_REGEX.containsMatchIn(key)) { val namespace = this.multiplexNamespace() return key.startsWith(namespace) @@ -311,12 +329,7 @@ class MemoryCard { return this.payload!!.map.values } - fun multiplex (name: String): MemoryCard { - log.info("MemoryCard, multiplex({})", name) - // FIXME: as any ? - return multiplex(this, name) - } override fun toString(): String { var mpString = "" @@ -332,17 +345,29 @@ class MemoryCard { return "MemoryCard<${name}>${mpString}" } - companion object{ + + fun getVersion(): String { + return VERSION + } + + // 会将当前的类作为parent, 后面那个为namespace + fun multiplex(nameSpace: String): MemoryCard { + log.info("MemoryCard, multiplex({})", nameSpace) + return multiplex(this, nameSpace) + } + + protected fun multiplex(parent: MemoryCard, nameSpace: String): MemoryCard { + log.info("MemoryCard, multiplex({}, {})", parent, nameSpace) + parent.options.name = parent.name + parent.options.multiplex = Multiplex(name = nameSpace, parent = parent) + val mpMemory = MemoryCard(options = parent.options) + return mpMemory + } + + companion object { private val log = LoggerFactory.getLogger(MemoryCard::class.java) val VERSION = "0.0.0" - fun multiplex(memory: MemoryCard, name: String): MemoryCard{ - log.info("MemoryCard, static multiplex({}, {})", memory, name) - memory.options.multiplex = Multiplex(name = name, parent = memory) - val mpMemory = MemoryCard(options = memory.options) - return mpMemory - } - fun fromJSON(text: String): MemoryCard { log.info("MemoryCard, fromJSON(...)") var jsonObj: MemoryCardJsonObject From faa5b6fb9496170e64f0ffc037b799f7789d13f9 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 18 Jul 2020 23:18:18 +0800 Subject: [PATCH 22/46] =?UTF-8?q?1.=20=E4=BF=AE=E6=94=B9=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=202.=20=E5=A2=9E=E5=8A=A0S3=E9=94=99=E8=AF=AF=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wechaty/memorycard/backend/StorageFile.kt | 1 + .../wechaty/memorycard/backend/StorageOSS.kt | 14 +--------- .../wechaty/memorycard/backend/StorageS3.kt | 26 ++++++++++++++----- 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index 6e6494a..77cb3d7 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -48,6 +48,7 @@ class StorageFile(val name: String, var options: StorageBackendOptions) : Storag if(!file.exists()){ return MemoryCardPayload() } + var text = "" try { text = FileUtils.readFileToString(file, "UTF-8") diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt index c7a146a..fa2cc7c 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageOSS.kt @@ -108,17 +108,5 @@ class StorageOSS(val name: String, var options: StorageBackendOptions) : Storage } fun main() { - val storageOSSOptions = StorageOSSOptions("LTAI4G2iSKd5m8aTZprdj133", "UT9ns4KvNdZkdMIIPEU87upQv2fsBp", - "oss-cn-beijing.aliyuncs.com", "cybersa") - // 如果有后缀要带上完整的后缀 - val storageOSS = StorageOSS("PAT.jpg", storageOSSOptions) -// val load = storageOSS.load() - storageOSS.destory() -// load.map.forEach { t, u -> -// println("key:" + t + " value:" + u) -// } - // ok -// load.map.put("a", "b") -// storageOSS.save(load) - storageOSS.shutdown() + } diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 314c20a..1bd0cf8 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -27,20 +27,29 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB override fun save(payload: MemoryCardPayload) { log.info("StorageS3, save()") val options = this.options as StorageS3Options - - this.s3.putObject(JsonUtils.write(payload.map), options.bucket, this.name) - + try { + this.s3.putObject(JsonUtils.write(payload.map), options.bucket, this.name) + } + catch (e: Exception) { + log.error("上传文件:${this.name}错误") + } } override fun load(): MemoryCardPayload { log.info("StorageS3, load()") val options = this.options as StorageS3Options - val result = this.s3.getObject(options.bucket, this.name) + val result = try { + this.s3.getObject(options.bucket, this.name) + } + catch (e: Exception) { + log.error("获取文件:${this.name}错误") + null + } + if (result == null || result.objectContent == null) { return MemoryCardPayload() } - // 这里还有问题 val objectContent = result.objectContent var payloadMap = StringBuffer() @@ -64,7 +73,12 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB override fun destory() { log.info("StorageS3, destory()") val options = this.options as StorageS3Options - this.s3.deleteObject(options.bucket, this.name) + try { + this.s3.deleteObject(options.bucket, this.name) + } + catch (e: Exception) { + log.error("删除${this.name}错误") + } } override fun toString(): String { From 62342f362bfc69b186468b68c5acfcc49fe55c65 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 19 Jul 2020 13:43:44 +0800 Subject: [PATCH 23/46] =?UTF-8?q?1.=20=E5=B0=86=E6=96=B9=E6=B3=95=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/wechaty/memorycard/MemoryCard.kt | 48 +++++++++---------- .../io/github/wechaty/status/StateSwitch.kt | 19 ++++---- 2 files changed, 34 insertions(+), 33 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 59f340d..1d8f63f 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -102,11 +102,11 @@ class MemoryCard { } } - fun load(): Future { + fun load() { log.info("MemoryCard, load() from storage: {}", this.storage ?: "N/A") if (this.isMultiplex()) { log.info("MemoryCard, load() should not be called on a multiplex MemoryCard. NOOP") - return CompletableFuture.completedFuture(null) + return } if (this.payload != null) { throw Exception("memory had already loaded before.") @@ -119,10 +119,9 @@ class MemoryCard { log.info("MemoryCard, load() no storagebackend") this.payload = MemoryCardPayload() } - return CompletableFuture.completedFuture(null) } - fun save(): Future { + fun save() { if (this.isMultiplex()) { if (this.parent == null) { throw Exception("multiplex memory no parent") @@ -137,14 +136,13 @@ class MemoryCard { if (this.storage == null) { log.info("MemoryCard, save() no storage, NOOP") - return CompletableFuture.completedFuture(null) + return } this.storage!!.save(this.payload!!) - return CompletableFuture.completedFuture(null) } - fun destory(): Future { + fun destory() { log.info("MemoryCard, destroy() storage: {}", this.storage ?: "N/A") if (this.isMultiplex()) { throw Exception("can not destroy on a multiplexed memory") @@ -157,11 +155,10 @@ class MemoryCard { this.storage = null } this.payload = null - return CompletableFuture.completedFuture(null) } - fun size(): Future { + fun size(): Int { log.info("MemoryCard, <{}> size", this.multiplexPath()) if (this.payload == null) { @@ -178,7 +175,7 @@ class MemoryCard { count = this.payload!!.map.size } - return CompletableFuture.completedFuture(count) + return count } @@ -199,6 +196,7 @@ class MemoryCard { this.multiplexNameList.joinToString(NAMESPACE_MULTIPLEX_SEPRATOR) return namespace } + protected fun isMultiplexKey(key: String): Boolean { if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.containsMatchIn(key) @@ -221,19 +219,24 @@ class MemoryCard { } } - fun get(name: String): CompletableFuture? { + fun get(name: String): Any? { log.info("MemoryCard, <{}> get({})", this.multiplexPath(), name) if (this.payload == null) { throw Exception("no payload, please call load() first.") } val key = this.resolveKey(name) - return CompletableFuture.supplyAsync { - this.payload!!.map.get(key) - } + return this.payload!!.map.get(key) } - - fun set(name: String, data: T): Future { + /** + * 功能描述: + * + * @Param: + * @Return: + * @Author: a1725 + * @Date: 2020/7/18 23:54 + */ + fun set(name: String, data: T) { log.info("MemoryCard, <{}> set({}, {})", this.multiplexPath(), name, data) if (this.payload == null) { @@ -242,10 +245,9 @@ class MemoryCard { val key = this.resolveKey(name) this.payload!!.map[key] = data as Any - return CompletableFuture.completedFuture(null) } - fun clear(): Future { + fun clear() { log.info("MemoryCard, <{}> clear()", this.multiplexPath()) if (this.payload == null) { @@ -260,10 +262,9 @@ class MemoryCard { else { this.payload = MemoryCardPayload() } - return CompletableFuture.completedFuture(null) } - fun delete(name: String): Future { + fun delete(name: String) { log.info("MemoryCard, <{}> delete({})", this.multiplexPath(), name) if (this.payload == null) { throw Exception("no payload, please call load() first.") @@ -271,7 +272,6 @@ class MemoryCard { val key = this.resolveKey(name) this.payload!!.map.remove(key) - return CompletableFuture.completedFuture(null) } fun entries(): MutableSet> { @@ -284,7 +284,7 @@ class MemoryCard { return this.payload!!.map.entries } - fun has(key: String): Future { + fun has(key: String): Boolean { log.info("MemoryCard, <{}> has ({})", this.multiplexPath(), key) if (this.payload == null) { @@ -292,9 +292,7 @@ class MemoryCard { } val absoluteKey = this.resolveKey(key) - return CompletableFuture.supplyAsync { - this.payload!!.map.containsKey(absoluteKey) - } + return this.payload!!.map.containsKey(absoluteKey) } fun keys(): MutableSet { diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index c15af20..51f504a 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -34,7 +34,7 @@ class StateSwitch: EventEmitter(){ private lateinit var offQueue: ArrayBlockingQueue<() -> Unit> init { - log.info("StateSwitch, constructor(%s)", this.name) + log.info("StateSwitch, constructor({})", this.name) this.onoff = false this.pending = false @@ -92,12 +92,12 @@ class StateSwitch: EventEmitter(){ "true" else "false" - log.info("StateSwitch, <%s> on() is %s", this.name, on) + log.info("StateSwitch, <{}> on() is {}", this.name, on) return on } fun off(state: StateEnum): String { - log.info("StateSwitch, <%s> off(%s) <- (%s)", this.name, state, this.off()) + log.info("StateSwitch, <{}> off({}) <- ({})", this.name, state, this.off()) if (state == StateEnum.ON) { throw Exception("the parameter state shouldn't be on") } @@ -122,7 +122,11 @@ class StateSwitch: EventEmitter(){ } return this.off() } - // get the current off state + + /** + * + * @return 返回当前off的状态 + */ fun off(): String { val off = if (!this.onoff) @@ -132,7 +136,7 @@ class StateSwitch: EventEmitter(){ "true" else "false" - log.info("StateSwitch, <%s> off() is %s", this.name, off) + log.info("StateSwitch, <{}> off() is {}", this.name, off) return off } @@ -142,7 +146,7 @@ class StateSwitch: EventEmitter(){ * 好像可以去掉runblocking */ fun ready(state: StateEnum = StateEnum.ON, cross: Boolean = true) { - log.info("StateSwitch, <%s> ready(%s, %s)", name, state, cross) + log.info("StateSwitch, <{}> ready({}, {})", name, state, cross) // 如果准备变换的状态为on if (state == StateEnum.ON) { @@ -159,7 +163,6 @@ class StateSwitch: EventEmitter(){ // } CoroutineScope(Dispatchers.Default).launch { onQueue.take() - println("on") } } // 如果准备变为off @@ -183,7 +186,7 @@ class StateSwitch: EventEmitter(){ else { throw Exception("should not go here. ${state} should be of type 'never'") } - log.info("StateSwitch, <%s> ready(%s, %s) resolved.", name, state, cross) + log.info("StateSwitch, <{}> ready({}, {}) resolved.", name, state, cross) } fun addEventListener(type: StateEnum, listener: Listener) { From 709fb78b6a120dc5409344b4f7af5cd514928f81 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 19 Jul 2020 14:05:50 +0800 Subject: [PATCH 24/46] =?UTF-8?q?1.=20=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84close=E8=AF=AD=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index d063d3d..591ec72 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -48,6 +48,7 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage private fun putObject(payload: MemoryCardPayload) { val options = this.options as StorageObsOptions + val putObject = this.obs.putObject(options.bucket, this.name, ByteArrayInputStream(JsonUtils.write(payload.map).toByteArray())) if (putObject.statusCode >= 300) { throw Exception("obs putObject error") @@ -83,7 +84,6 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage } input.close() - obs.close() var card = MemoryCardPayload() card.map = JsonUtils.readValue(String(bos.toByteArray())) return card From 6cc770743f72033d320aaad999c6addb2d0f51e7 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 19 Jul 2020 14:09:21 +0800 Subject: [PATCH 25/46] =?UTF-8?q?1.=20=E5=88=A0=E9=99=A4=E4=B8=8D=E5=BA=94?= =?UTF-8?q?=E8=AF=A5=E6=98=BE=E7=A4=BA=E7=9A=84=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wechaty/memorycard/backend/StorageObs.kt | 26 +++---------------- 1 file changed, 3 insertions(+), 23 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt index 591ec72..71153b7 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageObs.kt @@ -122,30 +122,10 @@ class StorageObs(val name: String, var options: StorageBackendOptions) : Storage fun main(){ - val storageObsOptions = StorageObsOptions("D5RKYDQRCRYICGP65H2R", "K0Va8jn8kWBK8jzdmC4QC2vvqsgF5Epz1iWhZOOp", - "obs.cn-north-4.myhuaweicloud.com", "cybersa") + val storageObsOptions = StorageObsOptions("aaa", "aaa", + "aaa", "aaa") val storageObs = StorageObs("notexist", storageObsOptions) val load = storageObs.load() -// var memory = MemoryCardPayload() -// var address = Address("福州", "付件") -// var person = Person("sda", 13, address) -// memory.map.put("person", person) -// storageObs.save(memory) - -// val load = storageObs.load() -// println(load.map) -// load.map.forEach { t, u -> print(t + ":" + u) } -// storageObs.destory() - -// var obsClient = ObsClient("D5RKYDQRCRYICGP65H2R", "K0Va8jn8kWBK8jzdmC4QC2vvqsgF5Epz1iWhZOOp", -// "obs.cn-north-4.myhuaweicloud.com") -// var map = mutableMapOf() -// map.put("a", "nihsdasd") -// obsClient.putObject("cybersa", "objectname", ByteArrayInputStream(JsonUtils.write(map).toByteArray())) -// val obsObject = obsClient.getObject("cybersa", "objectname") -// var byte = ByteArray(1024) -// var len = obsObject.objectContent.read(byte) -// println(String(byte, 0 , len)) -// obsClient.close() + } From 2925fd7dc5c731db2de46c7dc1598e4c9cc7e63a Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 19 Jul 2020 15:19:40 +0800 Subject: [PATCH 26/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0StateSwitchListene?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/github/wechaty/status/StateSwitch.kt | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index 51f504a..f206363 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -1,15 +1,15 @@ -package io.github.wechaty.io.github.wechaty.status +package io.github.wechaty.status import io.github.wechaty.StateEnum import io.github.wechaty.eventEmitter.EventEmitter import io.github.wechaty.eventEmitter.Listener import io.github.wechaty.io.github.wechaty.schemas.EventEnum +import io.github.wechaty.io.github.wechaty.status.StateSwitchListener import kotlinx.coroutines.* import org.slf4j.LoggerFactory import java.util.concurrent.ArrayBlockingQueue -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Future import java.util.concurrent.atomic.AtomicInteger +import javax.swing.plaf.nimbus.State var COUNTER = AtomicInteger() val nop: () -> Unit = {} @@ -28,7 +28,7 @@ class StateSwitch: EventEmitter(){ private lateinit var onResolver : () -> Unit private lateinit var offResolver : () -> Unit - private val name :String = "#${COUNTER.addAndGet(1)}" + private var name :String = "#${COUNTER.addAndGet(1)}" private lateinit var onQueue: ArrayBlockingQueue<() -> Unit> private lateinit var offQueue: ArrayBlockingQueue<() -> Unit> @@ -189,12 +189,22 @@ class StateSwitch: EventEmitter(){ log.info("StateSwitch, <{}> ready({}, {}) resolved.", name, state, cross) } - fun addEventListener(type: StateEnum, listener: Listener) { - super.addListener(type, listener) + fun addEventListener(type: StateEnum, listener: StateSwitchListener) { + super.addListener(type, object : Listener { + override fun handler(vararg any: Any) { + listener.handler(any[0] as StateEnum) + } + + }) } - fun removeEventListener(type: StateEnum, listener: Listener) { - super.removeListener(type, listener) + fun removeEventListener(type: StateEnum, listener: StateSwitchListener) { + super.removeListener(type, object : Listener { + override fun handler(vararg any: Any) { + // 有问题 + listener.handler(any[0] as StateEnum) + } + }) } companion object { From 95add40e913d8766303267313527af15114d66f8 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 19 Jul 2020 15:44:56 +0800 Subject: [PATCH 27/46] =?UTF-8?q?1.=20ready=E5=8F=98=E4=B8=BArunblocking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/kotlin/io/github/wechaty/status/StateSwitch.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index f206363..f5aae5b 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -145,7 +145,7 @@ class StateSwitch: EventEmitter(){ * @param cross: 是否变换状态,默认可以 * 好像可以去掉runblocking */ - fun ready(state: StateEnum = StateEnum.ON, cross: Boolean = true) { + fun ready(state: StateEnum = StateEnum.ON, cross: Boolean = true) = runBlocking { log.info("StateSwitch, <{}> ready({}, {})", name, state, cross) // 如果准备变换的状态为on From 37def841c1d216039881a27ca73b40194ce39f91 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 19 Jul 2020 15:46:42 +0800 Subject: [PATCH 28/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0StateSwitchListene?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/kotlin/io/github/wechaty/status/StateListener.kt | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateListener.kt diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateListener.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateListener.kt new file mode 100644 index 0000000..2c57339 --- /dev/null +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateListener.kt @@ -0,0 +1,8 @@ +package io.github.wechaty.io.github.wechaty.status + +import io.github.wechaty.StateEnum + +@FunctionalInterface +interface StateSwitchListener { + fun handler(state: StateEnum) +} From d3e2065952522087cd596695c48dc421c517080e Mon Sep 17 00:00:00 2001 From: cunkoulaocai <30389241+cunkoulaocai@users.noreply.github.com> Date: Sun, 19 Jul 2020 21:29:36 +0800 Subject: [PATCH 29/46] Delete MemoryCardTest.kt --- .../MemoryCardTest.kt | 71 ------------------- 1 file changed, 71 deletions(-) delete mode 100644 wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt diff --git a/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt b/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt deleted file mode 100644 index 6f37d95..0000000 --- a/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.wechaty.io.github.wechaty.memorycard.test - -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile -import io.github.wechaty.memorycard.* -import org.junit.Before -import org.junit.Test - - -class MemoryCardTest { - - lateinit var memoryCard: MemoryCard - - @Before - fun setUp() { - memoryCard = MemoryCard("test") - } - @Test - fun testCreate() { - - this.memoryCard.load() - this.memoryCard.values().forEach { - println(it) - } - this.memoryCard.destory() - } - - @Test - fun testLoad() { - this.memoryCard.load() - this.memoryCard.set("a", "b") - this.memoryCard.save() - } - - @Test - fun testSave() { - var card = MemoryCard() - card.load() - card.set("a", "你好") -// println(card.get("a")?.get()) - card.keys().forEach { - println(it) - } - card.save() - } - @Test - fun testDestory() { - } - - @Test - fun testMultiplex() { - memoryCard.load() - // 这里的name是前缀的名字 - // \rparent\nson - val multiplex = Multiplex(this.memoryCard, "parent") - val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) - println(memoryCardOptions) - // 用debug模式会有问题 - // 如果一个memory是multiple的,那么它自身就不会保存,只会保存一个父类的 - var son = MemoryCard(options = memoryCardOptions) - son.load() - - son.set("son", "b") - son.set("nihao", "asdasd") - println(son.get("son")?.get()) - son.delete("nihao") - println(son.has("nihao").get()) - println(son.has("son").get()) - son.save() - } - -} From d02913756c49c69f8c73c2f6b2b5a9c2e821f7ff Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Tue, 21 Jul 2020 23:11:23 +0800 Subject: [PATCH 30/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0memorycard?= =?UTF-8?q?=E5=92=8Cstateswitch=E6=B5=8B=E8=AF=95=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/test/java/MemoryCardTest.java | 18 ++ .../MemoryCardTest.kt | 71 -------- .../memorycard/MemoryCardMultiplexTest.kt | 59 ++++++ .../wechaty/memorycard/MemoryCardTest.kt | 170 ++++++++++++++++++ .../wechaty/memorycard/StorageOptionsTest.kt | 14 ++ .../memorycard/backend/StorageFileTest.kt | 45 +++++ .../memorycard/backend/StorageNopTest.kt | 30 ++++ .../memorycard/backend/StorageOSSTest.kt | 56 ++++++ .../memorycard/backend/StorageObsTest.kt | 23 +++ .../github/wechaty/status/StateSwitchTes.java | 22 +++ .../github/wechaty/status/StateSwitchTest.kt | 57 ++++++ 11 files changed, 494 insertions(+), 71 deletions(-) create mode 100644 wechaty-puppet/src/test/java/MemoryCardTest.java delete mode 100644 wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java create mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt diff --git a/wechaty-puppet/src/test/java/MemoryCardTest.java b/wechaty-puppet/src/test/java/MemoryCardTest.java new file mode 100644 index 0000000..a02b615 --- /dev/null +++ b/wechaty-puppet/src/test/java/MemoryCardTest.java @@ -0,0 +1,18 @@ +import io.github.wechaty.memorycard.MemoryCard; +import org.junit.Test; + +import java.util.Map; +import java.util.concurrent.ExecutionException; + +public class MemoryCardTest { + + @Test + public void testLoad() throws ExecutionException, InterruptedException { + MemoryCard card = new MemoryCard("default", null); + card.load(); + Map map = (Map) card.get("person"); + map.forEach((key, value) -> { + System.out.println(key + ":" + value); + }); + } +} diff --git a/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt b/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt deleted file mode 100644 index 6f37d95..0000000 --- a/wechaty-puppet/src/test/kotlin/io.github.wechaty.memorycard/MemoryCardTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -package io.github.wechaty.io.github.wechaty.memorycard.test - -import io.github.wechaty.io.github.wechaty.memorycard.backend.StorageFile -import io.github.wechaty.memorycard.* -import org.junit.Before -import org.junit.Test - - -class MemoryCardTest { - - lateinit var memoryCard: MemoryCard - - @Before - fun setUp() { - memoryCard = MemoryCard("test") - } - @Test - fun testCreate() { - - this.memoryCard.load() - this.memoryCard.values().forEach { - println(it) - } - this.memoryCard.destory() - } - - @Test - fun testLoad() { - this.memoryCard.load() - this.memoryCard.set("a", "b") - this.memoryCard.save() - } - - @Test - fun testSave() { - var card = MemoryCard() - card.load() - card.set("a", "你好") -// println(card.get("a")?.get()) - card.keys().forEach { - println(it) - } - card.save() - } - @Test - fun testDestory() { - } - - @Test - fun testMultiplex() { - memoryCard.load() - // 这里的name是前缀的名字 - // \rparent\nson - val multiplex = Multiplex(this.memoryCard, "parent") - val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) - println(memoryCardOptions) - // 用debug模式会有问题 - // 如果一个memory是multiple的,那么它自身就不会保存,只会保存一个父类的 - var son = MemoryCard(options = memoryCardOptions) - son.load() - - son.set("son", "b") - son.set("nihao", "asdasd") - println(son.get("son")?.get()) - son.delete("nihao") - println(son.has("nihao").get()) - println(son.has("son").get()) - son.save() - } - -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt new file mode 100644 index 0000000..dc0a0fe --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt @@ -0,0 +1,59 @@ +package io.github.wechaty.io.github.wechaty.memorycard.test + +import io.github.wechaty.memorycard.* +import io.github.wechaty.memorycard.backend.Address +import io.github.wechaty.memorycard.backend.Person +import io.github.wechaty.utils.JsonUtils +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.junit.Assert.* + + +class MemoryCardMultiplexTest { + + lateinit var memoryCard: MemoryCard + + @Before + fun setUp() { + memoryCard = MemoryCard("A") + + } + + @Test + fun testLoadAndSave() { + memoryCard.load() + val cardA = memoryCard.multiplex("cardA") + val cardB = memoryCard.multiplex("cardB") + memoryCard.set("a", "b") + cardA.set("a", "b") +// cardB.set("a", "b") + println(memoryCard.size()) + println(memoryCard.keys().size) + println(cardA.keys().size) + println(cardA.size()) + println(cardB.keys().size) + memoryCard.save() + } + + @Test + fun testLoadAd() { + memoryCard.load() + val cardA = memoryCard.multiplex("cardA") + val cardB = memoryCard.multiplex("cardB") + println(memoryCard.size()) + println(memoryCard.keys().size) + } + + @Test + fun testParttern() { + var a:String = "\rcardA\na" + val NAMESPACE_MULTIPLEX_SEPRATOR_REGEX = Regex("\r") + val NAMESPACE_KEY_SEPRATOR_REGEX = Regex("\n") + if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.containsMatchIn(a)) { + println(1) + } + } +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt new file mode 100644 index 0000000..73a6d44 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt @@ -0,0 +1,170 @@ +package io.github.wechaty.io.github.wechaty.memorycard.test + +import io.github.wechaty.memorycard.* +import io.github.wechaty.memorycard.backend.Address +import io.github.wechaty.memorycard.backend.Person +import io.github.wechaty.utils.JsonUtils +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.junit.Assert.* + + +class MemoryCardTest { + + lateinit var memoryCard: MemoryCard + + @Before + fun setUp() { + memoryCard = MemoryCard("test") + } + + @Test + fun testCreate() { + this.memoryCard.load() + this.memoryCard.values().forEach { + assertEquals("b", it) + } + } + + @Test + fun testLoadAsync() { + runBlocking { + var job = GlobalScope.launch { + memoryCard.loadAsync() + } + job.join() + } + + println(memoryCard.keys().size) + } + + @Test + fun testSet() { + this.memoryCard.load() + this.memoryCard.set("list", listOf(1, 2, 3)) + this.memoryCard.save() + } + + @Test + fun testDefultSave() { + var son = MemoryCard() + son.load() + son.set("a", "你好") + var map = mapOf("key" to "value") + son.set("this is map", map) + son.keys().forEach { + println(it) + } + son.save() + } + + @Test + fun testDelete() { + memoryCard.load() + memoryCard.delete("a") + memoryCard.save() + } + @Test + fun testDestory() { + var de = MemoryCard() + de.load() + de.destory() + } + + @Test + fun testMultiplex() { + memoryCard.load() + // 这里的name是前缀的名字 + // \rparent\nson + val multiplex = Multiplex(this.memoryCard, "parent") + val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) + println("options:" + memoryCardOptions) + // 用debug模式会有问题 + // 如果一个memory是multiple的,那么它自身就不会保存,只会保存一个父类的 + var son = MemoryCard(options = memoryCardOptions) + son.load() + + son.set("son", "b") + son.set("nihao", "asdasd") + println(son.get("son")) + son.delete("nihao") + println("has key{nihao}:" + son.has("nihao")) + println("has key{son}:" + son.has("son")) + println("has key{list}:" + son.has("list")) + son.save() + } + + @Test + fun newLoad() { + var card = MemoryCard() + card.load() + val get = card.get("person") as Map<*, *> + println(get["name"]) + + var address = Address("福州", "付件") + var person = Person("sda", 13, address) + var text = JsonUtils.write(person) + println(text) + var city = JsonUtils.readValue>(text)["address"] as Map<*, *> + println(city["province"]) + } + + @Test + fun testMap() { + var card = MemoryCard() + card.load() + println(card.keys().size) + for (value in card.values()) { + println(value) + } + card.keys().forEach { + println(it) + } + + card.entries().forEach { + println(it.key + ":" + it.value) + } + for (entry in card.get("person") as Map) { + println(entry.key + ":" + entry.value) + } + } + + @Test + fun testMultiplexSave() { + // 设置父memorycard + var parentCard = MemoryCard("aaaa") + parentCard.load() + parentCard.set("a", "b") + // \r后面的为parent + val multiplex = Multiplex(parentCard, "parent") + // 子card的名字为son + val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) + var sonCard = MemoryCard(options = memoryCardOptions) + sonCard.load() + sonCard.set("map", mapOf("a" to 1, "b" to 2)) + sonCard.set("list", listOf("1", "2", "3")) + sonCard.save() + } + + @Test + fun testMultiplexLoad() { + var parentCard = MemoryCard("parent") + parentCard.load() + + val multiplex = Multiplex(parentCard, "parent") + val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) + + var sonCard = MemoryCard(options = memoryCardOptions) + sonCard.load() + sonCard.keys().forEach { + println(it) + } + sonCard.values().forEach { + println(it) + } + } + +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt new file mode 100644 index 0000000..d18122f --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt @@ -0,0 +1,14 @@ +package io.github.wechaty.memorycard + +import org.junit.Test + + +class StorageOptionsTest { + + @Test + fun testBackendDict() { + BACKEND_DICT.forEach { t, u -> + println("key:" + t + " value:" + u) + } + } +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt new file mode 100644 index 0000000..32badc6 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt @@ -0,0 +1,45 @@ +package io.github.wechaty.io.github.wechaty.memorycard.test + +import io.github.wechaty.memorycard.MemoryCardPayload +import io.github.wechaty.memorycard.StorageFileOptions +import io.github.wechaty.memorycard.backend.StorageFile +import org.junit.Before +import org.junit.Test + + +class StorageFileTset { + + lateinit var storageFile: StorageFile + + @Before + fun setUp() { + this.storageFile = StorageFile("test", StorageFileOptions()) + } + @Test + fun testCreate() { + println(this.storageFile.name) + } + + @Test + fun testLoad() { + val load = this.storageFile.load() + for (mutableEntry in load.map) { + println("key:" + mutableEntry.key + " value:" + mutableEntry.value) + } + } + + @Test + fun testSave() { + val memoryCardPayload = MemoryCardPayload() + + memoryCardPayload.map.put("a", 123) + memoryCardPayload.map.put("b", "年后") + memoryCardPayload.map.put("c", "今年过节不收礼") + storageFile.save(memoryCardPayload) + } + @Test + fun testDestory() { + storageFile.destory() + + } +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt new file mode 100644 index 0000000..f53e076 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt @@ -0,0 +1,30 @@ +package io.github.wechaty.memorycard.backend + +import io.github.wechaty.memorycard.StorageNopOptions +import io.github.wechaty.memorycard.StorageObsOptions +import org.junit.Test + + +class StorageNopTest { + @Test + fun testLoad() { + val storageNop = StorageNop("objectname", StorageNopOptions()) + val load = storageNop.load() + println(load.map) + println(storageNop) + } + + @Test + fun testSave() { + val storageNop = StorageNop("myname", StorageNopOptions()) + val load = storageNop.load() + storageNop.save(load) + } + + @Test + fun testDestory() { + val storageNop = StorageNop("myname", StorageNopOptions()) + val load = storageNop.load() + storageNop.destory() + } +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt new file mode 100644 index 0000000..6543560 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt @@ -0,0 +1,56 @@ +package io.github.wechaty.memorycard.backend + +import io.github.wechaty.memorycard.StorageOSSOptions +import io.github.wechaty.utils.JsonUtils +import org.junit.Test +import org.junit.Assert.*; +class Person(var name: String, var age: Int, var address: Address) +class Address(var city: String, var province: String) +class StorageOSSTest { + val storageOSSOptions = StorageOSSOptions("xxx", "xxx", + "oss-cn-beijing.aliyuncs.com", "xxx") + + // 如果对应的name存在 + @Test + fun testLoadExist() { + val storageOSS = StorageOSS("objectname", storageOSSOptions) + val load = storageOSS.load() + println(load.map) + } + + + // 如果对应的name不存在 + @Test + fun testLoadNotExist() { + val storageOSS = StorageOSS("objectname", storageOSSOptions) + val load = storageOSS.load() + assertEquals(0, load.map.size) + } + + @Test + fun testSave() { + val storageOSS = StorageOSS("objectname", storageOSSOptions) + val load = storageOSS.load() + load.map.put("key", "value") + load.map.put("list", listOf(1, 2, 3)) + load.map.put("a", mapOf("a" to 1, "b" to 2)) + storageOSS.save(load) + } + + @Test + fun testDestory() { + // 如果有后缀要带上完整的后缀 + val storageOSS = StorageOSS("objectname", storageOSSOptions) + storageOSS.destory() + } + @Test + fun testJson() { + var map = mutableMapOf() + var list = listOf(1, 2, 3) + map.put("list", list) + val write = JsonUtils.write(map) + println(write) + var readValue: Map = JsonUtils.readValue(write) + println(readValue.get("list") is List<*>) + } +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt new file mode 100644 index 0000000..4aaa898 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt @@ -0,0 +1,23 @@ +package io.github.wechaty.memorycard.backend + +import io.github.wechaty.memorycard.StorageObsOptions +import org.junit.Test + + +class StorageObsTest { + val storageObsOptions = StorageObsOptions("xxx", "xxx", + "obs.cn-north-4.myhuaweicloud.com", "xxx") + @Test + fun testLoad() { + val storageObs = StorageObs("objectname", storageObsOptions) + val load = storageObs.load() + println(load.map) + } + + @Test + fun testLoadNotExist() { + // 如果name不存在会返回一个空的payload + val storageObs = StorageObs("myname", storageObsOptions) + val load = storageObs.load() + } +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java new file mode 100644 index 0000000..50cc966 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java @@ -0,0 +1,22 @@ +package io.github.wechaty.status; + +import io.github.wechaty.StateEnum; +import org.junit.Test; + +/** + * @ClassName : StateSwitchTest + * @Description : + * @Author : cybersa + * @Date: 2020-07-19 14:52 + */ +public class StateSwitchTes { + + @Test + public void test() { + StateSwitch stateSwitch = new StateSwitch(); + stateSwitch.addEventListener(StateEnum.ON, (a) -> { + System.out.println(a); + }); + } + +} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt new file mode 100644 index 0000000..27ffcc3 --- /dev/null +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt @@ -0,0 +1,57 @@ +package io.github.wechaty.status + +import io.github.wechaty.StateEnum +import io.github.wechaty.eventEmitter.Listener +import org.junit.Test +import org.junit.Assert.*; +class StateSwitchTest { + + @Test + fun testOn() { + val stateSwitch = StateSwitch() + assertEquals("default is not on", "false", stateSwitch.on()) + + stateSwitch.on(StateEnum.PENDING) + assertEquals("should be state pending", "pending", stateSwitch.on()) + stateSwitch.on(StateEnum.ON) + assertEquals("should be state true", "true", stateSwitch.on()) + assertEquals("should not off", "false", stateSwitch.off()) + stateSwitch.off(StateEnum.OFF) + assertEquals("should not on after off()", "false", stateSwitch.on()) + + } + + @Test + fun testOff() { + val stateSwitch = StateSwitch() + stateSwitch.off(StateEnum.PENDING) + println(stateSwitch.off()) + + stateSwitch.ready(StateEnum.OFF) + println(stateSwitch.on()) + + stateSwitch.off(StateEnum.OFF) + println(stateSwitch.on()) + } + + @Test + fun name() { + + } + @Test + fun ready() { + val stateSwitch = StateSwitch() + stateSwitch.on(StateEnum.PENDING) + println("调用on(pending):" + stateSwitch.on()) + println("调用on(pending):" + stateSwitch.off()) + stateSwitch.ready(StateEnum.ON) + println("调用ready(on)之后:" + stateSwitch.on()) + stateSwitch.on(StateEnum.ON) + println("调用on(on):" + stateSwitch.on()) + } + + @Test + fun add() { + val stateSwitch = StateSwitch() + } +} From 59a9c331eb527621f86f69864e3a145a4a0948a1 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Wed, 22 Jul 2020 19:00:57 +0800 Subject: [PATCH 31/46] =?UTF-8?q?1.=20=E4=BF=AE=E6=94=B9stateSwitch=20on?= =?UTF-8?q?=E5=92=8Coff=E7=9A=84=E8=BF=94=E5=9B=9E=E5=80=BC=202.=20?= =?UTF-8?q?=E5=AE=8C=E5=96=84stateswitch=E7=9A=84=E6=B5=8B=E8=AF=95=203.?= =?UTF-8?q?=20=E5=B0=86stateswitch=E7=9A=84name=E5=B1=9E=E6=80=A7=E4=BD=9C?= =?UTF-8?q?=E4=B8=BA=E6=9E=84=E9=80=A0=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet/default.memory-card.json | 1 + wechaty-puppet/src/main/kotlin/Puppet.kt | 1 - .../wechaty/eventEmitter/EventEmitter.kt | 1 - .../wechaty/memorycard/backend/StorageFile.kt | 2 - .../wechaty/memorycard/backend/StorageS3.kt | 1 - .../io/github/wechaty/status/StateSwitch.kt | 66 +++++------------ .../wechaty/memorycard/MemoryCardTest.kt | 1 - .../github/wechaty/status/StateSwitchTes.java | 22 ------ .../github/wechaty/status/StateSwitchTest.kt | 71 +++++++++++++++---- 9 files changed, 77 insertions(+), 89 deletions(-) create mode 100644 wechaty-puppet/default.memory-card.json delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java diff --git a/wechaty-puppet/default.memory-card.json b/wechaty-puppet/default.memory-card.json new file mode 100644 index 0000000..7f228f9 --- /dev/null +++ b/wechaty-puppet/default.memory-card.json @@ -0,0 +1 @@ +{"a":"b"} \ No newline at end of file diff --git a/wechaty-puppet/src/main/kotlin/Puppet.kt b/wechaty-puppet/src/main/kotlin/Puppet.kt index a91cdc1..e70d7be 100644 --- a/wechaty-puppet/src/main/kotlin/Puppet.kt +++ b/wechaty-puppet/src/main/kotlin/Puppet.kt @@ -61,7 +61,6 @@ abstract class Puppet : EventEmitter { /** * */ - constructor(puppetOptions: PuppetOptions) { count.addAndGet(1) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/eventEmitter/EventEmitter.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/eventEmitter/EventEmitter.kt index 9e60edf..27b532c 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/eventEmitter/EventEmitter.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/eventEmitter/EventEmitter.kt @@ -84,7 +84,6 @@ open class EventEmitter : EventEmitterInterface { } map.put(event, wrapListener) - } override fun removeAllListeners(event:Event): Boolean { diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt index 77cb3d7..003ffb3 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageFile.kt @@ -13,8 +13,6 @@ import java.io.File import java.io.IOException import java.lang.Exception -// 本身是不存储数据的 -// 存储了持久化的文件名和以及用什么方式存储 class StorageFile(val name: String, var options: StorageBackendOptions) : StorageBackend(name, options) { private var absFileName: String diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt index 1bd0cf8..aa7522e 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/backend/StorageS3.kt @@ -21,7 +21,6 @@ class StorageS3(val name: String, var options: StorageBackendOptions) : StorageB val basicAWSCredentials = BasicAWSCredentials(_options.accessKeyId, _options.secretAccessKey) this.s3 = AmazonS3ClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(basicAWSCredentials)) .withRegion(_options.region).build() - } override fun save(payload: MemoryCardPayload) { diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt index f5aae5b..acf78de 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/status/StateSwitch.kt @@ -12,9 +12,8 @@ import java.util.concurrent.atomic.AtomicInteger import javax.swing.plaf.nimbus.State var COUNTER = AtomicInteger() -val nop: () -> Unit = {} val resolver: () -> Unit = {} -class StateSwitch: EventEmitter(){ +class StateSwitch(var name :String = "#${COUNTER.addAndGet(1)}"): EventEmitter(){ @Volatile private var onoff:Boolean = false @@ -28,8 +27,8 @@ class StateSwitch: EventEmitter(){ private lateinit var onResolver : () -> Unit private lateinit var offResolver : () -> Unit - private var name :String = "#${COUNTER.addAndGet(1)}" - +// private var name :String = "#${COUNTER.addAndGet(1)}" + private val VERSION: String = "0.0.0" private lateinit var onQueue: ArrayBlockingQueue<() -> Unit> private lateinit var offQueue: ArrayBlockingQueue<() -> Unit> @@ -42,36 +41,21 @@ class StateSwitch: EventEmitter(){ offQueue = ArrayBlockingQueue(1) this.offQueue.put(resolver) -// runBlocking { -// onPromise = { -// onResolver = nop -// } -// onPromise() -// } } // 传入on的状态只能是on或者说pending - fun on(state: StateEnum): String { + fun on(state: StateEnum): StateEnum { log.debug("statusSwitch $name on ${state.name} <- ${this.on()}") if (state == StateEnum.OFF) { - throw Exception("the parameter state shouldn't be off") + throw Exception("the parameter state shouldn't be OFF") } onoff = true pending = (state == StateEnum.PENDING) emit(EventEnum.ON, state.name) -// if (this.offResolver === nop) { -// runBlocking { -// offPromise = { -// offResolver = nop -// } -// offPromise() -// } -// } - if (this.offQueue.isEmpty()) { this.offQueue.put(resolver) } @@ -83,37 +67,29 @@ class StateSwitch: EventEmitter(){ } // get the current on state - fun on(): String { + fun on(): StateEnum { val on = if (this.onoff == true) if (this.pending == true) - "pending" + StateEnum.PENDING else - "true" + StateEnum.ON else - "false" + StateEnum.OFF log.info("StateSwitch, <{}> on() is {}", this.name, on) return on } - fun off(state: StateEnum): String { + fun off(state: StateEnum): StateEnum { log.info("StateSwitch, <{}> off({}) <- ({})", this.name, state, this.off()) if (state == StateEnum.ON) { - throw Exception("the parameter state shouldn't be on") + throw Exception("the parameter state shouldn't be ON") } this.onoff = false this.pending = (state == StateEnum.PENDING) this.emit(StateEnum.OFF, state) -// if (this.onResolver === nop) { -// runBlocking { -// onPromise = { -// onResolver = nop -// } -// onPromise() -// } -// } if (this.onQueue.isEmpty()) { this.onQueue.put(resolver) } @@ -127,15 +103,15 @@ class StateSwitch: EventEmitter(){ * * @return 返回当前off的状态 */ - fun off(): String { + fun off(): StateEnum { val off = if (!this.onoff) if (this.pending) - "pending" + StateEnum.PENDING else - "true" + StateEnum.OFF else - "false" + StateEnum.ON log.info("StateSwitch, <{}> off() is {}", this.name, off) return off } @@ -157,10 +133,6 @@ class StateSwitch: EventEmitter(){ // 当前状态为on // 或者说当前状态为off, 但是允许变换状态 // his.onPromise -// coroutineScope { -// val job = launch { onPromise } -// job.join() -// } CoroutineScope(Dispatchers.Default).launch { onQueue.take() } @@ -173,11 +145,6 @@ class StateSwitch: EventEmitter(){ } // 当前状态为off,或者说当前状态为on, 但是允许变换状态 // 执行状态改变时执行的函数 -// this.offPromise -// coroutineScope { -// val job = launch { offPromise } -// job.join() -// } CoroutineScope(Dispatchers.Default).launch { offQueue.take() } @@ -207,6 +174,9 @@ class StateSwitch: EventEmitter(){ }) } + fun version(): String { + return this.VERSION + } companion object { private val log = LoggerFactory.getLogger(StateSwitch::class.java) } diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt index 73a6d44..49c138c 100644 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt @@ -166,5 +166,4 @@ class MemoryCardTest { println(it) } } - } diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java deleted file mode 100644 index 50cc966..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTes.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.wechaty.status; - -import io.github.wechaty.StateEnum; -import org.junit.Test; - -/** - * @ClassName : StateSwitchTest - * @Description : - * @Author : cybersa - * @Date: 2020-07-19 14:52 - */ -public class StateSwitchTes { - - @Test - public void test() { - StateSwitch stateSwitch = new StateSwitch(); - stateSwitch.addEventListener(StateEnum.ON, (a) -> { - System.out.println(a); - }); - } - -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt index 27ffcc3..2d3aea8 100644 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt +++ b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt @@ -2,6 +2,7 @@ package io.github.wechaty.status import io.github.wechaty.StateEnum import io.github.wechaty.eventEmitter.Listener +import io.github.wechaty.io.github.wechaty.status.StateSwitchListener import org.junit.Test import org.junit.Assert.*; class StateSwitchTest { @@ -9,49 +10,93 @@ class StateSwitchTest { @Test fun testOn() { val stateSwitch = StateSwitch() - assertEquals("default is not on", "false", stateSwitch.on()) + assertEquals("default is not on", StateEnum.OFF, stateSwitch.on()) stateSwitch.on(StateEnum.PENDING) - assertEquals("should be state pending", "pending", stateSwitch.on()) + assertEquals("should be state pending", StateEnum.PENDING, stateSwitch.on()) stateSwitch.on(StateEnum.ON) - assertEquals("should be state true", "true", stateSwitch.on()) - assertEquals("should not off", "false", stateSwitch.off()) + assertEquals("should be state true", StateEnum.ON, stateSwitch.on()) + assertEquals("should not off", StateEnum.ON, stateSwitch.off()) stateSwitch.off(StateEnum.OFF) - assertEquals("should not on after off()", "false", stateSwitch.on()) + assertEquals("should not on after off()", StateEnum.OFF, stateSwitch.off()) } @Test fun testOff() { val stateSwitch = StateSwitch() - stateSwitch.off(StateEnum.PENDING) - println(stateSwitch.off()) - stateSwitch.ready(StateEnum.OFF) - println(stateSwitch.on()) + assertEquals("default is OFF", StateEnum.OFF, stateSwitch.off()) + stateSwitch.off(StateEnum.PENDING) + assertEquals("should be state PENDING", StateEnum.PENDING, stateSwitch.off()) stateSwitch.off(StateEnum.OFF) - println(stateSwitch.on()) + assertEquals("should be state OFF", StateEnum.OFF, stateSwitch.off()) + assertEquals("should not ON", StateEnum.OFF, stateSwitch.on()) + + stateSwitch.on(StateEnum.ON) + assertEquals("should not OFF after on()", StateEnum.ON, stateSwitch.on()) + } + + @Test + fun testPending() { + val stateSwitch = StateSwitch() + assertEquals("default is not PENDING", StateEnum.OFF, stateSwitch.off()) + stateSwitch.on(StateEnum.PENDING) + assertEquals("should in PENDING state", StateEnum.PENDING, stateSwitch.on()) + + stateSwitch.on(StateEnum.ON) + assertEquals("should not in pending state", StateEnum.ON, stateSwitch.on()) + + stateSwitch.off(StateEnum.PENDING) + assertEquals("should in PENDING state", StateEnum.PENDING, stateSwitch.off()) } @Test - fun name() { + fun testName() { + var CLIENT_NAME = "StateSwitchTest" + val stateSwitch = StateSwitch(CLIENT_NAME) + assertEquals("should get the same client name as init", CLIENT_NAME, stateSwitch.name) + } + @Test + fun testVersion() { + val stateSwitch = StateSwitch() + println(stateSwitch.name) + assertNotNull("should get version", stateSwitch.version()) } + + @Test fun ready() { val stateSwitch = StateSwitch() + println("刚开始:" + stateSwitch.off()) stateSwitch.on(StateEnum.PENDING) println("调用on(pending):" + stateSwitch.on()) - println("调用on(pending):" + stateSwitch.off()) stateSwitch.ready(StateEnum.ON) println("调用ready(on)之后:" + stateSwitch.on()) stateSwitch.on(StateEnum.ON) println("调用on(on):" + stateSwitch.on()) + + stateSwitch.off(StateEnum.PENDING) + println("调用off(pending):" + stateSwitch.off()) + stateSwitch.off(StateEnum.OFF) + println("调用off(off):" + stateSwitch.off()) } @Test - fun add() { + fun addEventListener() { val stateSwitch = StateSwitch() + stateSwitch.addEventListener(StateEnum.ON, object : StateSwitchListener { + override fun handler(state: StateEnum) { + println(state.name) + } + }); + + stateSwitch.removeEventListener(StateEnum.OFF, object : StateSwitchListener { + override fun handler(state: StateEnum) { + println(state.name) + } + }) } } From 6ab498f725f0d03624cb20e99d29d26e9ea7a36f Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Fri, 24 Jul 2020 21:24:04 +0800 Subject: [PATCH 32/46] =?UTF-8?q?1.=20=E6=9A=82=E6=97=B6=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E4=BA=86memory=E5=92=8Cstateswitch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet/src/main/kotlin/Puppet.kt | 28 +++++++---- .../main/kotlin/io/github/wechaty/Wechaty.kt | 50 +++++++++++++++---- .../io/github/wechaty/WechatyListener.kt | 1 - .../io/github/wechaty/WechatyOptions.kt | 6 +-- .../user/manager/RoomInvitationManager.kt | 3 +- .../github/wechaty/user/manager/TagManager.kt | 2 +- wechaty/src/main/resources/log4j2.xml | 1 - 7 files changed, 64 insertions(+), 27 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/Puppet.kt b/wechaty-puppet/src/main/kotlin/Puppet.kt index e70d7be..3a945b0 100644 --- a/wechaty-puppet/src/main/kotlin/Puppet.kt +++ b/wechaty-puppet/src/main/kotlin/Puppet.kt @@ -14,6 +14,7 @@ import io.github.wechaty.io.github.wechaty.watchdag.WatchDog import io.github.wechaty.io.github.wechaty.watchdag.WatchdogFood import io.github.wechaty.io.github.wechaty.watchdag.WatchdogListener import io.github.wechaty.listener.* +import io.github.wechaty.memorycard.MemoryCard import io.github.wechaty.schemas.* import io.github.wechaty.utils.FutureUtils import io.github.wechaty.utils.JsonUtils @@ -42,7 +43,7 @@ abstract class Puppet : EventEmitter { private val HEARTBEAT_COUNTER = AtomicLong() private val HOSTIE_KEEPALIVE_TIMEOUT = 15 * 1000L private val DEFAULT_WATCHDOG_TIMEOUT = 60L -// private var memory: MemoryCard + private var memory: MemoryCard private val executorService = Executors.newSingleThreadScheduledExecutor() @@ -66,9 +67,15 @@ abstract class Puppet : EventEmitter { count.addAndGet(1) this.puppetOptions = puppetOptions -// this.memory = MemoryCard() -// this.memory.load() - + // for test + this.memory = MemoryCard() + try { + this.memory.load() + log.debug("Puppet, constructor() memory.load() done") + } + catch (e: Exception) { + log.warn("Puppet, constructor() memory.load() rejection: {}", e) + } val timeOut = puppetOptions.timeout ?: DEFAULT_WATCHDOG_TIMEOUT watchDog = WatchDog(1000 * timeOut, "puppet") @@ -911,13 +918,14 @@ abstract class Puppet : EventEmitter { } } -// fun setMemory(memoryCard: MemoryCard){ -// this.memory = memoryCard -// } + fun setMemory(memoryCard: MemoryCard) { + log.debug("Puppet, setMemory()") + this.memory = memoryCard + } -// fun getEventBus(): EventBus { -// return eb -// } + override fun toString(): String { + return "Puppet#${count}<${this.puppetOptions?.name}>(${this.memory.getName()})" + } companion object { private val log = LoggerFactory.getLogger(Puppet::class.java) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index ea75d4a..3305d76 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -6,15 +6,16 @@ import io.github.wechaty.eventEmitter.EventEmitter import io.github.wechaty.eventEmitter.Listener import io.github.wechaty.io.github.wechaty.schemas.EventEnum import io.github.wechaty.listener.* -//import io.github.wechaty.memorycard.MemoryCard +import io.github.wechaty.memorycard.MemoryCard import io.github.wechaty.schemas.* +import io.github.wechaty.status.StateSwitch import io.github.wechaty.user.* import io.github.wechaty.user.manager.* import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.locks.ReentrantLock - +val PUPPET_MEMORY_NAME = "puppet" class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : EventEmitter() { private val LOCK = ReentrantLock() @@ -26,12 +27,12 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : private val globalPluginList: MutableList = mutableListOf() @Volatile - private var readyState = StateEnum.OFF + private var readyState = StateSwitch("Wechaty") @Volatile - private var status = StateEnum.OFF + private var status = StateSwitch("WechatyReady") -// private var memory:MemoryCard? = null + private var memory: MemoryCard? = null val tagManager: TagManager = TagManager(this) val contactManager = ContactManager(this) @@ -41,16 +42,21 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : val imageManager = ImageManager(this) init { -// this.memory = wechatyOptions.memory + if (wechatyOptions.memory == null) { + this.memory = MemoryCard(wechatyOptions.name) + } + else { + this.memory = wechatyOptions.memory + } installGlobalPlugin() } fun start(await: Boolean = false):Wechaty { - initPuppet() puppet.start().get() - status = StateEnum.ON +// status = StateEnum.ON + status.on(StateEnum.ON) emit(EventEnum.START, "") if (await) { @@ -220,6 +226,11 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : private fun initPuppet() { // this.puppet = GrpcPuppet(puppetOptions) this.puppet = PuppetManager.resolveInstance(wechatyOptions).get() + if (this.memory == null) { + throw Exception("no memory") + } + val puppetMemory = this.memory!!.multiplex(PUPPET_MEMORY_NAME) + this.puppet.setMemory(puppetMemory) initPuppetEventBridge(puppet) } @@ -317,7 +328,8 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : puppet.on(it, object : PuppetReadyListener { override fun handler(payload: EventReadyPayload) { emit(EventEnum.READY); - readyState = StateEnum.ON +// readyState = StateEnum.ON + readyState.on(StateEnum.ON) } }) } @@ -438,6 +450,26 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : } }, "StartMain-shutdown-hook")) } + + override fun toString(): String { + if (this.wechatyOptions == null) { + return "default" + } + val first = if (this.wechatyOptions != null && this.puppet != null) { + this.wechatyOptions.puppet + } + else { + "puppet" + } + + val second = if (this.memory != null) { + this.memory!!.getName() + } + else { + "default" + } + return "Wechaty#<${first}><${second}>" + } } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt b/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt index 8da5e0b..35f71fc 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt @@ -77,6 +77,5 @@ interface ReadyListener { @FunctionalInterface interface MessageListener { fun handler(message: Message) - } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/WechatyOptions.kt b/wechaty/src/main/kotlin/io/github/wechaty/WechatyOptions.kt index d930bf7..5d337f1 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/WechatyOptions.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/WechatyOptions.kt @@ -1,11 +1,11 @@ package io.github.wechaty -//import io.github.wechaty.memorycard.MemoryCard +import io.github.wechaty.memorycard.MemoryCard import io.github.wechaty.schemas.PuppetOptions class WechatyOptions { -// var memory:MemoryCard? = null + var memory: MemoryCard? = null var name:String = "Wechaty" @@ -17,5 +17,5 @@ class WechatyOptions { var ioToken:String? = null } - typealias WechatyPlugin = (Wechaty) -> Unit +typealias WechatyPlugin = (Wechaty) -> Unit diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt index a2b514d..08a033e 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt @@ -9,11 +9,10 @@ import org.slf4j.LoggerFactory class RoomInvitationManager (wechaty: Wechaty):Accessory(wechaty){ - fun load(id:String):RoomInvitation{ + fun load(id:String): RoomInvitation { return RoomInvitation(wechaty,id) } - companion object { private val log = LoggerFactory.getLogger(Contact::class.java) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt index 02435da..8694b36 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt @@ -18,7 +18,7 @@ class TagManager(wechaty: Wechaty):Accessory(wechaty){ }!! } - fun get(id:String):Tag{ + fun get(id:String): Tag{ return load(id) } diff --git a/wechaty/src/main/resources/log4j2.xml b/wechaty/src/main/resources/log4j2.xml index 0e80944..b7f6060 100644 --- a/wechaty/src/main/resources/log4j2.xml +++ b/wechaty/src/main/resources/log4j2.xml @@ -11,7 +11,6 @@ - From 35efab6a57250faafe2327adc2f2182b1ed21f12 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Fri, 24 Jul 2020 22:26:57 +0800 Subject: [PATCH 33/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0=E8=8E=B7=E5=8F=96?= =?UTF-8?q?qrcode,name,signture=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/github/wechaty/user/ContactSelf.kt | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt index 8183c77..94f8f5e 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt @@ -2,6 +2,8 @@ package io.github.wechaty.user import io.github.wechaty.Wechaty import io.github.wechaty.filebox.FileBox +import io.github.wechaty.utils.QrcodeUtils.Companion.guardQrCodeValue +import org.slf4j.LoggerFactory import java.util.concurrent.CompletableFuture import java.util.concurrent.Future @@ -19,4 +21,62 @@ class ContactSelf(wechaty: Wechaty,id: String) : Contact(wechaty,id){ } + fun qrcode(): Future { + log.info("Contact, qrcode()") + + val puppetId: String = try { + this.puppet.selfId().toString() + } + catch (e: Exception) { + throw Exception("Can not get qrcode, user might be either not logged in or already logged out") + } + + if (this.id !== puppetId) { + throw Exception("only can get qrcode for the login userself") + } + + return CompletableFuture.supplyAsync { + val qrcodeValue = this.puppet.contactSelfQRCode().get() + guardQrCodeValue(qrcodeValue) + } + } + + fun name(name: String?): String? { + if (name == null) { + return super.name() + } + val puppetId = try { + this.puppet.selfId() + } + catch (e: Exception) { + throw Exception("Can not get qrcode, user might be either not logged in or already logged out") + } + if (this.id !== puppetId) { + throw Exception("only can get qrcode for the login userself") + } + this.puppet.contactSelfName(name) + return null + } + + fun signature (signature: String): Future { + log.debug("ContactSelf, signature()") + + val puppetId = try { + this.puppet.selfId() + } + catch (e: Exception) { + throw Exception("Can not get qrcode, user might be either not logged in or already logged out") + } + + if (this.id !== puppetId) { + throw Exception("only can get qrcode for the login userself") + } + + return this.puppet.contactSelfSignature(signature) + } + + companion object { + private val log = LoggerFactory.getLogger(ContactSelf::class.java) + } + } From 2eea542d118298e19431cc304a755049e8b7317b Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Fri, 24 Jul 2020 22:27:40 +0800 Subject: [PATCH 34/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0=E8=8E=B7=E5=8F=96?= =?UTF-8?q?owner=E5=92=8Cavatar=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/kotlin/io/github/wechaty/user/Room.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt index 2b5bd87..7bb663d 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt @@ -16,6 +16,7 @@ import io.github.wechaty.schemas.RoomMemberQueryFilter import io.github.wechaty.schemas.RoomPayload import io.github.wechaty.type.Sayable import io.github.wechaty.utils.QrcodeUtils +import io.grpc.netty.shaded.io.netty.util.concurrent.CompleteFuture import org.apache.commons.collections4.CollectionUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory @@ -340,8 +341,23 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { val roomMemberPayload = wechaty.getPuppet().roomMemberPayload(this.id, contact.id).get() return roomMemberPayload?.roomAlias + } + + fun owner(): Contact? { + log.debug("Room, owner()") + val ownerId = if (this.payload != null && this.payload!!.ownerId != null) { + this.payload?.ownerId + } + else { + return null + } + return ownerId?.let { wechaty.contactManager.load(it) } + } + fun avatar(): Future { + log.debug("Room, acatar()") + return this.puppet.roomAvatar(this.id) } fun has(contact: Contact): Boolean { From 9fe61a1e9e54f81e9240b0d787755675970deaa4 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Fri, 24 Jul 2020 22:28:10 +0800 Subject: [PATCH 35/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0hello,=20type?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kotlin/io/github/wechaty/user/Friendship.kt | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt index 104e5f5..cc1b93d 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt @@ -33,7 +33,13 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ return contact } + fun hello(): String { + if (this.payload == null) { + throw Exception("no payload") + } + return this.payload!!.hello ?: "" + } fun add(contact: Contact, hello:String){ log.debug("add contact: {} hello: {}",contact,hello) wechaty.getPuppet().friendshipAdd(contact.id!!,hello).get() @@ -78,7 +84,15 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ } - + fun type(): FriendshipType? { + val result = if (this.payload != null) { + this.payload!!.type + } + else { + FriendshipType.Unknown + } + return result + } companion object{ private val log = LoggerFactory.getLogger(Friendship::class.java) } From a9d0ad244eb055c20f1f075e6e9a84e31ddad550 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sat, 25 Jul 2020 23:53:15 +0800 Subject: [PATCH 36/46] =?UTF-8?q?1.=20Contact.kt=E6=B7=BB=E5=8A=A0type,pro?= =?UTF-8?q?vince=E7=AD=89=E4=B8=80=E7=B3=BB=E5=88=97=E6=96=B9=E6=B3=95=202?= =?UTF-8?q?.=20Message.kt=E6=B7=BB=E5=8A=A0date,forward=E7=AD=89=E6=96=B9?= =?UTF-8?q?=E6=B3=95=203.=20=E6=B7=BB=E5=8A=A0say=E6=96=B9=E6=B3=95=204.?= =?UTF-8?q?=20=E8=BF=98=E6=9C=AA=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/kotlin/io/github/wechaty/Wechaty.kt | 31 +++++++++++++++++++ .../kotlin/io/github/wechaty/user/Contact.kt | 25 +++++++++++++++ .../io/github/wechaty/user/ContactSelf.kt | 1 - .../kotlin/io/github/wechaty/user/Message.kt | 24 ++++++++++++++ .../io/github/wechaty/user/MiniProgram.kt | 2 +- .../wechaty/user/manager/ContactManager.kt | 3 -- 6 files changed, 81 insertions(+), 5 deletions(-) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index 3305d76..1e7312d 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -4,6 +4,7 @@ package io.github.wechaty; import io.github.wechaty.eventEmitter.Event import io.github.wechaty.eventEmitter.EventEmitter import io.github.wechaty.eventEmitter.Listener +import io.github.wechaty.filebox.FileBox import io.github.wechaty.io.github.wechaty.schemas.EventEnum import io.github.wechaty.listener.* import io.github.wechaty.memorycard.MemoryCard @@ -13,6 +14,8 @@ import io.github.wechaty.user.* import io.github.wechaty.user.manager.* import org.slf4j.LoggerFactory import java.util.* +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Future import java.util.concurrent.locks.ReentrantLock val PUPPET_MEMORY_NAME = "puppet" @@ -82,6 +85,34 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : return wechatyOptions.name } + fun say(something: Any): Future { + + val msgId: String? + this.puppet.selfId()?.let { + when (something) { + is String -> { + msgId = puppet.messageSendText(it, something).get() + } + is Contact -> { + msgId = puppet.messageSendContact(it, something.id).get() + } + is FileBox -> { + msgId = puppet.messageSendFile(it, something).get() + } + is UrlLink -> { + msgId = puppet.messageSendUrl(it, something.payload).get() + } + is MiniProgram -> { + msgId = puppet.messageSendMiniProgram(it, something.payload).get() + } + else -> { + throw Exception("unsupported arg:$something") + } + } + return@let + } + return CompletableFuture.completedFuture(null) + } fun onLogin(listener: LoginListener):Wechaty{ return on(EventEnum.LOGIN,listener) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index b7556f6..558145e 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -4,8 +4,10 @@ import io.github.wechaty.Accessory import io.github.wechaty.Puppet import io.github.wechaty.Wechaty import io.github.wechaty.filebox.FileBox +import io.github.wechaty.schemas.ContactGender import io.github.wechaty.schemas.ContactPayload import io.github.wechaty.schemas.ContactQueryFilter +import io.github.wechaty.schemas.ContactType import io.github.wechaty.type.Sayable import io.github.wechaty.utils.FutureUtils import org.apache.commons.lang3.StringUtils @@ -94,6 +96,29 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) fun name():String{ return payload?.name ?: "" } + fun type(): ContactType { + return payload?.type ?: ContactType.Unknown + } + fun gender(): ContactGender { + return payload?.gender ?: ContactGender.Unknown + } + + fun province(): String? { + return payload?.province + } + + fun city(): String? { + return payload?.city + } + + fun self(): Boolean { + val userId = this.puppet.selfId() + + if (userId == null) { + return false + } + return this.id === userId + } fun setAlias(newAlias:String){ if(payload == null){ diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt index 94f8f5e..8ae1c6f 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt @@ -18,7 +18,6 @@ class ContactSelf(wechaty: Wechaty,id: String) : Contact(wechaty,id){ puppet.setContactAvatar(super.id, fileBox) null } - } fun qrcode(): Future { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt index 7dd15c9..3e6c917 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt @@ -7,9 +7,11 @@ import io.github.wechaty.schemas.MessagePayload import io.github.wechaty.schemas.MessageType import io.github.wechaty.schemas.RoomMemberQueryFilter import io.github.wechaty.type.Sayable +import io.grpc.netty.shaded.io.netty.util.concurrent.CompleteFuture import org.apache.commons.collections4.CollectionUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory +import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import java.util.regex.Pattern @@ -124,6 +126,28 @@ open class Message(wechaty: Wechaty,val id: String) : Sayable, Accessory(wechaty return StringUtils.equals(selfId,from?.id) } + fun date(): Date { + val payload = wechaty.getPuppet().messagePayload(this.id).get() + return Date(payload.timestamp!! * 1000) + } + + fun forward(to: Any): Future { + log.debug("Message, forward({})", to) + when(to) { + is Room -> { + this.puppet.messageForward(to.id, this.id).get() + } + is Contact -> { + this.puppet.messageForward(to.id, this.id).get() + } + else -> { + throw Exception("unkown forward type") + } + } + return CompletableFuture.completedFuture(null) + } + + fun mentionList():List{ val room = this.room() diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt index afc5fc2..8243a20 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/MiniProgram.kt @@ -35,7 +35,7 @@ class MiniProgram(var payload: MiniProgramPayload) { companion object{ - fun create():MiniProgram{ + fun create(): MiniProgram { val payload = MiniProgramPayload() return MiniProgram(payload); } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt index b6ccb8c..a696124 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt @@ -30,9 +30,6 @@ class ContactManager(wechaty: Wechaty):Accessory(wechaty) { } - - - fun find(queryFilter: ContactQueryFilter):Contact?{ val findAll = findAll(queryFilter) From 1170012cd225e95d15d239427c7d372f2b5b466a Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 26 Jul 2020 16:28:59 +0800 Subject: [PATCH 37/46] =?UTF-8?q?1.=20Contact.kt=E6=B7=BB=E5=8A=A0friend?= =?UTF-8?q?=E6=96=B9=E6=B3=95=202.=20Message.kt=E6=B7=BB=E5=8A=A0age?= =?UTF-8?q?=E6=96=B9=E6=B3=95=203.=20MemoryCard.kt=E6=B7=BB=E5=8A=A0getNam?= =?UTF-8?q?e()fangfa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kotlin/io/github/wechaty/memorycard/MemoryCard.kt | 10 +++------- .../src/main/kotlin/io/github/wechaty/user/Contact.kt | 4 ++++ .../main/kotlin/io/github/wechaty/user/ContactSelf.kt | 2 +- .../main/kotlin/io/github/wechaty/user/Friendship.kt | 4 +--- .../src/main/kotlin/io/github/wechaty/user/Message.kt | 5 +++++ wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt | 2 -- .../kotlin/io/github/wechaty/user/RoomInvitation.kt | 2 -- 7 files changed, 14 insertions(+), 15 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt index 1d8f63f..f6753a3 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/memorycard/MemoryCard.kt @@ -1,14 +1,7 @@ package io.github.wechaty.memorycard import io.github.wechaty.utils.JsonUtils -import kotlinx.coroutines.* import org.slf4j.LoggerFactory -import java.lang.Exception -import java.util.concurrent.ArrayBlockingQueue -import java.util.concurrent.CompletableFuture -import java.util.concurrent.Future -import javax.xml.bind.JAXBElement -import kotlin.math.abs const val NAMESPACE_MULTIPLEX_SEPRATOR = "\r" const val NAMESPACE_KEY_SEPRATOR = "\n" @@ -348,6 +341,9 @@ class MemoryCard { return VERSION } + fun getName(): String? { + return this.name + } // 会将当前的类作为parent, 后面那个为namespace fun multiplex(nameSpace: String): MemoryCard { log.info("MemoryCard, multiplex({})", nameSpace) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index 558145e..0f9c990 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -93,6 +93,10 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) return (payload != null && StringUtils.isNotEmpty(payload!!.name)) } + fun friend(): Boolean? { + return payload?.friend + } + fun name():String{ return payload?.name ?: "" } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt index 8ae1c6f..4f89fc9 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt @@ -70,7 +70,7 @@ class ContactSelf(wechaty: Wechaty,id: String) : Contact(wechaty,id){ if (this.id !== puppetId) { throw Exception("only can get qrcode for the login userself") } - + // maybe return this.puppet.contactSelfSignature(signature) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt index cc1b93d..6c4c964 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt @@ -40,6 +40,7 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ return this.payload!!.hello ?: "" } + fun add(contact: Contact, hello:String){ log.debug("add contact: {} hello: {}",contact,hello) wechaty.getPuppet().friendshipAdd(contact.id!!,hello).get() @@ -77,11 +78,8 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ wechaty.getPuppet().friendshipAccept(this.id!!).get() val contact = contact() - contact.ready() - contact.sync() - } fun type(): FriendshipType? { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt index 3e6c917..4584126 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt @@ -131,6 +131,11 @@ open class Message(wechaty: Wechaty,val id: String) : Sayable, Accessory(wechaty return Date(payload.timestamp!! * 1000) } + fun age(): Long { + val ageMilliseconds = Date().time - this.date().time + val ageSeconds = Math.floor(ageMilliseconds / 1000.0).toLong() + return ageSeconds + } fun forward(to: Any): Future { log.debug("Message, forward({})", to) when(to) { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt index 7bb663d..d102465 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt @@ -58,9 +58,7 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { message.ready().get() return@supplyAsync message } - return@supplyAsync null - } } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt index 9859504..626a0be 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt @@ -71,6 +71,4 @@ class RoomInvitation(wechaty: Wechaty,val id:String) : Accessory(wechaty){ private val log = LoggerFactory.getLogger(RoomInvitation::class.java) } - - } From 225d4941272a1aceeb4b91868999b3a5ef714a5c Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Mon, 3 Aug 2020 14:14:55 +0800 Subject: [PATCH 38/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0plugin-contrib?= =?UTF-8?q?=E4=BE=9D=E8=B5=96(=E5=BF=98=E4=BA=86=E4=B8=BA=E4=BB=80?= =?UTF-8?q?=E4=B9=88=E6=B7=BB=E5=8A=A0=E4=BA=86)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/pom.xml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/examples/pom.xml b/examples/pom.xml index c80f478..d641ee9 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -32,6 +32,13 @@ wechaty-puppet-hostie ${wechaty.version} + + + io.github.wechaty + java-wechaty-plugin-contrib + 1.0.0-SNAPSHOT + + org.apache.logging.log4j log4j-api @@ -61,11 +68,7 @@ 1.7.30 - - io.github.wechaty - java-wechaty-plugin-contrib - 1.0.0-SNAPSHOT - + org.apache.commons commons-lang3 From c5b240c3427387614b19c94bef382ad064a06f35 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Mon, 3 Aug 2020 14:17:00 +0800 Subject: [PATCH 39/46] =?UTF-8?q?1.=20=E6=94=B9=E6=AD=A3=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E5=AE=9E=E4=BE=8B=E7=9A=84=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet-hostie/pom.xml | 1 - .../io/github/wechaty/grpc/GrpcPuppet.kt | 1 - wechaty-puppet/src/main/kotlin/Puppet.kt | 75 ++++++++++++------- .../wechaty/user/manager/ContactManager.kt | 2 +- .../wechaty/user/manager/MessageManager.kt | 2 +- .../user/manager/RoomInvitationManager.kt | 2 +- 6 files changed, 52 insertions(+), 31 deletions(-) diff --git a/wechaty-puppet-hostie/pom.xml b/wechaty-puppet-hostie/pom.xml index c691c40..6151f51 100644 --- a/wechaty-puppet-hostie/pom.xml +++ b/wechaty-puppet-hostie/pom.xml @@ -62,7 +62,6 @@ org.apache.commons commons-lang3 - diff --git a/wechaty-puppet-hostie/src/main/kotlin/io/github/wechaty/grpc/GrpcPuppet.kt b/wechaty-puppet-hostie/src/main/kotlin/io/github/wechaty/grpc/GrpcPuppet.kt index f7202d4..bdc4de1 100644 --- a/wechaty-puppet-hostie/src/main/kotlin/io/github/wechaty/grpc/GrpcPuppet.kt +++ b/wechaty-puppet-hostie/src/main/kotlin/io/github/wechaty/grpc/GrpcPuppet.kt @@ -389,7 +389,6 @@ class GrpcPuppet(puppetOptions: PuppetOptions) : Puppet(puppetOptions) { } override fun contactRawPayload(contractId: String): Future { - val request = Contact.ContactPayloadRequest.newBuilder() .setId(contractId) .build() diff --git a/wechaty-puppet/src/main/kotlin/Puppet.kt b/wechaty-puppet/src/main/kotlin/Puppet.kt index 3a945b0..5f68b8c 100644 --- a/wechaty-puppet/src/main/kotlin/Puppet.kt +++ b/wechaty-puppet/src/main/kotlin/Puppet.kt @@ -18,6 +18,7 @@ import io.github.wechaty.memorycard.MemoryCard import io.github.wechaty.schemas.* import io.github.wechaty.utils.FutureUtils import io.github.wechaty.utils.JsonUtils +import okhttp3.internal.toImmutableList import org.apache.commons.collections4.CollectionUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory @@ -447,13 +448,13 @@ abstract class Puppet : EventEmitter { if (StringUtils.isNotBlank(query.id)) { stream = stream?.filter { - StringUtils.equals(query.alias, it.alias) + StringUtils.equals(query.id, it.id) } } if (StringUtils.isNotBlank(query.weixin)) { stream = stream?.filter { - StringUtils.equals(query.alias, it.alias) + StringUtils.equals(query.weixin, it.weixin) } } @@ -825,37 +826,35 @@ abstract class Puppet : EventEmitter { abstract fun roomMemberList(roomId: String): Future> fun roomMemberSearch(roomId: String, query: RoomMemberQueryFilter): Future> { - TODO() - } - - fun roomReach(query: RoomQueryFilter?): Future> { - TODO() - } - - fun roomValidate(roomId: String): Future { - return CompletableFuture.completedFuture(true) - } + return CompletableFuture.supplyAsync { + val roomMemberIdList = roomMemberList(roomId).get() - fun roomPayloadCache(roomId: String): RoomPayload? { - return cacheRoomPayload.getIfPresent(roomId) - } + val contactQuery = if (query.name != null || query.contactAlias != null) { + val contactQueryFilter = ContactQueryFilter() + contactQueryFilter.name = query.name + contactQueryFilter + } + else { + val contactQueryFilter = ContactQueryFilter() + contactQueryFilter.alias = query.contactAlias + contactQueryFilter + } + var idList = ArrayList(contactSearch(contactQuery, roomMemberIdList).get()) + val memberPayloadList = roomMemberIdList.mapNotNull { x -> roomMemberPayload(roomId, x).get() } - fun roomPayload(roomId: String): Future { - return CompletableFuture.supplyAsync { - return@supplyAsync cacheRoomPayload.get(roomId) { t: String -> - val get = roomRawPayload(t).get() - return@get roomRawPayloadParser(get).get() + if (query.roomAlias != null) { + val result = memberPayloadList.filter { payload -> + payload.roomAlias === query.roomAlias + }.map { payload -> + payload.id + } + idList.addAll(result) } + return@supplyAsync idList; } } - fun roomPayloadDirty(roomId: String): Future { - cacheRoomPayload.invalidate(roomId) - return CompletableFuture.completedFuture(null) - } - - fun roomSearch(query: RoomQueryFilter): Future> { return CompletableFuture.supplyAsync { val allRoomList = roomList().get() @@ -885,6 +884,30 @@ abstract class Puppet : EventEmitter { } } + fun roomValidate(roomId: String): Future { + return CompletableFuture.completedFuture(true) + } + + fun roomPayloadCache(roomId: String): RoomPayload? { + return cacheRoomPayload.getIfPresent(roomId) + } + + + fun roomPayload(roomId: String): Future { + return CompletableFuture.supplyAsync { + return@supplyAsync cacheRoomPayload.get(roomId) { t: String -> + val get = roomRawPayload(t).get() + return@get roomRawPayloadParser(get).get() + } + } + } + + fun roomPayloadDirty(roomId: String): Future { + cacheRoomPayload.invalidate(roomId) + return CompletableFuture.completedFuture(null) + } + + /** * Concat roomId & contactId to one string */ diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt index a696124..33e2046 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/ContactManager.kt @@ -69,7 +69,7 @@ class ContactManager(wechaty: Wechaty):Accessory(wechaty) { } companion object { - private val log = LoggerFactory.getLogger(Contact::class.java) + private val log = LoggerFactory.getLogger(ContactManager::class.java) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/MessageManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/MessageManager.kt index e9dc3c9..f4208ee 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/MessageManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/MessageManager.kt @@ -56,7 +56,7 @@ class MessageManager (wechaty: Wechaty):Accessory(wechaty){ } companion object { - private val log = LoggerFactory.getLogger(Contact::class.java) + private val log = LoggerFactory.getLogger(MessageManager::class.java) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt index 08a033e..eabed38 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/RoomInvitationManager.kt @@ -14,7 +14,7 @@ class RoomInvitationManager (wechaty: Wechaty):Accessory(wechaty){ } companion object { - private val log = LoggerFactory.getLogger(Contact::class.java) + private val log = LoggerFactory.getLogger(RoomInvitationManager::class.java) } } From 9b4f815d435c24d858b43904a9d304f67e574cf1 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Mon, 3 Aug 2020 14:21:33 +0800 Subject: [PATCH 40/46] =?UTF-8?q?1.=20=E6=B7=BB=E5=8A=A0FriendShipmanger?= =?UTF-8?q?=202.=20Contact=E6=B7=BB=E5=8A=A0=E8=8E=B7=E5=8F=96=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E7=9A=84=E6=96=B9=E6=B3=95=203.=20Room=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0member=E6=96=B9=E6=B3=95=204.=20Wechaty=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0say=E5=92=8ConReady=E4=BA=8B=E4=BB=B6=205.=20WechatyLi?= =?UTF-8?q?stener=E4=BF=AE=E6=94=B9FriendShiplistener=E5=8F=82=E6=95=B0=20?= =?UTF-8?q?6.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/kotlin/io/github/wechaty/Wechaty.kt | 77 +++++++++++-------- .../io/github/wechaty/WechatyListener.kt | 9 +-- .../kotlin/io/github/wechaty/user/Contact.kt | 35 ++++++--- .../kotlin/io/github/wechaty/user/Favorite.kt | 6 +- .../io/github/wechaty/user/Friendship.kt | 4 +- .../kotlin/io/github/wechaty/user/Message.kt | 2 + .../kotlin/io/github/wechaty/user/Room.kt | 13 ++++ .../main/kotlin/io/github/wechaty/user/Tag.kt | 1 - .../wechaty/user/manager/FriendShipManager.kt | 49 ++++++++++++ .../github/wechaty/user/manager/TagManager.kt | 7 ++ 10 files changed, 150 insertions(+), 53 deletions(-) create mode 100644 wechaty/src/main/kotlin/io/github/wechaty/user/manager/FriendShipManager.kt diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index 1e7312d..f9d6f0d 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -43,7 +43,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : val roomManager = RoomManager(this) val roomInvitationManager = RoomInvitationManager(this) val imageManager = ImageManager(this) - + val friendShipManager = FriendShipManager(this) init { if (wechatyOptions.memory == null) { this.memory = MemoryCard(wechatyOptions.name) @@ -88,29 +88,30 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : fun say(something: Any): Future { val msgId: String? - this.puppet.selfId()?.let { - when (something) { - is String -> { - msgId = puppet.messageSendText(it, something).get() - } - is Contact -> { - msgId = puppet.messageSendContact(it, something.id).get() - } - is FileBox -> { - msgId = puppet.messageSendFile(it, something).get() - } - is UrlLink -> { - msgId = puppet.messageSendUrl(it, something.payload).get() - } - is MiniProgram -> { - msgId = puppet.messageSendMiniProgram(it, something.payload).get() - } - else -> { - throw Exception("unsupported arg:$something") - } - } - return@let - } + this.userSelf().say(something) +// this.puppet.selfId()?.let { +// when (something) { +// is String -> { +// msgId = puppet.messageSendText(it, something).get() +// } +// is Contact -> { +// msgId = puppet.messageSendContact(it, something.id).get() +// } +// is FileBox -> { +// msgId = puppet.messageSendFile(it, something).get() +// } +// is UrlLink -> { +// msgId = puppet.messageSendUrl(it, something.payload).get() +// } +// is MiniProgram -> { +// msgId = puppet.messageSendMiniProgram(it, something.payload).get() +// } +// else -> { +// throw Exception("unsupported arg:$something") +// } +// } +// return@let +// } return CompletableFuture.completedFuture(null) } fun onLogin(listener: LoginListener):Wechaty{ @@ -123,12 +124,16 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : fun onScan(listener: ScanListener):Wechaty{ return on(EventEnum.SCAN,listener); } + + fun onReady(listener: ReadyListener): Wechaty { + return on(EventEnum.READY, listener) + } fun onFriendship(listener: FriendshipListener): Wechaty { return on(EventEnum.FRIENDSHIP, listener) } fun onRoomJoin(listener: RoomJoinListener):Wechaty { - return on(EventEnum.ROOM_JOIN,listener) + return on(EventEnum.ROOM_JOIN, listener) } fun onRoomLeave(listener: RoomLeaveListener):Wechaty { @@ -170,6 +175,14 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : }) return this } + private fun on(event: Event,listener: ReadyListener):Wechaty{ + super.on(event, object : Listener { + override fun handler(vararg any: Any) { + listener.handler() + } + }) + return this + } private fun on(event: Event, listener: LogoutListener): Wechaty { super.on(event, object : Listener { @@ -212,7 +225,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : private fun on(event: Event, listener: FriendshipListener): Wechaty { super.on(event, object : Listener { override fun handler(vararg any: Any) { - listener.handler(any[0] as String) + listener.handler(any[0] as Friendship) } }) return this @@ -222,7 +235,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : super.on(eventName, object : Listener { override fun handler(vararg any: Any) { // roomInvitationId - listener.handler(any[0] as String) + listener.handler(any[0] as RoomInvitation) } }) return this @@ -315,10 +328,10 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : EventEnum.FRIENDSHIP -> { puppet.on(it, object : PuppetFriendshipListener { override fun handler(payload: EventFriendshipPayload) { - val friendship = friendship().load(payload.friendshipId) +// val friendship = friendship().load(payload.friendshipId) + val friendship = friendShipManager.load(payload.friendshipId) friendship.ready() -// emit(EventEnum.FRIENDSHIP, friendship) - emit(EventEnum.FRIENDSHIP, payload.friendshipId) + emit(EventEnum.FRIENDSHIP, friendship) } }) } @@ -401,7 +414,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : puppet.on(it, object : PuppetRoomLeaveListener { override fun handler(payload: EventRoomLeavePayload) { val room = roomManager.load(payload.roomId) - room.sync() + room.sync().get() val leaverList = payload.removeeIdList.map { id -> val contact = contactManager.loadSelf(id) @@ -423,7 +436,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : puppet.on(it, object : PuppetRoomTopicListener { override fun handler(payload: EventRoomTopicPayload) { val room = roomManager.load(payload.roomId) - room.sync() + room.sync().get() val changer = contactManager.loadSelf(payload.changerId) changer.ready() diff --git a/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt b/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt index 35f71fc..a76da29 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/WechatyListener.kt @@ -1,10 +1,7 @@ package io.github.wechaty import io.github.wechaty.schemas.ScanStatus -import io.github.wechaty.user.Contact -import io.github.wechaty.user.ContactSelf -import io.github.wechaty.user.Message -import io.github.wechaty.user.Room +import io.github.wechaty.user.* import java.util.* @FunctionalInterface @@ -19,7 +16,7 @@ interface ErrorListener { @FunctionalInterface interface FriendshipListener { - fun handler(friendshipId: String) + fun handler(friendship: Friendship) } @FunctionalInterface @@ -66,7 +63,7 @@ interface RoomTopicListener { @FunctionalInterface interface RoomInviteListener { - fun handler(roomInvitationId: String) + fun handler(roomInvitation : RoomInvitation) } @FunctionalInterface diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index 0f9c990..595e410 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -93,26 +93,43 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) return (payload != null && StringUtils.isNotEmpty(payload!!.name)) } - fun friend(): Boolean? { - return payload?.friend + fun friend(): Boolean { + return payload?.friend ?: false } - fun name():String{ + fun name():String { return payload?.name ?: "" } + fun type(): ContactType { return payload?.type ?: ContactType.Unknown } + fun gender(): ContactGender { return payload?.gender ?: ContactGender.Unknown } - fun province(): String? { - return payload?.province + fun address(): String { + return this.payload?.address ?: "" + } + fun province(): String { + return this.payload?.province ?: "" + } + + fun signature(): String { + return this.payload?.signature ?: "" + } + + fun city(): String { + return this.payload?.city ?: "" + } + + fun star(): Boolean { + return this.payload?.star ?: false } - fun city(): String? { - return payload?.city + fun weixin(): String { + return this.payload?.weixin ?: "" } fun self(): Boolean { @@ -139,8 +156,8 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) } - fun getAlias():String?{ - return payload?.alias ?:null + fun getAlias():String? { + return payload?.alias } open fun avatar(): Future { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Favorite.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Favorite.kt index 56f4897..de7d7a3 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Favorite.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Favorite.kt @@ -1,10 +1,10 @@ package io.github.wechaty.user import io.github.wechaty.Accessory +import io.github.wechaty.Puppet import io.github.wechaty.Wechaty +import io.github.wechaty.schemas.ContactPayload class Favorite(wechaty: Wechaty):Accessory(wechaty){ - - -} \ No newline at end of file +} diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt index 6c4c964..251358a 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt @@ -18,7 +18,7 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ private var payload:FriendshipPayload? = null - fun load(id:String):Friendship{ + fun load(id:String):Friendship { this.id = id return this } @@ -41,6 +41,7 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ return this.payload!!.hello ?: "" } + // 这个应该是静态方法吧 fun add(contact: Contact, hello:String){ log.debug("add contact: {} hello: {}",contact,hello) wechaty.getPuppet().friendshipAdd(contact.id!!,hello).get() @@ -56,7 +57,6 @@ class Friendship (wechaty: Wechaty):Accessory(wechaty){ } this.payload = wechaty.getPuppet().friendshipPayload(id!!).get() contact().ready() - } fun contact():Contact{ diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt index 4584126..ac9591d 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt @@ -132,10 +132,12 @@ open class Message(wechaty: Wechaty,val id: String) : Sayable, Accessory(wechaty } fun age(): Long { + // 这里会是负数,payload里面的时间提前了 val ageMilliseconds = Date().time - this.date().time val ageSeconds = Math.floor(ageMilliseconds / 1000.0).toLong() return ageSeconds } + fun forward(to: Any): Future { log.debug("Message, forward({})", to) when(to) { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt index d102465..2f81996 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt @@ -15,6 +15,8 @@ import io.github.wechaty.io.github.wechaty.schemas.EventEnum import io.github.wechaty.schemas.RoomMemberQueryFilter import io.github.wechaty.schemas.RoomPayload import io.github.wechaty.type.Sayable +import io.github.wechaty.user.manager.RoomManager +import io.github.wechaty.utils.JsonUtils import io.github.wechaty.utils.QrcodeUtils import io.grpc.netty.shaded.io.netty.util.concurrent.CompleteFuture import org.apache.commons.collections4.CollectionUtils @@ -303,7 +305,18 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { return@supplyAsync QrcodeUtils.guardQrCodeValue(qrCodeValue) } } + fun member(query: RoomMemberQueryFilter?): Contact? { + val memberList = memberAll(query) + if (memberList == null || memberList.size == 0) { + return null + } + if (memberList.size > 1) { + log.warn("Room, member({}) get {} contacts, use the first one by default", query?.let { JsonUtils.write(it) }, memberList.size) + } + + return memberList[0]; + } fun memberAll(query: RoomMemberQueryFilter?): List { if (query == null) { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Tag.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Tag.kt index bd8af36..29bda65 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Tag.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Tag.kt @@ -14,7 +14,6 @@ class Tag(wechaty:Wechaty,val id:String):Accessory(wechaty){ wechaty.getPuppet().tagContactRemove(this.id!!,from.id!!).get() } - companion object{ private val log = LoggerFactory.getLogger(Tag::class.java) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/FriendShipManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/FriendShipManager.kt new file mode 100644 index 0000000..4a01f8c --- /dev/null +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/FriendShipManager.kt @@ -0,0 +1,49 @@ +package io.github.wechaty.user.manager + +import com.github.benmanes.caffeine.cache.Cache +import com.github.benmanes.caffeine.cache.Caffeine +import io.github.wechaty.Accessory +import io.github.wechaty.Wechaty +import io.github.wechaty.schemas.* +import io.github.wechaty.user.Contact +import io.github.wechaty.user.ContactSelf +import io.github.wechaty.user.Friendship +import io.github.wechaty.user.Tag +import org.apache.commons.collections4.CollectionUtils +import org.apache.commons.lang3.StringUtils +import org.slf4j.LoggerFactory +import java.util.* + +class FriendShipManager(wechaty: Wechaty):Accessory(wechaty) { + + private val friendshipCache: Cache = Caffeine.newBuilder().build() + + fun load(id:String): Friendship { + return friendshipCache.get(id) { + Friendship(wechaty, id) + }!! + } + + // 查找发送请求的好友 + fun search(queryFilter: FriendshipSearchCondition): Contact? { + val friendshipId = wechaty.getPuppet().friendshipSearch(queryFilter).get(); + if(StringUtils.isEmpty(friendshipId)){ + return null + } + val contact = wechaty.contactManager.load(friendshipId!!) + contact.ready() + return contact + } + + // 添加好友 + fun add(contact: Contact, hello:String) { + log.debug("add contact: {} hello: {}", contact, hello) + wechaty.getPuppet().friendshipAdd(contact.id, hello).get() + } + + companion object { + private val log = LoggerFactory.getLogger(FriendShipManager::class.java) + } + + +} diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt index 8694b36..1ec3700 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/manager/TagManager.kt @@ -26,6 +26,13 @@ class TagManager(wechaty: Wechaty):Accessory(wechaty){ wechaty.getPuppet().tagContactDelete(tag.id) } + fun tags():List{ + val tagIdList = wechaty.getPuppet().tagContactList().get() + return tagIdList.map { + wechaty.tagManager.load(it) + } + } + companion object{ private val log = LoggerFactory.getLogger(TagManager::class.java) } From 67b62c2b7469807a87fb266e3af7e8f7b818bc56 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Mon, 3 Aug 2020 20:11:41 +0800 Subject: [PATCH 41/46] =?UTF-8?q?1.=20=E4=BF=AE=E5=A4=8D=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E6=88=BF=E9=97=B4=E8=81=94=E7=B3=BB=E4=BA=BA=E7=9A=84=E6=97=B6?= =?UTF-8?q?=E5=80=99=E8=81=94=E7=B3=BB=E4=BA=BA=E6=B2=A1=E6=9C=89payload?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet/src/main/kotlin/Puppet.kt | 2 + .../main/kotlin/io/github/wechaty/Wechaty.kt | 41 ++++++++----------- .../kotlin/io/github/wechaty/user/Room.kt | 5 +-- 3 files changed, 21 insertions(+), 27 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/Puppet.kt b/wechaty-puppet/src/main/kotlin/Puppet.kt index 5f68b8c..1aee001 100644 --- a/wechaty-puppet/src/main/kotlin/Puppet.kt +++ b/wechaty-puppet/src/main/kotlin/Puppet.kt @@ -841,6 +841,7 @@ abstract class Puppet : EventEmitter { } var idList = ArrayList(contactSearch(contactQuery, roomMemberIdList).get()) + val memberPayloadList = roomMemberIdList.mapNotNull { x -> roomMemberPayload(roomId, x).get() } if (query.roomAlias != null) { @@ -943,6 +944,7 @@ abstract class Puppet : EventEmitter { fun setMemory(memoryCard: MemoryCard) { log.debug("Puppet, setMemory()") + this.memory = memoryCard } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index f9d6f0d..f0cdaf1 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -56,6 +56,14 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : fun start(await: Boolean = false):Wechaty { + if (this.status.on() == StateEnum.ON) { + this.status.ready(StateEnum.ON) + return this + } + + this.readyState.off(StateEnum.OFF) + this.status.on(StateEnum.PENDING) + initPuppet() puppet.start().get() // status = StateEnum.ON @@ -78,7 +86,16 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : } fun stop() { +// if (this.status.off() == StateEnum.OFF) { +// this.status.ready(StateEnum.OFF) +// return +// } +// +// this.readyState.off(StateEnum.OFF) +// this.status.off(StateEnum.PENDING) puppet.stop() + +// this.status.off(StateEnum.OFF) } fun name(): String { @@ -86,32 +103,8 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : } fun say(something: Any): Future { - val msgId: String? this.userSelf().say(something) -// this.puppet.selfId()?.let { -// when (something) { -// is String -> { -// msgId = puppet.messageSendText(it, something).get() -// } -// is Contact -> { -// msgId = puppet.messageSendContact(it, something.id).get() -// } -// is FileBox -> { -// msgId = puppet.messageSendFile(it, something).get() -// } -// is UrlLink -> { -// msgId = puppet.messageSendUrl(it, something.payload).get() -// } -// is MiniProgram -> { -// msgId = puppet.messageSendMiniProgram(it, something.payload).get() -// } -// else -> { -// throw Exception("unsupported arg:$something") -// } -// } -// return@let -// } return CompletableFuture.completedFuture(null) } fun onLogin(listener: LoginListener):Wechaty{ diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt index 2f81996..b307010 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt @@ -325,11 +325,10 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { val contactIdList = wechaty.getPuppet().roomMemberSearch(this.id, query).get() val contactList = contactIdList.map { - wechaty.contactManager.load(id) + id -> wechaty.contactManager.load(id) } return contactList - } fun memberList(): List { @@ -341,7 +340,7 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { } val contactList = memberIdList.map { - wechaty.contactManager.load(id) + id -> wechaty.contactManager.load(id) } return contactList From 4629b610756abfbe8e50a1c1dd93d53cc5e9c539 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Mon, 3 Aug 2020 20:40:12 +0800 Subject: [PATCH 42/46] =?UTF-8?q?1.=20=E7=AE=80=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index 595e410..1b8251e 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -112,6 +112,7 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) fun address(): String { return this.payload?.address ?: "" } + fun province(): String { return this.payload?.province ?: "" } @@ -133,11 +134,8 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) } fun self(): Boolean { - val userId = this.puppet.selfId() + val userId = this.puppet.selfId() ?: return false - if (userId == null) { - return false - } return this.id === userId } From 6c129a6ab86f95c60f825967bd1275bf9a26b068 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Mon, 3 Aug 2020 22:51:38 +0800 Subject: [PATCH 43/46] =?UTF-8?q?1=20=E8=A7=A3=E5=86=B3=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/kotlin/io/github/wechaty/Wechaty.kt | 45 +++++++++---------- .../kotlin/io/github/wechaty/user/Contact.kt | 28 +----------- .../io/github/wechaty/user/ContactSelf.kt | 32 ++++++------- .../io/github/wechaty/user/Friendship.kt | 15 +------ .../kotlin/io/github/wechaty/user/Room.kt | 17 ------- 5 files changed, 38 insertions(+), 99 deletions(-) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt index cbbda6e..ba9daa0 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/Wechaty.kt @@ -44,7 +44,7 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : val roomInvitationManager = RoomInvitationManager(this) val imageManager = ImageManager(this) - val friendShipManager = FriendShipManager(this) + val friendShipManager = FriendshipManager(this) init { if (wechatyOptions.memory == null) { this.memory = MemoryCard(wechatyOptions.name) @@ -121,11 +121,6 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : return wechatyOptions.name } - fun say(something: Any): Future { - val msgId: String? - this.userSelf().say(something) - return CompletableFuture.completedFuture(null) - } fun onLogin(listener: LoginListener):Wechaty{ return on(EventEnum.LOGIN,listener) } @@ -512,25 +507,25 @@ class Wechaty private constructor(private var wechatyOptions: WechatyOptions) : }, "StartMain-shutdown-hook")) } - override fun toString(): String { - if (this.wechatyOptions == null) { - return "default" - } - val first = if (this.wechatyOptions != null && this.puppet != null) { - this.wechatyOptions.puppet - } - else { - "puppet" - } - - val second = if (this.memory != null) { - this.memory!!.getName() - } - else { - "default" - } - return "Wechaty#<${first}><${second}>" - } +// override fun toString(): String { +// if (this.wechatyOptions == null) { +// return "default" +// } +// val first = if (this.wechatyOptions != null && this.puppet != null) { +// this.wechatyOptions.puppet +// } +// else { +// "puppet" +// } +// +// val second = if (this.memory != null) { +// this.memory!!.getName() +// } +// else { +// "default" +// } +// return "Wechaty#<${first}><${second}>" +// } } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index 320087e..d795811 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -94,38 +94,18 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) return (payload != null && StringUtils.isNotEmpty(payload!!.name)) } - fun friend(): Boolean { - return payload?.friend ?: false - } - fun name():String { return payload?.name ?: "" } - fun type(): ContactType { - return payload?.type ?: ContactType.Unknown - } - - fun gender(): ContactGender { - return payload?.gender ?: ContactGender.Unknown - } - fun address(): String { return this.payload?.address ?: "" } - fun province(): String { - return this.payload?.province ?: "" - } - fun signature(): String { return this.payload?.signature ?: "" } - fun city(): String { - return this.payload?.city ?: "" - } - fun star(): Boolean { return this.payload?.star ?: false } @@ -134,12 +114,6 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) return this.payload?.weixin ?: "" } - fun self(): Boolean { - val userId = this.puppet.selfId() ?: return false - - return this.id === userId - } - fun setAlias(newAlias:String){ if(payload == null){ throw Exception("no payload") @@ -208,7 +182,7 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) } } - fun self():Boolean{ + fun self():Boolean { val userId = puppet.selfId() if(StringUtils.isEmpty(userId)){ return false diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt index 31182c8..99a5743 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt @@ -67,22 +67,22 @@ class ContactSelf(wechaty: Wechaty, id: String) : Contact(wechaty, id) { return null } - fun signature (signature: String): Future { - log.debug("ContactSelf, signature()") - - val puppetId = try { - this.puppet.selfId() - } - catch (e: Exception) { - throw Exception("Can not get qrcode, user might be either not logged in or already logged out") - } - - if (this.id !== puppetId) { - throw Exception("only can get qrcode for the login userself") - } - // maybe - return this.puppet.contactSelfSignature(signature) - } +// fun signature (signature: String): Future { +// log.debug("ContactSelf, signature()") +// +// val puppetId = try { +// this.puppet.selfId() +// } +// catch (e: Exception) { +// throw Exception("Can not get qrcode, user might be either not logged in or already logged out") +// } +// +// if (this.id !== puppetId) { +// throw Exception("only can get qrcode for the login userself") +// } +// // maybe +// return this.puppet.contactSelfSignature(signature) +// } companion object { private val log = LoggerFactory.getLogger(ContactSelf::class.java) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt index 27b3292..e8f4d1f 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt @@ -14,11 +14,6 @@ class Friendship (wechaty: Wechaty,val id:String):Accessory(wechaty){ private var payload:FriendshipPayload? = null - fun load(id:String):Friendship { - this.id = id - return this - } - fun search(queryFilter: FriendshipSearchCondition):Contact?{ val contactId = wechaty.getPuppet().friendshipSearch(queryFilter).get(); if(StringUtils.isEmpty(contactId)){ @@ -29,20 +24,12 @@ class Friendship (wechaty: Wechaty,val id:String):Accessory(wechaty){ return contact } - fun hello(): String { - if (this.payload == null) { - throw Exception("no payload") - } - - return this.payload!!.hello ?: "" - } - // 这个应该是静态方法吧 fun add(contact: Contact, hello:String){ log.debug("add contact: {} hello: {}",contact,hello) wechaty.getPuppet().friendshipAdd(contact.id!!,hello).get() } - + fun isReady():Boolean{ return payload != null } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt index b4e9d7b..4350c88 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt @@ -404,23 +404,6 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { return roomMemberPayload?.roomAlias } - - fun owner(): Contact? { - log.debug("Room, owner()") - val ownerId = if (this.payload != null && this.payload!!.ownerId != null) { - this.payload?.ownerId - } - else { - return null - } - return ownerId?.let { wechaty.contactManager.load(it) } - } - - fun avatar(): Future { - log.debug("Room, acatar()") - return this.puppet.roomAvatar(this.id) - } - fun has(contact: Contact): Boolean { val memberIdList = puppet.roomMemberList(id).get() if (memberIdList.isEmpty()) { From b8bf47a3a5b5e9d556f1abf87a87da6ba82e2d2b Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 6 Aug 2020 20:50:37 +0800 Subject: [PATCH 44/46] =?UTF-8?q?1=20=E5=88=A0=E9=99=A4=E6=9A=82=E6=97=B6?= =?UTF-8?q?=E6=B2=A1=E7=94=A8=E7=9A=84=E6=B5=8B=E8=AF=95=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/test/java/MemoryCardTest.java | 8 +- .../memorycard/MemoryCardMultiplexTest.kt | 59 ------ .../wechaty/memorycard/MemoryCardTest.kt | 169 ------------------ .../wechaty/memorycard/StorageOptionsTest.kt | 14 -- .../memorycard/backend/StorageFileTest.kt | 45 ----- .../memorycard/backend/StorageNopTest.kt | 30 ---- .../memorycard/backend/StorageOSSTest.kt | 56 ------ .../memorycard/backend/StorageObsTest.kt | 23 --- .../github/wechaty/status/StateSwitchTest.kt | 102 ----------- 9 files changed, 5 insertions(+), 501 deletions(-) delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt delete mode 100644 wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt diff --git a/wechaty-puppet/src/test/java/MemoryCardTest.java b/wechaty-puppet/src/test/java/MemoryCardTest.java index a02b615..7959595 100644 --- a/wechaty-puppet/src/test/java/MemoryCardTest.java +++ b/wechaty-puppet/src/test/java/MemoryCardTest.java @@ -11,8 +11,10 @@ public void testLoad() throws ExecutionException, InterruptedException { MemoryCard card = new MemoryCard("default", null); card.load(); Map map = (Map) card.get("person"); - map.forEach((key, value) -> { - System.out.println(key + ":" + value); - }); + if (map != null) { + map.forEach((key, value) -> { + System.out.println(key + ":" + value); + }); + } } } diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt deleted file mode 100644 index dc0a0fe..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardMultiplexTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.wechaty.io.github.wechaty.memorycard.test - -import io.github.wechaty.memorycard.* -import io.github.wechaty.memorycard.backend.Address -import io.github.wechaty.memorycard.backend.Person -import io.github.wechaty.utils.JsonUtils -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Test -import org.junit.Assert.* - - -class MemoryCardMultiplexTest { - - lateinit var memoryCard: MemoryCard - - @Before - fun setUp() { - memoryCard = MemoryCard("A") - - } - - @Test - fun testLoadAndSave() { - memoryCard.load() - val cardA = memoryCard.multiplex("cardA") - val cardB = memoryCard.multiplex("cardB") - memoryCard.set("a", "b") - cardA.set("a", "b") -// cardB.set("a", "b") - println(memoryCard.size()) - println(memoryCard.keys().size) - println(cardA.keys().size) - println(cardA.size()) - println(cardB.keys().size) - memoryCard.save() - } - - @Test - fun testLoadAd() { - memoryCard.load() - val cardA = memoryCard.multiplex("cardA") - val cardB = memoryCard.multiplex("cardB") - println(memoryCard.size()) - println(memoryCard.keys().size) - } - - @Test - fun testParttern() { - var a:String = "\rcardA\na" - val NAMESPACE_MULTIPLEX_SEPRATOR_REGEX = Regex("\r") - val NAMESPACE_KEY_SEPRATOR_REGEX = Regex("\n") - if (NAMESPACE_MULTIPLEX_SEPRATOR_REGEX.containsMatchIn(a)) { - println(1) - } - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt deleted file mode 100644 index 49c138c..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/MemoryCardTest.kt +++ /dev/null @@ -1,169 +0,0 @@ -package io.github.wechaty.io.github.wechaty.memorycard.test - -import io.github.wechaty.memorycard.* -import io.github.wechaty.memorycard.backend.Address -import io.github.wechaty.memorycard.backend.Person -import io.github.wechaty.utils.JsonUtils -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Test -import org.junit.Assert.* - - -class MemoryCardTest { - - lateinit var memoryCard: MemoryCard - - @Before - fun setUp() { - memoryCard = MemoryCard("test") - } - - @Test - fun testCreate() { - this.memoryCard.load() - this.memoryCard.values().forEach { - assertEquals("b", it) - } - } - - @Test - fun testLoadAsync() { - runBlocking { - var job = GlobalScope.launch { - memoryCard.loadAsync() - } - job.join() - } - - println(memoryCard.keys().size) - } - - @Test - fun testSet() { - this.memoryCard.load() - this.memoryCard.set("list", listOf(1, 2, 3)) - this.memoryCard.save() - } - - @Test - fun testDefultSave() { - var son = MemoryCard() - son.load() - son.set("a", "你好") - var map = mapOf("key" to "value") - son.set("this is map", map) - son.keys().forEach { - println(it) - } - son.save() - } - - @Test - fun testDelete() { - memoryCard.load() - memoryCard.delete("a") - memoryCard.save() - } - @Test - fun testDestory() { - var de = MemoryCard() - de.load() - de.destory() - } - - @Test - fun testMultiplex() { - memoryCard.load() - // 这里的name是前缀的名字 - // \rparent\nson - val multiplex = Multiplex(this.memoryCard, "parent") - val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) - println("options:" + memoryCardOptions) - // 用debug模式会有问题 - // 如果一个memory是multiple的,那么它自身就不会保存,只会保存一个父类的 - var son = MemoryCard(options = memoryCardOptions) - son.load() - - son.set("son", "b") - son.set("nihao", "asdasd") - println(son.get("son")) - son.delete("nihao") - println("has key{nihao}:" + son.has("nihao")) - println("has key{son}:" + son.has("son")) - println("has key{list}:" + son.has("list")) - son.save() - } - - @Test - fun newLoad() { - var card = MemoryCard() - card.load() - val get = card.get("person") as Map<*, *> - println(get["name"]) - - var address = Address("福州", "付件") - var person = Person("sda", 13, address) - var text = JsonUtils.write(person) - println(text) - var city = JsonUtils.readValue>(text)["address"] as Map<*, *> - println(city["province"]) - } - - @Test - fun testMap() { - var card = MemoryCard() - card.load() - println(card.keys().size) - for (value in card.values()) { - println(value) - } - card.keys().forEach { - println(it) - } - - card.entries().forEach { - println(it.key + ":" + it.value) - } - for (entry in card.get("person") as Map) { - println(entry.key + ":" + entry.value) - } - } - - @Test - fun testMultiplexSave() { - // 设置父memorycard - var parentCard = MemoryCard("aaaa") - parentCard.load() - parentCard.set("a", "b") - // \r后面的为parent - val multiplex = Multiplex(parentCard, "parent") - // 子card的名字为son - val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) - var sonCard = MemoryCard(options = memoryCardOptions) - sonCard.load() - sonCard.set("map", mapOf("a" to 1, "b" to 2)) - sonCard.set("list", listOf("1", "2", "3")) - sonCard.save() - } - - @Test - fun testMultiplexLoad() { - var parentCard = MemoryCard("parent") - parentCard.load() - - val multiplex = Multiplex(parentCard, "parent") - val memoryCardOptions = MemoryCardOptions("son", multiplex = multiplex) - - var sonCard = MemoryCard(options = memoryCardOptions) - sonCard.load() - sonCard.keys().forEach { - println(it) - } - sonCard.values().forEach { - println(it) - } - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt deleted file mode 100644 index d18122f..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/StorageOptionsTest.kt +++ /dev/null @@ -1,14 +0,0 @@ -package io.github.wechaty.memorycard - -import org.junit.Test - - -class StorageOptionsTest { - - @Test - fun testBackendDict() { - BACKEND_DICT.forEach { t, u -> - println("key:" + t + " value:" + u) - } - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt deleted file mode 100644 index 32badc6..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageFileTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.wechaty.io.github.wechaty.memorycard.test - -import io.github.wechaty.memorycard.MemoryCardPayload -import io.github.wechaty.memorycard.StorageFileOptions -import io.github.wechaty.memorycard.backend.StorageFile -import org.junit.Before -import org.junit.Test - - -class StorageFileTset { - - lateinit var storageFile: StorageFile - - @Before - fun setUp() { - this.storageFile = StorageFile("test", StorageFileOptions()) - } - @Test - fun testCreate() { - println(this.storageFile.name) - } - - @Test - fun testLoad() { - val load = this.storageFile.load() - for (mutableEntry in load.map) { - println("key:" + mutableEntry.key + " value:" + mutableEntry.value) - } - } - - @Test - fun testSave() { - val memoryCardPayload = MemoryCardPayload() - - memoryCardPayload.map.put("a", 123) - memoryCardPayload.map.put("b", "年后") - memoryCardPayload.map.put("c", "今年过节不收礼") - storageFile.save(memoryCardPayload) - } - @Test - fun testDestory() { - storageFile.destory() - - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt deleted file mode 100644 index f53e076..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageNopTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.wechaty.memorycard.backend - -import io.github.wechaty.memorycard.StorageNopOptions -import io.github.wechaty.memorycard.StorageObsOptions -import org.junit.Test - - -class StorageNopTest { - @Test - fun testLoad() { - val storageNop = StorageNop("objectname", StorageNopOptions()) - val load = storageNop.load() - println(load.map) - println(storageNop) - } - - @Test - fun testSave() { - val storageNop = StorageNop("myname", StorageNopOptions()) - val load = storageNop.load() - storageNop.save(load) - } - - @Test - fun testDestory() { - val storageNop = StorageNop("myname", StorageNopOptions()) - val load = storageNop.load() - storageNop.destory() - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt deleted file mode 100644 index 6543560..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageOSSTest.kt +++ /dev/null @@ -1,56 +0,0 @@ -package io.github.wechaty.memorycard.backend - -import io.github.wechaty.memorycard.StorageOSSOptions -import io.github.wechaty.utils.JsonUtils -import org.junit.Test -import org.junit.Assert.*; -class Person(var name: String, var age: Int, var address: Address) -class Address(var city: String, var province: String) -class StorageOSSTest { - val storageOSSOptions = StorageOSSOptions("xxx", "xxx", - "oss-cn-beijing.aliyuncs.com", "xxx") - - // 如果对应的name存在 - @Test - fun testLoadExist() { - val storageOSS = StorageOSS("objectname", storageOSSOptions) - val load = storageOSS.load() - println(load.map) - } - - - // 如果对应的name不存在 - @Test - fun testLoadNotExist() { - val storageOSS = StorageOSS("objectname", storageOSSOptions) - val load = storageOSS.load() - assertEquals(0, load.map.size) - } - - @Test - fun testSave() { - val storageOSS = StorageOSS("objectname", storageOSSOptions) - val load = storageOSS.load() - load.map.put("key", "value") - load.map.put("list", listOf(1, 2, 3)) - load.map.put("a", mapOf("a" to 1, "b" to 2)) - storageOSS.save(load) - } - - @Test - fun testDestory() { - // 如果有后缀要带上完整的后缀 - val storageOSS = StorageOSS("objectname", storageOSSOptions) - storageOSS.destory() - } - @Test - fun testJson() { - var map = mutableMapOf() - var list = listOf(1, 2, 3) - map.put("list", list) - val write = JsonUtils.write(map) - println(write) - var readValue: Map = JsonUtils.readValue(write) - println(readValue.get("list") is List<*>) - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt deleted file mode 100644 index 4aaa898..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/memorycard/backend/StorageObsTest.kt +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.wechaty.memorycard.backend - -import io.github.wechaty.memorycard.StorageObsOptions -import org.junit.Test - - -class StorageObsTest { - val storageObsOptions = StorageObsOptions("xxx", "xxx", - "obs.cn-north-4.myhuaweicloud.com", "xxx") - @Test - fun testLoad() { - val storageObs = StorageObs("objectname", storageObsOptions) - val load = storageObs.load() - println(load.map) - } - - @Test - fun testLoadNotExist() { - // 如果name不存在会返回一个空的payload - val storageObs = StorageObs("myname", storageObsOptions) - val load = storageObs.load() - } -} diff --git a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt b/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt deleted file mode 100644 index 2d3aea8..0000000 --- a/wechaty-puppet/src/test/kotlin/io/github/wechaty/status/StateSwitchTest.kt +++ /dev/null @@ -1,102 +0,0 @@ -package io.github.wechaty.status - -import io.github.wechaty.StateEnum -import io.github.wechaty.eventEmitter.Listener -import io.github.wechaty.io.github.wechaty.status.StateSwitchListener -import org.junit.Test -import org.junit.Assert.*; -class StateSwitchTest { - - @Test - fun testOn() { - val stateSwitch = StateSwitch() - assertEquals("default is not on", StateEnum.OFF, stateSwitch.on()) - - stateSwitch.on(StateEnum.PENDING) - assertEquals("should be state pending", StateEnum.PENDING, stateSwitch.on()) - stateSwitch.on(StateEnum.ON) - assertEquals("should be state true", StateEnum.ON, stateSwitch.on()) - assertEquals("should not off", StateEnum.ON, stateSwitch.off()) - stateSwitch.off(StateEnum.OFF) - assertEquals("should not on after off()", StateEnum.OFF, stateSwitch.off()) - - } - - @Test - fun testOff() { - val stateSwitch = StateSwitch() - - assertEquals("default is OFF", StateEnum.OFF, stateSwitch.off()) - stateSwitch.off(StateEnum.PENDING) - assertEquals("should be state PENDING", StateEnum.PENDING, stateSwitch.off()) - - stateSwitch.off(StateEnum.OFF) - assertEquals("should be state OFF", StateEnum.OFF, stateSwitch.off()) - assertEquals("should not ON", StateEnum.OFF, stateSwitch.on()) - - stateSwitch.on(StateEnum.ON) - assertEquals("should not OFF after on()", StateEnum.ON, stateSwitch.on()) - } - - @Test - fun testPending() { - val stateSwitch = StateSwitch() - assertEquals("default is not PENDING", StateEnum.OFF, stateSwitch.off()) - stateSwitch.on(StateEnum.PENDING) - assertEquals("should in PENDING state", StateEnum.PENDING, stateSwitch.on()) - - stateSwitch.on(StateEnum.ON) - assertEquals("should not in pending state", StateEnum.ON, stateSwitch.on()) - - stateSwitch.off(StateEnum.PENDING) - assertEquals("should in PENDING state", StateEnum.PENDING, stateSwitch.off()) - } - - @Test - fun testName() { - var CLIENT_NAME = "StateSwitchTest" - val stateSwitch = StateSwitch(CLIENT_NAME) - assertEquals("should get the same client name as init", CLIENT_NAME, stateSwitch.name) - } - - @Test - fun testVersion() { - val stateSwitch = StateSwitch() - println(stateSwitch.name) - assertNotNull("should get version", stateSwitch.version()) - } - - - @Test - fun ready() { - val stateSwitch = StateSwitch() - println("刚开始:" + stateSwitch.off()) - stateSwitch.on(StateEnum.PENDING) - println("调用on(pending):" + stateSwitch.on()) - stateSwitch.ready(StateEnum.ON) - println("调用ready(on)之后:" + stateSwitch.on()) - stateSwitch.on(StateEnum.ON) - println("调用on(on):" + stateSwitch.on()) - - stateSwitch.off(StateEnum.PENDING) - println("调用off(pending):" + stateSwitch.off()) - stateSwitch.off(StateEnum.OFF) - println("调用off(off):" + stateSwitch.off()) - } - - @Test - fun addEventListener() { - val stateSwitch = StateSwitch() - stateSwitch.addEventListener(StateEnum.ON, object : StateSwitchListener { - override fun handler(state: StateEnum) { - println(state.name) - } - }); - - stateSwitch.removeEventListener(StateEnum.OFF, object : StateSwitchListener { - override fun handler(state: StateEnum) { - println(state.name) - } - }) - } -} From c594ad8d41fd3430c61366adc96bba868c561ec0 Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Thu, 6 Aug 2020 21:00:39 +0800 Subject: [PATCH 45/46] delete demo file --- wechaty-puppet/aaaa.memory-card.json | 1 + wechaty-puppet/parent.memory-card.json | 1 + wechaty-puppet/test.memory-card.json | 1 + .../java/io/github/wechaty/ContatcDemo.java | 40 --------------- .../java/io/github/wechaty/FindRoomDemo.java | 32 ------------ .../java/io/github/wechaty/MetionDemo.java | 30 ------------ .../io/github/wechaty/MiniProgramDemo.java | 26 ---------- .../main/java/io/github/wechaty/RoomDemo.java | 35 ------------- .../java/io/github/wechaty/SimpleExample.java | 49 ------------------- .../main/java/io/github/wechaty/Token.java | 5 -- 10 files changed, 3 insertions(+), 217 deletions(-) create mode 100644 wechaty-puppet/aaaa.memory-card.json create mode 100644 wechaty-puppet/parent.memory-card.json create mode 100644 wechaty-puppet/test.memory-card.json delete mode 100644 wechaty/src/main/java/io/github/wechaty/ContatcDemo.java delete mode 100644 wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java delete mode 100644 wechaty/src/main/java/io/github/wechaty/MetionDemo.java delete mode 100644 wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java delete mode 100644 wechaty/src/main/java/io/github/wechaty/RoomDemo.java delete mode 100644 wechaty/src/main/java/io/github/wechaty/SimpleExample.java delete mode 100644 wechaty/src/main/java/io/github/wechaty/Token.java diff --git a/wechaty-puppet/aaaa.memory-card.json b/wechaty-puppet/aaaa.memory-card.json new file mode 100644 index 0000000..d0d386b --- /dev/null +++ b/wechaty-puppet/aaaa.memory-card.json @@ -0,0 +1 @@ +{"a":"b","\rparent\nmap":{"a":1,"b":2},"\rparent\nlist":["1","2","3"]} \ No newline at end of file diff --git a/wechaty-puppet/parent.memory-card.json b/wechaty-puppet/parent.memory-card.json new file mode 100644 index 0000000..d0d386b --- /dev/null +++ b/wechaty-puppet/parent.memory-card.json @@ -0,0 +1 @@ +{"a":"b","\rparent\nmap":{"a":1,"b":2},"\rparent\nlist":["1","2","3"]} \ No newline at end of file diff --git a/wechaty-puppet/test.memory-card.json b/wechaty-puppet/test.memory-card.json new file mode 100644 index 0000000..9d908d9 --- /dev/null +++ b/wechaty-puppet/test.memory-card.json @@ -0,0 +1 @@ +{"\rparent\nson":"b","list":[1,2,3]} \ No newline at end of file diff --git a/wechaty/src/main/java/io/github/wechaty/ContatcDemo.java b/wechaty/src/main/java/io/github/wechaty/ContatcDemo.java deleted file mode 100644 index af11d65..0000000 --- a/wechaty/src/main/java/io/github/wechaty/ContatcDemo.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.wechaty; - -import io.github.wechaty.schemas.ContactQueryFilter; -import io.github.wechaty.user.Contact; -import io.github.wechaty.user.Room; -import io.github.wechaty.user.manager.ContactManager; -import io.github.wechaty.user.manager.MessageManager; -import io.github.wechaty.utils.QrcodeUtils; - -import java.util.List; - -public class ContatcDemo { - public static void main(String[] args) { - Wechaty bot = Wechaty.instance(Token.token) - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println("User logined :" + user.name())) - .onMessage(message -> { - String text = message.text(); - Contact from = message.from(); - Contact to = message.to(); - Room room = message.room(); - System.out.println("收到来自" + from.name() + "的消息:" + text); - - if (text.contains("find")) { - from.say("请输入联系人名字:"); - } - else { - ContactQueryFilter queryFilter = new ContactQueryFilter(); - queryFilter.setName("犀利豆"); - ContactManager contactManager = new ContactManager(to.getWechaty()); - Contact contact = contactManager.find(queryFilter); - // 如果查询参数为空,那么就查询全部 - contactManager.findAll(new ContactQueryFilter()); - assert contact != null; - System.out.println(contact.name()); - } - }) - .start(true); - } -} diff --git a/wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java b/wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java deleted file mode 100644 index c61957b..0000000 --- a/wechaty/src/main/java/io/github/wechaty/FindRoomDemo.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.wechaty; - -import com.sun.xml.internal.ws.encoding.policy.MtomPolicyMapConfigurator; -import io.github.wechaty.schemas.ContactQueryFilter; -import io.github.wechaty.schemas.RoomQueryFilter; -import io.github.wechaty.user.Contact; -import io.github.wechaty.user.Room; -import io.github.wechaty.user.manager.ContactManager; -import io.github.wechaty.user.manager.RoomManager; -import io.github.wechaty.utils.QrcodeUtils; - -import java.util.List; - -public class FindRoomDemo { - public static void main(String[] args) { - Wechaty bot = Wechaty.instance(Token.token) - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println("User logined :" + user.name())) - .onMessage(message -> { - String text = message.text(); - Contact from = message.from(); - Contact to = message.to(); - Room room = message.room(); - System.out.println("接收到了消息" + text); - }) - .onLogout((contactId, reason) -> { - System.out.println("用户id为:" + contactId); - System.out.println("理由为:" + reason); - }) - .start(true); - } -} diff --git a/wechaty/src/main/java/io/github/wechaty/MetionDemo.java b/wechaty/src/main/java/io/github/wechaty/MetionDemo.java deleted file mode 100644 index f7cd1c6..0000000 --- a/wechaty/src/main/java/io/github/wechaty/MetionDemo.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.wechaty; - -import io.github.wechaty.filebox.FileBox; -import io.github.wechaty.user.Contact; -import io.github.wechaty.user.Room; -import io.github.wechaty.user.UrlLink; -import io.github.wechaty.utils.QrcodeUtils; - -import java.util.List; - -public class MetionDemo { - public static void main(String[] args) { - Wechaty bot = Wechaty.instance(Token.token) - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println("User logined :" + user.name())) - .onMessage(message -> { - String text = message.text(); - Contact from = message.from(); - Room room = message.room(); - System.out.println(message.text()); - System.out.println("收到来自" + from.name() + "的消息:" + text); - - List contacts = message.mentionList(); - for (Contact contact : contacts) { - System.out.println(contact.name()); - } - }) - .start(true); - } -} diff --git a/wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java b/wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java deleted file mode 100644 index 78b3219..0000000 --- a/wechaty/src/main/java/io/github/wechaty/MiniProgramDemo.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.wechaty; - -import io.github.wechaty.schemas.ContactQueryFilter; -import io.github.wechaty.user.Contact; -import io.github.wechaty.user.MiniProgram; -import io.github.wechaty.user.Room; -import io.github.wechaty.user.manager.ContactManager; -import io.github.wechaty.utils.QrcodeUtils; - -public class MiniProgramDemo { - public static void main(String[] args) { - Wechaty bot = Wechaty.instance(Token.token) - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println("User logined :" + user.name())) - .onMessage(message -> { - String text = message.text(); - Contact from = message.from(); - Contact to = message.to(); - Room room = message.room(); - System.out.println("收到来自" + from.name() + "的消息:" + text); - - from.say(MiniProgram.Companion.create()); - }) - .start(true); - } -} diff --git a/wechaty/src/main/java/io/github/wechaty/RoomDemo.java b/wechaty/src/main/java/io/github/wechaty/RoomDemo.java deleted file mode 100644 index 4315e4f..0000000 --- a/wechaty/src/main/java/io/github/wechaty/RoomDemo.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.wechaty; - -import io.github.wechaty.schemas.ContactQueryFilter; -import io.github.wechaty.user.Contact; -import io.github.wechaty.user.Room; -import io.github.wechaty.user.manager.ContactManager; -import io.github.wechaty.user.manager.RoomManager; -import io.github.wechaty.utils.QrcodeUtils; - -public class RoomDemo { - public static void main(String[] args) { - Wechaty bot = Wechaty.instance(Token.token) - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println("User logined :" + user.name())) - .onMessage(message -> { - String text = message.text(); - Contact from = message.from(); - Contact to = message.to(); - Room room = message.room(); - System.out.println("收到来自" + from.name() + "的消息:" + text); - - ContactQueryFilter queryFilter = new ContactQueryFilter(); - queryFilter.setName("Friday BOT"); - ContactManager contactManager = new ContactManager(to.getWechaty()); - Contact contact = contactManager.find(queryFilter); - - if (contact != null) { - room.add(contact); - System.out.println(contact.name()); - room.say("已邀请" + contact.name() + "加入群聊"); - } - }) - .start(true); - } -} diff --git a/wechaty/src/main/java/io/github/wechaty/SimpleExample.java b/wechaty/src/main/java/io/github/wechaty/SimpleExample.java deleted file mode 100644 index 5b5c9f9..0000000 --- a/wechaty/src/main/java/io/github/wechaty/SimpleExample.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.github.wechaty; - -import io.github.wechaty.filebox.FileBox; -import io.github.wechaty.user.Contact; -import io.github.wechaty.user.Room; -import io.github.wechaty.user.UrlLink; -import io.github.wechaty.user.UrlLinkKt; -import io.github.wechaty.utils.QrcodeUtils; - -import java.util.List; - -public class SimpleExample { - public static void main(String[] args) { - - Wechaty bot = Wechaty.instance(Token.token) - .onScan((qrcode, statusScanStatus, data) -> System.out.println(QrcodeUtils.getQr(qrcode))) - .onLogin(user -> System.out.println("User logined :" + user.name())) - .onMessage(message -> { - Contact to = message.to(); - String text = message.text(); - Contact from = message.from(); - Room room = message.room(); - UrlLink urlLink = UrlLink.Companion.create("https://wechaty.js.org/v/zh/api"); - System.out.println(message.text()); - System.out.println("收到来自" + from.name() + "的消息:" + text); - if (text.contains("ding")) { - if (room != null) { - room.say("nihao" + from.name()); - } else { - System.out.println("现在是单对单聊天"); - // 向from说话 - from.say("nihaosdasd"); - from.say(urlLink); - from.say(FileBox.fromUrl("https://upload-images.jianshu.io/upload_images/13859386-effeaff79bda02fd.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240/format/webp", "images.jpg", null)); - to.say("woyehao"); - } - } - - else { - System.out.println("不包含ding"); - } - }) - .onLogout((contactId, reason) -> { - System.out.println("用户id为:" + contactId); - System.out.println("理由为" + contactId); - }) - .start(true); - } -} diff --git a/wechaty/src/main/java/io/github/wechaty/Token.java b/wechaty/src/main/java/io/github/wechaty/Token.java deleted file mode 100644 index de9d121..0000000 --- a/wechaty/src/main/java/io/github/wechaty/Token.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.github.wechaty; - -public class Token { - static final String token = "puppet_padplus_0d01102884cd1233"; -} From fac8b236bc0035da700181369b26e373a00a587e Mon Sep 17 00:00:00 2001 From: cunkoulaocai <1184016190@qq.com> Date: Sun, 9 Aug 2020 21:11:04 +0800 Subject: [PATCH 46/46] =?UTF-8?q?1.=20=E8=8E=B7=E5=8F=96=E5=B1=9E=E6=80=A7?= =?UTF-8?q?=E7=9A=84=E6=96=B9=E6=B3=95=E5=8F=98=E4=B8=BAgetXXX=202.=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0messageQueryFilterFactory=E6=96=B9=E6=B3=95?= =?UTF-8?q?=EF=BC=8C=E6=96=B0=E5=A2=9E=E7=9B=B8=E5=85=B3=E7=9A=84typealias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wechaty-puppet/src/main/kotlin/Puppet.kt | 42 +++++++++++- .../io/github/wechaty/schemas/Message.kt | 5 +- .../kotlin/io/github/wechaty/user/Contact.kt | 54 ++++++++++++++- .../io/github/wechaty/user/ContactSelf.kt | 68 ++++++++++++++----- .../io/github/wechaty/user/Friendship.kt | 6 +- .../kotlin/io/github/wechaty/user/Message.kt | 16 ++++- .../kotlin/io/github/wechaty/user/Room.kt | 24 ++++++- .../io/github/wechaty/user/RoomInvitation.kt | 18 +++++ 8 files changed, 205 insertions(+), 28 deletions(-) diff --git a/wechaty-puppet/src/main/kotlin/Puppet.kt b/wechaty-puppet/src/main/kotlin/Puppet.kt index 1aee001..fe12f5a 100644 --- a/wechaty-puppet/src/main/kotlin/Puppet.kt +++ b/wechaty-puppet/src/main/kotlin/Puppet.kt @@ -707,8 +707,46 @@ abstract class Puppet : EventEmitter { } - protected fun messageQueryFilterFactory(query: MessageQueryFilter) { - TODO() + protected fun messageQueryFilterFactory(query: MessageQueryFilter): MessagePayloadFilterFunction { + val clz = query::class.java + val fields = clz.fields + val list = fields.map { + it.name to it.get(query) + } + + var filterFunctionList = ArrayList() + + list.forEach { pair -> + if (StringUtils.isNotEmpty(pair.second.toString())) { + val filterFunction = if (StringUtils.equals(pair.first.toString(), "textReg")) { + { + payload: MessagePayload -> Boolean + val clazz = payload::class.java + val field = clazz.getField(pair.first) + val realValue = field.get(payload).toString() + Regex(pair.second.toString()).matches(realValue) + } + } + else { + { + payload: MessagePayload -> Boolean + val clazz = payload::class.java + val field = clazz.getField(pair.first) + val realValue = field.get(payload).toString() + StringUtils.equals(realValue, pair.second.toString()) + } + } + filterFunctionList.add(filterFunction) + } + } + val allFilterFunction: MessagePayloadFilterFunction = { + payload: MessagePayload -> + filterFunctionList.all { + func -> func(payload) + } + } + return allFilterFunction + } fun messageForward(conversationId: String, messageId: String): Future { diff --git a/wechaty-puppet/src/main/kotlin/io/github/wechaty/schemas/Message.kt b/wechaty-puppet/src/main/kotlin/io/github/wechaty/schemas/Message.kt index 7b5e02d..d1cd7cc 100644 --- a/wechaty-puppet/src/main/kotlin/io/github/wechaty/schemas/Message.kt +++ b/wechaty-puppet/src/main/kotlin/io/github/wechaty/schemas/Message.kt @@ -61,6 +61,7 @@ class MessageQueryFilter { override fun toString(): String { return "MessageQueryFilter(fromId=$fromId, id=$id, roomId=$roomId, text=$text, toId=$toId, type=$type, textReg=$textReg)" } - - } + +typealias MessagePayloadFilterFunction = (payload: MessagePayload) -> Boolean +typealias MessagePayloadFilterFactory = (query: MessageQueryFilter) -> MessagePayloadFilterFunction diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt index d795811..56c6b36 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Contact.kt @@ -98,13 +98,24 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) return payload?.name ?: "" } + fun getName():String? { + return payload?.name + } + fun address(): String { return this.payload?.address ?: "" } + fun getAddress(): String? { + return this.payload?.address + } + fun signature(): String { return this.payload?.signature ?: "" } + fun getSignature(): String? { + return this.payload?.signature + } fun star(): Boolean { return this.payload?.star ?: false @@ -114,6 +125,10 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) return this.payload?.weixin ?: "" } + fun getWeixin(): String? { + return this.payload?.weixin + } + fun setAlias(newAlias:String){ if(payload == null){ throw Exception("no payload") @@ -148,28 +163,54 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) fun type():ContactType{ return payload?.type ?: throw Exception("no payload") } + fun getType(): ContactType { + return payload?.type ?: throw Exception("no payload") + } fun gender():ContactGender{ return payload?.gender ?: ContactGender.Unknown } + fun getGender():ContactGender{ + return payload?.gender ?: throw Exception("no payload") + } fun province():String?{ return payload?.province } + fun getProvince():String?{ + return payload?.province + } fun city():String?{ return payload?.city } + fun getCity():String?{ + return payload?.city + } + open fun avatar(): FileBox { try { return wechaty.getPuppet().getContactAvatar(this.id).get() } catch (e: Exception) { log.error("error",e) - TODO() + return qrCodeForChatie() + } + } + fun getAvatar(): FileBox { + try { + return wechaty.getPuppet().getContactAvatar(this.id).get() + } catch (e: Exception) { + log.error("error",e) + return qrCodeForChatie() } } + fun qrCodeForChatie (): FileBox { + val CHATIE_OFFICIAL_ACCOUNT_QRCODE = "http://weixin.qq.com/r/qymXj7DEO_1ErfTs93y5" + return FileBox.fromQRCode(CHATIE_OFFICIAL_ACCOUNT_QRCODE) + } + fun tags():List{ val tagIdList = wechaty.getPuppet().tagContactList(this.id).get() return try { @@ -181,6 +222,17 @@ open class Contact(wechaty: Wechaty,val id:String) : Sayable, Accessory(wechaty) listOf() } } + fun getTags():List { + val tagIdList = wechaty.getPuppet().tagContactList(this.id).get() + return try { + tagIdList.map { + wechaty.tagManager.load(it) + } + } catch (e: Exception) { + log.error("error",e) + listOf() + } + } fun self():Boolean { val userId = puppet.selfId() diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt index 99a5743..e1c859f 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/ContactSelf.kt @@ -13,6 +13,10 @@ class ContactSelf(wechaty: Wechaty, id: String) : Contact(wechaty, id) { puppet.setContactAvatar(super.id, fileBox) } + fun getAvatar(fileBox: FileBox) { + puppet.setContactAvatar(super.id, fileBox) + } + fun setName(name:String){ puppet.contactSelfName(name).get() sync() @@ -29,6 +33,17 @@ class ContactSelf(wechaty: Wechaty, id: String) : Contact(wechaty, id) { sync() } } + fun setSignature(signature:String) { + + var puppetId:String? = puppet.selfId() + + let{ + puppetId != null + }.run { + puppet.contactSelfSignature(signature).get() + sync() + } + } fun qrcode(): Future { log.info("Contact, qrcode()") @@ -49,6 +64,25 @@ class ContactSelf(wechaty: Wechaty, id: String) : Contact(wechaty, id) { guardQrCodeValue(qrcodeValue) } } + fun getQrcode(): Future { + log.info("Contact, qrcode()") + + val puppetId: String = try { + this.puppet.selfId().toString() + } + catch (e: Exception) { + throw Exception("Can not get qrcode, user might be either not logged in or already logged out") + } + + if (this.id !== puppetId) { + throw Exception("only can get qrcode for the login userself") + } + + return CompletableFuture.supplyAsync { + val qrcodeValue = this.puppet.contactSelfQRCode().get() + guardQrCodeValue(qrcodeValue) + } + } fun name(name: String?): String? { if (name == null) { @@ -56,8 +90,7 @@ class ContactSelf(wechaty: Wechaty, id: String) : Contact(wechaty, id) { } val puppetId = try { this.puppet.selfId() - } - catch (e: Exception) { + } catch (e: Exception) { throw Exception("Can not get qrcode, user might be either not logged in or already logged out") } if (this.id !== puppetId) { @@ -67,22 +100,21 @@ class ContactSelf(wechaty: Wechaty, id: String) : Contact(wechaty, id) { return null } -// fun signature (signature: String): Future { -// log.debug("ContactSelf, signature()") -// -// val puppetId = try { -// this.puppet.selfId() -// } -// catch (e: Exception) { -// throw Exception("Can not get qrcode, user might be either not logged in or already logged out") -// } -// -// if (this.id !== puppetId) { -// throw Exception("only can get qrcode for the login userself") -// } -// // maybe -// return this.puppet.contactSelfSignature(signature) -// } + fun getName(name: String?): String? { + if (name == null) { + return super.name() + } + val puppetId = try { + this.puppet.selfId() + } catch (e: Exception) { + throw Exception("Can not get qrcode, user might be either not logged in or already logged out") + } + if (this.id !== puppetId) { + throw Exception("only can get qrcode for the login userself") + } + this.puppet.contactSelfName(name) + return null + } companion object { private val log = LoggerFactory.getLogger(ContactSelf::class.java) diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt index e8f4d1f..cfbf567 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Friendship.kt @@ -70,10 +70,14 @@ class Friendship (wechaty: Wechaty,val id:String):Accessory(wechaty){ return this.payload?.hello ?: ""; } - fun type():FriendshipType{ + fun type(): FriendshipType { return this.payload?.type ?:FriendshipType.Unknown } + fun getType(): FriendshipType { + return this.payload?.type ?: throw Exception("ne payload") + } + fun toJson():String{ if(payload==null){ throw Exception("ne payload") diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt index ac9591d..f1b30ee 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Message.kt @@ -118,6 +118,9 @@ open class Message(wechaty: Wechaty,val id: String) : Sayable, Accessory(wechaty } return this.payload?.type ?: MessageType.Unknown } + fun getType(): MessageType{ + return this.payload?.type ?: throw Exception("no payload") + } fun self():Boolean{ val selfId = puppet.selfId() @@ -131,8 +134,18 @@ open class Message(wechaty: Wechaty,val id: String) : Sayable, Accessory(wechaty return Date(payload.timestamp!! * 1000) } + fun getDate(): Date { + val payload = wechaty.getPuppet().messagePayload(this.id).get() + return Date(payload.timestamp!! * 1000) + } + fun age(): Long { - // 这里会是负数,payload里面的时间提前了 + val ageMilliseconds = Date().time - this.date().time + val ageSeconds = Math.floor(ageMilliseconds / 1000.0).toLong() + return ageSeconds + } + + fun getAge(): Long { val ageMilliseconds = Date().time - this.date().time val ageSeconds = Math.floor(ageMilliseconds / 1000.0).toLong() return ageSeconds @@ -202,7 +215,6 @@ open class Message(wechaty: Wechaty,val id: String) : Sayable, Accessory(wechaty return text() } - fun ready():Future{ return CompletableFuture.supplyAsync { diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt index 4350c88..35d94c5 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/Room.kt @@ -350,12 +350,29 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { } } + fun getAnnounce(): Future { + return CompletableFuture.supplyAsync { + puppet.getRoomAnnounce(id).get() + } + } + + fun setAnnounce(text: String): Future { + return puppet.setRoomAnnounce(id, text) + } + fun qrCode(): Future { return CompletableFuture.supplyAsync { val qrCodeValue = puppet.roomQRCode(id).get() return@supplyAsync QrcodeUtils.guardQrCodeValue(qrCodeValue) } } + fun getQrCode(): Future { + return CompletableFuture.supplyAsync { + val qrCodeValue = puppet.roomQRCode(id).get() + return@supplyAsync QrcodeUtils.guardQrCodeValue(qrCodeValue) + } + } + fun member(query: RoomMemberQueryFilter?): Contact? { val memberList = memberAll(query) @@ -398,9 +415,7 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { } fun alias(contact: Contact): String? { - val roomMemberPayload = wechaty.getPuppet().roomMemberPayload(this.id, contact.id).get() - return roomMemberPayload?.roomAlias } @@ -431,6 +446,11 @@ class Room(wechaty: Wechaty, val id: String) : Accessory(wechaty), Sayable { return puppet.roomAvatar(this.id).get() } + fun getAvatar(): FileBox { + log.debug("getAvatar:{}", getAvatar()) + return puppet.roomAvatar(this.id).get() + } + companion object { private val log = LoggerFactory.getLogger(Room::class.java) } diff --git a/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt b/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt index 01f41cd..5ef4ec9 100644 --- a/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt +++ b/wechaty/src/main/kotlin/io/github/wechaty/user/RoomInvitation.kt @@ -52,21 +52,39 @@ class RoomInvitation(wechaty: Wechaty,val id:String) : Accessory(wechaty){ return Date(payload.timestamp!! * 1000) } + fun getDate(): Date { + val payload = wechaty.getPuppet().roomInvitationPayload(this.id).get() + return Date(payload.timestamp!! * 1000) + } fun age():Long{ val recvDate = this.date() return System.currentTimeMillis() - recvDate.time; } + fun getAge():Long{ + val recvDate = this.date() + return System.currentTimeMillis() - recvDate.time; + } fun inviter():Contact{ val payload = wechaty.getPuppet().roomInvitationPayload(this.id).get() return wechaty.contactManager.load(payload.inviterId!!) } + fun getInviter():Contact{ + val payload = wechaty.getPuppet().roomInvitationPayload(this.id).get() + return wechaty.contactManager.load(payload.inviterId!!) + } + fun topic():String { val payload = wechaty.getPuppet().roomInvitationPayload(this.id).get() return payload.topic ?:"" } + fun getTopic():String { + val payload = wechaty.getPuppet().roomInvitationPayload(this.id).get() + return payload.topic ?:"" + } + companion object{ private val log = LoggerFactory.getLogger(RoomInvitation::class.java) }