├── .gitignore ├── README.md ├── .travis.yml ├── cmdTags.go ├── cmdClean.go ├── cmdShrug.go ├── go.mod ├── cmdStream.go ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── workflows │ └── go.yml ├── cmdDelete.go ├── cmdUnfollow.go ├── cmdFollow.go ├── cmdPost.go ├── cmdReply.go ├── cmdHelp.go ├── cmdReact.go ├── tcmdShowReactions.go ├── cmdExec.go ├── cmdUploadFile.go ├── CONTRIBUTING.md ├── cmdJoin.go ├── userTags.go ├── cmdDownload.go ├── cmdWallet.go ├── cmdEdit.go ├── cmdConfig.go ├── kbtui.toml ├── defaultConfig.go ├── mage.go ├── cmdWall.go ├── CODE_OF_CONDUCT.md ├── types.go ├── go.sum ├── cmdInspect.go ├── colors.go ├── tabComplete.go ├── main.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | kbtui 2 | emojiList.go 3 | *~ 4 | .\#* 5 | \#*\# 6 | .idea/* 7 | .idea 8 | *.log 9 | .travis.yml 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Announcement 2 | Development on this branch of kbtui has been stopped and migrated to https://git.hugfreevikings.wtf/keybase/kbtui 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - tip 5 | - 1.13.x 6 | 7 | install: true 8 | 9 | script: 10 | - go get -u github.com/magefile/mage/mage 11 | - go run build.go buildBeta 12 | - go vet ./... 13 | - go fmt ./... -------------------------------------------------------------------------------- /cmdTags.go: -------------------------------------------------------------------------------- 1 | // +ignore 2 | // +build allcommands tagscmd 3 | 4 | package main 5 | 6 | func init() { 7 | command := Command{ 8 | Cmd: []string{"tags", "map"}, 9 | Description: "$- Create map of users following users, to populate $TAGS", 10 | Help: "", 11 | Exec: cmdTags, 12 | } 13 | 14 | RegisterCommand(command) 15 | } 16 | 17 | func cmdTags(cmd []string) { 18 | go generateFollowersList() 19 | } 20 | -------------------------------------------------------------------------------- /cmdClean.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands cleancmd 2 | 3 | package main 4 | 5 | func init() { 6 | command := Command{ 7 | Cmd: []string{"clean", "c"}, 8 | Description: "- Clean, or redraw chat view", 9 | Help: "", 10 | Exec: cmdClean, 11 | } 12 | 13 | RegisterCommand(command) 14 | } 15 | 16 | func cmdClean(cmd []string) { 17 | clearView("Chat") 18 | clearView("List") 19 | go populateChat() 20 | go populateList() 21 | } 22 | -------------------------------------------------------------------------------- /cmdShrug.go: -------------------------------------------------------------------------------- 1 | // +ignore 2 | // +build allcommands shrugcmd 3 | 4 | package main 5 | 6 | import "strings" 7 | 8 | func init() { 9 | command := Command{ 10 | Cmd: []string{"shrug", "shrg"}, 11 | Description: "$message - append a shrug ( ¯\\_(ツ)_/¯ )to your message", 12 | Help: "", 13 | Exec: cmdShrug, 14 | } 15 | 16 | RegisterCommand(command) 17 | } 18 | 19 | func cmdShrug(cmd []string) { 20 | cmd = append(cmd, " ¯\\_(ツ)_/¯") 21 | 22 | sendChat(strings.Join(cmd[1:], " ")) 23 | } 24 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/rudi9719/kbtui 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/awesome-gocui/gocui v1.0.1-0.20210720125732-36a608772b4d 7 | github.com/gdamore/tcell/v2 v2.4.0 // indirect 8 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 9 | github.com/magefile/mage v1.11.0 10 | github.com/mattn/go-runewidth v0.0.13 // indirect 11 | github.com/pelletier/go-toml v1.9.1 12 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c // indirect 13 | golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b // indirect 14 | golang.org/x/text v0.3.6 // indirect 15 | samhofi.us/x/keybase v1.0.0 16 | ) 17 | -------------------------------------------------------------------------------- /cmdStream.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands streamcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func init() { 10 | command := Command{ 11 | Cmd: []string{"stream", "s"}, 12 | Description: "- Stream all incoming messages", 13 | Help: "", 14 | Exec: cmdStream, 15 | } 16 | 17 | RegisterCommand(command) 18 | } 19 | 20 | func cmdStream(cmd []string) { 21 | stream = true 22 | channel.Name = "" 23 | 24 | printInfo("You are now viewing the formatted stream") 25 | setViewTitle("Input", fmt.Sprintf(" Stream - Not in a chat. %sj to join ", config.Basics.CmdPrefix)) 26 | clearView("Chat") 27 | } 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /cmdDelete.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands deletecmd 2 | 3 | package main 4 | 5 | import ( 6 | "strconv" 7 | ) 8 | 9 | func init() { 10 | command := Command{ 11 | Cmd: []string{"delete", "del", "-"}, 12 | Description: "$messageId - Delete a message by $messageId", 13 | Help: "", 14 | Exec: cmdDelete, 15 | } 16 | 17 | RegisterCommand(command) 18 | } 19 | func cmdDelete(cmd []string) { 20 | var messageID int 21 | if len(cmd) > 1 { 22 | messageID, _ = strconv.Atoi(cmd[1]) 23 | } else { 24 | messageID = lastMessage.ID 25 | } 26 | 27 | chat := k.NewChat(channel) 28 | _, err := chat.Delete(messageID) 29 | if err != nil { 30 | printError("There was an error deleting your message.") 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /cmdUnfollow.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands followcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func init() { 10 | command := Command{ 11 | Cmd: []string{"unfollow"}, 12 | Description: "$username - Unfollows the given user", 13 | Help: "", 14 | Exec: cmdUnfollow, 15 | } 16 | RegisterCommand(command) 17 | } 18 | 19 | func cmdUnfollow(cmd []string) { 20 | if len(cmd) == 2 { 21 | go unfollow(cmd[1]) 22 | } else { 23 | printUnfollowHelp() 24 | } 25 | } 26 | func unfollow(username string) { 27 | k.Exec("unfollow", username) 28 | printInfoF("Now unfollows $TEXT", config.Colors.Message.LinkKeybase.stylize(username)) 29 | } 30 | 31 | func printUnfollowHelp() { 32 | printInfo(fmt.Sprintf("To unfollow a user use %sunfollow ", config.Basics.CmdPrefix)) 33 | } 34 | -------------------------------------------------------------------------------- /cmdFollow.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands followcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func init() { 10 | command := Command{ 11 | Cmd: []string{"follow"}, 12 | Description: "$username - Follows the given user", 13 | Help: "", 14 | Exec: cmdFollow, 15 | } 16 | RegisterCommand(command) 17 | } 18 | 19 | func cmdFollow(cmd []string) { 20 | if len(cmd) == 2 { 21 | go follow(cmd[1]) 22 | } else { 23 | printFollowHelp() 24 | } 25 | } 26 | func follow(username string) { 27 | k.Exec("follow", username, "-y") 28 | printInfoF("Now follows $TEXT", config.Colors.Message.LinkKeybase.stylize(username)) 29 | followedInSteps[username] = 1 30 | } 31 | 32 | func printFollowHelp() { 33 | printInfo(fmt.Sprintf("To follow a user use %sfollow ", config.Basics.CmdPrefix)) 34 | } 35 | -------------------------------------------------------------------------------- /cmdPost.go: -------------------------------------------------------------------------------- 1 | // +ignore 2 | // +build allcommands postcmd 3 | 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "strings" 9 | 10 | "samhofi.us/x/keybase" 11 | ) 12 | 13 | func init() { 14 | command := Command{ 15 | Cmd: []string{"post"}, 16 | Description: "- Post public messages on your wall", 17 | Help: "", 18 | Exec: cmdPost, 19 | } 20 | 21 | RegisterCommand(command) 22 | } 23 | func cmdPost(cmd []string) { 24 | var pubChan keybase.Channel 25 | pubChan.Public = true 26 | pubChan.MembersType = keybase.USER 27 | pubChan.Name = k.Username 28 | post := strings.Join(cmd[1:], " ") 29 | chat := k.NewChat(pubChan) 30 | _, err := chat.Send(post) 31 | if err != nil { 32 | printError(fmt.Sprintf("There was an error with your post: %+v", err)) 33 | } else { 34 | printInfo("You have publically posted to your wall, signed by your current device.") 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /cmdReply.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands replycmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | command := Command{ 13 | Cmd: []string{"reply", "re"}, 14 | Description: "$messageId $response - Reply to a message", 15 | Help: "", 16 | Exec: cmdReply, 17 | } 18 | 19 | RegisterCommand(command) 20 | } 21 | 22 | func cmdReply(cmd []string) { 23 | chat := k.NewChat(channel) 24 | if len(cmd) < 2 { 25 | printInfo(fmt.Sprintf("%s%s $ID - Reply to message $ID", config.Basics.CmdPrefix, cmd[0])) 26 | return 27 | } 28 | messageID, err := strconv.Atoi(cmd[1]) 29 | if err != nil { 30 | printError(fmt.Sprintf("There was an error determining message ID %s", cmd[1])) 31 | return 32 | } 33 | _, err = chat.Reply(messageID, strings.Join(cmd[2:], " ")) 34 | if err != nil { 35 | printError("There was an error with your reply.") 36 | return 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /cmdHelp.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands helpcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "sort" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | command := Command{ 13 | Cmd: []string{"help", "h"}, 14 | Description: "Show information about available commands", 15 | Help: "", 16 | Exec: cmdHelp, 17 | } 18 | 19 | RegisterCommand(command) 20 | } 21 | 22 | func cmdHelp(cmd []string) { 23 | var helpText string 24 | var tCommands []string 25 | if len(cmd) == 1 { 26 | sort.Strings(baseCommands) 27 | for _, c := range baseCommands { 28 | helpText = fmt.Sprintf("%s%s%s\t\t%s\n", helpText, config.Basics.CmdPrefix, c, commands[c].Description) 29 | } 30 | if len(typeCommands) > 0 { 31 | for c := range typeCommands { 32 | tCommands = append(tCommands, typeCommands[c].Name) 33 | } 34 | sort.Strings(tCommands) 35 | helpText = fmt.Sprintf("%s\nThe following Type Commands are currently loaded: %s", helpText, strings.Join(tCommands, ", ")) 36 | } 37 | } 38 | printToView("Chat", helpText) 39 | } 40 | -------------------------------------------------------------------------------- /cmdReact.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands reactcmd 2 | 3 | package main 4 | 5 | import ( 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | func init() { 11 | command := Command{ 12 | Cmd: []string{"react", "r", "+"}, 13 | Description: "$messageID $reaction - React to a message (messageID is optional)", 14 | Help: "", 15 | Exec: cmdReact, 16 | } 17 | 18 | RegisterCommand(command) 19 | } 20 | 21 | func cmdReact(cmd []string) { 22 | if len(cmd) > 2 { 23 | reactToMessageID(cmd[1], strings.Join(cmd[2:], " ")) 24 | } else if len(cmd) == 2 { 25 | reactToMessage(cmd[1]) 26 | } 27 | 28 | } 29 | 30 | func reactToMessage(reaction string) { 31 | doReact(lastMessage.ID, reaction) 32 | } 33 | func reactToMessageID(messageID string, reaction string) { 34 | ID, _ := strconv.Atoi(messageID) 35 | doReact(ID, reaction) 36 | } 37 | func doReact(messageID int, reaction string) { 38 | chat := k.NewChat(channel) 39 | _, err := chat.React(messageID, reaction) 40 | if err != nil { 41 | printError("There was an error reacting to the message.") 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: [push] 3 | jobs: 4 | build: 5 | strategy: 6 | matrix: 7 | platform: [ubuntu-latest, macos-latest, windows-latest] 8 | name: Build 9 | runs-on: ${{ matrix.platform }} 10 | steps: 11 | 12 | - name: Set up Go 1.13 13 | uses: actions/setup-go@v1 14 | with: 15 | go-version: 1.13 16 | id: go 17 | 18 | - name: Check out code into the Go module directory 19 | uses: actions/checkout@v1 20 | 21 | - name: Get dependencies 22 | run: | 23 | go get -v -t -d ./... 24 | go get github.com/magefile/mage 25 | 26 | - name: Build 27 | run: go run build.go buildbeta 28 | - name: Upload Artifact 29 | if: matrix.platform != 'windows-latest' 30 | uses: actions/upload-artifact@v1.0.0 31 | with: 32 | name: kbtui-${{ matrix.platform }}-buildbeta 33 | path: kbtui 34 | 35 | - name: Upload Artifact 36 | if: matrix.platform == 'windows-latest' 37 | uses: actions/upload-artifact@v1.0.0 38 | with: 39 | name: kbtui-${{ matrix.platform }}-buildbeta 40 | path: kbtui.exe 41 | -------------------------------------------------------------------------------- /tcmdShowReactions.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands type_commands showreactionscmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | 8 | "samhofi.us/x/keybase" 9 | ) 10 | 11 | func init() { 12 | command := TypeCommand{ 13 | Cmd: []string{"reaction"}, 14 | Name: "ShowReactions", 15 | Description: "Prints a message in the feed any time a reaction is received", 16 | Exec: tcmdShowReactions, 17 | } 18 | 19 | RegisterTypeCommand(command) 20 | } 21 | 22 | func tcmdShowReactions(m keybase.ChatAPI) { 23 | team := false 24 | user := colorUsername(m.Msg.Sender.Username) 25 | id := config.Colors.Message.ID.stylize(fmt.Sprintf("%d", m.Msg.Content.Reaction.M)) 26 | reaction := config.Colors.Message.Reaction.stylize(m.Msg.Content.Reaction.B) 27 | where := config.Colors.Message.LinkKeybase.stylize("a PM") 28 | if m.Msg.Channel.MembersType == keybase.TEAM { 29 | team = true 30 | where = formatChannel(m.Msg.Channel) 31 | } else { 32 | } 33 | printInfoF("$TEXT reacted to [$TEXT] with $TEXT in $TEXT", user, id, reaction, where) 34 | if channel.Name == m.Msg.Channel.Name { 35 | if team { 36 | if channel.TopicName == m.Msg.Channel.TopicName { 37 | clearView("Chat") 38 | go populateChat() 39 | } 40 | 41 | } else { 42 | clearView("Chat") 43 | go populateChat() 44 | } 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /cmdExec.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands execcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | func init() { 11 | command := Command{ 12 | Cmd: []string{"exec", "ex"}, 13 | Description: "$keybase args - executes keybase $args and returns the output", 14 | Help: "", 15 | Exec: cmdExec, 16 | } 17 | RegisterCommand(command) 18 | } 19 | 20 | func cmdExec(cmd []string) { 21 | l := len(cmd) 22 | switch { 23 | case l >= 2: 24 | if cmd[1] == "keybase" { 25 | // if the user types /exec keybase wallet list 26 | // only send ["wallet", "list"] 27 | runKeybaseExec(cmd[2:]) 28 | } else { 29 | // send everything except the command 30 | runKeybaseExec(cmd[1:]) 31 | } 32 | case l == 1: 33 | fallthrough 34 | default: 35 | printExecHelp() 36 | } 37 | } 38 | 39 | func runKeybaseExec(args []string) { 40 | outputBytes, err := k.Exec(args...) 41 | if err != nil { 42 | printToView("Feed", fmt.Sprintf("Exec error: %+v", err)) 43 | } else { 44 | channel.Name = "" 45 | // unjoin the chat 46 | clearView("Chat") 47 | setViewTitle("Input", fmt.Sprintf(" /exec %s ", strings.Join(args, " "))) 48 | output := string(outputBytes) 49 | printToView("Chat", fmt.Sprintf("%s", output)) 50 | } 51 | } 52 | 53 | func printExecHelp() { 54 | printInfo(fmt.Sprintf("To execute a keybase command use %sexec ", config.Basics.CmdPrefix)) 55 | } 56 | -------------------------------------------------------------------------------- /cmdUploadFile.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands uploadcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | command := Command{ 13 | Cmd: []string{"upload", "u"}, 14 | Description: "$filePath $fileName - Upload file from absolute path with optional name", 15 | Help: "", 16 | Exec: cmdUploadFile, 17 | } 18 | 19 | RegisterCommand(command) 20 | } 21 | 22 | func cmdUploadFile(cmd []string) { 23 | if len(cmd) < 2 { 24 | printInfo(fmt.Sprintf("%s%s $filePath $fileName - Upload file from absolute path with optional name", config.Basics.CmdPrefix, cmd[0])) 25 | return 26 | } 27 | filePath := cmd[1] 28 | if !strings.HasPrefix(filePath, "/") { 29 | dir, err := os.Getwd() 30 | if err != nil { 31 | printError(fmt.Sprintf("There was an error determining path %+v", err)) 32 | } 33 | filePath = fmt.Sprintf("%s/%s", dir, filePath) 34 | } 35 | var fileName string 36 | if len(cmd) == 3 { 37 | fileName = cmd[2] 38 | } else { 39 | fileName = "" 40 | } 41 | chat := k.NewChat(channel) 42 | _, err := chat.Upload(fileName, filePath) 43 | channelName := config.Colors.Message.LinkKeybase.stylize(channel.Name) 44 | fileNameStylized := config.Colors.Feed.File.stylize(filePath) 45 | if err != nil { 46 | printError(fmt.Sprintf("There was an error uploading %s to %s\n%+v", filePath, channel.Name, err)) 47 | } else { 48 | printInfoF("Uploaded $TEXT to $TEXT", fileNameStylized, channelName) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Welcome to [kbtui](https://keybase.io/team/kbtui)! 2 | An application for those who want to use Keybase, but don't want to leave the comfort of their terminal. 3 | 4 | ## Basic Rules 5 | Thank you for taking the time to contribute to this project! There are two main rules: 6 | * Don't be rude 7 | * Keep it simple, stupid 8 | 9 | There is nothing to be gained by being rude anywhere; contributions to this project are no different. 10 | Also when in doubt, simplify everything. There are other people who are reading, forking, and working on this project. 11 | See the style guidelines below in the [Getting Started](#getting-started) section. 12 | 13 | ## Pull Requests 14 | In order for a PR to be accepted it must be two things: 15 | * Reviewed by [@dxb](https://keybase.io/dxb) or [@rudi9719](https://keybase.io/rudi9719) 16 | * Consistent with the Go formatting guidelines below. 17 | 18 | # Getting Started! 19 | Please read through [Effective Go](https://golang.org/doc/effective_go.html]) and [Style guidelines for go](https://rakyll.org/style-packages/). 20 | If you're having difficulties getting started I suggest you try to [learn go with tests](https://quii.gitbook.io/learn-go-with-tests). 21 | 22 | It might also help to read the godoc for [@dxb's Keybase framework](https://godoc.org/samhofi.us/x/keybase), 23 | as well as the godoc for [gocui](https://godoc.org/github.com/awesome-gocui/gocui), the library we're using for the TUI. 24 | Please note, we're using the awesome-gocui version of gocui. 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /cmdJoin.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands joincmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "samhofi.us/x/keybase" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | command := Command{ 13 | Cmd: []string{"join", "j"}, 14 | Description: "$team/user $channel - Join a chat, $user or $team $channel", 15 | Help: "", 16 | Exec: cmdJoin, 17 | } 18 | 19 | RegisterCommand(command) 20 | } 21 | 22 | func cmdJoin(cmd []string) { 23 | stream = false 24 | switch l := len(cmd); l { 25 | case 3: 26 | fallthrough 27 | case 2: 28 | // if people write it in one singular line, with a `#` 29 | firstArgSplit := strings.Split(cmd[1], "#") 30 | channel.Name = strings.Replace(firstArgSplit[0], "@", "", 1) 31 | joinedName := fmt.Sprintf("@%s", channel.Name) 32 | if l == 3 || len(firstArgSplit) == 2 { 33 | channel.MembersType = keybase.TEAM 34 | if l == 3 { 35 | channel.TopicName = strings.Replace(cmd[2], "#", "", 1) 36 | } else { 37 | channel.TopicName = firstArgSplit[1] 38 | } 39 | joinedName = fmt.Sprintf("%s#%s", joinedName, channel.TopicName) 40 | } else { 41 | channel.TopicName = "" 42 | channel.MembersType = keybase.USER 43 | } 44 | printInfoF("You are joining: $TEXT", config.Colors.Message.LinkKeybase.stylize(joinedName)) 45 | clearView("Chat") 46 | setViewTitle("Input", fmt.Sprintf(" %s ", joinedName)) 47 | lastChat = joinedName 48 | autoScrollView("Chat") 49 | go populateChat() 50 | default: 51 | printInfo(fmt.Sprintf("To join a team use %sjoin ", config.Basics.CmdPrefix)) 52 | printInfo(fmt.Sprintf("To join a PM use %sjoin ", config.Basics.CmdPrefix)) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /userTags.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | var followedInSteps = make(map[string]int) 9 | var trustTreeParent = make(map[string]string) 10 | 11 | func clearFlagCache() { 12 | followedInSteps = make(map[string]int) 13 | trustTreeParent = make(map[string]string) 14 | } 15 | 16 | var maxDepth = 4 17 | 18 | func generateFollowersList() { 19 | // Does a BFS of followedInSteps 20 | queue := []string{k.Username} 21 | printInfo("Generating Tree of Trust...") 22 | lastDepth := 1 23 | for len(queue) > 0 { 24 | head := queue[0] 25 | queue = queue[1:] 26 | depth := followedInSteps[head] + 1 27 | if depth > maxDepth { 28 | continue 29 | } 30 | if depth > lastDepth { 31 | printInfo(fmt.Sprintf("Trust generated at Level #%d", depth-1)) 32 | lastDepth = depth 33 | } 34 | 35 | bytes, _ := k.Exec("list-following", head) 36 | bigString := string(bytes) 37 | following := strings.Split(bigString, "\n") 38 | for _, user := range following { 39 | if followedInSteps[user] == 0 && user != k.Username { 40 | followedInSteps[user] = depth 41 | trustTreeParent[user] = head 42 | queue = append(queue, user) 43 | } 44 | } 45 | } 46 | printInfo(fmt.Sprintf("Trust-level estabilished for %d users", len(followedInSteps))) 47 | } 48 | 49 | func getUserFlags(username string) StyledString { 50 | tags := "" 51 | followDepth := followedInSteps[username] 52 | if followDepth == 1 { 53 | tags += fmt.Sprintf(" %s", config.Formatting.IconFollowingUser) 54 | } else if followDepth > 1 { 55 | tags += fmt.Sprintf(" %s%d", config.Formatting.IconIndirectFollowUser, followDepth-1) 56 | } 57 | return config.Colors.Message.SenderTags.stylize(tags) 58 | } 59 | -------------------------------------------------------------------------------- /cmdDownload.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands downloadcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "strconv" 8 | ) 9 | 10 | func init() { 11 | command := Command{ 12 | Cmd: []string{"download", "d"}, 13 | Description: "$messageId $fileName - Download a file to user's downloadpath", 14 | Help: "", 15 | Exec: cmdDownloadFile, 16 | } 17 | 18 | RegisterCommand(command) 19 | } 20 | 21 | func cmdDownloadFile(cmd []string) { 22 | 23 | if len(cmd) < 2 { 24 | printInfo(fmt.Sprintf("%s%s $messageId $fileName - Download a file to user's downloadpath", config.Basics.CmdPrefix, cmd[0])) 25 | return 26 | } 27 | messageID, err := strconv.Atoi(cmd[1]) 28 | if err != nil { 29 | printError("There was an error converting your messageID to an int") 30 | return 31 | } 32 | chat := k.NewChat(channel) 33 | api, err := chat.ReadMessage(messageID) 34 | if err != nil { 35 | printError(fmt.Sprintf("There was an error pulling message %d", messageID)) 36 | return 37 | } 38 | if api.Result.Messages[0].Msg.Content.Type != "attachment" { 39 | printError("No attachment detected") 40 | return 41 | } 42 | var fileName string 43 | if len(cmd) == 3 { 44 | fileName = cmd[2] 45 | } else { 46 | fileName = api.Result.Messages[0].Msg.Content.Attachment.Object.Filename 47 | } 48 | 49 | _, err = chat.Download(messageID, fmt.Sprintf("%s/%s", config.Basics.DownloadPath, fileName)) 50 | channelName := config.Colors.Message.LinkKeybase.stylize(channel.Name) 51 | fileNameStylizied := config.Colors.Feed.File.stylize(fileName) 52 | if err != nil { 53 | printErrorF("There was an error downloading $TEXT from $TEXT", fileNameStylizied, channelName) 54 | } else { 55 | printInfoF("Downloaded $TEXT from $TEXT", fileNameStylizied, channelName) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /cmdWallet.go: -------------------------------------------------------------------------------- 1 | // ignore 2 | // +build allcommands walletcmd 3 | 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "math/rand" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | var walletConfirmationCode string 14 | var walletConfirmationUser string 15 | var walletTransactionAmnt string 16 | 17 | func init() { 18 | command := Command{ 19 | Cmd: []string{"wallet", "confirm"}, 20 | Description: "$user $amount / $user $confirmation - Send or confirm a wallet payment", 21 | Help: "", 22 | Exec: cmdWallet, 23 | } 24 | 25 | RegisterCommand(command) 26 | } 27 | 28 | func cmdWallet(cmd []string) { 29 | if len(cmd) < 3 { 30 | return 31 | } 32 | if cmd[0] == "wallet" { 33 | rand.Seed(time.Now().UnixNano()) 34 | chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + 35 | "abcdefghijklmnopqrstuvwxyz" + 36 | "0123456789") 37 | length := 8 38 | var b strings.Builder 39 | for i := 0; i < length; i++ { 40 | b.WriteRune(chars[rand.Intn(len(chars))]) 41 | } 42 | walletConfirmationCode = b.String() 43 | walletConfirmationUser = cmd[1] 44 | walletTransactionAmnt = cmd[2] 45 | printInfo(fmt.Sprintf("To confirm sending %s to %s, type /confirm %s %s", cmd[2], cmd[1], cmd[1], walletConfirmationCode)) 46 | 47 | } else if cmd[0] == "confirm" { 48 | if cmd[1] == walletConfirmationUser && cmd[2] == walletConfirmationCode { 49 | txWallet := k.NewWallet() 50 | wAPI, err := txWallet.SendXLM(walletConfirmationUser, walletTransactionAmnt, "") 51 | if err != nil { 52 | printError(fmt.Sprintf("There was an error with your wallet tx:\n\t%+v", err)) 53 | } else { 54 | printInfo(fmt.Sprintf("You have sent %sXLM to %s with tx ID: %s", wAPI.Result.Amount, wAPI.Result.ToUsername, wAPI.Result.TxID)) 55 | } 56 | 57 | } else { 58 | printError("There was an error validating your confirmation. Your wallet has been untouched.") 59 | } 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /cmdEdit.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands editcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | command := Command{ 13 | Cmd: []string{"edit", "e"}, 14 | Description: "$messageID - Edit a message (messageID is optional)", 15 | Help: "", 16 | Exec: cmdEdit, 17 | } 18 | 19 | RegisterCommand(command) 20 | } 21 | 22 | func cmdEdit(cmd []string) { 23 | var messageID int 24 | chat := k.NewChat(channel) 25 | if len(cmd) == 2 || len(cmd) == 1 { 26 | if len(cmd) == 2 { 27 | messageID, _ = strconv.Atoi(cmd[1]) 28 | } else if lastMessage.ID != 0 { 29 | message, _ := chat.ReadMessage(lastMessage.ID) 30 | lastMessage.Type = message.Result.Messages[0].Msg.Content.Type 31 | if lastMessage.Type != "text" { 32 | printError("Last message isn't editable (is it an edit?)") 33 | return 34 | } 35 | messageID = lastMessage.ID 36 | } else { 37 | printError("No message to edit") 38 | return 39 | } 40 | origMessage, _ := chat.ReadMessage(messageID) 41 | if origMessage.Result.Messages[0].Msg.Content.Type != "text" { 42 | printInfo(fmt.Sprintf("%+v", origMessage)) 43 | return 44 | } 45 | if origMessage.Result.Messages[0].Msg.Sender.Username != k.Username { 46 | printError("You cannot edit another user's messages.") 47 | return 48 | } 49 | editString := origMessage.Result.Messages[0].Msg.Content.Text.Body 50 | clearView("Edit") 51 | popupView("Edit") 52 | printToView("Edit", fmt.Sprintf("/e %d %s", messageID, editString)) 53 | setViewTitle("Edit", fmt.Sprintf(" Editing message %d ", messageID)) 54 | moveCursorToEnd("Edit") 55 | return 56 | } 57 | if len(cmd) < 3 { 58 | printError("Not enough options for Edit") 59 | return 60 | } 61 | messageID, _ = strconv.Atoi(cmd[1]) 62 | newMessage := strings.Join(cmd[2:], " ") 63 | _, err := chat.Edit(messageID, newMessage) 64 | if err != nil { 65 | printError(fmt.Sprintf("Error editing message %d, %+v", messageID, err)) 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /cmdConfig.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands setcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | 10 | "github.com/pelletier/go-toml" 11 | ) 12 | 13 | func init() { 14 | command := Command{ 15 | Cmd: []string{"config"}, 16 | Description: "Change various settings", 17 | Help: "", 18 | Exec: cmdConfig, 19 | } 20 | 21 | RegisterCommand(command) 22 | } 23 | 24 | func cmdConfig(cmd []string) { 25 | var err error 26 | switch { 27 | case len(cmd) == 2: 28 | if cmd[1] == "load" { 29 | config, err = readConfig() 30 | if err != nil { 31 | printError(err.Error()) 32 | return 33 | } 34 | printInfoF("Config file loaded: $TEXT", config.Colors.Feed.File.stylize(config.filepath)) 35 | return 36 | } 37 | case len(cmd) > 2: 38 | if cmd[1] == "load" { 39 | config, err = readConfig(cmd[3]) 40 | if err != nil { 41 | printError(err.Error()) 42 | return 43 | } 44 | printInfoF("Config file loaded: $TEXT", config.Colors.Feed.File.stylize(config.filepath)) 45 | return 46 | } 47 | } 48 | printError("Must pass a valid command") 49 | } 50 | 51 | func readConfig(filepath ...string) (*Config, error) { 52 | var result = new(Config) 53 | var configFile, path string 54 | var env bool 55 | 56 | // Load default config first, this way any values missing from the provided config file will remain the default value 57 | d := []byte(defaultConfig) 58 | toml.Unmarshal(d, result) 59 | 60 | switch len(filepath) { 61 | case 0: 62 | configFile, env = os.LookupEnv("KBTUI_CFG") 63 | if !env { 64 | path, env = os.LookupEnv("HOME") 65 | if env { 66 | configFile = path + "/.config/kbtui.toml" 67 | if _, err := os.Stat(configFile); os.IsNotExist(err) { 68 | configFile = "kbtui.toml" 69 | } 70 | } else { 71 | configFile = "kbtui.toml" 72 | } 73 | } 74 | default: 75 | configFile = filepath[0] 76 | if _, err := os.Stat(configFile); os.IsNotExist(err) { 77 | return result, fmt.Errorf("Unable to load config: %s not found", configFile) 78 | } 79 | } 80 | 81 | f, err := ioutil.ReadFile(configFile) 82 | if err != nil { 83 | f = []byte(defaultConfig) 84 | } 85 | 86 | err = toml.Unmarshal(f, result) 87 | if err != nil { 88 | return result, err 89 | } 90 | 91 | result.filepath = configFile 92 | return result, nil 93 | } 94 | -------------------------------------------------------------------------------- /kbtui.toml: -------------------------------------------------------------------------------- 1 | [basics] 2 | download_path = "/tmp/" 3 | colorless = false 4 | unicode_emojis = true 5 | 6 | # The prefix before evaluating a command 7 | cmd_prefix = "/" 8 | 9 | [formatting] 10 | # BASH-like PS1 variable equivalent 11 | output_format = "$REPL┌──[$USER@$DEVICE$TAGS] [$ID] [$DATE - $TIME]\n└╼ $MSG" 12 | output_stream_format = "┌──[$USER@$DEVICE$TAGS] [$ID] [$DATE - $TIME]\n└╼ $MSG" 13 | output_mention_format = "┌──[$USER@$DEVICE$TAGS] [$ID] [$DATE - $TIME]\n└╼ $MSG" 14 | pm_format = "PM from $USER@$DEVICE: $MSG" 15 | 16 | # 02 = Day, Jan = Month, 06 = Year 17 | date_format = "02Jan06" 18 | 19 | # 15 = hours, 04 = minutes, 05 = seconds 20 | time_format = "15:04" 21 | 22 | icon_following_user = "[*]" 23 | icon_indirect_following_user = "[?]" 24 | 25 | [colors] 26 | [colors.channels] 27 | [colors.channels.basic] 28 | foreground = "normal" 29 | [colors.channels.header] 30 | foreground = "magenta" 31 | bold = true 32 | [colors.channels.unread] 33 | foreground = "green" 34 | italic = true 35 | 36 | [colors.message] 37 | [colors.message.body] 38 | foreground = "normal" 39 | [colors.message.header] 40 | foreground = "grey" 41 | bold = true 42 | [colors.message.mention] 43 | foreground = "green" 44 | italic = true 45 | bold = true 46 | [colors.message.id] 47 | foreground = "yellow" 48 | bold = true 49 | [colors.message.time] 50 | foreground = "magenta" 51 | bold = true 52 | [colors.message.sender_default] 53 | foreground = "cyan" 54 | bold = true 55 | [colors.message.sender_device] 56 | foreground = "cyan" 57 | bold = true 58 | [colors.message.sender_tags] 59 | foreground = "yellow" 60 | [colors.message.attachment] 61 | foreground = "red" 62 | [colors.message.link_url] 63 | foreground = "yellow" 64 | [colors.message.link_keybase] 65 | foreground = "cyan" 66 | [colors.message.reaction] 67 | foreground = "magenta" 68 | bold = true 69 | [colors.message.quote] 70 | foreground = "green" 71 | [colors.message.code] 72 | foreground = "cyan" 73 | background = "grey" 74 | 75 | [colors.feed] 76 | [colors.feed.basic] 77 | foreground = "grey" 78 | [colors.feed.error] 79 | foreground = "red" 80 | [colors.feed.success] 81 | foreground = "green" 82 | [colors.feed.file] 83 | foreground = "yellow" 84 | -------------------------------------------------------------------------------- /defaultConfig.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var defaultConfig = ` 4 | [basics] 5 | download_path = "/tmp/" 6 | colorless = false 7 | unicode_emojis = true 8 | 9 | # The prefix before evaluating a command 10 | cmd_prefix = "/" 11 | 12 | [formatting] 13 | # BASH-like PS1 variable equivalent 14 | output_format = "┌──[$USER@$DEVICE$TAGS] [$ID] [$DATE - $TIME]\n└╼ $MSG" 15 | output_stream_format = "┌──[$USER@$DEVICE$TAGS] [$ID] [$DATE - $TIME]\n└╼ $MSG" 16 | output_mention_format = "┌──[$USER@$DEVICE$TAGS] [$ID] [$DATE - $TIME]\n└╼ $MSG" 17 | pm_format = "PM from $USER@$DEVICE: $MSG" 18 | 19 | # 02 = Day, Jan = Month, 06 = Year 20 | date_format = "02Jan06" 21 | 22 | # 15 = hours, 04 = minutes, 05 = seconds 23 | time_format = "15:04" 24 | 25 | icon_following_user = "[*]" 26 | icon_indirect_following_user = "[?]" 27 | 28 | [colors] 29 | [colors.channels] 30 | [colors.channels.basic] 31 | foreground = "normal" 32 | [colors.channels.header] 33 | foreground = "magenta" 34 | bold = true 35 | [colors.channels.unread] 36 | foreground = "green" 37 | italic = true 38 | 39 | [colors.message] 40 | [colors.message.body] 41 | foreground = "normal" 42 | [colors.message.header] 43 | foreground = "grey" 44 | bold = true 45 | [colors.message.mention] 46 | foreground = "green" 47 | italic = true 48 | bold = true 49 | [colors.message.id] 50 | foreground = "yellow" 51 | bold = true 52 | [colors.message.time] 53 | foreground = "magenta" 54 | bold = true 55 | [colors.message.sender_default] 56 | foreground = "cyan" 57 | bold = true 58 | [colors.message.sender_device] 59 | foreground = "cyan" 60 | bold = true 61 | [colors.message.sender_tags] 62 | foreground = "yellow" 63 | [colors.message.attachment] 64 | foreground = "red" 65 | [colors.message.link_url] 66 | foreground = "yellow" 67 | [colors.message.link_keybase] 68 | foreground = "cyan" 69 | [colors.message.reaction] 70 | foreground = "magenta" 71 | bold = true 72 | [colors.message.quote] 73 | foreground = "green" 74 | [colors.message.code] 75 | foreground = "cyan" 76 | background = "grey" 77 | 78 | [colors.feed] 79 | [colors.feed.basic] 80 | foreground = "grey" 81 | [colors.feed.error] 82 | foreground = "red" 83 | [colors.feed.success] 84 | foreground = "green" 85 | [colors.feed.file] 86 | foreground = "yellow" 87 | ` 88 | -------------------------------------------------------------------------------- /mage.go: -------------------------------------------------------------------------------- 1 | // +build mage 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "os" 8 | 9 | "github.com/magefile/mage/mg" 10 | "github.com/magefile/mage/sh" 11 | ) 12 | 13 | func getRemotePackages() error { 14 | var packages = []string{ 15 | "samhofi.us/x/keybase", 16 | "github.com/awesome-gocui/gocui", 17 | "github.com/magefile/mage/mage", 18 | "github.com/magefile/mage/mg", 19 | "github.com/magefile/mage/sh", 20 | "github.com/pelletier/go-toml", 21 | } 22 | for _, p := range packages { 23 | if err := sh.Run("go", "get", "-u", p); err != nil { 24 | return err 25 | } 26 | } 27 | return nil 28 | } 29 | 30 | // proper error reporting and exit code 31 | func exit(err error) { 32 | if err != nil { 33 | fmt.Fprintf(os.Stderr, "%+v\n", err) 34 | os.Exit(1) 35 | } 36 | } 37 | 38 | // Build kbtui with just the basic commands. 39 | func Build() { 40 | mg.Deps(getRemotePackages) 41 | if err := sh.Run("go", "build"); err != nil { 42 | defer func() { 43 | exit(err) 44 | }() 45 | } 46 | } 47 | 48 | // Build kbtui with the basic commands, and the ShowReactions "TypeCommand". 49 | // The ShowReactions TypeCommand will print a message in the feed window when 50 | // a reaction is received in the current conversation. 51 | func BuildShowReactions() { 52 | mg.Deps(getRemotePackages) 53 | if err := sh.Run("go", "build", "-tags", "showreactionscmd"); err != nil { 54 | defer func() { 55 | exit(err) 56 | }() 57 | } 58 | } 59 | 60 | // Build kbtui with the basec commands, and the AutoReact "TypeCommand". 61 | // The AutoReact TypeCommand will automatically react to every message 62 | // received in the current conversation. This gets pretty annoying, and 63 | // is not recommended. 64 | func BuildAutoReact() { 65 | mg.Deps(getRemotePackages) 66 | if err := sh.Run("go", "build", "-tags", "autoreactcmd"); err != nil { 67 | defer func() { 68 | exit(err) 69 | }() 70 | } 71 | } 72 | 73 | // Build kbtui with all commands and TypeCommands disabled. 74 | func BuildAllCommands() { 75 | mg.Deps(getRemotePackages) 76 | if err := sh.Run("go", "build", "-tags", "allcommands"); err != nil { 77 | defer func() { 78 | exit(err) 79 | }() 80 | } 81 | } 82 | 83 | // Build kbtui with all Commands and TypeCommands enabled. 84 | func BuildAllCommandsT() { 85 | mg.Deps(getRemotePackages) 86 | if err := sh.Run("go", "build", "-tags", "type_commands allcommands"); err != nil { 87 | defer func() { 88 | exit(err) 89 | }() 90 | } 91 | } 92 | 93 | // Build kbtui with beta functionality 94 | func BuildBeta() { 95 | mg.Deps(getRemotePackages) 96 | if err := sh.Run("go", "build", "-tags", "allcommands showreactionscmd tabcompletion execcmd"); err != nil { 97 | defer func() { 98 | exit(err) 99 | }() 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /cmdWall.go: -------------------------------------------------------------------------------- 1 | // +ignore 2 | // +build allcommands wallcmd 3 | 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "sort" 9 | "strings" 10 | "time" 11 | 12 | "samhofi.us/x/keybase" 13 | ) 14 | 15 | func init() { 16 | command := Command{ 17 | Cmd: []string{"wall", "w"}, 18 | Description: "$user / !all - Show public messages for a user or all users you follow", 19 | Help: "", 20 | Exec: cmdWall, 21 | } 22 | 23 | RegisterCommand(command) 24 | } 25 | func cmdWall(cmd []string) { 26 | go cmdPopulateWall(cmd) 27 | } 28 | 29 | func cmdPopulateWall(cmd []string) { 30 | var users []keybase.Channel 31 | var requestedUsers string 32 | var printMe []string 33 | var actuallyPrintMe string 34 | result := make(map[int]keybase.ChatAPI) 35 | start := time.Now() 36 | if len(cmd) > 1 { 37 | if cmd[1] == "!all" { 38 | go cmdAllWall() 39 | return 40 | } 41 | for _, username := range cmd[1:] { 42 | requestedUsers += fmt.Sprintf("%s ", username) 43 | var newChan keybase.Channel 44 | newChan.MembersType = keybase.USER 45 | newChan.Name = username 46 | newChan.TopicName = "" 47 | newChan.Public = true 48 | users = append(users, newChan) 49 | } 50 | } else if channel.MembersType == keybase.USER { 51 | users = append(users, channel) 52 | users[0].Public = true 53 | requestedUsers += cleanChannelName(channel.Name) 54 | 55 | } else { 56 | requestedUsers += k.Username 57 | var newChan keybase.Channel 58 | newChan.MembersType = keybase.USER 59 | newChan.Name = k.Username 60 | newChan.TopicName = "" 61 | newChan.Public = true 62 | users = append(users, newChan) 63 | } 64 | if len(users) < 1 { 65 | return 66 | } 67 | 68 | printInfoF("Displaying public messages for user $TEXT", config.Colors.Message.LinkKeybase.stylize(requestedUsers)) 69 | for _, chann := range users { 70 | chat := k.NewChat(chann) 71 | api, err := chat.Read() 72 | if err != nil { 73 | if len(users) < 6 { 74 | printError(fmt.Sprintf("There was an error for user %s: %+v", cleanChannelName(chann.Name), err)) 75 | return 76 | } 77 | } else { 78 | for i, message := range api.Result.Messages { 79 | if message.Msg.Content.Type == "text" { 80 | var apiCast keybase.ChatAPI 81 | apiCast.Msg = &api.Result.Messages[i].Msg 82 | result[apiCast.Msg.SentAt] = apiCast 83 | newMessage := formatOutput(apiCast) 84 | printMe = append(printMe, newMessage.string()) 85 | 86 | } 87 | } 88 | } 89 | 90 | } 91 | 92 | keys := make([]int, 0, len(result)) 93 | for k := range result { 94 | keys = append(keys, k) 95 | } 96 | sort.Ints(keys) 97 | time.Sleep(1 * time.Millisecond) 98 | for _, k := range keys { 99 | actuallyPrintMe += formatOutput(result[k]).string() + "\n" 100 | } 101 | printToView("Chat", fmt.Sprintf("\n\n\n%s\nYour wall query took %s\n\n", actuallyPrintMe, time.Since(start))) 102 | } 103 | func cmdAllWall() { 104 | bytes, _ := k.Exec("list-following") 105 | bigString := string(bytes) 106 | following := strings.Split(bigString, "\n") 107 | go cmdPopulateWall(following) 108 | } 109 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team [@kbtui](https://keybase.io/team/kbtui). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "samhofi.us/x/keybase" 4 | 5 | // Command outlines a command 6 | type Command struct { 7 | Cmd []string // Any aliases that trigger this command 8 | Description string // A short description of the command 9 | Help string // The full help text explaining how to use the command 10 | Exec func([]string) // A function that takes the command (arg[0]) and any arguments (arg[1:]) as input 11 | } 12 | 13 | // TypeCommand outlines a command that reacts on message type 14 | type TypeCommand struct { 15 | Cmd []string // Message types that trigger this command 16 | Name string // The name of this command 17 | Description string // A short description of the command 18 | Exec func(keybase.ChatAPI) // A function that takes a raw chat message as input 19 | } 20 | 21 | // Config holds user-configurable values 22 | type Config struct { 23 | filepath string `toml:"-"` // filepath is not stored in the config file, but is written to the Config struct so it's known where the config was loaded from 24 | Basics Basics `toml:"basics"` 25 | Formatting Formatting `toml:"formatting"` 26 | Colors Colors `toml:"colors"` 27 | } 28 | 29 | // Basics holds the 'basics' section of the config file 30 | type Basics struct { 31 | DownloadPath string `toml:"download_path"` 32 | Colorless bool `toml:"colorless"` 33 | CmdPrefix string `toml:"cmd_prefix"` 34 | UnicodeEmojis bool `toml:"unicode_emojis"` 35 | } 36 | 37 | // Formatting holds the 'formatting' section of the config file 38 | type Formatting struct { 39 | OutputFormat string `toml:"output_format"` 40 | OutputStreamFormat string `toml:"output_stream_format"` 41 | OutputMentionFormat string `toml:"output_mention_format"` 42 | PMFormat string `toml:"pm_format"` 43 | DateFormat string `toml:"date_format"` 44 | TimeFormat string `toml:"time_format"` 45 | IconFollowingUser string `toml:"icon_following_user"` 46 | IconIndirectFollowUser string `toml:"icon_indirect_following_user"` 47 | } 48 | 49 | // Colors holds the 'colors' section of the config file 50 | type Colors struct { 51 | Channels Channels `toml:"channels"` 52 | Message Message `toml:"message"` 53 | Feed Feed `toml:"feed"` 54 | } 55 | 56 | // Style holds basic style information 57 | type Style struct { 58 | Foreground string `toml:"foreground"` 59 | Background string `toml:"background"` 60 | Italic bool `toml:"italic"` 61 | Bold bool `toml:"bold"` 62 | Underline bool `toml:"underline"` 63 | Strikethrough bool `toml:"strikethrough"` 64 | Inverse bool `toml:"inverse"` 65 | } 66 | 67 | // Channels holds the style information for various elements of a channel 68 | type Channels struct { 69 | Basic Style `toml:"basic"` 70 | Header Style `toml:"header"` 71 | Unread Style `toml:"unread"` 72 | } 73 | 74 | // Message holds the style information for various elements of a message 75 | type Message struct { 76 | Body Style `toml:"body"` 77 | Header Style `toml:"header"` 78 | Mention Style `toml:"mention"` 79 | ID Style `toml:"id"` 80 | Tags Style `toml:"tags"` 81 | Time Style `toml:"time"` 82 | SenderDefault Style `toml:"sender_default"` 83 | SenderDevice Style `toml:"sender_device"` 84 | SenderTags Style `toml:"sender_tags"` 85 | Attachment Style `toml:"attachment"` 86 | LinkURL Style `toml:"link_url"` 87 | LinkKeybase Style `toml:"link_keybase"` 88 | Reaction Style `toml:"reaction"` 89 | Quote Style `toml:"quote"` 90 | Code Style `toml:"code"` 91 | } 92 | 93 | // Feed holds the style information for various elements of the feed window 94 | type Feed struct { 95 | Basic Style `toml:"basic"` 96 | Error Style `toml:"error"` 97 | File Style `toml:"file"` 98 | Success Style `toml:"success"` 99 | } 100 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/awesome-gocui/gocui v1.0.0 h1:1bf0DAr2JqWNxGFS8Kex4fM/khICjEnCi+a1+NfWy+w= 2 | github.com/awesome-gocui/gocui v1.0.0/go.mod h1:UvP3dP6+UsTGl9IuqP36wzz6Lemo90wn5p3tJvZ2OqY= 3 | github.com/awesome-gocui/gocui v1.0.1-0.20210720125732-36a608772b4d h1:5TGmGxIeTNcsvqqL1kbcPNP7RMG0wZtvPgmNmqB/UeY= 4 | github.com/awesome-gocui/gocui v1.0.1-0.20210720125732-36a608772b4d/go.mod h1:UvP3dP6+UsTGl9IuqP36wzz6Lemo90wn5p3tJvZ2OqY= 5 | github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= 6 | github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= 7 | github.com/gdamore/tcell/v2 v2.0.0/go.mod h1:vSVL/GV5mCSlPC6thFP5kfOFdM9MGZcalipmpTxTgQA= 8 | github.com/gdamore/tcell/v2 v2.3.5 h1:fSiuoOf40N1w1otj2kQf4IlJ7rI/dcF3zVZL+GRmwuQ= 9 | github.com/gdamore/tcell/v2 v2.3.5/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU= 10 | github.com/gdamore/tcell/v2 v2.4.0 h1:W6dxJEmaxYvhICFoTY3WrLLEXsQ11SaFnKGVEXW57KM= 11 | github.com/gdamore/tcell/v2 v2.4.0/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU= 12 | github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 13 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 14 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 15 | github.com/magefile/mage v1.11.0 h1:C/55Ywp9BpgVVclD3lRnSYCwXTYxmSppIgLeDYlNuls= 16 | github.com/magefile/mage v1.11.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= 17 | github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 18 | github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 19 | github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= 20 | github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= 21 | github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 22 | github.com/pelletier/go-toml v1.9.1 h1:a6qW1EVNZWH9WGI6CsYdD8WAylkoXBS5yv0XHlh17Tc= 23 | github.com/pelletier/go-toml v1.9.1/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= 24 | github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 25 | github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= 26 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 27 | golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 28 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 29 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 30 | golang.org/x/sys v0.0.0-20210601080250-7ecdf8ef093b h1:qh4f65QIVFjq9eBURLEYWqaEXmOyqdUyiBSgaXWccWk= 31 | golang.org/x/sys v0.0.0-20210601080250-7ecdf8ef093b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 32 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 33 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I= 34 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 35 | golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 36 | golang.org/x/term v0.0.0-20210503060354-a79de5458b56 h1:b8jxX3zqjpqb2LklXPzKSGJhzyxCOZSz8ncv8Nv+y7w= 37 | golang.org/x/term v0.0.0-20210503060354-a79de5458b56/go.mod h1:tfny5GFUkzUvx4ps4ajbZsCe5lw1metzhBm9T3x7oIY= 38 | golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE= 39 | golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 40 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 41 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 42 | golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= 43 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 44 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 45 | samhofi.us/x/keybase v1.0.0 h1:ht//EtYMS/hQeZCznA1ibQ515JCKaEkvTD/tarw/9k8= 46 | samhofi.us/x/keybase v1.0.0/go.mod h1:fcva80IUFyWcHtV4bBSzgKg07K6Rvuvi3GtGCLNGkyE= 47 | -------------------------------------------------------------------------------- /cmdInspect.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands inspectcmd 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "regexp" 8 | "samhofi.us/x/keybase" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func init() { 14 | command := Command{ 15 | Cmd: []string{"inspect", "id"}, 16 | Description: "$identifier - shows info about $identifier ($identifier is either username, messageId or team)", 17 | Help: "", 18 | Exec: cmdInspect, 19 | } 20 | 21 | RegisterCommand(command) 22 | } 23 | 24 | func cmdInspect(cmd []string) { 25 | if len(cmd) == 2 { 26 | regexIsNumeric := regexp.MustCompile(`^\d+$`) 27 | if regexIsNumeric.MatchString(cmd[1]) { 28 | // Then it must be a message id 29 | id, _ := strconv.Atoi(cmd[1]) 30 | go printMessage(id) 31 | 32 | } else { 33 | go printUser(strings.Replace(cmd[1], "@", "", -1)) 34 | } 35 | 36 | } else { 37 | printInfo(fmt.Sprintf("To inspect something use %sid ", config.Basics.CmdPrefix)) 38 | } 39 | 40 | } 41 | func printMessage(id int) { 42 | chat := k.NewChat(channel) 43 | messages, err := chat.ReadMessage(id) 44 | if err == nil { 45 | var response StyledString 46 | if messages != nil && len((*messages).Result.Messages) > 0 { 47 | message := (*messages).Result.Messages[0].Msg 48 | var apiCast keybase.ChatAPI 49 | apiCast.Msg = &message 50 | response = formatOutput(apiCast) 51 | } else { 52 | response = config.Colors.Feed.Error.stylize("message not found") 53 | } 54 | printToView("Chat", response.string()) 55 | } 56 | } 57 | 58 | func formatProofs(userLookup keybase.UserAPI) StyledString { 59 | messageColor := config.Colors.Message 60 | message := basicStyle.stylize("") 61 | for _, proof := range userLookup.Them[0].ProofsSummary.All { 62 | style := config.Colors.Feed.Success 63 | if proof.State != 1 { 64 | style = config.Colors.Feed.Error 65 | } 66 | proofString := style.stylize("Proof [$NAME@$SITE]: $URL\n") 67 | proofString = proofString.replace("$NAME", messageColor.SenderDefault.stylize(proof.Nametag)) 68 | proofString = proofString.replace("$SITE", messageColor.SenderDevice.stylize(proof.ProofType)) 69 | proofString = proofString.replace("$URL", messageColor.LinkURL.stylize(proof.HumanURL)) 70 | message = message.append(proofString) 71 | } 72 | return message.appendString("\n") 73 | } 74 | func formatProfile(userLookup keybase.UserAPI) StyledString { 75 | messageColor := config.Colors.Message 76 | user := userLookup.Them[0] 77 | profileText := messageColor.Body.stylize("Name: $FNAME\nLocation: $LOC\nBio: $BIO\n") 78 | profileText = profileText.replaceString("$FNAME", user.Profile.FullName) 79 | profileText = profileText.replaceString("$LOC", user.Profile.Location) 80 | profileText = profileText.replaceString("$BIO", user.Profile.Bio) 81 | 82 | return profileText 83 | } 84 | 85 | func formatFollowState(userLookup keybase.UserAPI) StyledString { 86 | username := userLookup.Them[0].Basics.Username 87 | followSteps := followedInSteps[username] 88 | if followSteps == 1 { 89 | return config.Colors.Feed.Success.stylize("\n\n") 90 | } else if followSteps > 1 { 91 | var steps []string 92 | for head := username; head != ""; head = trustTreeParent[head] { 93 | steps = append(steps, fmt.Sprintf("[%s]", head)) 94 | } 95 | trustLine := fmt.Sprintf("Indirect follow: <%s>\n\n", strings.Join(steps, " Followed by ")) 96 | return config.Colors.Message.Body.stylize(trustLine) 97 | } 98 | 99 | return basicStyle.stylize("") 100 | 101 | } 102 | 103 | func formatFollowerAndFollowedList(username string, listType string) StyledString { 104 | messageColor := config.Colors.Message 105 | response := basicStyle.stylize("") 106 | bytes, _ := k.Exec("list-"+listType, username) 107 | bigString := string(bytes) 108 | lines := strings.Split(bigString, "\n") 109 | response = response.appendString(fmt.Sprintf("%s (%d): ", listType, len(lines)-1)) 110 | for i, user := range lines[:len(lines)-1] { 111 | if i != 0 { 112 | response = response.appendString(", ") 113 | } 114 | response = response.append(messageColor.LinkKeybase.stylize(user)) 115 | response = response.append(getUserFlags(user)) 116 | } 117 | return response.appendString("\n\n") 118 | } 119 | 120 | func printUser(username string) { 121 | messageColor := config.Colors.Message 122 | 123 | userLookup, _ := k.UserLookup(username) 124 | 125 | response := messageColor.Header.stylize("[Inspecting `$USER`]\n") 126 | response = response.replace("$USER", messageColor.SenderDefault.stylize(username)) 127 | response = response.append(formatProfile(userLookup)) 128 | response = response.append(formatFollowState(userLookup)) 129 | 130 | response = response.append(formatProofs(userLookup)) 131 | response = response.append(formatFollowerAndFollowedList(username, "followers")) 132 | response = response.append(formatFollowerAndFollowedList(username, "following")) 133 | 134 | printToView("Chat", response.string()) 135 | } 136 | -------------------------------------------------------------------------------- /colors.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | "strings" 7 | ) 8 | 9 | const ( 10 | black int = iota 11 | red 12 | green 13 | yellow 14 | purple 15 | magenta 16 | cyan 17 | grey 18 | normal int = -1 19 | ) 20 | 21 | var colorMapString = map[string]int{ 22 | "black": black, 23 | "red": red, 24 | "green": green, 25 | "yellow": yellow, 26 | "purple": purple, 27 | "magenta": magenta, 28 | "cyan": cyan, 29 | "grey": grey, 30 | "normal": normal, 31 | } 32 | 33 | var colorMapInt = map[int]string{ 34 | black: "black", 35 | red: "red", 36 | green: "green", 37 | yellow: "yellow", 38 | purple: "purple", 39 | magenta: "magenta", 40 | cyan: "cyan", 41 | grey: "grey", 42 | normal: "normal", 43 | } 44 | 45 | func colorFromString(color string) int { 46 | var result int 47 | color = strings.ToLower(color) 48 | result, ok := colorMapString[color] 49 | if !ok { 50 | return normal 51 | } 52 | return result 53 | } 54 | 55 | func colorFromInt(color int) string { 56 | var result string 57 | result, ok := colorMapInt[color] 58 | if !ok { 59 | return "normal" 60 | } 61 | return result 62 | } 63 | 64 | var basicStyle = Style{ 65 | Foreground: colorMapInt[normal], 66 | Background: colorMapInt[normal], 67 | Italic: false, 68 | Bold: false, 69 | Underline: false, 70 | Strikethrough: false, 71 | Inverse: false, 72 | } 73 | 74 | func (s Style) withForeground(color int) Style { 75 | s.Foreground = colorFromInt(color) 76 | return s 77 | } 78 | func (s Style) withBackground(color int) Style { 79 | s.Background = colorFromInt(color) 80 | return s 81 | } 82 | 83 | func (s Style) withBold() Style { 84 | s.Bold = true 85 | return s 86 | } 87 | func (s Style) withInverse() Style { 88 | s.Inverse = true 89 | return s 90 | } 91 | func (s Style) withItalic() Style { 92 | s.Italic = true 93 | return s 94 | } 95 | func (s Style) withStrikethrough() Style { 96 | s.Strikethrough = true 97 | return s 98 | } 99 | func (s Style) withUnderline() Style { 100 | s.Underline = true 101 | return s 102 | } 103 | 104 | // TODO create both as `reset` (which it is now) as well as `append` 105 | // which essentially just adds on top. that is relevant in the case of 106 | // bold/italic etc - it should add style - not clear. 107 | func (s Style) toANSI() string { 108 | if config.Basics.Colorless { 109 | return "" 110 | } 111 | styleSlice := []string{"0"} 112 | 113 | if colorFromString(s.Foreground) != normal { 114 | styleSlice = append(styleSlice, fmt.Sprintf("%d", 30+colorFromString(s.Foreground))) 115 | } 116 | if colorFromString(s.Background) != normal { 117 | styleSlice = append(styleSlice, fmt.Sprintf("%d", 40+colorFromString(s.Background))) 118 | } 119 | if s.Bold { 120 | styleSlice = append(styleSlice, "1") 121 | } 122 | if s.Italic { 123 | styleSlice = append(styleSlice, "3") 124 | } 125 | if s.Underline { 126 | styleSlice = append(styleSlice, "4") 127 | } 128 | if s.Inverse { 129 | styleSlice = append(styleSlice, "7") 130 | } 131 | if s.Strikethrough { 132 | styleSlice = append(styleSlice, "9") 133 | } 134 | 135 | return "\x1b[" + strings.Join(styleSlice, ";") + "m" 136 | } 137 | 138 | // End Colors 139 | // Begin StyledString 140 | 141 | // StyledString is used to save a message with a style, which can then later be rendered to a string 142 | type StyledString struct { 143 | message string 144 | style Style 145 | } 146 | 147 | func (ss StyledString) withStyle(style Style) StyledString { 148 | return StyledString{ss.message, style} 149 | } 150 | 151 | // TODO change StyledString to have styles at start-end indexes. 152 | 153 | // TODO handle all formatting types 154 | func (s Style) sprintf(base string, parts ...StyledString) StyledString { 155 | text := s.stylize(removeFormatting(base)) 156 | //TODO handle posibility to escape 157 | re := regexp.MustCompile(`\$TEXT`) 158 | for len(re.FindAllString(text.message, 1)) > 0 { 159 | part := parts[0] 160 | parts = parts[1:] 161 | text = text.replaceN("$TEXT", part, 1) 162 | } 163 | return text 164 | } 165 | 166 | func (s Style) stylize(msg string) StyledString { 167 | return StyledString{msg, s} 168 | } 169 | func (ss StyledString) stringFollowedByStyle(style Style) string { 170 | return ss.style.toANSI() + ss.message + style.toANSI() 171 | } 172 | func (ss StyledString) string() string { 173 | return ss.stringFollowedByStyle(basicStyle) 174 | } 175 | 176 | func (ss StyledString) replace(match string, value StyledString) StyledString { 177 | return ss.replaceN(match, value, -1) 178 | } 179 | func (ss StyledString) replaceN(match string, value StyledString, n int) StyledString { 180 | ss.message = strings.Replace(ss.message, match, value.stringFollowedByStyle(ss.style), n) 181 | return ss 182 | } 183 | func (ss StyledString) replaceString(match string, value string) StyledString { 184 | ss.message = strings.Replace(ss.message, match, value, -1) 185 | return ss 186 | } 187 | 188 | // Overrides current formatting 189 | func (ss StyledString) colorRegex(match string, style Style) StyledString { 190 | return ss.regexReplaceFunc(match, func(subString string) string { 191 | return style.stylize(removeFormatting(subString)).stringFollowedByStyle(ss.style) 192 | }) 193 | } 194 | 195 | // Replacer function takes the current match as input and should return how the match should be preseneted instead 196 | func (ss StyledString) regexReplaceFunc(match string, replacer func(string) string) StyledString { 197 | re := regexp.MustCompile(match) 198 | locations := re.FindAllStringIndex(ss.message, -1) 199 | var newMessage string 200 | var prevIndex int 201 | for _, loc := range locations { 202 | newSubstring := replacer(ss.message[loc[0]:loc[1]]) 203 | newMessage += ss.message[prevIndex:loc[0]] 204 | newMessage += newSubstring 205 | prevIndex = loc[1] 206 | } 207 | // Append any string after the final match 208 | newMessage += ss.message[prevIndex:len(ss.message)] 209 | ss.message = newMessage 210 | return ss 211 | } 212 | 213 | // Appends the other stylize at the end, but retains same style 214 | func (ss StyledString) append(other StyledString) StyledString { 215 | ss.message = ss.message + other.stringFollowedByStyle(ss.style) 216 | return ss 217 | } 218 | func (ss StyledString) appendString(other string) StyledString { 219 | ss.message += other 220 | return ss 221 | } 222 | 223 | // Begin Formatting 224 | 225 | func removeFormatting(s string) string { 226 | reFormatting := regexp.MustCompile(`(?m)\x1b\[(\d*;?)*m`) 227 | return reFormatting.ReplaceAllString(s, "") 228 | } 229 | -------------------------------------------------------------------------------- /tabComplete.go: -------------------------------------------------------------------------------- 1 | // +build !rm_basic_commands allcommands tabcompletion 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "regexp" 8 | "strings" 9 | 10 | "samhofi.us/x/keybase" 11 | ) 12 | 13 | var ( 14 | tabSlice []string 15 | commandSlice []string 16 | ) 17 | 18 | // This defines the handleTab function thats called by key bindind tab for the input control. 19 | func handleTab(viewName string) error { 20 | inputString, err := getInputString(viewName) 21 | if err != nil { 22 | return err 23 | } 24 | // if you successfully get an input string, grab the last word from the string 25 | ss := regexp.MustCompile(`[ #]`).Split(inputString, -1) 26 | s := ss[len(ss)-1] 27 | // create a variable in which to store the result 28 | var resultSlice []string 29 | // if the word starts with a : its an emoji lookup 30 | if strings.HasPrefix(s, ":") { 31 | resultSlice = getEmojiTabCompletionSlice(s) 32 | } else if strings.HasPrefix(s, "/") { 33 | generateCommandTabCompletionSlice() 34 | s = strings.Replace(s, "/", "", 1) 35 | resultSlice = getCommandTabCompletionSlice(s) 36 | } else { 37 | if strings.HasPrefix(s, "@") { 38 | // now in case the word (s) is a mention @something, lets remove it to normalize 39 | s = strings.Replace(s, "@", "", 1) 40 | } 41 | // now call get the list of all possible cantidates that have that as a prefix 42 | resultSlice = getChannelTabCompletionSlice(s) 43 | } 44 | rLen := len(resultSlice) 45 | lcp := longestCommonPrefix(resultSlice) 46 | if lcp != "" { 47 | originalViewTitle := getViewTitle("Input") 48 | newViewTitle := "" 49 | if rLen >= 1 && originalViewTitle != "" { 50 | if rLen == 1 { 51 | newViewTitle = originalViewTitle 52 | } else if rLen <= 5 { 53 | newViewTitle = fmt.Sprintf("%s|| %s", originalViewTitle, strings.Join(resultSlice, " ")) 54 | } else if rLen > 5 { 55 | newViewTitle = fmt.Sprintf("%s|| %s +%d more", originalViewTitle, strings.Join(resultSlice[:6], " "), rLen-5) 56 | } 57 | setViewTitle(viewName, newViewTitle) 58 | remainder := stringRemainder(s, lcp) 59 | writeToView(viewName, remainder) 60 | } 61 | } 62 | 63 | return nil 64 | } 65 | 66 | // Main tab completion functions 67 | func getEmojiTabCompletionSlice(inputWord string) []string { 68 | // use the emojiSlice from emojiList.go and filter it for the input word 69 | //resultSlice := filterStringSlice(emojiSlice, inputWord) 70 | resultSlice := filterEmojiMap(emojiMap, inputWord) 71 | return resultSlice 72 | } 73 | func getChannelTabCompletionSlice(inputWord string) []string { 74 | // use the tabSlice from above and filter it for the input word 75 | resultSlice := filterStringSlice(tabSlice, inputWord) 76 | return resultSlice 77 | } 78 | func getCommandTabCompletionSlice(inputWord string) []string { 79 | // use the commandSlice from above and filter it for the input word 80 | resultSlice := filterStringSlice(commandSlice, inputWord) 81 | return resultSlice 82 | } 83 | 84 | //Generator Functions (should be called externally when chat/list/join changes 85 | func generateChannelTabCompletionSlice() { 86 | // fetch all members of the current channel and add them to the slice 87 | channelSlice := getCurrentChannelMembership() 88 | for _, m := range channelSlice { 89 | tabSlice = appendIfNotInSlice(tabSlice, m) 90 | } 91 | } 92 | func generateCommandTabCompletionSlice() { 93 | // get the maps of all built commands - this should only need to be done on startup 94 | // removing typeCommands for now, since they aren't actually commands you can type - contrary to the naming 95 | /*for commandString1 := range typeCommands { 96 | commandSlice = appendIfNotInSlice(commandSlice, commandString1) 97 | }*/ 98 | for commandString2 := range commands { 99 | commandSlice = appendIfNotInSlice(commandSlice, commandString2) 100 | } 101 | for _, commandString3 := range baseCommands { 102 | commandSlice = appendIfNotInSlice(commandSlice, commandString3) 103 | } 104 | } 105 | func generateRecentTabCompletionSlice() { 106 | var recentSlice []string 107 | for _, s := range channels { 108 | if s.MembersType == keybase.TEAM { 109 | // its a team so add the topic name and channel name 110 | recentSlice = appendIfNotInSlice(recentSlice, s.TopicName) 111 | recentSlice = appendIfNotInSlice(recentSlice, s.Name) 112 | } else { 113 | //its a user, so clean the name and append 114 | recentSlice = appendIfNotInSlice(recentSlice, cleanChannelName(s.Name)) 115 | } 116 | } 117 | for _, s := range recentSlice { 118 | tabSlice = appendIfNotInSlice(tabSlice, s) 119 | } 120 | } 121 | 122 | // Helper functions 123 | func getCurrentChannelMembership() []string { 124 | var rs []string 125 | if channel.Name != "" { 126 | t := k.NewTeam(channel.Name) 127 | testVar, err := t.MemberList() 128 | if err != nil { 129 | return rs // then this isn't a team, its a PM or there was an error in the API call 130 | } 131 | for _, m := range testVar.Result.Members.Owners { 132 | rs = append(rs, fmt.Sprintf("%+v", m.Username)) 133 | } 134 | for _, m := range testVar.Result.Members.Admins { 135 | rs = append(rs, fmt.Sprintf("%+v", m.Username)) 136 | } 137 | for _, m := range testVar.Result.Members.Writers { 138 | rs = append(rs, fmt.Sprintf("%+v", m.Username)) 139 | } 140 | for _, m := range testVar.Result.Members.Readers { 141 | rs = append(rs, fmt.Sprintf("%+v", m.Username)) 142 | } 143 | 144 | } 145 | return rs 146 | } 147 | func filterStringSlice(ss []string, fv string) []string { 148 | var rs []string 149 | for _, s := range ss { 150 | if strings.HasPrefix(s, fv) { 151 | rs = append(rs, s) 152 | } 153 | } 154 | return rs 155 | } 156 | func filterEmojiMap(eMap map[string]emojiData, fv string) []string { 157 | var rs []string 158 | for k, _ := range eMap { 159 | if strings.HasPrefix(k, fv) { 160 | rs = append(rs, k) 161 | } 162 | } 163 | return rs 164 | } 165 | func longestCommonPrefix(ss []string) string { 166 | // cover the case where the slice has no or one members 167 | switch len(ss) { 168 | case 0: 169 | return "" 170 | case 1: 171 | return ss[0] 172 | } 173 | // all strings are compared by bytes here forward (TBD unicode normalization?) 174 | // establish min, max lenth members of the slice by iterating over the members 175 | min, max := ss[0], ss[0] 176 | for _, s := range ss[1:] { 177 | switch { 178 | case s < min: 179 | min = s 180 | case s > max: 181 | max = s 182 | } 183 | } 184 | // then iterate over the characters from min to max, as soon as chars don't match return 185 | for i := 0; i < len(min) && i < len(max); i++ { 186 | if min[i] != max[i] { 187 | return min[:i] 188 | } 189 | } 190 | // to cover the case where all members are equal, just return one 191 | return min 192 | } 193 | func stringRemainder(aStr, bStr string) string { 194 | var long, short string 195 | //figure out which string is longer 196 | switch { 197 | case len(aStr) < len(bStr): 198 | short = aStr 199 | long = bStr 200 | default: 201 | short = bStr 202 | long = aStr 203 | } 204 | // iterate over the strings using an external iterator so we don't lose the value 205 | i := 0 206 | for i < len(short) && i < len(long) { 207 | if short[i] != long[i] { 208 | // the strings aren't equal so don't return anything 209 | return "" 210 | } 211 | i++ 212 | } 213 | // return whatever's left of the longer string 214 | return long[i:] 215 | } 216 | func appendIfNotInSlice(ss []string, s string) []string { 217 | for _, element := range ss { 218 | if element == s { 219 | return ss 220 | } 221 | } 222 | return append(ss, s) 223 | } 224 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "sort" 8 | "strings" 9 | "time" 10 | 11 | "github.com/awesome-gocui/gocui" 12 | "samhofi.us/x/keybase" 13 | "unicode/utf8" 14 | ) 15 | 16 | var ( 17 | typeCommands = make(map[string]TypeCommand) 18 | commands = make(map[string]Command) 19 | baseCommands = make([]string, 0) 20 | 21 | dev = false 22 | k = keybase.NewKeybase() 23 | channel keybase.Channel 24 | channels []keybase.Channel 25 | stream = false 26 | lastMessage keybase.ChatAPI 27 | lastChat = "" 28 | g *gocui.Gui 29 | ) 30 | 31 | var config *Config 32 | 33 | func main() { 34 | if !k.LoggedIn { 35 | fmt.Println("You are not logged in.") 36 | return 37 | } 38 | var err error 39 | g, err = gocui.NewGui(gocui.OutputNormal, false) 40 | if err != nil { 41 | fmt.Printf("%+v", err) 42 | } 43 | defer g.Close() 44 | g.SetManagerFunc(layout) 45 | RunCommand("config", "load") 46 | go populateList() 47 | go updateChatWindow() 48 | if len(os.Args) > 1 { 49 | os.Args[0] = "join" 50 | RunCommand(os.Args...) 51 | 52 | } 53 | fmt.Println("initKeybindings") 54 | if err := initKeybindings(); err != nil { 55 | fmt.Printf("%+v", err) 56 | } 57 | if err := g.MainLoop(); err != nil && err != gocui.ErrQuit { 58 | fmt.Printf("%+v", err) 59 | } 60 | go generateChannelTabCompletionSlice() 61 | } 62 | 63 | // Gocui basic setup 64 | func layout(g *gocui.Gui) error { 65 | maxX, maxY := g.Size() 66 | if editView, err := g.SetView("Edit", maxX/2-maxX/3+1, maxY/2, maxX-2, maxY/2+10, 0); err != nil { 67 | if err != gocui.ErrUnknownView { 68 | return err 69 | } 70 | editView.Editable = true 71 | editView.Wrap = true 72 | fmt.Fprintln(editView, "Edit window. Should disappear") 73 | } 74 | if feedView, err := g.SetView("Feed", maxX/2-maxX/3, 0, maxX-1, maxY/5, 0); err != nil { 75 | if err != gocui.ErrUnknownView { 76 | return err 77 | } 78 | feedView.Autoscroll = true 79 | feedView.Wrap = true 80 | feedView.Title = "Feed Window" 81 | printInfo("Feed Window - If you are mentioned or receive a PM it will show here") 82 | } 83 | if chatView, err2 := g.SetView("Chat", maxX/2-maxX/3, maxY/5+1, maxX-1, maxY-5, 0); err2 != nil { 84 | if err2 != gocui.ErrUnknownView { 85 | return err2 86 | } 87 | chatView.Autoscroll = true 88 | chatView.Wrap = true 89 | welcomeText := basicStyle.stylize("Welcome $USER!\n\nYour chats will appear here.\nSupported commands are as follows:\n") 90 | welcomeText = welcomeText.replace("$USER", config.Colors.Message.Mention.stylize(k.Username)) 91 | fmt.Fprintln(chatView, welcomeText.string()) 92 | RunCommand("help") 93 | } 94 | if inputView, err3 := g.SetView("Input", maxX/2-maxX/3, maxY-4, maxX-1, maxY-1, 0); err3 != nil { 95 | if err3 != gocui.ErrUnknownView { 96 | return err3 97 | } 98 | if _, err := g.SetCurrentView("Input"); err != nil { 99 | return err 100 | } 101 | inputView.Editable = true 102 | inputView.Wrap = true 103 | inputView.Title = fmt.Sprintf(" Not in a chat - write `%sj` to join", config.Basics.CmdPrefix) 104 | g.Cursor = true 105 | } 106 | if listView, err4 := g.SetView("List", 0, 0, maxX/2-maxX/3-1, maxY-1, 0); err4 != nil { 107 | if err4 != gocui.ErrUnknownView { 108 | return err4 109 | } 110 | listView.Title = "Channels" 111 | fmt.Fprintf(listView, "Lists\nWindow\nTo view\n activity") 112 | } 113 | return nil 114 | } 115 | func scrollViewUp(v *gocui.View) error { 116 | scrollView(v, -1) 117 | return nil 118 | } 119 | func scrollViewDown(v *gocui.View) error { 120 | scrollView(v, 1) 121 | return nil 122 | } 123 | func scrollView(v *gocui.View, delta int) error { 124 | if v != nil { 125 | _, y := v.Size() 126 | ox, oy := v.Origin() 127 | if oy+delta > strings.Count(v.ViewBuffer(), "\n")-y { 128 | v.Autoscroll = true 129 | } else { 130 | v.Autoscroll = false 131 | if err := v.SetOrigin(ox, oy+delta); err != nil { 132 | return err 133 | } 134 | } 135 | } 136 | return nil 137 | } 138 | func autoScrollView(vn string) error { 139 | v, err := g.View(vn) 140 | if err != nil { 141 | return err 142 | } else if v != nil { 143 | v.Autoscroll = true 144 | } 145 | return nil 146 | } 147 | func initKeybindings() error { 148 | if err := g.SetKeybinding("", gocui.KeyPgup, gocui.ModNone, 149 | func(g *gocui.Gui, v *gocui.View) error { 150 | cv, _ := g.View("Chat") 151 | err := scrollViewUp(cv) 152 | if err != nil { 153 | return err 154 | } 155 | return nil 156 | }); err != nil { 157 | return err 158 | } 159 | if err := g.SetKeybinding("", gocui.KeyPgdn, gocui.ModNone, 160 | func(g *gocui.Gui, v *gocui.View) error { 161 | cv, _ := g.View("Chat") 162 | err := scrollViewDown(cv) 163 | if err != nil { 164 | return err 165 | } 166 | return nil 167 | }); err != nil { 168 | return err 169 | } 170 | if err := g.SetKeybinding("", gocui.KeyEsc, gocui.ModNone, 171 | func(g *gocui.Gui, v *gocui.View) error { 172 | autoScrollView("Chat") 173 | return nil 174 | }); err != nil { 175 | return err 176 | } 177 | if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, 178 | func(g *gocui.Gui, v *gocui.View) error { 179 | input, err := getInputString("Input") 180 | if err != nil { 181 | return err 182 | } 183 | if input != "" { 184 | clearView("Input") 185 | return nil 186 | } 187 | return gocui.ErrQuit 188 | }); err != nil { 189 | return err 190 | } 191 | if err := g.SetKeybinding("", gocui.KeyCtrlZ, gocui.ModNone, 192 | func(g *gocui.Gui, v *gocui.View) error { 193 | cmdJoin([]string{"/join", lastChat}) 194 | return nil 195 | }); err != nil { 196 | return err 197 | } 198 | if err := g.SetKeybinding("Edit", gocui.KeyCtrlC, gocui.ModNone, 199 | func(g *gocui.Gui, v *gocui.View) error { 200 | popupView("Chat") 201 | popupView("Input") 202 | clearView("Edit") 203 | return nil 204 | }); err != nil { 205 | return err 206 | } 207 | if err := g.SetKeybinding("Input", gocui.KeyEnter, gocui.ModNone, 208 | func(g *gocui.Gui, v *gocui.View) error { 209 | return handleInput("Input") 210 | }); err != nil { 211 | return err 212 | } 213 | if err := g.SetKeybinding("Input", gocui.KeyTab, gocui.ModNone, 214 | func(g *gocui.Gui, v *gocui.View) error { 215 | return handleTab("Input") 216 | }); err != nil { 217 | return err 218 | } 219 | if err := g.SetKeybinding("Edit", gocui.KeyEnter, gocui.ModNone, 220 | func(g *gocui.Gui, v *gocui.View) error { 221 | popupView("Chat") 222 | popupView("Input") 223 | return handleInput("Edit") 224 | 225 | }); err != nil { 226 | return err 227 | } 228 | if err := g.SetKeybinding("Input", gocui.KeyArrowUp, gocui.ModNone, 229 | func(g *gocui.Gui, v *gocui.View) error { 230 | RunCommand("edit") 231 | return nil 232 | }); err != nil { 233 | return err 234 | } 235 | return nil 236 | } 237 | 238 | // End gocui basic setup 239 | 240 | // Gocui helper funcs 241 | func setViewTitle(viewName string, title string) { 242 | g.Update(func(g *gocui.Gui) error { 243 | updatingView, err := g.View(viewName) 244 | if err != nil { 245 | return err 246 | } 247 | updatingView.Title = title 248 | return nil 249 | }) 250 | } 251 | func getViewTitle(viewName string) string { 252 | view, err := g.View(viewName) 253 | if err != nil { 254 | // in case there is active tab completion, filter that to just the view title and not the completion options. 255 | printError(fmt.Sprintf("Error getting view title: %s", err)) 256 | return "" 257 | } 258 | return strings.Split(view.Title, "||")[0] 259 | } 260 | func popupView(viewName string) { 261 | _, err := g.SetCurrentView(viewName) 262 | if err != nil { 263 | printError(fmt.Sprintf("%+v", err)) 264 | } 265 | _, err = g.SetViewOnTop(viewName) 266 | if err != nil { 267 | printError(fmt.Sprintf("%+v", err)) 268 | } 269 | g.Update(func(g *gocui.Gui) error { 270 | updatingView, err := g.View(viewName) 271 | if err != nil { 272 | return err 273 | } 274 | updatingView.MoveCursor(0, 0) 275 | 276 | return nil 277 | 278 | }) 279 | } 280 | func moveCursorToEnd(viewName string) { 281 | g.Update(func(g *gocui.Gui) error { 282 | inputView, err := g.View(viewName) 283 | if err != nil { 284 | return err 285 | } 286 | inputString, _ := getInputString(viewName) 287 | stringLen := len(inputString) 288 | maxX, _ := inputView.Size() 289 | x := stringLen % maxX 290 | y := stringLen / maxX 291 | inputView.SetCursor(0, 0) 292 | inputView.SetOrigin(0, 0) 293 | inputView.MoveCursor(x, y) 294 | return nil 295 | 296 | }) 297 | } 298 | func clearView(viewName string) { 299 | g.Update(func(g *gocui.Gui) error { 300 | inputView, err := g.View(viewName) 301 | if err != nil { 302 | return err 303 | } 304 | inputView.Clear() 305 | inputView.SetCursor(0, 0) 306 | inputView.SetOrigin(0, 0) 307 | 308 | return nil 309 | }) 310 | 311 | } 312 | func writeToView(viewName string, message string) { 313 | g.Update(func(g *gocui.Gui) error { 314 | updatingView, err := g.View(viewName) 315 | if err != nil { 316 | return err 317 | } 318 | for _, c := range message { 319 | updatingView.EditWrite(c) 320 | } 321 | 322 | return nil 323 | }) 324 | } 325 | 326 | // this removes formatting 327 | func printError(message string) { 328 | printErrorF(message) 329 | } 330 | func printErrorF(message string, parts ...StyledString) { 331 | printToView("Feed", config.Colors.Feed.Error.sprintf(removeFormatting(message), parts...).string()) 332 | } 333 | 334 | // this removes formatting 335 | func printInfo(message string) { 336 | printInfoF(message) 337 | } 338 | func printInfoStyledString(message StyledString) { 339 | printInfoF("$TEXT", message) 340 | } 341 | 342 | // this removes formatting 343 | func printInfoF(message string, parts ...StyledString) { 344 | printToView("Feed", config.Colors.Feed.Basic.sprintf(removeFormatting(message), parts...).string()) 345 | } 346 | func printToView(viewName string, message string) { 347 | g.Update(func(g *gocui.Gui) error { 348 | updatingView, err := g.View(viewName) 349 | if err != nil { 350 | return err 351 | } 352 | 353 | if config.Basics.UnicodeEmojis { 354 | message = emojiUnicodeConvert(message) 355 | } 356 | fmt.Fprintf(updatingView, "%s\n", message) 357 | return nil 358 | }) 359 | } 360 | 361 | // End gocui helper funcs 362 | 363 | // Update/Populate views automatically 364 | func updateChatWindow() { 365 | 366 | runOpts := keybase.RunOptions{ 367 | Dev: dev, 368 | } 369 | k.Run(func(api keybase.ChatAPI) { 370 | handleMessage(api) 371 | }, 372 | runOpts) 373 | 374 | } 375 | func populateChat() { 376 | lastMessage.ID = 0 377 | chat := k.NewChat(channel) 378 | maxX, _ := g.Size() 379 | api, err := chat.Read(maxX / 2) 380 | if err != nil || api.Result == nil { 381 | for _, testChan := range channels { 382 | if channel.Name == testChan.Name { 383 | channel = testChan 384 | channel.TopicName = "general" 385 | } 386 | } 387 | chat = k.NewChat(channel) 388 | _, err2 := chat.Read(2) 389 | if err2 != nil { 390 | printError(fmt.Sprintf("%+v", err)) 391 | return 392 | } 393 | go populateChat() 394 | go generateChannelTabCompletionSlice() 395 | return 396 | } 397 | var printMe []string 398 | var actuallyPrintMe string 399 | if len(api.Result.Messages) > 0 { 400 | lastMessage.ID = api.Result.Messages[0].Msg.ID 401 | } 402 | for _, message := range api.Result.Messages { 403 | if message.Msg.Content.Type == "text" || message.Msg.Content.Type == "attachment" { 404 | if lastMessage.ID < 1 { 405 | lastMessage.ID = message.Msg.ID 406 | } 407 | var apiCast keybase.ChatAPI 408 | apiCast.Msg = &message.Msg 409 | newMessage := formatOutput(apiCast).string() 410 | printMe = append(printMe, newMessage) 411 | } 412 | } 413 | for i := len(printMe) - 1; i >= 0; i-- { 414 | actuallyPrintMe += printMe[i] 415 | if i > 0 { 416 | actuallyPrintMe += "\n" 417 | } 418 | } 419 | printToView("Chat", actuallyPrintMe) 420 | go populateList() 421 | } 422 | func populateList() { 423 | _, maxY := g.Size() 424 | if testVar, err := k.ChatList(); err != nil { 425 | log.Printf("%+v", err) 426 | } else { 427 | clearView("List") 428 | conversationSlice := testVar.Result.Conversations 429 | sort.SliceStable(conversationSlice, func(i, j int) bool { 430 | return conversationSlice[i].ActiveAt > conversationSlice[j].ActiveAt 431 | }) 432 | var textBase = config.Colors.Channels.Basic.stylize("") 433 | var recentPMs = textBase.append(config.Colors.Channels.Header.stylize("---[PMs]---\n")) 434 | var recentPMsCount = 0 435 | var recentChannels = textBase.append(config.Colors.Channels.Header.stylize("---[Teams]---\n")) 436 | var recentChannelsCount = 0 437 | for _, s := range conversationSlice { 438 | channels = append(channels, s.Channel) 439 | if s.Channel.MembersType == keybase.TEAM { 440 | recentChannelsCount++ 441 | if recentChannelsCount <= ((maxY - 2) / 3) { 442 | channel := fmt.Sprintf("%s\n\t#%s\n", s.Channel.Name, s.Channel.TopicName) 443 | if s.Unread { 444 | recentChannels = recentChannels.append(config.Colors.Channels.Unread.stylize("*" + channel)) 445 | } else { 446 | recentChannels = recentChannels.appendString(channel) 447 | } 448 | } 449 | } else { 450 | recentPMsCount++ 451 | if recentPMsCount <= ((maxY - 2) / 3) { 452 | pmName := fmt.Sprintf("%s\n", cleanChannelName(s.Channel.Name)) 453 | if s.Unread { 454 | recentPMs = recentPMs.append(config.Colors.Channels.Unread.stylize("*" + pmName)) 455 | } else { 456 | recentPMs = recentPMs.appendString(pmName) 457 | } 458 | } 459 | } 460 | } 461 | time.Sleep(1 * time.Millisecond) 462 | printToView("List", fmt.Sprintf("%s%s", recentPMs.string(), recentChannels.string())) 463 | generateRecentTabCompletionSlice() 464 | } 465 | } 466 | 467 | // End update/populate views automatically 468 | 469 | // Formatting 470 | func formatMessageBody(body string) StyledString { 471 | body = strings.Replace(body, "```", "\n\n", -1) 472 | message := config.Colors.Message.Body.stylize(body) 473 | 474 | message = message.colorRegex(`@[\w_]*([\.#][\w_]+)*`, config.Colors.Message.LinkKeybase) 475 | message = colorReplaceMentionMe(message) 476 | 477 | // TODO when gocui actually fixes there shit with formatting, then un comment these lines 478 | // message = message.colorRegex(`_[^_]*_`, config.Colors.Message.Body.withItalic()) 479 | // message = message.colorRegex(`~[^~]*~`, config.Colors.Message.Body.withStrikethrough()) 480 | message = message.colorRegex(`@[\w_]*([\.#][\w_]+)*`, config.Colors.Message.LinkKeybase) 481 | // TODO change how bold, italic etc works, so it uses boldOn boldOff ([1m and [22m) 482 | message = message.colorRegex(`\*[^\*]*\*`, config.Colors.Message.Body.withBold()) 483 | message = message.colorRegex("^>.*$", config.Colors.Message.Quote) 484 | message = message.regexReplaceFunc("\n(.*\n)*\n", func(match string) string { 485 | maxWidth, _ := g.Size() 486 | output := "" 487 | match = strings.Replace(strings.Replace(match, "```", "\n\n", -1), "\t", " ", -1) 488 | match = removeFormatting(match) 489 | lines := strings.Split(match, "\n") 490 | for _, line := range lines { 491 | maxLineLength := maxWidth/2 + maxWidth/3 - 2 492 | spaces := maxLineLength - utf8.RuneCountInString(line) 493 | for i := 1; spaces < 0; i++ { 494 | spaces = i*maxLineLength - utf8.RuneCountInString(line) 495 | } 496 | output += line + strings.Repeat(" ", spaces) + "\n" 497 | } 498 | // TODO stylize should remove formatting - in general everything should 499 | 500 | return config.Colors.Message.Code.stylize(output).stringFollowedByStyle(message.style) 501 | }) 502 | message = message.colorRegex("`[^`]*`", config.Colors.Message.Code) 503 | // mention URL 504 | message = message.colorRegex(`(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))`, config.Colors.Message.LinkURL) 505 | return message 506 | } 507 | 508 | // TODO use this more 509 | func formatChannel(ch keybase.Channel) StyledString { 510 | return config.Colors.Message.LinkKeybase.stylize(fmt.Sprintf("@%s#%s", ch.Name, ch.TopicName)) 511 | } 512 | 513 | func colorReplaceMentionMe(msg StyledString) StyledString { 514 | return msg.colorRegex(`(@?\b`+k.Username+`\b)`, config.Colors.Message.Mention) 515 | } 516 | func colorUsername(username string) StyledString { 517 | var color = config.Colors.Message.SenderDefault 518 | if username == k.Username { 519 | color = config.Colors.Message.Mention 520 | } 521 | return color.stylize(username) 522 | } 523 | 524 | func cleanChannelName(c string) string { 525 | newChannelName := strings.Replace(c, fmt.Sprintf("%s,", k.Username), "", 1) 526 | return strings.Replace(newChannelName, fmt.Sprintf(",%s", k.Username), "", 1) 527 | } 528 | 529 | func formatMessage(api keybase.ChatAPI, formatString string) StyledString { 530 | msg := api.Msg 531 | ret := config.Colors.Message.Header.stylize("") 532 | msgType := msg.Content.Type 533 | switch msgType { 534 | case "text", "attachment": 535 | ret = config.Colors.Message.Header.stylize(formatString) 536 | tm := time.Unix(int64(msg.SentAt), 0) 537 | var body = formatMessageBody(msg.Content.Text.Body) 538 | if msgType == "attachment" { 539 | body = config.Colors.Message.Body.stylize("$TITLE\n$FILE") 540 | attachment := msg.Content.Attachment 541 | body = body.replaceString("$TITLE", attachment.Object.Title) 542 | body = body.replace("$FILE", config.Colors.Message.Attachment.stylize(fmt.Sprintf("[Attachment: %s]", attachment.Object.Filename))) 543 | } 544 | reply := "" 545 | if msg.Content.Text.ReplyTo != 0 { 546 | chat := k.NewChat(channel) 547 | replyMsg, replErr := chat.ReadMessage(msg.Content.Text.ReplyTo) 548 | if replErr == nil { 549 | replyUser := replyMsg.Result.Messages[0].Msg.Sender.Username 550 | replyBody := "" 551 | if replyMsg.Result.Messages[0].Msg.Content.Type == "text" { 552 | replyBody = replyMsg.Result.Messages[0].Msg.Content.Text.Body 553 | } 554 | reply = fmt.Sprintf("\nReplyTo> %s: %s\n", replyUser, replyBody) 555 | } 556 | } 557 | 558 | user := colorUsername(msg.Sender.Username) 559 | device := config.Colors.Message.SenderDevice.stylize(msg.Sender.DeviceName) 560 | msgID := config.Colors.Message.ID.stylize(fmt.Sprintf("%d", msg.ID)) 561 | date := config.Colors.Message.Time.stylize(tm.Format(config.Formatting.DateFormat)) 562 | msgTime := config.Colors.Message.Time.stylize(tm.Format(config.Formatting.TimeFormat)) 563 | c0ck := config.Colors.Message.Quote.stylize(reply) 564 | channelName := config.Colors.Message.ID.stylize(fmt.Sprintf("@%s#%s", msg.Channel.Name, msg.Channel.TopicName)) 565 | ret = ret.replace("$REPL", c0ck) 566 | ret = ret.replace("$MSG", body) 567 | ret = ret.replace("$USER", user) 568 | ret = ret.replace("$DEVICE", device) 569 | ret = ret.replace("$ID", msgID) 570 | ret = ret.replace("$TIME", msgTime) 571 | ret = ret.replace("$DATE", date) 572 | ret = ret.replace("$TEAM", channelName) 573 | ret = ret.replace("$TAGS", getUserFlags(api.Msg.Sender.Username)) 574 | } 575 | return ret 576 | } 577 | 578 | func formatOutput(api keybase.ChatAPI) StyledString { 579 | format := config.Formatting.OutputFormat 580 | if stream { 581 | format = config.Formatting.OutputStreamFormat 582 | } 583 | return formatMessage(api, format) 584 | } 585 | 586 | // End formatting 587 | 588 | // Input handling 589 | func handleMessage(api keybase.ChatAPI) { 590 | if api.ErrorListen != nil { 591 | printError(fmt.Sprintf("%+v", api.ErrorListen)) 592 | return 593 | } 594 | if _, ok := typeCommands[api.Msg.Content.Type]; ok { 595 | if api.Msg.Channel.MembersType == channel.MembersType && cleanChannelName(api.Msg.Channel.Name) == channel.Name { 596 | if channel.MembersType == keybase.TEAM && channel.TopicName != api.Msg.Channel.TopicName { 597 | } else { 598 | go typeCommands[api.Msg.Content.Type].Exec(api) 599 | } 600 | } 601 | } 602 | if api.Msg.Content.Type == "text" || api.Msg.Content.Type == "attachment" { 603 | go populateList() 604 | msgSender := api.Msg.Sender.Username 605 | if !stream { 606 | if msgSender != k.Username { 607 | if api.Msg.Channel.MembersType == keybase.TEAM { 608 | topicName := api.Msg.Channel.TopicName 609 | for _, m := range api.Msg.Content.Text.UserMentions { 610 | if m.Text == k.Username { 611 | // We are in a team 612 | if topicName != channel.TopicName { 613 | printInfoStyledString(formatMessage(api, config.Formatting.OutputMentionFormat)) 614 | fmt.Print("\a") 615 | } 616 | 617 | break 618 | } 619 | } 620 | } else { 621 | if msgSender != channel.Name { 622 | printInfoStyledString(formatMessage(api, config.Formatting.PMFormat)) 623 | fmt.Print("\a") 624 | } 625 | 626 | } 627 | } 628 | if api.Msg.Channel.MembersType == channel.MembersType && cleanChannelName(api.Msg.Channel.Name) == channel.Name { 629 | if channel.MembersType == keybase.USER || channel.MembersType == keybase.TEAM && channel.TopicName == api.Msg.Channel.TopicName { 630 | printToView("Chat", formatOutput(api).string()) 631 | chat := k.NewChat(channel) 632 | lastMessage.ID = api.Msg.ID 633 | chat.Read(api.Msg.ID) 634 | } 635 | } 636 | } else { 637 | if api.Msg.Channel.MembersType == keybase.TEAM { 638 | printToView("Chat", formatOutput(api).string()) 639 | } else { 640 | printToView("Chat", formatMessage(api, config.Formatting.PMFormat).string()) 641 | } 642 | } 643 | } else { 644 | //TODO: For edit/delete run this 645 | if api.Msg.Channel.MembersType == channel.MembersType && cleanChannelName(api.Msg.Channel.Name) == channel.Name { 646 | go populateChat() 647 | } 648 | } 649 | } 650 | func getInputString(viewName string) (string, error) { 651 | inputView, err := g.View(viewName) 652 | if err != nil { 653 | return "", err 654 | } 655 | retString := inputView.Buffer() 656 | retString = strings.Replace(retString, "\n", "", 800) 657 | return retString, err 658 | } 659 | func deleteEmpty(s []string) []string { 660 | var r []string 661 | for _, str := range s { 662 | if str != "" { 663 | r = append(r, str) 664 | } 665 | } 666 | return r 667 | } 668 | func handleInput(viewName string) error { 669 | clearView(viewName) 670 | inputString, _ := getInputString(viewName) 671 | if inputString == "" { 672 | return nil 673 | } 674 | if strings.HasPrefix(inputString, config.Basics.CmdPrefix) { 675 | cmd := deleteEmpty(strings.Split(inputString[len(config.Basics.CmdPrefix):], " ")) 676 | if len(cmd) < 1 { 677 | return nil 678 | } 679 | if c, ok := commands[cmd[0]]; ok { 680 | c.Exec(cmd) 681 | return nil 682 | } else if cmd[0] == "q" || cmd[0] == "quit" { 683 | return gocui.ErrQuit 684 | } else { 685 | printError(fmt.Sprintf("Command '%s' not recognized", cmd[0])) 686 | return nil 687 | } 688 | } 689 | if inputString[:1] == "+" || inputString[:1] == "-" { 690 | cmd := strings.Split(inputString, " ") 691 | cmd[0] = inputString[:1] 692 | RunCommand(cmd...) 693 | } else { 694 | inputString = resolveRootEmojis(inputString) 695 | go sendChat(inputString) 696 | } 697 | // restore any tab completion view titles on input commit 698 | if newViewTitle := getViewTitle(viewName); newViewTitle != "" { 699 | setViewTitle(viewName, newViewTitle) 700 | } 701 | 702 | go populateList() 703 | return nil 704 | } 705 | func sendChat(message string) { 706 | autoScrollView("Chat") 707 | chat := k.NewChat(channel) 708 | _, err := chat.Send(message) 709 | if err != nil { 710 | printError(fmt.Sprintf("There was an error %+v", err)) 711 | } 712 | } 713 | 714 | // End input handling 715 | 716 | func quit(g *gocui.Gui, v *gocui.View) error { 717 | return gocui.ErrQuit 718 | } 719 | 720 | // RegisterTypeCommand registers a command to be used within the client 721 | func RegisterTypeCommand(c TypeCommand) error { 722 | var notAdded string 723 | for _, cmd := range c.Cmd { 724 | if _, ok := typeCommands[cmd]; !ok { 725 | typeCommands[cmd] = c 726 | continue 727 | } 728 | notAdded = fmt.Sprintf("%s, %s", notAdded, cmd) 729 | } 730 | if notAdded != "" { 731 | return fmt.Errorf("The following aliases were not added because they already exist: %s", notAdded) 732 | } 733 | return nil 734 | } 735 | 736 | // RegisterCommand registers a command to be used within the client 737 | func RegisterCommand(c Command) error { 738 | var notAdded string 739 | for i, cmd := range c.Cmd { 740 | if _, ok := commands[cmd]; !ok { 741 | if i == 0 { 742 | baseCommands = append(baseCommands, cmd) 743 | } 744 | commands[cmd] = c 745 | continue 746 | } 747 | notAdded = fmt.Sprintf("%s, %s", notAdded, cmd) 748 | } 749 | if notAdded != "" { 750 | return fmt.Errorf("The following aliases were not added because they already exist: %s", notAdded) 751 | } 752 | return nil 753 | } 754 | 755 | // RunCommand calls a command as if it was run by the user 756 | func RunCommand(c ...string) { 757 | commands[c[0]].Exec(c) 758 | } 759 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------