Skip to content

Commit

Permalink
Merge pull request #72 from evan-buss/development
Browse files Browse the repository at this point in the history
OpenBooks v4.3.0
  • Loading branch information
evan-buss committed Feb 15, 2022
2 parents 79ad1c3 + e7cb4da commit 81aa86e
Show file tree
Hide file tree
Showing 39 changed files with 472 additions and 330 deletions.
2 changes: 1 addition & 1 deletion .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
&& apt-get -y install --no-install-recommends tmux

# [Optional] Uncomment the next line to use go get to install anything else you need
# RUN go get -x <your-dependency-or-tool>
RUN go get golang.org/x/tools/cmd/stringer

# [Optional] Uncomment this line to install global node packages.
RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g npm-check-updates" 2>&1
3 changes: 2 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"golang.Go",
"eamodio.gitlens",
"bradlc.vscode-tailwindcss",
"esbenp.prettier-vscode"
"esbenp.prettier-vscode",
"GitHub.copilot"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# openbooks

> NOTE: OpenBooks has been updated to comply with requests from IRC admins. Please download the latest release to continue using it. See [Issue #52](https://github.com/evan-buss/openbooks/issues/52) for context.
> NOTE: Going forward only the latest release will be supported. If you encounter any issues, be sure you are using the latest version.
[![Docker Pulls](https://img.shields.io/docker/pulls/evanbuss/openbooks.svg)](https://hub.docker.com/r/evanbuss/openbooks/)

Expand Down Expand Up @@ -64,8 +64,7 @@ that you can visit in your browser.

- The mock server allows you to debug responses and requests to simplified IRC / DCC
servers that mimic the responses received from IRC Highway.
-
```bash
- ```bash
cd cmd/mock_server
go run .
# Another Terminal
Expand All @@ -82,11 +81,12 @@ that you can visit in your browser.

- Backend
- Golang
- Archiver (extract files from various archive formats)
- Chi
- gorilla/websocket
- Archiver (extract files from various archive formats)
- Frontend
- React.js
- TypeScript
- Redux / Redux Toolkit
- Styled Components
- Tailwind CSS
- Evergreen UI
40 changes: 25 additions & 15 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"context"
"fmt"
"time"

"github.com/evan-buss/openbooks/core"
"github.com/evan-buss/openbooks/irc"
Expand All @@ -14,6 +15,7 @@ type Config struct {
Dir string
Server string
irc *irc.Conn
Version string
}

// StartInteractive instantiates the OpenBooks CLI interface
Expand All @@ -22,30 +24,31 @@ func StartInteractive(config Config) {
fmt.Println(" Welcome to OpenBooks ")
fmt.Println("=======================================")

conn := instantiate(config)
config.irc = conn
instantiate(&config)
defer config.irc.Close()

ctx, cancel := context.WithCancel(context.Background())
registerShutdown(conn, cancel)
registerShutdown(config.irc, cancel)

handler := fullHandler(config)
if config.Log {
file := config.setupLogger(handler)
defer file.Close()
}

go core.StartReader(ctx, conn, handler)
terminalMenu(conn)
go core.StartReader(ctx, config.irc, handler)
terminalMenu(config.irc)

<-ctx.Done()
}

func StartDownload(config Config, download string) {
conn := instantiate(config)
defer conn.Close()
instantiate(&config)
defer config.irc.Close()
ctx, cancel := context.WithCancel(context.Background())

handler := core.EventHandler{}
addEssentialHandlers(handler, &config)
handler[core.BookResult] = func(text string) {
fmt.Printf("%sReceived file response.\n", clearLine)
config.downloadHandler(text)
Expand All @@ -57,21 +60,23 @@ func StartDownload(config Config, download string) {
}

fmt.Printf("Sending download request.")
go core.StartReader(ctx, conn, handler)
core.DownloadBook(conn, download)
go core.StartReader(ctx, config.irc, handler)
core.DownloadBook(config.irc, download)
fmt.Printf("%sSent download request.", clearLine)
fmt.Printf("Waiting for file response.")

registerShutdown(conn, cancel)
registerShutdown(config.irc, cancel)
<-ctx.Done()
}

func StartSearch(config Config, query string) {
conn := instantiate(config)
defer conn.Close()
nextSearchTime := getLastSearchTime().Add(15 * time.Second)
instantiate(&config)
defer config.irc.Close()
ctx, cancel := context.WithCancel(context.Background())

handler := core.EventHandler{}
addEssentialHandlers(handler, &config)
handler[core.SearchResult] = func(text string) {
fmt.Printf("%sReceived file response.\n", clearLine)
config.searchHandler(text)
Expand All @@ -84,11 +89,16 @@ func StartSearch(config Config, query string) {
}

fmt.Printf("Sending search request.")
go core.StartReader(ctx, conn, handler)
core.SearchBook(conn, query)
warnIfServerOffline(query)
time.Sleep(time.Until(nextSearchTime))

go core.StartReader(ctx, config.irc, handler)
core.SearchBook(config.irc, query)

setLastSearchTime()
fmt.Printf("%sSent search request.", clearLine)
fmt.Printf("Waiting for file response.")

registerShutdown(conn, cancel)
registerShutdown(config.irc, cancel)
<-ctx.Done()
}
4 changes: 4 additions & 0 deletions cli/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,7 @@ func (c Config) matchesFoundHandler(num string) {
func (c Config) pingHandler(_ string) {
c.irc.Pong(c.Server)
}

func (c *Config) versionHandler(line string) {
core.SendVersionInfo(c.irc, line, c.Version)
}
24 changes: 16 additions & 8 deletions cli/interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ import (
"github.com/evan-buss/openbooks/irc"
)

var lastSearch time.Time

func terminalMenu(irc *irc.Conn) {
fmt.Print("\ns)search\ng)et book\nd)one\n~> ")
fmt.Print("\ns)search\ng)et book\nse)rvers\nd)one\n~> ")

// Trim user input so we don't send 2 messages
clean := func(message string) string { return strings.Trim(message, "\r\n") }
Expand All @@ -26,16 +24,26 @@ func terminalMenu(irc *irc.Conn) {
switch input {
case "s":
fmt.Print("@search ")
message, _ := reader.ReadString('\n')
query, _ := reader.ReadString('\n')
fmt.Println("\nSent search request.")
time.Sleep(time.Until(lastSearch.Add(time.Second * 15)))
core.SearchBook(irc, clean(message))
lastSearch = time.Now()

nextSearchTime := getLastSearchTime().Add(15 * time.Second)
time.Sleep(time.Until(nextSearchTime))

core.SearchBook(irc, clean(query))
setLastSearchTime()
case "g":
fmt.Print("Download String: ")
message, _ := reader.ReadString('\n')
core.DownloadBook(irc, clean(message))
fmt.Println("\nSent download request.")
warnIfServerOffline(clean(message))
case "se":
fmt.Println("\nAvailable Servers:")
for _, server := range servers {
fmt.Printf(" %s\n", server)
}
terminalMenu(irc)
case "d":
fmt.Println("Disconnecting.")
irc.Disconnect()
Expand All @@ -48,6 +56,7 @@ func terminalMenu(irc *irc.Conn) {

func fullHandler(config Config) core.EventHandler {
handler := core.EventHandler{}
addEssentialHandlers(handler, &config)

handler[core.BadServer] = func(text string) {
config.badServerHandler(text)
Expand All @@ -67,7 +76,6 @@ func fullHandler(config Config) core.EventHandler {
terminalMenu(config.irc)
}
handler[core.MatchesFound] = config.matchesFoundHandler
handler[core.Ping] = config.pingHandler

return handler
}
37 changes: 31 additions & 6 deletions cli/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"

Expand All @@ -17,6 +18,8 @@ import (
"github.com/evan-buss/openbooks/util"
)

var servers []string

const clearLine = "\r\033[2K"

func registerShutdown(conn *irc.Conn, cancel context.CancelFunc) {
Expand All @@ -30,12 +33,23 @@ func registerShutdown(conn *irc.Conn, cancel context.CancelFunc) {
}()
}

func instantiate(config Config) *irc.Conn {
// Connect to IRC server and save connection to Config
func instantiate(config *Config) {
fmt.Printf("Connecting to %s.", config.Server)
conn := irc.New(config.UserName, "OpenBooks CLI")
conn := irc.New(config.UserName, config.Version)
config.irc = conn
core.Join(conn, config.Server)
fmt.Printf("%sConnected to %s.\n", clearLine, config.Server)
return conn
}

// Required handlers are used regardless of what CLI mode is selected.
// Keep alive pings and other core IRC client features
func addEssentialHandlers(handler core.EventHandler, config *Config) {
handler[core.Ping] = config.pingHandler
handler[core.Version] = config.versionHandler
handler[core.ServerList] = func(text string) {
servers = core.ParseServers(text).ElevatedUsers
}
}

func (config *Config) setupLogger(handler core.EventHandler) io.Closer {
Expand All @@ -50,18 +64,29 @@ func (config *Config) setupLogger(handler core.EventHandler) io.Closer {
return file
}

func GetLastSearchTime() time.Time {
// Show warning message if the server they are downloading from is not online.
func warnIfServerOffline(bookLine string) {
for _, server := range servers {
if strings.HasPrefix(bookLine[1:], server) {
return
}
}

fmt.Println("WARNING: That server is not online. Your request will never complete.")
}

func getLastSearchTime() time.Time {
timestampFilePath := filepath.Join(os.TempDir(), ".openbooks")
fileInfo, err := os.Stat(timestampFilePath)

if errors.Is(err, os.ErrNotExist) {
return time.Time{}
return time.Now()
}

return fileInfo.ModTime()
}

func SetLastSearchTime() {
func setLastSearchTime() {
timestampFilePath := filepath.Join(os.TempDir(), ".openbooks")
_, err := os.Stat(timestampFilePath)

Expand Down
22 changes: 10 additions & 12 deletions cmd/openbooks/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ package main

import (
"errors"
"fmt"
"log"
"os"
"strings"
"time"

"github.com/evan-buss/openbooks/cli"
"github.com/spf13/cobra"
)

var config cli.Config
var cliConfig cli.Config

func init() {
rootCmd.AddCommand(cliCmd)
Expand All @@ -23,17 +23,18 @@ func init() {
log.Fatalln("Could not get current working directory.", err)
}

cliCmd.PersistentFlags().StringVarP(&config.UserName, "name", "n", generateUserName(), "Use a name that isn't randomly generated. One word only.")
cliCmd.PersistentFlags().StringVarP(&config.Dir, "directory", "d", cwd, "Directory where files are downloaded.")
cliCmd.PersistentFlags().BoolVarP(&config.Log, "log", "l", false, "Whether or not to log IRC messages to an output file.")
cliCmd.PersistentFlags().StringVarP(&config.Server, "server", "s", "irc.irchighway.net", "IRC server to connect to.")
cliConfig.Version = fmt.Sprintf("OpenBooks CLI %s", version)
cliCmd.PersistentFlags().StringVarP(&cliConfig.UserName, "name", "n", generateUserName(), "Use a name that isn't randomly generated. One word only.")
cliCmd.PersistentFlags().StringVarP(&cliConfig.Dir, "directory", "d", cwd, "Directory where files are downloaded.")
cliCmd.PersistentFlags().BoolVarP(&cliConfig.Log, "log", "l", false, "Whether or not to log IRC messages to an output file.")
cliCmd.PersistentFlags().StringVarP(&cliConfig.Server, "server", "s", "irc.irchighway.net", "IRC server to connect to.")
}

var cliCmd = &cobra.Command{
Use: "cli",
Short: "Run openbooks from the terminal in CLI mode.",
Run: func(cmd *cobra.Command, args []string) {
cli.StartInteractive(config)
cli.StartInteractive(cliConfig)
},
}

Expand All @@ -52,7 +53,7 @@ var downloadCmd = &cobra.Command{
return nil
},
Run: func(cmd *cobra.Command, args []string) {
cli.StartDownload(config, args[0])
cli.StartDownload(cliConfig, args[0])
},
}

Expand All @@ -61,9 +62,6 @@ var searchCmd = &cobra.Command{
Short: "Searches for a book and exits.",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
nextSearchTime := cli.GetLastSearchTime().Add(15 * time.Second)
time.Sleep(time.Until(nextSearchTime))
cli.StartSearch(config, args[0])
cli.SetLastSearchTime()
cli.StartSearch(cliConfig, args[0])
},
}
7 changes: 5 additions & 2 deletions cmd/openbooks/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ import (
"github.com/spf13/cobra"
)

const version = "4.3.0"

var rootCmd = &cobra.Command{
Use: "openbooks",
Short: "Quickly and easily download eBooks from IRCHighway.",
Use: "openbooks",
Short: "Quickly and easily download eBooks from IRCHighway.",
Version: version,
}

func main() {
Expand Down

0 comments on commit 81aa86e

Please sign in to comment.