Removed unnecessary threading (ThreadedModule, etc.)

This commit is contained in:
Erik C. Thauvin 2022-12-07 12:08:15 -08:00
parent e510a77af1
commit 0fba4445f8
24 changed files with 73 additions and 181 deletions

View file

@ -54,7 +54,7 @@
<ID>NestedBlockDepth:EntryLink.kt$EntryLink$private fun setTags(tags: List&lt;String?&gt;)</ID>
<ID>NestedBlockDepth:FeedsManager.kt$FeedsManager.Companion$@JvmStatic @Throws(IOException::class, FeedException::class) fun loadFeed(entries: Entries, currentFile: String = currentXml): String</ID>
<ID>NestedBlockDepth:FeedsManager.kt$FeedsManager.Companion$@JvmStatic fun saveFeed(entries: Entries, currentFile: String = currentXml)</ID>
<ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch$override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:GoogleSearch.kt$GoogleSearch.Companion$@JvmStatic @Throws(ModuleException::class) fun searchGoogle( query: String, apiKey: String?, cseKey: String?, quotaUser: String = ReleaseInfo.PROJECT ): List&lt;Message&gt;</ID>
<ID>NestedBlockDepth:LinksManager.kt$LinksManager$override fun commandResponse(channel: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:Lookup.kt$Lookup$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
@ -66,7 +66,7 @@
<ID>NestedBlockDepth:TwitterOAuth.kt$TwitterOAuth$@JvmStatic fun main(args: Array&lt;String&gt;)</ID>
<ID>NestedBlockDepth:Utils.kt$Utils$@JvmStatic fun loadData(file: String, default: Any, logger: Logger, description: String): Any</ID>
<ID>NestedBlockDepth:Utils.kt$Utils$@JvmStatic fun saveData(file: String, data: Any, logger: Logger, description: String)</ID>
<ID>NestedBlockDepth:Weather2.kt$Weather2$override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:Weather2.kt$Weather2$override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent)</ID>
<ID>NestedBlockDepth:Weather2.kt$Weather2.Companion$@JvmStatic @Throws(ModuleException::class) fun getWeather(query: String, apiKey: String?): List&lt;Message&gt;</ID>
<ID>PrintStackTrace:TwitterOAuth.kt$TwitterOAuth$ioe</ID>
<ID>PrintStackTrace:TwitterOAuth.kt$TwitterOAuth$te</ID>

View file

@ -65,7 +65,7 @@ class FeedReader(private val url: String, val event: GenericMessageEvent) : Runn
event.sendMessage("An error has occurred while parsing the feed: ${e.message}")
} catch (e: IOException) {
if (logger.isWarnEnabled) logger.warn("Unable to fetch the feed at $url", e)
event.sendMessage("An error has occurred while fetching the feed: ${e.message}")
event.sendMessage("An IO error has occurred while fetching the feed: ${e.message}")
}
}

View file

@ -176,7 +176,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
override fun onDisconnect(event: DisconnectEvent?) {
event?.let {
with(event.getBot<PircBotX>()) {
LinksManager.socialManager.notification("$nick disconnected from irc://$serverHostname")
LinksManager.socialManager.notification("$nick disconnected from $serverHostname")
seen.add(userChannelDao.getChannel(channel).users)
}
}
@ -202,7 +202,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
with(event.getBot<PircBotX>()) {
if (user.nick == nick) {
LinksManager.socialManager.notification(
"$nick has joined ${event.channel.name} on irc://$serverHostname"
"$nick has joined ${event.channel.name} on $serverHostname"
)
seen.add(userChannelDao.getChannel(channel).users)
} else {
@ -215,12 +215,10 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
override fun onMessage(event: MessageEvent?) {
event?.user?.let { user ->
val sender = user.nick
val message = event.message
tell.send(event)
if (message.matches("(?i)${Pattern.quote(event.bot().nick)}:.*".toRegex())) { // mobibot: <command>
if (logger.isTraceEnabled) logger.trace(">>> $sender: $message")
val cmds = message.substring(message.indexOf(':') + 1).trim().split(" ".toRegex(), 2)
if (event.message.matches("(?i)${Pattern.quote(event.bot().nick)}:.*".toRegex())) { // mobibot: <command>
if (logger.isTraceEnabled) logger.trace(">>> ${user.nick}: ${event.message}")
val cmds = event.message.substring(event.bot().nick.length + 1).trim().split(" ".toRegex(), 2)
val cmd = cmds[0].lowercase()
val args = cmds.lastOrEmpty().trim()
if (cmd.startsWith(Constants.HELP_CMD)) { // mobibot: help
@ -230,10 +228,10 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
addons.exec(channel, cmd, args, event)
}
} else if (addons.match(channel, event)) { // Links, e.g.: https://www.example.com/ or L1: , etc.
if (logger.isTraceEnabled) logger.trace(">>> $sender: $message")
if (logger.isTraceEnabled) logger.trace(">>> ${user.nick}: ${event.message}")
}
storeRecap(sender, message, false)
seen.add(sender)
storeRecap(user.nick, event.message, false)
seen.add(user.nick)
}
}
@ -252,7 +250,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
with(event.getBot<PircBotX>()) {
if (user.nick == nick) {
LinksManager.socialManager.notification(
"$nick has left ${event.channel.name} on irc://$serverHostname"
"$nick has left ${event.channel.name} on $serverHostname"
)
seen.add(userChannelDao.getChannel(channel).users)
} else {

View file

@ -32,8 +32,6 @@
package net.thauvin.erik.mobibot
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.entries.EntryLink
import net.thauvin.erik.pinboard.PinboardPoster
import java.time.ZoneId
@ -53,15 +51,11 @@ class Pinboard {
*/
fun addPin(ircServer: String, entry: EntryLink) {
if (poster.apiToken.isNotBlank()) {
runBlocking {
launch {
with(entry) {
poster.addPin(link, title, postedBy(ircServer), formatTags(), date.toTimestamp())
}
}
}
}
}
/**
* Sets the pinboard API token.
@ -75,12 +69,9 @@ class Pinboard {
*/
fun deletePin(entry: EntryLink) {
if (poster.apiToken.isNotBlank()) {
runBlocking {
launch {
poster.deletePin(entry.link)
}
}
}
}
/**
@ -88,8 +79,6 @@ class Pinboard {
*/
fun updatePin(ircServer: String, oldUrl: String, entry: EntryLink) {
if (poster.apiToken.isNotBlank()) {
runBlocking {
launch {
with(entry) {
if (oldUrl != link) {
poster.deletePin(oldUrl)
@ -98,16 +87,13 @@ class Pinboard {
}
}
}
}
}
/**
* Formats a date to a UTC timestamp.
*/
private fun Date.toTimestamp(): String {
return ZonedDateTime.ofInstant(
toInstant().truncatedTo(ChronoUnit.SECONDS),
ZoneId.systemDefault()
toInstant().truncatedTo(ChronoUnit.SECONDS), ZoneId.systemDefault()
).format(DateTimeFormatter.ISO_INSTANT)
}

View file

@ -32,8 +32,6 @@
package net.thauvin.erik.mobibot.commands
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.FeedReader
import net.thauvin.erik.mobibot.Utils.helpFormat
import org.pircbotx.hooks.types.GenericMessageEvent
@ -55,13 +53,9 @@ class ChannelFeed(channel: String) : AbstractCommand() {
override fun commandResponse(channel: String, args: String, event: GenericMessageEvent) {
if (isEnabled()) {
runBlocking {
launch {
properties[FEED_PROP]?.let { FeedReader(it, event).run() }
}
}
}
}
override fun isEnabled(): Boolean {
return !properties[FEED_PROP].isNullOrBlank()

View file

@ -33,6 +33,7 @@
package net.thauvin.erik.mobibot.commands
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.Utils.bot
import net.thauvin.erik.mobibot.Utils.helpFormat
@ -51,11 +52,13 @@ class Cycle : AbstractCommand() {
with(event.bot()) {
if (event.isChannelOp(channel)) {
runBlocking {
launch {
sendIRC().message(channel, "${event.user.nick} asked me to leave. I'll be back!")
userChannelDao.getChannel(channel).send().part()
delay(wait * 1000L)
sendIRC().joinChannel(channel)
}
}
} else {
helpResponse(channel, args, event)
}

View file

@ -141,7 +141,7 @@ class Ignore : AbstractCommand() {
override fun setProperty(key: String, value: String) {
super.setProperty(key, value)
if (IGNORE_PROP == key) {
ignored.addAll(value.split(LinksManager.TAG_MATCH)
ignored.addAll(value.split(LinksManager.TAG_MATCH))
}
}

View file

@ -45,15 +45,7 @@ class Users : AbstractCommand() {
override val isVisible = true
override fun commandResponse(channel: String, args: String, event: GenericMessageEvent) {
val nicks = mutableListOf<String>()
val ch = event.bot().userChannelDao.getChannel(channel)
ch.users.forEach {
if (it.channelsOpIn.contains(ch)) {
nicks.add("@${it.nick}")
} else {
nicks.add(it.nick)
}
}
event.sendList(nicks, 8)
event.sendList(ch.users.map { if (it.channelsOpIn.contains(ch)) "@${it.nick}" else it.nick }, 8)
}
}

View file

@ -37,7 +37,7 @@ import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* The `TellMessage` class.
* Tell Message.
*/
class TellMessage(
/**

View file

@ -46,12 +46,12 @@ import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
class ChatGpt : ThreadedModule() {
class ChatGpt : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(ChatGpt::class.java)
override val name = "ChatGPT"
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) {
try {
event.sendMessage(

View file

@ -46,7 +46,7 @@ import java.io.IOException
/**
* The Cryptocurrency Prices module.
*/
class CryptoPrices : ThreadedModule() {
class CryptoPrices : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(CryptoPrices::class.java)
override val name = "CryptoPrices"
@ -55,7 +55,7 @@ class CryptoPrices : ThreadedModule() {
* Returns the cryptocurrency market price from
* [Coinbase](https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices#get-spot-price).
*/
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (CURRENCIES.isEmpty()) {
try {
loadCurrencies()

View file

@ -52,7 +52,7 @@ import java.util.TreeMap
/**
* The CurrencyConverter module.
*/
class CurrencyConverter : ThreadedModule() {
class CurrencyConverter : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(CurrencyConverter::class.java)
override val name = "CurrencyConverter"
@ -71,7 +71,7 @@ class CurrencyConverter : ThreadedModule() {
/**
* Converts the specified currencies.
*/
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
reload()
if (SYMBOLS.isEmpty()) {

View file

@ -54,7 +54,7 @@ import java.net.URL
/**
* The GoogleSearch module.
*/
class GoogleSearch : ThreadedModule() {
class GoogleSearch : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(GoogleSearch::class.java)
override val name = "GoogleSearch"
@ -62,7 +62,7 @@ class GoogleSearch : ThreadedModule() {
/**
* Searches Google.
*/
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) {
try {
val results = searchGoogle(

View file

@ -31,8 +31,6 @@
*/
package net.thauvin.erik.mobibot.modules
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.jokeapi.exceptions.HttpErrorException
import net.thauvin.erik.jokeapi.exceptions.JokeException
import net.thauvin.erik.jokeapi.getJoke
@ -52,21 +50,15 @@ import java.io.IOException
/**
* The Joke module.
*/
class Joke : ThreadedModule() {
class Joke : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(Joke::class.java)
override val name = "Joke"
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
runBlocking {
launch { run(channel, cmd, args, event) }
}
}
/**
* Returns a random joke from [JokeAPI](https://v2.jokeapi.dev/).
*/
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
with(event.bot()) {
try {
randomJoke().forEach {
@ -92,12 +84,8 @@ class Joke : ThreadedModule() {
@Throws(ModuleException::class)
fun randomJoke(): List<Message> {
return try {
val messages = mutableListOf<Message>()
val joke = getJoke(safe = true, type = Type.SINGLE, splitNewLine = true)
joke.joke.forEach {
messages.add(PublicMessage(it, Colors.CYAN))
}
messages
joke.joke.map { PublicMessage(it, Colors.CYAN) }
} catch (e: JokeException) {
throw ModuleException("randomJoke(): ${e.additionalInfo}", e.message, e)
} catch (e: HttpErrorException) {

View file

@ -93,7 +93,7 @@ class Mastodon : SocialModule() {
private const val MASTODON_CMD = "mastodon"
/**
* Toots on Mastodon.
* Post on Mastodon.
*/
@JvmStatic
@Throws(ModuleException::class)

View file

@ -52,7 +52,7 @@ import java.net.URL
/**
* The StockQuote module.
*/
class StockQuote : ThreadedModule() {
class StockQuote : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(StockQuote::class.java)
override val name = "StockQuote"
@ -60,7 +60,7 @@ class StockQuote : ThreadedModule() {
/**
* Returns the specified stock quote from Alpha Vantage.
*/
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) {
try {
val messages = getQuote(args, properties[ALPHAVANTAGE_API_KEY_PROP])

View file

@ -1,58 +0,0 @@
/*
* ThreadedModule.kt
*
* Copyright (c) 2004-2022, Erik C. Thauvin (erik@thauvin.net)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of this project nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.thauvin.erik.mobibot.modules
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.pircbotx.hooks.types.GenericMessageEvent
/**
* The `ThreadedModule` class.
*/
abstract class ThreadedModule : AbstractModule() {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (isEnabled && event.message.isNotEmpty()) {
runBlocking {
launch {
run(channel, cmd, args, event)
}
}
} else {
helpResponse(event)
}
}
/**
* Runs the thread.
*/
abstract fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent)
}

View file

@ -88,7 +88,7 @@ class Twitter : SocialModule() {
private const val TWITTER_CMD = "twitter"
/**
* Tweets on Twitter.
* Post on Twitter.
*/
@JvmStatic
@Throws(ModuleException::class)

View file

@ -54,7 +54,7 @@ import kotlin.math.roundToInt
/**
* The `Weather2` module.
*/
class Weather2 : ThreadedModule() {
class Weather2 : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(Weather2::class.java)
override val name = "Weather"
@ -62,7 +62,7 @@ class Weather2 : ThreadedModule() {
/**
* Fetches the weather data from a specific city.
*/
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) {
try {
val messages = getWeather(args, properties[OWM_API_KEY_PROP])

View file

@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory
import java.io.IOException
import java.net.URL
class WolframAlpha : ThreadedModule() {
class WolframAlpha : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(WolframAlpha::class.java)
override val name = "WolframAlpha"
@ -56,7 +56,7 @@ class WolframAlpha : ThreadedModule() {
}
}
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
if (args.isNotBlank()) {
try {
val query = args.trim().split("units=", limit = 2, ignoreCase = true)

View file

@ -110,8 +110,8 @@ class SocialManager {
*/
fun shutdown() {
timer.cancel()
for (index in entries) {
postEntry(index)
entries.forEach {
postEntry(it)
}
}
}

View file

@ -32,18 +32,16 @@
package net.thauvin.erik.mobibot.social
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.mobibot.commands.links.LinksManager
import net.thauvin.erik.mobibot.entries.EntriesUtils.toLinkLabel
import net.thauvin.erik.mobibot.entries.EntryLink
import net.thauvin.erik.mobibot.modules.AbstractModule
import net.thauvin.erik.mobibot.modules.ModuleException
import net.thauvin.erik.mobibot.modules.ThreadedModule
import org.pircbotx.hooks.types.GenericMessageEvent
import org.slf4j.Logger
import org.slf4j.LoggerFactory
abstract class SocialModule : ThreadedModule() {
abstract class SocialModule : AbstractModule() {
private val logger: Logger = LoggerFactory.getLogger(SocialManager::class.java)
abstract val handle: String?
@ -56,8 +54,6 @@ abstract class SocialModule : ThreadedModule() {
*/
fun notification(msg: String) {
if (isEnabled && !handle.isNullOrBlank()) {
runBlocking {
launch {
try {
post(message = msg, isDm = true)
if (logger.isDebugEnabled) logger.debug("Notified $handle on $name: $msg")
@ -66,8 +62,6 @@ abstract class SocialModule : ThreadedModule() {
}
}
}
}
}
abstract fun post(message: String, isDm: Boolean): String
@ -76,8 +70,6 @@ abstract class SocialModule : ThreadedModule() {
*/
fun postEntry(index: Int) {
if (isAutoPost && LinksManager.entries.links.size >= index) {
runBlocking {
launch {
try {
if (logger.isDebugEnabled) {
logger.debug("Posting {} to $name.", index.toLinkLabel())
@ -91,10 +83,8 @@ abstract class SocialModule : ThreadedModule() {
}
}
}
}
}
override fun run(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
override fun commandResponse(channel: String, cmd: String, args: String, event: GenericMessageEvent) {
try {
event.respond(post("$args (by ${event.user.nick} on $channel)", false))
} catch (e: ModuleException) {

View file

@ -40,7 +40,6 @@ import assertk.assertions.isFalse
import assertk.assertions.isTrue
import assertk.assertions.prop
import assertk.assertions.size
import assertk.assertions.startsWith
import com.rometools.rome.feed.synd.SyndCategory
import com.rometools.rome.feed.synd.SyndCategoryImpl
import org.testng.annotations.Test

View file

@ -1,9 +1,9 @@
#Generated by the Semver Plugin for Gradle
#Wed Dec 07 02:53:01 PST 2022
version.buildmeta=857
#Sat Dec 10 10:16:56 PST 2022
version.buildmeta=874
version.major=0
version.minor=8
version.patch=0
version.prerelease=rc
version.project=mobibot
version.semver=0.8.0-rc+857
version.semver=0.8.0-rc+874