Initial commit, lots of cleanup and stuff to do, it may not work.

This commit is contained in:
Storm Dragon 2025-01-15 23:43:44 -05:00
commit 3f0246a4f8
80 changed files with 11306 additions and 0 deletions

339
LICENSE Normal file
View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

176
README.md Normal file
View File

@ -0,0 +1,176 @@
# Barnard
## Documentation
Please feel free to give suggestions and corrections for this file (as wellas Barnard propper).
Find a sample notification script in examples/.
## Audio boost
If a user is too soft to hear, you can boost their audio.
The audio should drastically increase once you have hit the VolumeUp key over 10 times (from the silent/0 position).
The boost setting is saved per user, just like per user volume.
## FIFO Control
If you pass the --fifo option to Barnard, a FIFO pipe will be created.
You can control Barnard by sending commands to this FIFO.
Each command must end with a \n (0x0a) character.
Commands may be added at any time.
Per the robustness principle, be liberal in what you receive.
Current Commands:
* error: An error has occured to prevent transmitting audio, or taking another action.
* micup: Start transmitting, just as when you hold down the talk key. Does nothing if you are already transmiting.
* micdown: Stop transmitting, just like when you release your talk key. Does nothing if you are not already transmitting.
* toggle: Toggle your transmission state.
* talk: Synonym for toggle.
* exit: Exit Barnard, just like when you press your quit key.
## Event Notification
You can use the notifycommand parameter in your config file to run a program on certain events.
Each event has the following parameters:
* event: the name of the event
- join: user has joined the channel you are in
- leave: user has left the channel you are in
- micup: you have begun transmitting
- micdown: you have stopped transmitting
- connect: you have connected to a server
- disconnect: you have disconnected from a server
- msg: the channel you are currently connected to has received a message
- pm: you have received a private message
* who: the person causing initiation of the event ("me" for self-generated events)
* what: the body of the event as applicable (message, channel name, etc)
Warning:
Keep in mind that Barnard opens an Alsa sound device when starting.
For this reason, any notification command used here will need to be able to work while other sound is playing.
It is recommended that you test your notification command by hand, while Barnard is running, before including it here.
You can create a command that will take any of these parameters as desired, by prepending the name of the parameter in your command with a % (percent) sign.
As an example, to attempt to play wave files for each event, you could set notifycommand to:
aplay /home/username/sounds/mumble/%event.wav
When you begin transmitting, aplay will attempt to play /home/username/sounds/mumble/micup.wav.
The same will be attempted for the other events, such as leave, join, micdown, etc.
In order to process messages and the like, Barnard will parse your command as a properly quoted shell command.
For this reason, you should put quotes around arguments that have spaces.
If you want to do more complex things, write a shell script (or c application, python script, etc) to process the arguments passed into it.
## Connecting Via Text Interface
You can now manage your server lists in a text GUI.
An Ncurses interface has been created by members of the [F123 Group](https://gitlab.com/f123).
Make sure the folder in which you store the barnard binary is in your path. This should be the default for any f123 user.
Then just run ./barnard-ui from this folder, and follow the instructions.
You can add barnard-ui to your path as well, and access it from anywhere.
## Modifications
This copy of Barnard and it's associated Gumble library have been modified to support usage by blind users.
Our thanks go out to Tim Cooper for the massive amount of work put into this client, originally found at [github.com/layeh/barnard](https://github.com/layeh/barnard).
## Config
By default, the file $HOME/.barnard.yaml will hold the configuration for Barnard.
You can have barnard read another file by using the -c option, like `./barnard -c ~/.anotherbarnard.yaml`.
It will be created automatically if it doesn't exist.
If you modify the config file while Barnard is running, your changes may be overwritten.
## Defaults
You can set username and defaultserver in your config file, and they will be used if none is specified when launching barnard.
(Note that the default username (an empty string) and the default server name (localhost:64738) have been the defaults for barnard up to this point, and have been left that way for compatibility.)
## Audio Devices
You can set the default input and output devices in the config file as well.
Pass the -list_devices parameter to barnard to be given a list of audio input and output devices.
Copy lines from the above list into inputdevice and outputdevice as desired.
To clear your inputdevice or outputdevice options and set them to defaults, set them to "" or delete them entirely.
## Keystrokes
You can see the below keystrokes in your config file.
Pressing tab inside the main window switches between the user/channel tree view and the message input box.
When in the message input box:
* left and right arrow keys move by character
* home/end moves to the beginning/end of the text respectively
* enter submits the entered message
When in the treeview, pressing:
* f5 or f6 on a channel changes the volume for all users in that channel
* f5 or f6 on a user changes the volume for that user.
* enter on de-selected user selects that user for PM mode.
* enter on selected user de-selects the user
* enter on a channel de-selects any selected users (if any) and moves you to the specified channel.
## Volume
If you set the volume for a user (using the F5/F6 keys by default), Barnard will remember that volume, and will keep that user at that volume.
The volume is set for a single user on a single server.
This means you may have to set a person to a custom volume multiple times, if you are both on multiple servers together.
If you set the volume of a channel, you are basically relatively adjusting each user's volume.
If Jim's volume is set to 0.1, and larry's volume is set to 0.9, lowering the channel by one increment will mute Jim,and set Larry to 0.8.
You can change the volume for a user once that user has spoken at least once during a session.
Attempts to change the volume of a user who has not spoken will be ignored.
If you are unable to hear a user speaking, you can edit the .barnard.yaml file in your home directory, after closing Barnard, and set the volume parameter to 1.0 for a particular user.
### Technical
The volume for each user is set via the audio session created for that user; no talking means no session means no settable volume.
## PM Mode
This mode sets the text to the left of your message entry box to [@username], where username is the name of the person you are PMing.
While a user is selected, both private messages and channel messages are displayed.
However, any messages you send will be delivered only to the selected user.
Private messages between you and another party are shown as `pm/source/dest`, where source and dest are the sender and receiver of the message respectively.
When you are finished sending private messages to a user, press tab to reactivate the tree view, and de-select the user as above.
## Info
barnard is a terminal-based client for the [Mumble](https://mumble.info) voice
chat software.
![Screenshot](https://i.imgur.com/B8ldT5k.png)
## Installation
Requirements:
1. [Go](https://golang.org/)
2. [Git](https://git-scm.com/)
3. [Opus](https://opus-codec.org/) development headers
4. [OpenAL](http://kcat.strangesoft.net/openal.html) development headers
To fetch and build:
go get -u git.2mb.codes/~cmb/barnard
After running the command above, `barnard` will be compiled as `$(go env GOPATH)/bin/barnard`.
## Manual
### Key bindings
- <kbd>F1</kbd>: toggle voice transmission
- <kbd>Ctrl+L</kbd>: clear chat log
- <kbd>Tab</kbd>: toggle focus between chat and user tree
- <kbd>Page Up</kbd>: scroll chat up
- <kbd>Page Down</kbd>: scroll chat down
- <kbd>Home</kbd>: scroll chat to the top
- <kbd>End</kbd>: scroll chat to the bottom
- <kbd>F10</kbd>: quit
## License
GPLv2
## Contributors
Tim Cooper (<tim.cooper@layeh.com>)
Brandon McGinty-Carroll (<bmmcginty.barnard@bmcginty.us>)

28
add_alt_keys.py Normal file
View File

@ -0,0 +1,28 @@
import os,string
fc=open("uiterm/keys.go","rb").read()
marker="//##altkeys##\n"
fc=fc.split(marker,1)[0]
fc+=marker
fc+="\n"
lines=[i.strip() for i in fc.split("\n")]
keys=[i.split(" ")[0].split("\t")[0] for i in lines if i.startswith("Key")]
keys=[i for i in keys if (i.startswith("Key") or i.startswith("Mouse"))]
fc+="const(\n"
for i in keys:
if i.startswith("Key"):
prefix="Key"
elif i.startswith("Mouse"):
prefix="Mouse"
else:
raise "no prefix for %s" % (i,)
key=i[len(prefix):]
fc+="%s%s%s Key = %s%s + (1<<16)\n" % (prefix,"Alt",key,prefix,key,)
for i in string.letters[:26].upper():
fc+="%s%s%s Key = %s + (1<<16)\n" % ("Key","Alt",i,hex(ord(i.lower())),)
fc+=")\n"
fh=open("uiterm/keys.go.tmp","wb")
fh.write(fc)
fh.close()
os.rename("uiterm/keys.go.tmp","uiterm/keys.go")

BIN
barnard Executable file

Binary file not shown.

174
barnard-ui Executable file
View File

@ -0,0 +1,174 @@
#!/bin/bash
# barnard-ui
# Description: Make managing servers with barnard easy.
#
# Copyright 2019, F123 Consulting, <information@f123.org>
# Copyright 2019, Stormux, <storm_dragon@linux-a11y.org>
# Copyright 2019, Storm Dragon, <storm_dragon@linux-a11y.org>
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later
# version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; see the file COPYING. If not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#--code--
# the gettext essentials
export TEXTDOMAIN=barnard-ui
export TEXTDOMAINDIR=/usr/share/locale
source gettext.sh
# Log writing function
log() {
# Usage: command | log for just stdout.
# Or command |& log for stderr and stdout.
while read -r line ; do
echo "$line" | tee -a "$logFile" &> /dev/null
done
}
# Log file name is ~/.cache/scriptname.log
logFile="$HOME/.cache/${0##*/}.log"
# Clear previous logs
echo -n | tee "$logFile" &> /dev/null
# Settings to improve accessibility of dialog.
export DIALOGOPTS='--insecure --no-lines --visit-items'
inputbox() {
# Returns: text entered by the user
# Args 1, Instructions for box.
# args: 2 initial text (optional)
dialog --clear --backtitle "$(gettext "Enter text and press enter.")" \
--inputbox "$1" 0 0 "$2" --stdout
}
passwordbox() {
# Returns: text entered by the user
# Args 1, Instructions for box.
# args: 2 initial text (optional)
dialog --clear --backtitle "$(gettext "Enter text and press enter.")" \
--passwordbox "$1" 0 0 "$2" --stdout
}
msgbox() {
# Returns: None
# Shows the provided message on the screen with an ok button.
dialog --clear --msgbox "$*" 10 72
}
yesno() {
# Returns: Yes or No
# Args: Question to user.
# Called in if $(yesno) == "Yes"
# Or variable=$(yesno)
dialog --clear --backtitle "$(gettext "Press 'Enter' for \"yes\" or 'Escape' for \"no\".")" --yesno "$*" 10 80 --stdout
if [[ $? -eq 0 ]]; then
echo "Yes"
else
echo "No"
fi
}
menulist() {
# Args: menu options.
# returns: selected tag
local i
local menuList
for i in $@ ; do
menuList+=("$i" "$i")
done
dialog --backtitle "$(gettext "Use the up and down arrow keys to find the option you want, then press enter to select it.")" \
--clear \
--no-tags \
--menu "$(gettext "Please select one")" 0 0 0 "${menuList[@]}" --stdout
}
[[ -d ~/.config/barnard ]] || mkdir ~/.config/barnard
if [[ ! -r ~/.config/barnard/servers.conf ]]; then
echo "Adding default mumble server." | log
echo "declare -Ag mumbleServerList=(" > ~/.config/barnard/servers.conf
echo "[Slint]=\"slint.fr:64738 -insecure\"" >> ~/.config/barnard/servers.conf
echo ")" >> ~/.config/barnard/servers.conf
fi
source ~/.config/barnard/servers.conf
function add-server() {
local serverName="$(inputbox "$(gettext "Enter a name for the new server:")")"
[[ $? -ne 0 ]] && return
local serverAddress="$(inputbox "$(gettext "Enter the address of the server. If there is a password, do it in the form, password@address, if the port is not standard, add it after a :, address:port:")")"
[[ $? -ne 0 ]] && return
local serverPassword="${serverAddress%@*}"
local serverAddress="${serverAddress#*@}"
local serverPort="${serverAddress##*:}"
local serverAddress="${serverAddress%:*}"
if ! [[ "$serverPort" =~ ^[0-9]+ ]]; then
serverPort=64738
fi
mumbleServerList[$serverName]="${serverAddress}:${serverPort}${serverPassword:+ -password ${serverPassword}}"
echo "declare -Ag mumbleServerList=(" > ~/.config/barnard/servers.conf
for i in "${!mumbleServerList[@]}" ; do
echo "[${i}]=\"${mumbleServerList[$i]}\"" >> ~/.config/barnard/servers.conf
done
echo ")" >> ~/.config/barnard/servers.conf
echo "Added server $serverName ${serverAddress}:${serverPort}" | log
msgbox "$(gettext "Added server") $serverName"
}
connect() {
ifs="$IFS"
IFS=$'\n'
local serverName
serverName="$(menulist "${!mumbleServerList[@]}" "Go Back")"
[[ $? -eq 1 ]] && exit 0
IFS="$ifs"
if [[ -z "$serverName" || "$serverName" == "Go Back" ]]; then
return
fi
local username="$(grep '^username: .*$' ~/.barnard.yaml 2> /dev/null | cut -d ' ' -f2-)"
username="${username//[[:space:]]/_}"
username="${username//\"/}"
command barnard -username "${username:-${USER}-${HOSTNAME}}" -server ${mumbleServerList[$serverName]} --fifo ~/.config/barnard/cmd --buffers 16 |& log
}
remove-server() {
ifs="$IFS"
IFS=$'\n'
local serverName="$(menulist "${!mumbleServerList[@]}" "Go Back")"
IFS="$ifs"
if [[ -z "$serverName" || "$serverName" == "Go Back" ]]; then
return
fi
unset "mumbleServerList[$serverName]"
echo "declare -Ag mumbleServerList=(" > ~/.config/barnard/servers.conf
for i in "${!mumbleServerList[@]}" ; do
echo "[${i}]=\"${mumbleServerList[$i]}\"" >> ~/.config/barnard/servers.conf
done
echo ")" >> ~/.config/barnard/servers.conf
echo "Removed server $serverName ${serverAddress}:${serverPort}" | log
msgbox "$(gettext "Removed server") $serverName"
}
# main menu
while : ; do
action="$(menulist "Connect" "Add_server" "Remove_server")"
[[ $? -eq 1 ]] && exit 0
action="${action,,}"
action="${action//_/-}"
if [[ "$action" == "exit" ]]; then
exit 0
fi
eval "$action"
done

38
barnard.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"crypto/tls"
"git.2mb.codes/~cmb/barnard/config"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"git.2mb.codes/~cmb/barnard/gumble/gumbleopenal"
"git.2mb.codes/~cmb/barnard/uiterm"
)
type Barnard struct {
Config *gumble.Config
UserConfig *config.Config
Hotkeys *config.Hotkeys
Client *gumble.Client
Address string
TLSConfig tls.Config
Stream *gumbleopenal.Stream
Tx bool
Connected bool
Ui *uiterm.Ui
UiOutput uiterm.Textview
UiInput uiterm.Textbox
UiStatus uiterm.Label
UiTree uiterm.Tree
UiInputStatus uiterm.Label
SelectedChannel *gumble.Channel
selectedUser *gumble.User
notifyChannel chan []string
exitStatus int
exitMessage string
}

213
client.go Normal file
View File

@ -0,0 +1,213 @@
package main
import (
"fmt"
"net"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"git.2mb.codes/~cmb/barnard/gumble/gumbleopenal"
"git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
)
func (b *Barnard) start() {
b.Config.Attach(gumbleutil.AutoBitrate)
b.Config.Attach(b)
b.Config.Address = b.Address
// test Audio
_, err := gumbleopenal.New(b.Client, b.UserConfig.GetInputDevice(), b.UserConfig.GetOutputDevice(), true)
if err != nil {
b.exitWithError(err)
return
}
//connect, not reconnect
b.connect(false)
}
func (b *Barnard) exitWithError(err error) {
b.Ui.Close()
b.exitStatus = 1
b.exitMessage = err.Error()
}
func (b *Barnard) connect(reconnect bool) bool {
var err error
_, err = gumble.DialWithDialer(new(net.Dialer), b.Config, &b.TLSConfig)
if err != nil {
if reconnect {
b.Log(err.Error())
} else {
b.exitWithError(err)
}
return false
}
stream, err := gumbleopenal.New(b.Client, b.UserConfig.GetInputDevice(), b.UserConfig.GetOutputDevice(), false)
if err != nil {
b.exitWithError(err)
return false
}
b.Stream = stream
b.Stream.AttachStream(b.Client)
b.Connected = true
return true
}
func (b *Barnard) OnConnect(e *gumble.ConnectEvent) {
b.Client = e.Client
b.Ui.SetActive(uiViewInput)
b.UiTree.Rebuild()
b.Ui.Refresh()
for _, u := range b.Client.Users {
b.UserConfig.UpdateUser(u)
}
b.UpdateInputStatus(fmt.Sprintf("[%s]", e.Client.Self.Channel.Name))
b.AddOutputLine(fmt.Sprintf("Connected to %s", b.Client.Conn.RemoteAddr()))
wmsg := ""
if e.WelcomeMessage != nil {
wmsg = esc(*e.WelcomeMessage)
}
b.Notify("connect", "me", wmsg)
if wmsg != "" {
b.AddOutputLine(fmt.Sprintf("Welcome message: %s", wmsg))
}
b.Ui.Refresh()
}
func (b *Barnard) OnDisconnect(e *gumble.DisconnectEvent) {
var reason string
switch e.Type {
case gumble.DisconnectError:
reason = "connection error"
}
b.Notify("disconnect", "me", reason)
if reason == "" {
b.AddOutputLine("Disconnected")
} else {
b.AddOutputLine("Disconnected: " + reason)
}
b.Tx = false
b.Connected = false
b.UiTree.Rebuild()
b.Ui.Refresh()
go b.reconnectGoroutine()
}
func (b *Barnard) reconnectGoroutine() {
for {
res := b.connect(true)
if res == true {
break
}
time.Sleep(15 * time.Second)
}
}
func (b *Barnard) Log(s string) {
b.AddOutputMessage(nil, s)
}
func (b *Barnard) OnTextMessage(e *gumble.TextMessageEvent) {
var public = false
for _, c := range e.Channels {
if c.Name == b.Client.Self.Channel.Name {
public = true
break
}
}
if public {
b.Notify("msg", e.Sender.Name, e.Message)
b.AddOutputMessage(e.Sender, e.Message)
} else {
var sender string
if e.Sender == nil {
sender = "Server"
} else {
sender = e.Sender.Name
}
b.Notify("pm", sender, e.Message)
b.AddOutputPrivateMessage(e.Sender, b.Client.Self, e.Message)
}
}
func (b *Barnard) OnUserChange(e *gumble.UserChangeEvent) {
if e.User != nil {
b.UserConfig.UpdateUser(e.User)
}
var s = "unknown"
var t = "unknown"
if e.Type.Has(gumble.UserChangeConnected) {
s = "joined"
t = "join"
}
if e.Type.Has(gumble.UserChangeDisconnected) {
s = "left"
t = "leave"
if e.User == b.selectedUser {
b.SetSelectedUser(nil)
}
}
if e.User.Channel.Name == b.Client.Self.Channel.Name {
b.Notify(t, e.User.Name, e.User.Channel.Name)
b.AddOutputLine(fmt.Sprintf("%s %s %s", e.User.Name, s, e.User.Channel.Name))
}
if e.Type.Has(gumble.UserChangeChannel) && e.User == b.Client.Self {
b.UpdateInputStatus(fmt.Sprintf("[%s]", e.User.Channel.Name))
}
b.UiTree.Rebuild()
b.Ui.Refresh()
}
func (b *Barnard) OnChannelChange(e *gumble.ChannelChangeEvent) {
b.UpdateInputStatus(fmt.Sprintf("[%s]", e.Channel.Name))
b.UiTree.Rebuild()
b.Ui.Refresh()
}
func (b *Barnard) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
var info string
switch e.Type {
case gumble.PermissionDeniedOther:
info = e.String
case gumble.PermissionDeniedPermission:
info = "insufficient permissions"
case gumble.PermissionDeniedSuperUser:
info = "cannot modify SuperUser"
case gumble.PermissionDeniedInvalidChannelName:
info = "invalid channel name"
case gumble.PermissionDeniedTextTooLong:
info = "text too long"
case gumble.PermissionDeniedTemporaryChannel:
info = "temporary channel"
case gumble.PermissionDeniedMissingCertificate:
info = "missing certificate"
case gumble.PermissionDeniedInvalidUserName:
info = "invalid user name"
case gumble.PermissionDeniedChannelFull:
info = "channel full"
case gumble.PermissionDeniedNestingLimit:
info = "nesting limit"
}
b.AddOutputLine(fmt.Sprintf("Permission denied: %s", info))
}
func (b *Barnard) OnUserList(e *gumble.UserListEvent) {
//for _,u := range e.UserList {
//b.UserConfig.UpdateUser(u)
//}
}
func (b *Barnard) OnACL(e *gumble.ACLEvent) {
}
func (b *Barnard) OnBanList(e *gumble.BanListEvent) {
}
func (b *Barnard) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
}
func (b *Barnard) OnServerConfig(e *gumble.ServerConfigEvent) {
}

19
config/hotkey_config.go Normal file
View File

@ -0,0 +1,19 @@
package config
import (
"git.2mb.codes/~cmb/barnard/uiterm"
)
type Hotkeys struct {
Talk *uiterm.Key
VolumeDown *uiterm.Key
VolumeUp *uiterm.Key
Exit *uiterm.Key
ToggleTimestamps *uiterm.Key
SwitchViews *uiterm.Key
ClearOutput *uiterm.Key
ScrollUp *uiterm.Key
ScrollDown *uiterm.Key
ScrollToTop *uiterm.Key
ScrollToBottom *uiterm.Key
}

281
config/user_config.go Normal file
View File

@ -0,0 +1,281 @@
package config
import (
"fmt"
"git.2mb.codes/~cmb/barnard/uiterm"
"gopkg.in/yaml.v2"
// "encoding/yaml"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"io/ioutil"
"os"
"os/user"
"strconv"
"strings"
)
type Config struct {
config *exportableConfig
fn string
}
type exportableConfig struct {
Hotkeys *Hotkeys
MicVolume *float32
InputDevice *string
OutputDevice *string
Servers []*server
DefaultServer *string
Username *string
NotifyCommand *string
}
type server struct {
Host string
Port int
Users []*eUser
}
type eUser struct {
Username string
Boost uint16
Volume float32
}
func (c *Config) SaveConfig() {
var data []byte
data, err := yaml.Marshal(c.config)
if err != nil {
panic(err)
}
err = ioutil.WriteFile(c.fn+".tmp", data, 0600)
if err != nil {
panic(err)
}
err = os.Rename(c.fn+".tmp", c.fn)
if err != nil {
panic(err)
}
}
func key(k uiterm.Key) *uiterm.Key {
return &k
}
func (c *Config) LoadConfig() {
var jc exportableConfig
jc = exportableConfig{}
jc.Hotkeys = &Hotkeys{
Talk: key(uiterm.KeyF1),
VolumeDown: key(uiterm.KeyF5),
VolumeUp: key(uiterm.KeyF6),
Exit: key(uiterm.KeyF10),
ToggleTimestamps: key(uiterm.KeyF3),
SwitchViews: key(uiterm.KeyTab),
ScrollUp: key(uiterm.KeyPgup),
ScrollDown: key(uiterm.KeyPgdn),
}
if fileExists(c.fn) {
var data []byte
data = readFile(c.fn)
if data != nil {
err := yaml.UnmarshalStrict(data, &jc)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing \"%s\".\n%s\n", c.fn, err.Error())
os.Exit(1)
} //panic
} //if data
} //if exists
c.config = &jc
if c.config.MicVolume == nil {
micvol := float32(1.0)
jc.MicVolume = &micvol
}
if c.config.InputDevice == nil {
idev := string("")
jc.InputDevice = &idev
}
if c.config.OutputDevice == nil {
odev := string("")
jc.OutputDevice = &odev
}
if c.config.DefaultServer == nil {
defaultServer := string("localhost:64738")
jc.DefaultServer = &defaultServer
}
if c.config.Username == nil {
username := string("")
jc.Username = &username
}
if c.config.NotifyCommand == nil {
ncmd := string("")
jc.NotifyCommand = &ncmd
}
}
func (c *Config) findServer(address string) *server {
if c.config.Servers == nil {
c.config.Servers = make([]*server, 0)
}
host, port := makeHostPort(address)
var t *server
for _, s := range c.config.Servers {
if s.Port == port && s.Host == host {
t = s
break
}
}
if t == nil {
t = &server{
Host: host,
Port: port,
}
c.config.Servers = append(c.config.Servers, t)
}
return t
}
func (c *Config) findUser(address string, username string) *eUser {
var s *server
s = c.findServer(address)
if s.Users == nil {
s.Users = make([]*eUser, 0)
}
var t *eUser
for _, u := range s.Users {
if u.Username == username {
t = u
break
}
}
if t == nil {
t = &eUser{
Username: username,
Boost: uint16(1),
Volume: 1.0,
}
s.Users = append(s.Users, t)
}
return t
}
func (c *Config) SetMicVolume(v float32) {
t := float32(v)
c.config.MicVolume = &t
}
func (c *Config) GetHotkeys() *Hotkeys {
return c.config.Hotkeys
}
func (c *Config) GetNotifyCommand() *string {
return c.config.NotifyCommand
}
func (c *Config) GetInputDevice() *string {
return c.config.InputDevice
}
func (c *Config) GetOutputDevice() *string {
return c.config.OutputDevice
}
func (c *Config) GetDefaultServer() *string {
return c.config.DefaultServer
}
func (c *Config) GetUsername() *string {
return c.config.Username
}
func (c *Config) UpdateUser(u *gumble.User) {
var j *eUser
var uc *gumble.Client
uc = u.GetClient()
if uc != nil {
j = c.findUser(uc.Config.Address, u.Name)
u.Boost = j.Boost
u.Volume = j.Volume
if u.Boost < 1 {
u.Boost = 1
}
}
}
func (c *Config) UpdateConfig(u *gumble.User) {
var j *eUser
j = c.findUser(u.GetClient().Config.Address, u.Name)
j.Boost = u.Boost
j.Volume = u.Volume
}
func NewConfig(fn *string) *Config {
var c *Config
c = &Config{}
c.fn = resolvePath(*fn)
c.LoadConfig()
return c
}
func readFile(path string) []byte {
if !fileExists(path) {
return nil
}
dat, err := ioutil.ReadFile(path)
if err != nil {
return nil
}
return dat
}
func fileExists(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func resolvePath(path string) string {
if strings.HasPrefix(path, "~/") || strings.Contains(path, "$HOME") {
usr, err := user.Current()
if err != nil {
panic(err)
}
var hd = usr.HomeDir
if strings.Contains(path, "$HOME") {
path = strings.Replace(path, "$HOME", hd, 1)
} else {
path = strings.Replace(path, "~", hd, 1)
}
}
return path
}
func makeHostPort(addr string) (string, int) {
parts := strings.Split(addr, ":")
host := parts[0]
port, err := strconv.Atoi(parts[1])
if err != nil {
panic(err)
}
return host, port
}
func Log(s string) {
log(s)
}
func log(s string) {
s += "\n"
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("log.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
if _, err := f.Write([]byte(s)); err != nil {
panic(err)
}
if err := f.Close(); err != nil {
panic(err)
}
}

2
doc.go Normal file
View File

@ -0,0 +1,2 @@
// barnard is a terminal based client for the Mumble VoIP system.
package main // import "git.2mb.codes/~cmb/barnard"

95
extras/barnard-sound.sh Executable file
View File

@ -0,0 +1,95 @@
#!/bin/bash
# barnard-sound.sh
# Description: Sounds and notification script for barnard.
#
# Copyright 2019, F123 Consulting, <information@f123.org>
# Copyright 2019, Storm Dragon, <storm_dragon@linux-a11y.org>
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later
# version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; see the file COPYING. If not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#--code--
# 1 is off, 0 is on
notify=0
sound=0
# Select notify type, notify-send or fenrir
notifyType="fenrir"
connect() {
[[ $sound ]] && play -n synth .05 pl 1050 pl 1100 remix - pad 0 .05 repeat
[[ $notify ]] && notify "${1}ed."
}
disconnect() {
[[ $sound ]] && play "|sox -np synth .1 sin 350 sin 440 norm -4 pad 0 .1 repeat 10 remix -" fade p 0 1 .5
[[ $notify ]] && notify "${1}ed."
}
is_function() {
LC_ALL=C type "$1" 2> /dev/null | grep -q "$1 is a function"
}
join() {
[[ $sound ]] && play "|sox -np synth .04 sin 1400 sin 2060 sin 2450 sin 2600 norm -8 remix - pad 0 .02 repeat 25" fade p 0 .75 .5
[[ $notify ]] && notify "$2 ${1}ed the channel."
}
leave() {
[[ $sound ]] && play -n synth .5 sin 480 sin 620 remix - norm -8 pad 0 0.5 repeat
[[ $notify ]] && notify "$2 left the channel."
}
micdown() {
[[ $sound ]] && play -qnV0 synth .25 sin G6:E5 norm -8
[[ $notify ]] && notify "You have stopped transmitting."
}
micup() {
[[ $sound ]] && play -qnV0 synth .25 sin E5:G6 norm -8
[[ $notify ]] && notify "You are now transmitting."
}
msg() {
[[ $sound ]] && play -n synth .3 sin 1290:1490 sin 1494:1294 remix - norm -8
[[ $notify ]] && notify "$1 from $2: $3"
}
notify() {
if [[ "$notifyType" == "notify-send" ]]; then
notify-send "$@"
else
if [[ -e "/tmp/fenrirscreenreader-deamon.sock" ]]; then
socatFile="/tmp/fenrirscreenreader-deamon.sock"
else
socatFile="$(find /tmp/ -maxdepth 1 -type s -name 'fenrirscreenreader-*.sock' | head -1)"
fi
echo "command say $@" | socat - UNIX-CLIENT:$socatFile
fi
}
pm() {
[[ $sound ]] && play -n synth .5 sin 440 sin 480 remix - norm -8
[[ $notify ]] && notify "$1 from $2: $3"
}
if is_function "$1" ; then
eval "$1" "$1" "$2" "$3" &> /dev/null
else
echo "The given barnard event has not yet been added."
fi
exit 0

21
go.mod Normal file
View File

@ -0,0 +1,21 @@
module git.2mb.codes/~cmb/barnard
go 1.21.5
require (
git.2mb.codes/~cmb/go-openal v0.0.0-20240129060821-44aa590ff5a5
github.com/alessio/shellescape v1.4.2
github.com/golang/protobuf v1.5.3
github.com/hraban/opus v0.0.0-00010101000000-000000000000
github.com/kennygrant/sanitize v1.2.4
github.com/nsf/termbox-go v1.1.1
gopkg.in/yaml.v2 v2.4.0
)
require (
github.com/mattn/go-runewidth v0.0.9 // indirect
golang.org/x/net v0.20.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect
)
replace github.com/hraban/opus => git.2mb.codes/~cmb/opus v0.0.0-20240129070855-574f355deea8

28
go.sum Normal file
View File

@ -0,0 +1,28 @@
git.2mb.codes/~cmb/go-openal v0.0.0-20240129060821-44aa590ff5a5 h1:FmLSfqZQ6WVQxzvfhdPD4hjYQbNKZcK2qLP9oT9rgeo=
git.2mb.codes/~cmb/go-openal v0.0.0-20240129060821-44aa590ff5a5/go.mod h1:zNFIOpVzzMAq/A8Nlv+iFhHFhZjp8lBPc/1rieycjJw=
git.2mb.codes/~cmb/opus v0.0.0-20240129070855-574f355deea8 h1:F8MWDgOcsxqU8+uBlrlgF69al2u9oBALC/zWAlMrGa4=
git.2mb.codes/~cmb/opus v0.0.0-20240129070855-574f355deea8/go.mod h1:XJUAtw77Ofc/j/tRGj+U991Fz8qvxu51x0S/M6F+yR8=
github.com/alessio/shellescape v1.4.2 h1:MHPfaU+ddJ0/bYWpgIeUnQUqKrlJ1S7BfEYPM4uEoM0=
github.com/alessio/shellescape v1.4.2/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/kennygrant/sanitize v1.2.4 h1:gN25/otpP5vAsO2djbMhF/LQX6R7+O1TB4yv8NzpJ3o=
github.com/kennygrant/sanitize v1.2.4/go.mod h1:LGsjYYtgxbetdg5owWB2mpgUL6e2nfw2eObZ0u0qvak=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/nsf/termbox-go v1.1.1 h1:nksUPLCb73Q++DwbYUBEglYBRPZyoXJdrj5L+TkjyZY=
github.com/nsf/termbox-go v1.1.1/go.mod h1:T0cTdVuOwf7pHQNtfhnEbzHbcNyCEcVU4YPpouCbVxo=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=

373
gumble/LICENSE Normal file
View File

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

50
gumble/README.md Normal file
View File

@ -0,0 +1,50 @@
# Note
Added from git.2mb.codes/~cmb/barnard/gumble for ease of future work and development.
# gumble
## Sub-projects
- gumble [![GoDoc](https://godoc.org/layeh.com/gumble/gumble?status.svg)](https://godoc.org/layeh.com/gumble/gumble)
- Client library
- gumbleopenal
- [OpenAL](http://kcat.strangesoft.net/openal.html) audio system for gumble
- gumbleffmpeg
- [ffmpeg](https://www.ffmpeg.org/) audio source for gumble
- gumbleutil
- Extras that can make working with gumble easier
## Example
package main
import (
"layeh.com/gumble/gumble"
"layeh.com/gumble/gumbleutil"
)
func main() {
gumbleutil.Main(gumbleutil.Listener{
UserChange: func(e *gumble.UserChangeEvent) {
if e.Type.Has(gumble.UserChangeConnected) {
e.User.Send("Welcome to the server, " + e.User.Name + "!")
}
},
})
}
## Related projects
- [barnard](https://layeh.com/barnard)
- terminal-based Mumble client
- [piepan](https://layeh.com/piepan)
- an easy to use framework for writing Mumble bots using Lua
## License
MPL 2.0
## Author
Tim Cooper (<tim.cooper@layeh.com>)

Binary file not shown.

View File

@ -0,0 +1,53 @@
package main // import "git.2mb.codes/~cmb/barnard/gumble/_examples/mumble-audio-player"
import (
"flag"
"fmt"
"os"
"path/filepath"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"git.2mb.codes/~cmb/barnard/gumble/gumbleffmpeg"
"git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
_ "git.2mb.codes/~cmb/barnard/gumble/opus"
)
func main() {
files := make(map[string]string)
var stream *gumbleffmpeg.Stream
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s: [flags] [audio files...]\n", os.Args[0])
flag.PrintDefaults()
}
gumbleutil.Main(gumbleutil.AutoBitrate, gumbleutil.Listener{
Connect: func(e *gumble.ConnectEvent) {
for _, file := range flag.Args() {
key := filepath.Base(file)
files[key] = file
}
fmt.Printf("audio player loaded! (%d files)\n", len(files))
},
TextMessage: func(e *gumble.TextMessageEvent) {
if e.Sender == nil {
return
}
file, ok := files[e.Message]
if !ok {
return
}
if stream != nil && stream.State() == gumbleffmpeg.StatePlaying {
return
}
stream = gumbleffmpeg.New(e.Client, gumbleffmpeg.SourceFile(file))
if err := stream.Play(); err != nil {
fmt.Printf("%s\n", err)
} else {
fmt.Printf("Playing %s\n", file)
}
},
})
}

View File

@ -0,0 +1,63 @@
package main // import "git.2mb.codes/~cmb/barnard/gumble/cmd/mumble-ping"
import (
"encoding/json"
"flag"
"fmt"
"net"
"os"
"strconv"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [flags] <destination>\n", os.Args[0])
flag.PrintDefaults()
}
interval := flag.Duration("interval", time.Second*1, "ping packet retransmission interval")
timeout := flag.Duration("timeout", time.Second*5, "ping timeout until failure")
jsonOutput := flag.Bool("json", false, "output success response as JSON")
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
server := flag.Arg(0)
host, port, err := net.SplitHostPort(server)
if err != nil {
host = server
port = strconv.Itoa(gumble.DefaultPort)
}
resp, err := gumble.Ping(net.JoinHostPort(host, port), *interval, *timeout)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
os.Exit(1)
}
major, minor, patch := resp.Version.SemanticVersion()
if !*jsonOutput {
fmt.Printf("Address: %s\n", resp.Address)
fmt.Printf("Ping: %s\n", resp.Ping)
fmt.Printf("Version: %d.%d.%d\n", major, minor, patch)
fmt.Printf("Connected Users: %d\n", resp.ConnectedUsers)
fmt.Printf("Maximum Users: %d\n", resp.MaximumUsers)
fmt.Printf("Maximum Bitrate: %d\n", resp.MaximumBitrate)
} else {
output := map[string]interface{}{
"address": resp.Address.String(),
"ping": float64(resp.Ping) / float64(time.Millisecond),
"version": fmt.Sprintf("%d.%d.%d", major, minor, patch),
"connected_users": resp.ConnectedUsers,
"maximum_users": resp.MaximumUsers,
"maximum_bitrate": resp.MaximumBitrate,
}
encoder := json.NewEncoder(os.Stdout)
encoder.Encode(output)
}
}

View File

@ -0,0 +1,37 @@
Copyright (C) 2005-2013, Thorvald Natvig <thorvald@natvig.com>
Copyright (C) 2007, Stefan Gehn <mETz AT gehn DOT net>
Copyright (C) 2007, Sebastian Schlingmann <mit_service@users.sourceforge.net>
Copyright (C) 2008-2013, Mikkel Krautz <mikkel@krautz.dk>
Copyright (C) 2008, Andreas Messer <andi@bupfen.de>
Copyright (C) 2007, Trenton Schulz
Copyright (C) 2008-2013, Stefan Hacker <dd0t@users.sourceforge.net>
Copyright (C) 2008-2011, Snares <snares@users.sourceforge.net>
Copyright (C) 2009-2013, Benjamin Jemlich <pcgod@users.sourceforge.net>
Copyright (C) 2009-2013, Kissaki <kissaki@gmx.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
//go:generate wget -O Mumble.proto https://raw.githubusercontent.com/mumble-voip/mumble/master/src/Mumble.proto
//go:generate protoc --go_out=. Mumble.proto
//go:generate rm -f Mumble.proto
//go:generate sed -i "s/^\\(package MumbleProto\\)$/\\1 \\/\\/ import \"layeh.com\\/gumble\\/gumble\\/MumbleProto\"/" Mumble.pb.go
package MumbleProto

View File

@ -0,0 +1,16 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// AccessTokens are additional passwords that can be provided to the server to
// gain access to restricted channels.
type AccessTokens []string
func (a AccessTokens) writeMessage(client *Client) error {
packet := MumbleProto.Authenticate{
Tokens: a,
}
return client.Conn.WriteProto(&packet)
}

116
gumble/gumble/acl.go Normal file
View File

@ -0,0 +1,116 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
"github.com/golang/protobuf/proto"
)
// ACL contains a list of ACLGroups and ACLRules linked to a channel.
type ACL struct {
// The channel to which the ACL belongs.
Channel *Channel
// The ACL's groups.
Groups []*ACLGroup
// The ACL's rules.
Rules []*ACLRule
// Does the ACL inherits the parent channel's ACLs?
Inherits bool
}
func (a *ACL) writeMessage(client *Client) error {
packet := MumbleProto.ACL{
ChannelId: &a.Channel.ID,
Groups: make([]*MumbleProto.ACL_ChanGroup, len(a.Groups)),
Acls: make([]*MumbleProto.ACL_ChanACL, len(a.Rules)),
InheritAcls: &a.Inherits,
Query: proto.Bool(false),
}
for i, group := range a.Groups {
packet.Groups[i] = &MumbleProto.ACL_ChanGroup{
Name: &group.Name,
Inherit: &group.InheritUsers,
Inheritable: &group.Inheritable,
Add: make([]uint32, 0, len(group.UsersAdd)),
Remove: make([]uint32, 0, len(group.UsersRemove)),
}
for _, user := range group.UsersAdd {
packet.Groups[i].Add = append(packet.Groups[i].Add, user.UserID)
}
for _, user := range group.UsersRemove {
packet.Groups[i].Remove = append(packet.Groups[i].Remove, user.UserID)
}
}
for i, rule := range a.Rules {
packet.Acls[i] = &MumbleProto.ACL_ChanACL{
ApplyHere: &rule.AppliesCurrent,
ApplySubs: &rule.AppliesChildren,
Grant: proto.Uint32(uint32(rule.Granted)),
Deny: proto.Uint32(uint32(rule.Denied)),
}
if rule.User != nil {
packet.Acls[i].UserId = &rule.User.UserID
}
if rule.Group != nil {
packet.Acls[i].Group = &rule.Group.Name
}
}
return client.Conn.WriteProto(&packet)
}
// ACLUser is a registered user who is part of or can be part of an ACL group
// or rule.
type ACLUser struct {
// The user ID of the user.
UserID uint32
// The name of the user.
Name string
}
// ACLGroup is a named group of registered users which can be used in an
// ACLRule.
type ACLGroup struct {
// The ACL group name.
Name string
// Is the group inherited from the parent channel's ACL?
Inherited bool
// Are group members are inherited from the parent channel's ACL?
InheritUsers bool
// Can the group be inherited by child channels?
Inheritable bool
// The users who are explicitly added to, explicitly removed from, and
// inherited into the group.
UsersAdd, UsersRemove, UsersInherited map[uint32]*ACLUser
}
// ACL group names that are built-in.
const (
ACLGroupEveryone = "all"
ACLGroupAuthenticated = "auth"
ACLGroupInsideChannel = "in"
ACLGroupOutsideChannel = "out"
)
// ACLRule is a set of granted and denied permissions given to an ACLUser or
// ACLGroup.
type ACLRule struct {
// Does the rule apply to the channel in which the rule is defined?
AppliesCurrent bool
// Does the rule apply to the children of the channel in which the rule is
// defined?
AppliesChildren bool
// Is the rule inherited from the parent channel's ACL?
Inherited bool
// The permissions granted by the rule.
Granted Permission
// The permissions denied by the rule.
Denied Permission
// The ACL user the rule applies to. Can be nil.
User *ACLUser
// The ACL group the rule applies to. Can be nil.
Group *ACLGroup
}

86
gumble/gumble/audio.go Normal file
View File

@ -0,0 +1,86 @@
package gumble
import (
"time"
)
const (
// AudioSampleRate is the audio sample rate (in hertz) for incoming and
// outgoing audio.
AudioSampleRate = 48000
// AudioDefaultInterval is the default interval that audio packets are sent
// at.
AudioDefaultInterval = 10 * time.Millisecond
// AudioMonoChannels is the number of channels used for voice transmission
AudioMonoChannels = 1
// AudioChannels is the number of channels used for playback
AudioChannels = 2
// AudioDefaultFrameSize is the number of audio frames that should be sent in
// a 10ms window (mono samples)
AudioDefaultFrameSize = AudioSampleRate / 100
// AudioMaximumFrameSize is the maximum audio frame size from another user
// that will be processed (accounting for stereo)
AudioMaximumFrameSize = (AudioSampleRate / 1000 * 60) * AudioChannels
// AudioDefaultDataBytes is the default number of bytes that an audio frame
// can use.
AudioDefaultDataBytes = 40
)
// AudioListener is the interface that must be implemented by types wishing to
// receive incoming audio data from the server.
//
// OnAudioStream is called when an audio stream for a user starts. It is the
// implementer's responsibility to continuously process AudioStreamEvent.C
// until it is closed.
type AudioListener interface {
OnAudioStream(e *AudioStreamEvent)
}
// AudioStreamEvent is event that is passed to AudioListener.OnAudioStream.
type AudioStreamEvent struct {
Client *Client
User *User
C <-chan *AudioPacket
}
// AudioBuffer is a slice of PCM audio samples.
type AudioBuffer []int16
func (a AudioBuffer) writeAudio(client *Client, seq int64, final bool) error {
encoder := client.AudioEncoder
if encoder == nil {
return nil
}
dataBytes := client.Config.AudioDataBytes
raw, err := encoder.Encode(a, len(a), dataBytes)
if final {
defer encoder.Reset()
}
if err != nil {
return err
}
var targetID byte
if target := client.VoiceTarget; target != nil {
targetID = byte(target.ID)
}
return client.Conn.WriteAudio(byte(4), targetID, seq, final, raw, nil, nil, nil)
}
// AudioPacket contains incoming audio samples and information.
type AudioPacket struct {
Client *Client
Sender *User
Target *VoiceTarget
AudioBuffer
HasPosition bool
X, Y, Z float32
}

View File

@ -0,0 +1,55 @@
package gumble
import (
"sync"
)
const (
audioCodecIDOpus = 4
)
var (
audioCodecsLock sync.Mutex
audioCodecs [8]AudioCodec
)
// RegisterAudioCodec registers an audio codec that can be used for encoding
// and decoding outgoing and incoming audio data. The function panics if the
// ID is invalid.
func RegisterAudioCodec(id int, codec AudioCodec) {
audioCodecsLock.Lock()
defer audioCodecsLock.Unlock()
if id < 0 || id >= len(audioCodecs) {
panic("id out of range")
}
audioCodecs[id] = codec
}
func getAudioCodec(id int) AudioCodec {
audioCodecsLock.Lock()
defer audioCodecsLock.Unlock()
return audioCodecs[id]
}
// AudioCodec can create a encoder and a decoder for outgoing and incoming
// data.
type AudioCodec interface {
ID() int
NewEncoder() AudioEncoder
NewDecoder() AudioDecoder
}
// AudioEncoder encodes a chunk of PCM audio samples to a certain type.
type AudioEncoder interface {
ID() int
Encode(pcm []int16, mframeSize, maxDataBytes int) ([]byte, error)
Reset()
}
// AudioDecoder decodes an encoded byte slice to a chunk of PCM audio samples.
type AudioDecoder interface {
ID() int
Decode(data []byte, frameSize int) ([]int16, error)
Reset()
}

View File

@ -0,0 +1,46 @@
package gumble
type audioEventItem struct {
parent *AudioListeners
prev, next *audioEventItem
listener AudioListener
streams map[*User]chan *AudioPacket
}
func (e *audioEventItem) Detach() {
if e.prev == nil {
e.parent.head = e.next
} else {
e.prev.next = e.next
}
if e.next == nil {
e.parent.tail = e.prev
} else {
e.next.prev = e.prev
}
}
// AudioListeners is a list of audio listeners. Each attached listener is
// called in sequence when a new user audio stream begins.
type AudioListeners struct {
head, tail *audioEventItem
}
// Attach adds a new audio listener to the end of the current list of listeners.
func (e *AudioListeners) Attach(listener AudioListener) Detacher {
item := &audioEventItem{
parent: e,
prev: e.tail,
listener: listener,
streams: make(map[*User]chan *AudioPacket),
}
if e.head == nil {
e.head = item
}
if e.tail == nil {
e.tail = item
} else {
e.tail.next = item
}
return item
}

101
gumble/gumble/bans.go Normal file
View File

@ -0,0 +1,101 @@
package gumble
import (
"net"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
"github.com/golang/protobuf/proto"
)
// BanList is a list of server ban entries.
//
// Whenever a ban is changed, it does not come into effect until the ban list
// is sent back to the server.
type BanList []*Ban
// Add creates a new ban list entry with the given parameters.
func (b *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban {
ban := &Ban{
Address: address,
Mask: mask,
Reason: reason,
Duration: duration,
}
*b = append(*b, ban)
return ban
}
// Ban represents an entry in the server ban list.
//
// This type should not be initialized manually. Instead, create new ban
// entries using BanList.Add().
type Ban struct {
// The banned IP address.
Address net.IP
// The IP mask that the ban applies to.
Mask net.IPMask
// The name of the banned user.
Name string
// The certificate hash of the banned user.
Hash string
// The reason for the ban.
Reason string
// The start time from which the ban applies.
Start time.Time
// How long the ban is for.
Duration time.Duration
unban bool
}
// SetAddress sets the banned IP address.
func (b *Ban) SetAddress(address net.IP) {
b.Address = address
}
// SetMask sets the IP mask that the ban applies to.
func (b *Ban) SetMask(mask net.IPMask) {
b.Mask = mask
}
// SetReason changes the reason for the ban.
func (b *Ban) SetReason(reason string) {
b.Reason = reason
}
// SetDuration changes the duration of the ban.
func (b *Ban) SetDuration(duration time.Duration) {
b.Duration = duration
}
// Unban will unban the user from the server.
func (b *Ban) Unban() {
b.unban = true
}
// Ban will ban the user from the server. This is only useful if Unban() was
// called on the ban entry.
func (b *Ban) Ban() {
b.unban = false
}
func (b BanList) writeMessage(client *Client) error {
packet := MumbleProto.BanList{
Query: proto.Bool(false),
}
for _, ban := range b {
if !ban.unban {
maskSize, _ := ban.Mask.Size()
packet.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{
Address: ban.Address,
Mask: proto.Uint32(uint32(maskSize)),
Reason: &ban.Reason,
Duration: proto.Uint32(uint32(ban.Duration / time.Second)),
})
}
}
return client.Conn.WriteProto(&packet)
}

207
gumble/gumble/channel.go Normal file
View File

@ -0,0 +1,207 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
"github.com/golang/protobuf/proto"
)
// Channel represents a channel in the server's channel tree.
type Channel struct {
// The channel's unique ID.
ID uint32
// The channel's name.
Name string
// The channel's parent. nil if the channel is the root channel.
Parent *Channel
// The channels directly underneath the channel.
Children Channels
// The channels that are linked to the channel.
Links Channels
// The users currently in the channel.
Users Users
// The channel's description. Contains the empty string if the channel does
// not have a description, or if it needs to be requested.
Description string
// The channel's description hash. nil if Channel.Description has
// been populated.
DescriptionHash []byte
// The maximum number of users allowed in the channel. If the value is zero,
// the maximum number of users per-channel is dictated by the server's
// "usersperchannel" setting.
MaxUsers uint32
// The position at which the channel should be displayed in an ordered list.
Position int32
// Is the channel temporary?
Temporary bool
client *Client
}
// IsRoot returns true if the channel is the server's root channel.
func (c *Channel) IsRoot() bool {
return c.ID == 0
}
// Add will add a sub-channel to the given channel.
func (c *Channel) Add(name string, temporary bool) {
packet := MumbleProto.ChannelState{
Parent: &c.ID,
Name: &name,
Temporary: &temporary,
}
c.client.Conn.WriteProto(&packet)
}
// Remove will remove the given channel and all sub-channels from the server's
// channel tree.
func (c *Channel) Remove() {
packet := MumbleProto.ChannelRemove{
ChannelId: &c.ID,
}
c.client.Conn.WriteProto(&packet)
}
// SetName will set the name of the channel. This will have no effect if the
// channel is the server's root channel.
func (c *Channel) SetName(name string) {
packet := MumbleProto.ChannelState{
ChannelId: &c.ID,
Name: &name,
}
c.client.Conn.WriteProto(&packet)
}
// SetDescription will set the description of the channel.
func (c *Channel) SetDescription(description string) {
packet := MumbleProto.ChannelState{
ChannelId: &c.ID,
Description: &description,
}
c.client.Conn.WriteProto(&packet)
}
// SetPosition will set the position of the channel.
func (c *Channel) SetPosition(position int32) {
packet := MumbleProto.ChannelState{
ChannelId: &c.ID,
Position: &position,
}
c.client.Conn.WriteProto(&packet)
}
// SetMaxUsers will set the maximum number of users allowed in the channel.
func (c *Channel) SetMaxUsers(maxUsers uint32) {
packet := MumbleProto.ChannelState{
ChannelId: &c.ID,
MaxUsers: &maxUsers,
}
c.client.Conn.WriteProto(&packet)
}
// Find returns a channel whose path (by channel name) from the current channel
// is equal to the arguments passed.
//
// For example, given the following server channel tree:
// Root
// Child 1
// Child 2
// Child 2.1
// Child 2.2
// Child 2.2.1
// Child 3
// To get the "Child 2.2.1" channel:
// root.Find("Child 2", "Child 2.2", "Child 2.2.1")
func (c *Channel) Find(names ...string) *Channel {
if len(names) == 0 {
return c
}
for _, child := range c.Children {
if child.Name == names[0] {
return child.Find(names[1:]...)
}
}
return nil
}
// RequestDescription requests that the actual channel description
// (i.e. non-hashed) be sent to the client.
func (c *Channel) RequestDescription() {
packet := MumbleProto.RequestBlob{
ChannelDescription: []uint32{c.ID},
}
c.client.Conn.WriteProto(&packet)
}
// RequestACL requests that the channel's ACL to be sent to the client.
func (c *Channel) RequestACL() {
packet := MumbleProto.ACL{
ChannelId: &c.ID,
Query: proto.Bool(true),
}
c.client.Conn.WriteProto(&packet)
}
// RequestPermission requests that the channel's permission information to be
// sent to the client.
//
// Note: the server will not reply to the request if the client has up-to-date
// permission information.
func (c *Channel) RequestPermission() {
packet := MumbleProto.PermissionQuery{
ChannelId: &c.ID,
}
c.client.Conn.WriteProto(&packet)
}
// Send will send a text message to the channel.
func (c *Channel) Send(message string, recursive bool) {
textMessage := TextMessage{
Message: message,
}
if recursive {
textMessage.Trees = []*Channel{c}
} else {
textMessage.Channels = []*Channel{c}
}
c.client.Send(&textMessage)
}
// Permission returns the permissions the user has in the channel, or nil if
// the permissions are unknown.
func (c *Channel) Permission() *Permission {
return c.client.permissions[c.ID]
}
// Link links the given channels to the channel.
func (c *Channel) Link(channel ...*Channel) {
packet := MumbleProto.ChannelState{
ChannelId: &c.ID,
LinksAdd: make([]uint32, len(channel)),
}
for i, ch := range channel {
packet.LinksAdd[i] = ch.ID
}
c.client.Conn.WriteProto(&packet)
}
// Unlink unlinks the given channels from the channel. If no arguments are
// passed, all linked channels are unlinked.
func (c *Channel) Unlink(channel ...*Channel) {
packet := MumbleProto.ChannelState{
ChannelId: &c.ID,
}
if len(channel) == 0 {
packet.LinksRemove = make([]uint32, len(c.Links))
i := 0
for channelID := range c.Links {
packet.LinksRemove[i] = channelID
i++
}
} else {
packet.LinksRemove = make([]uint32, len(channel))
for i, ch := range channel {
packet.LinksRemove[i] = ch.ID
}
}
c.client.Conn.WriteProto(&packet)
}

28
gumble/gumble/channels.go Normal file
View File

@ -0,0 +1,28 @@
package gumble
// Channels is a map of server channels.
type Channels map[uint32]*Channel
// create adds a new channel with the given id to the collection. If a channel
// with the given id already exists, it is overwritten.
func (c Channels) create(id uint32) *Channel {
channel := &Channel{
ID: id,
Links: Channels{},
Children: Channels{},
Users: Users{},
}
c[id] = channel
return channel
}
// Find returns a channel whose path (by channel name) from the server root
// channel is equal to the arguments passed. nil is returned if c does not
// containt the root channel.
func (c Channels) Find(names ...string) *Channel {
root := c[0]
if names == nil || root == nil {
return root
}
return root.Find(names...)
}

289
gumble/gumble/client.go Normal file
View File

@ -0,0 +1,289 @@
package gumble
import (
"crypto/tls"
"errors"
"math"
"net"
"runtime"
"sync/atomic"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
"github.com/golang/protobuf/proto"
)
// State is the current state of the client's connection to the server.
type State int
const (
// StateDisconnected means the client is no longer connected to the server.
StateDisconnected State = iota
// StateConnected means the client is connected to the server and is
// syncing initial information. This is an internal state that will
// never be returned by Client.State().
StateConnected
// StateSynced means the client is connected to a server and has been sent
// the server state.
StateSynced
)
// ClientVersion is the protocol version that Client implements.
const ClientVersion = 1<<16 | 3<<8 | 0
// Client is the type used to create a connection to a server.
type Client struct {
// The User associated with the client.
Self *User
// The client's configuration.
Config *Config
// The underlying Conn to the server.
Conn *Conn
// The users currently connected to the server.
Users Users
// The connected server's channels.
Channels Channels
permissions map[uint32]*Permission
tmpACL *ACL
// Ping stats
tcpPacketsReceived uint32
tcpPingTimes [12]float32
tcpPingAvg uint32
tcpPingVar uint32
// A collection containing the server's context actions.
ContextActions ContextActions
// The audio encoder used when sending audio to the server.
AudioEncoder AudioEncoder
audioCodec AudioCodec
// To whom transmitted audio will be sent. The VoiceTarget must have already
// been sent to the server for targeting to work correctly. Setting to nil
// will disable voice targeting (i.e. switch back to regular speaking).
VoiceTarget *VoiceTarget
state uint32
// volatile is held by the client when the internal data structures are being
// modified.
volatile rpwMutex
connect chan *RejectError
end chan struct{}
disconnectEvent DisconnectEvent
}
// Dial is an alias of DialWithDialer(new(net.Dialer), config, nil).
func Dial(config *Config) (*Client, error) {
return DialWithDialer(new(net.Dialer), config, nil)
}
// DialWithDialer connects to the Mumble server at the address given in config.
//
// The function returns after the connection has been established, the initial
// server information has been synced, and the OnConnect handlers have been
// called.
//
// nil and an error is returned if server synchronization does not complete by
// min(time.Now() + dialer.Timeout, dialer.Deadline), or if the server rejects
// the client.
func DialWithDialer(dialer *net.Dialer, config *Config, tlsConfig *tls.Config) (*Client, error) {
start := time.Now()
conn, err := tls.DialWithDialer(dialer, "tcp", config.Address, tlsConfig)
if err != nil {
return nil, err
}
client := &Client{
Conn: NewConn(conn),
Config: config,
Users: make(Users),
Channels: make(Channels),
permissions: make(map[uint32]*Permission),
state: uint32(StateConnected),
connect: make(chan *RejectError),
end: make(chan struct{}),
}
go client.readRoutine()
// Initial packets
versionPacket := MumbleProto.Version{
Version: proto.Uint32(ClientVersion),
Release: proto.String("gumble"),
Os: proto.String(runtime.GOOS),
OsVersion: proto.String(runtime.GOARCH),
}
authenticationPacket := MumbleProto.Authenticate{
Username: &client.Config.Username,
Password: &client.Config.Password,
Opus: proto.Bool(getAudioCodec(audioCodecIDOpus) != nil),
Tokens: client.Config.Tokens,
}
client.Conn.WriteProto(&versionPacket)
client.Conn.WriteProto(&authenticationPacket)
go client.pingRoutine()
var timeout <-chan time.Time
{
var deadline time.Time
if !dialer.Deadline.IsZero() {
deadline = dialer.Deadline
}
if dialer.Timeout > 0 {
diff := start.Add(dialer.Timeout)
if deadline.IsZero() || diff.Before(deadline) {
deadline = diff
}
}
if !deadline.IsZero() {
timer := time.NewTimer(deadline.Sub(start))
defer timer.Stop()
timeout = timer.C
}
}
select {
case <-timeout:
client.Conn.Close()
return nil, errors.New("gumble: synchronization timeout")
case err := <-client.connect:
if err != nil {
client.Conn.Close()
return nil, err
}
return client, nil
}
}
// State returns the current state of the client.
func (c *Client) State() State {
return State(atomic.LoadUint32(&c.state))
}
// AudioOutgoing creates a new channel that outgoing audio data can be written
// to. The channel must be closed after the audio stream is completed. Only
// a single channel should be open at any given time (i.e. close the channel
// before opening another).
func (c *Client) AudioOutgoing() chan<- AudioBuffer {
ch := make(chan AudioBuffer)
go func() {
var seq int64
previous := <-ch
for p := range ch {
previous.writeAudio(c, seq, false)
previous = p
seq = (seq + 1) % math.MaxInt32
}
if previous != nil {
previous.writeAudio(c, seq, true)
}
}()
return ch
}
// pingRoutine sends ping packets to the server at regular intervals.
func (c *Client) pingRoutine() {
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
var timestamp uint64
var tcpPingAvg float32
var tcpPingVar float32
packet := MumbleProto.Ping{
Timestamp: &timestamp,
TcpPackets: &c.tcpPacketsReceived,
TcpPingAvg: &tcpPingAvg,
TcpPingVar: &tcpPingVar,
}
t := time.Now()
for {
timestamp = uint64(t.UnixNano())
tcpPingAvg = math.Float32frombits(atomic.LoadUint32(&c.tcpPingAvg))
tcpPingVar = math.Float32frombits(atomic.LoadUint32(&c.tcpPingVar))
c.Conn.WriteProto(&packet)
select {
case <-c.end:
return
case t = <-ticker.C:
// continue to top of loop
}
}
}
// readRoutine reads protocol buffer messages from the server.
func (c *Client) readRoutine() {
c.disconnectEvent = DisconnectEvent{
Client: c,
Type: DisconnectError,
}
for {
pType, data, err := c.Conn.ReadPacket()
if err != nil {
break
}
if int(pType) < len(handlers) {
handlers[pType](c, data)
}
}
wasSynced := c.State() == StateSynced
atomic.StoreUint32(&c.state, uint32(StateDisconnected))
close(c.end)
if wasSynced {
c.Config.Listeners.onDisconnect(&c.disconnectEvent)
}
}
// RequestUserList requests that the server's registered user list be sent to
// the client.
func (c *Client) RequestUserList() {
packet := MumbleProto.UserList{}
c.Conn.WriteProto(&packet)
}
// RequestBanList requests that the server's ban list be sent to the client.
func (c *Client) RequestBanList() {
packet := MumbleProto.BanList{
Query: proto.Bool(true),
}
c.Conn.WriteProto(&packet)
}
// Disconnect disconnects the client from the server.
func (c *Client) Disconnect() error {
if c.State() == StateDisconnected {
return errors.New("gumble: client is already disconnected")
}
c.disconnectEvent.Type = DisconnectUser
c.Conn.Close()
return nil
}
// Do executes f in a thread-safe manner. It ensures that Client and its
// associated data will not be changed during the lifetime of the function
// call.
func (c *Client) Do(f func()) {
c.volatile.RLock()
defer c.volatile.RUnlock()
f()
}
// Send will send a Message to the server.
func (c *Client) Send(message Message) {
message.writeMessage(c)
}

57
gumble/gumble/config.go Normal file
View File

@ -0,0 +1,57 @@
package gumble
import (
"time"
)
// Config holds the Mumble configuration used by Client. A single Config should
// not be shared between multiple Client instances.
type Config struct {
// User name used when authenticating with the server.
Username string
// Password used when authenticating with the server. A password is not
// usually required to connect to a server.
Password string
//the address to use
Address string
// The initial access tokens to the send to the server. Access tokens can be
// resent to the server using:
// client.Send(config.Tokens)
Tokens AccessTokens
// AudioInterval is the interval at which audio packets are sent. Valid
// values are: 10ms, 20ms, 40ms, and 60ms.
AudioInterval time.Duration
// AudioDataBytes is the number of bytes that an audio frame can use.
AudioDataBytes int
// The event listeners used when client events are triggered.
Listeners Listeners
AudioListeners AudioListeners
Buffers int
}
// NewConfig returns a new Config struct with default values set.
func NewConfig() *Config {
return &Config{
Buffers: 8,
AudioInterval: AudioDefaultInterval,
AudioDataBytes: AudioDefaultDataBytes,
}
}
// Attach is an alias of c.Listeners.Attach.
func (c *Config) Attach(l EventListener) Detacher {
return c.Listeners.Attach(l)
}
// AttachAudio is an alias of c.AudioListeners.Attach.
func (c *Config) AttachAudio(l AudioListener) Detacher {
return c.AudioListeners.Attach(l)
}
// AudioFrameSize returns the appropriate audio frame size, based off of the
// audio interval.
func (c *Config) AudioFrameSize() int {
return int(c.AudioInterval/AudioDefaultInterval) * AudioDefaultFrameSize
}

200
gumble/gumble/conn.go Normal file
View File

@ -0,0 +1,200 @@
package gumble
import (
"encoding/binary"
"errors"
"io"
"net"
"sync"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
"git.2mb.codes/~cmb/barnard/gumble/gumble/varint"
"github.com/golang/protobuf/proto"
)
// DefaultPort is the default port on which Mumble servers listen.
const DefaultPort = 64738
// Conn represents a control protocol connection to a Mumble client/server.
type Conn struct {
sync.Mutex
net.Conn
MaximumPacketBytes int
Timeout time.Duration
buffer []byte
}
// NewConn creates a new Conn with the given net.Conn.
func NewConn(conn net.Conn) *Conn {
return &Conn{
Conn: conn,
Timeout: time.Second * 20,
MaximumPacketBytes: 1024 * 1024 * 10,
}
}
// ReadPacket reads a packet from the server. Returns the packet type, the
// packet data, and nil on success.
//
// This function should only be called by a single go routine.
func (c *Conn) ReadPacket() (uint16, []byte, error) {
c.Conn.SetReadDeadline(time.Now().Add(c.Timeout))
var header [6]byte
if _, err := io.ReadFull(c.Conn, header[:]); err != nil {
return 0, nil, err
}
pType := binary.BigEndian.Uint16(header[:])
pLength := binary.BigEndian.Uint32(header[2:])
pLengthInt := int(pLength)
if pLengthInt > c.MaximumPacketBytes {
return 0, nil, errors.New("gumble: packet larger than maximum allowed size")
}
if pLengthInt > len(c.buffer) {
c.buffer = make([]byte, pLengthInt)
}
if _, err := io.ReadFull(c.Conn, c.buffer[:pLengthInt]); err != nil {
return 0, nil, err
}
return pType, c.buffer[:pLengthInt], nil
}
// WriteAudio writes an audio packet to the connection.
func (c *Conn) WriteAudio(format, target byte, sequence int64, final bool, data []byte, X, Y, Z *float32) error {
var buff [1 + varint.MaxVarintLen*2]byte
buff[0] = (format << 5) | target
n := varint.Encode(buff[1:], sequence)
if n == 0 {
return errors.New("gumble: varint out of range")
}
l := int64(len(data))
if final {
l |= 0x2000
}
m := varint.Encode(buff[1+n:], l)
if m == 0 {
return errors.New("gumble: varint out of range")
}
header := buff[:1+n+m]
var positionalLength int
if X != nil {
positionalLength = 3 * 4
}
c.Lock()
defer c.Unlock()
if err := c.writeHeader(1, uint32(len(header)+len(data)+positionalLength)); err != nil {
return err
}
if _, err := c.Conn.Write(header); err != nil {
return err
}
if _, err := c.Conn.Write(data); err != nil {
return err
}
if positionalLength > 0 {
if err := binary.Write(c.Conn, binary.LittleEndian, *X); err != nil {
return err
}
if err := binary.Write(c.Conn, binary.LittleEndian, *Y); err != nil {
return err
}
if err := binary.Write(c.Conn, binary.LittleEndian, *Z); err != nil {
return err
}
}
return nil
}
// WritePacket writes a data packet of the given type to the connection.
func (c *Conn) WritePacket(ptype uint16, data []byte) error {
c.Lock()
defer c.Unlock()
if err := c.writeHeader(uint16(ptype), uint32(len(data))); err != nil {
return err
}
if _, err := c.Conn.Write(data); err != nil {
return err
}
return nil
}
func (c *Conn) writeHeader(pType uint16, pLength uint32) error {
var header [6]byte
binary.BigEndian.PutUint16(header[:], pType)
binary.BigEndian.PutUint32(header[2:], pLength)
if _, err := c.Conn.Write(header[:]); err != nil {
return err
}
return nil
}
// WriteProto writes a protocol buffer message to the connection.
func (c *Conn) WriteProto(message proto.Message) error {
var protoType uint16
switch message.(type) {
case *MumbleProto.Version:
protoType = 0
case *MumbleProto.Authenticate:
protoType = 2
case *MumbleProto.Ping:
protoType = 3
case *MumbleProto.Reject:
protoType = 4
case *MumbleProto.ServerSync:
protoType = 5
case *MumbleProto.ChannelRemove:
protoType = 6
case *MumbleProto.ChannelState:
protoType = 7
case *MumbleProto.UserRemove:
protoType = 8
case *MumbleProto.UserState:
protoType = 9
case *MumbleProto.BanList:
protoType = 10
case *MumbleProto.TextMessage:
protoType = 11
case *MumbleProto.PermissionDenied:
protoType = 12
case *MumbleProto.ACL:
protoType = 13
case *MumbleProto.QueryUsers:
protoType = 14
case *MumbleProto.CryptSetup:
protoType = 15
case *MumbleProto.ContextActionModify:
protoType = 16
case *MumbleProto.ContextAction:
protoType = 17
case *MumbleProto.UserList:
protoType = 18
case *MumbleProto.VoiceTarget:
protoType = 19
case *MumbleProto.PermissionQuery:
protoType = 20
case *MumbleProto.CodecVersion:
protoType = 21
case *MumbleProto.UserStats:
protoType = 22
case *MumbleProto.RequestBlob:
protoType = 23
case *MumbleProto.ServerConfig:
protoType = 24
case *MumbleProto.SuggestConfig:
protoType = 25
default:
return errors.New("gumble: unknown message type")
}
data, err := proto.Marshal(message)
if err != nil {
return err
}
return c.WritePacket(protoType, data)
}

View File

@ -0,0 +1,57 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// ContextActionType is a bitmask of contexts where a ContextAction can be
// triggered.
type ContextActionType int
// Supported ContextAction contexts.
const (
ContextActionServer ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Server)
ContextActionChannel ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Channel)
ContextActionUser ContextActionType = ContextActionType(MumbleProto.ContextActionModify_User)
)
// ContextAction is an triggerable item that has been added by a server-side
// plugin.
type ContextAction struct {
// The context action type.
Type ContextActionType
// The name of the context action.
Name string
// The user-friendly description of the context action.
Label string
client *Client
}
// Trigger will trigger the context action in the context of the server.
func (c *ContextAction) Trigger() {
packet := MumbleProto.ContextAction{
Action: &c.Name,
}
c.client.Conn.WriteProto(&packet)
}
// TriggerUser will trigger the context action in the context of the given
// user.
func (c *ContextAction) TriggerUser(user *User) {
packet := MumbleProto.ContextAction{
Session: &user.Session,
Action: &c.Name,
}
c.client.Conn.WriteProto(&packet)
}
// TriggerChannel will trigger the context action in the context of the given
// channel.
func (c *ContextAction) TriggerChannel(channel *Channel) {
packet := MumbleProto.ContextAction{
ChannelId: &channel.ID,
Action: &c.Name,
}
c.client.Conn.WriteProto(&packet)
}

View File

@ -0,0 +1,12 @@
package gumble
// ContextActions is a map of ContextActions.
type ContextActions map[string]*ContextAction
func (c ContextActions) create(action string) *ContextAction {
contextAction := &ContextAction{
Name: action,
}
c[action] = contextAction
return contextAction
}

View File

@ -0,0 +1,7 @@
package gumble
// Detacher is an interface that event listeners implement. After the Detach
// method is called, the listener will no longer receive events.
type Detacher interface {
Detach()
}

45
gumble/gumble/doc.go Normal file
View File

@ -0,0 +1,45 @@
// Package gumble is a client for the Mumble voice chat software.
//
// Getting started
//
// 1. Create a new Config to hold your connection settings:
//
// config := gumble.NewConfig()
// config.Username = "gumble-test"
//
// 2. Attach event listeners to the configuration:
//
// config.Attach(gumbleutil.Listener{
// TextMessage: func(e *gumble.TextMessageEvent) {
// fmt.Printf("Received text message: %s\n", e.Message)
// },
// })
//
// 3. Connect to the server:
//
// client, err := gumble.Dial("example.com:64738", config)
// if err != nil {
// panic(err)
// }
//
// Audio codecs
//
// Currently, only the Opus codec (https://www.opus-codec.org/) is supported
// for transmitting and receiving audio. It can be enabled by importing the
// following package for its side effect:
// import (
// _ "git.2mb.codes/~cmb/barnard/gumble/opus"
// )
//
// To ensure that gumble clients can always transmit and receive audio to and
// from your server, add the following line to your murmur configuration file:
//
// opusthreshold=0
//
// Thread safety
//
// As a general rule, a Client everything that is associated with it
// (Users, Channels, Config, etc.), is thread-unsafe. Accessing or modifying
// those structures should only be done from inside of an event listener or via
// Client.Do.
package gumble // import "git.2mb.codes/~cmb/barnard/gumble/gumble"

222
gumble/gumble/event.go Normal file
View File

@ -0,0 +1,222 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// EventListener is the interface that must be implemented by a type if it
// wishes to be notified of Client events.
//
// Listener methods are executed synchronously as event happen. They also block
// network reads from happening until all handlers for an event are called.
// Therefore, it is not recommended to do any long processing from inside of
// these methods.
type EventListener interface {
OnConnect(e *ConnectEvent)
OnDisconnect(e *DisconnectEvent)
OnTextMessage(e *TextMessageEvent)
OnUserChange(e *UserChangeEvent)
OnChannelChange(e *ChannelChangeEvent)
OnPermissionDenied(e *PermissionDeniedEvent)
OnUserList(e *UserListEvent)
OnACL(e *ACLEvent)
OnBanList(e *BanListEvent)
OnContextActionChange(e *ContextActionChangeEvent)
OnServerConfig(e *ServerConfigEvent)
}
// ConnectEvent is the event that is passed to EventListener.OnConnect.
type ConnectEvent struct {
Client *Client
WelcomeMessage *string
MaximumBitrate *int
}
// DisconnectType specifies why a Client disconnected from a server.
type DisconnectType int
// Client disconnect reasons.
const (
DisconnectError DisconnectType = iota + 1
DisconnectKicked
DisconnectBanned
DisconnectUser
)
// Has returns true if the DisconnectType has changeType part of its bitmask.
func (d DisconnectType) Has(changeType DisconnectType) bool {
return d&changeType == changeType
}
// DisconnectEvent is the event that is passed to EventListener.OnDisconnect.
type DisconnectEvent struct {
Client *Client
Type DisconnectType
String string
}
// TextMessageEvent is the event that is passed to EventListener.OnTextMessage.
type TextMessageEvent struct {
Client *Client
TextMessage
}
// UserChangeType is a bitmask of items that changed for a user.
type UserChangeType int
// User change items.
const (
UserChangeConnected UserChangeType = 1 << iota
UserChangeDisconnected
UserChangeKicked
UserChangeBanned
UserChangeRegistered
UserChangeUnregistered
UserChangeName
UserChangeChannel
UserChangeComment
UserChangeAudio
UserChangeTexture
UserChangePrioritySpeaker
UserChangeRecording
UserChangeStats
)
// Has returns true if the UserChangeType has changeType part of its bitmask.
func (u UserChangeType) Has(changeType UserChangeType) bool {
return u&changeType == changeType
}
// UserChangeEvent is the event that is passed to EventListener.OnUserChange.
type UserChangeEvent struct {
Client *Client
Type UserChangeType
User *User
Actor *User
String string
}
// ChannelChangeType is a bitmask of items that changed for a channel.
type ChannelChangeType int
// Channel change items.
const (
ChannelChangeCreated ChannelChangeType = 1 << iota
ChannelChangeRemoved
ChannelChangeMoved
ChannelChangeName
ChannelChangeLinks
ChannelChangeDescription
ChannelChangePosition
ChannelChangePermission
ChannelChangeMaxUsers
)
// Has returns true if the ChannelChangeType has changeType part of its
// bitmask.
func (c ChannelChangeType) Has(changeType ChannelChangeType) bool {
return c&changeType == changeType
}
// ChannelChangeEvent is the event that is passed to
// EventListener.OnChannelChange.
type ChannelChangeEvent struct {
Client *Client
Type ChannelChangeType
Channel *Channel
}
// PermissionDeniedType specifies why a Client was denied permission to perform
// a particular action.
type PermissionDeniedType int
// Permission denied types.
const (
PermissionDeniedOther PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Text)
PermissionDeniedPermission PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Permission)
PermissionDeniedSuperUser PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_SuperUser)
PermissionDeniedInvalidChannelName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelName)
PermissionDeniedTextTooLong PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TextTooLong)
PermissionDeniedTemporaryChannel PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TemporaryChannel)
PermissionDeniedMissingCertificate PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_MissingCertificate)
PermissionDeniedInvalidUserName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_UserName)
PermissionDeniedChannelFull PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelFull)
PermissionDeniedNestingLimit PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_NestingLimit)
)
// Has returns true if the PermissionDeniedType has changeType part of its
// bitmask.
func (p PermissionDeniedType) Has(changeType PermissionDeniedType) bool {
return p&changeType == changeType
}
// PermissionDeniedEvent is the event that is passed to
// EventListener.OnPermissionDenied.
type PermissionDeniedEvent struct {
Client *Client
Type PermissionDeniedType
Channel *Channel
User *User
Permission Permission
String string
}
// UserListEvent is the event that is passed to EventListener.OnUserList.
type UserListEvent struct {
Client *Client
UserList RegisteredUsers
}
// ACLEvent is the event that is passed to EventListener.OnACL.
type ACLEvent struct {
Client *Client
ACL *ACL
}
// BanListEvent is the event that is passed to EventListener.OnBanList.
type BanListEvent struct {
Client *Client
BanList BanList
}
// ContextActionChangeType specifies how a ContextAction changed.
type ContextActionChangeType int
// ContextAction change types.
const (
ContextActionAdd ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Add)
ContextActionRemove ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Remove)
)
// ContextActionChangeEvent is the event that is passed to
// EventListener.OnContextActionChange.
type ContextActionChangeEvent struct {
Client *Client
Type ContextActionChangeType
ContextAction *ContextAction
}
// ServerConfigEvent is the event that is passed to
// EventListener.OnServerConfig.
type ServerConfigEvent struct {
Client *Client
MaximumBitrate *int
WelcomeMessage *string
AllowHTML *bool
MaximumMessageLength *int
MaximumImageMessageLength *int
MaximumUsers *int
CodecAlpha *int32
CodecBeta *int32
CodecPreferAlpha *bool
CodecOpus *bool
SuggestVersion *Version
SuggestPositional *bool
SuggestPushToTalk *bool
}

1261
gumble/gumble/handlers.go Normal file

File diff suppressed because it is too large Load Diff

153
gumble/gumble/listeners.go Normal file
View File

@ -0,0 +1,153 @@
package gumble
type eventItem struct {
parent *Listeners
prev, next *eventItem
listener EventListener
}
func (e *eventItem) Detach() {
if e.prev == nil {
e.parent.head = e.next
} else {
e.prev.next = e.next
}
if e.next == nil {
e.parent.tail = e.prev
} else {
e.next.prev = e.prev
}
}
// Listeners is a list of event listeners. Each attached listener is called in
// sequence when a Client event is triggered.
type Listeners struct {
head, tail *eventItem
}
// Attach adds a new event listener to the end of the current list of listeners.
func (e *Listeners) Attach(listener EventListener) Detacher {
item := &eventItem{
parent: e,
prev: e.tail,
listener: listener,
}
if e.head == nil {
e.head = item
}
if e.tail != nil {
e.tail.next = item
}
e.tail = item
return item
}
func (e *Listeners) onConnect(event *ConnectEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnConnect(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onDisconnect(event *DisconnectEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnDisconnect(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onTextMessage(event *TextMessageEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnTextMessage(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onUserChange(event *UserChangeEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnUserChange(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onChannelChange(event *ChannelChangeEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnChannelChange(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onPermissionDenied(event *PermissionDeniedEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnPermissionDenied(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onUserList(event *UserListEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnUserList(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onACL(event *ACLEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnACL(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onBanList(event *BanListEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnBanList(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onContextActionChange(event *ContextActionChangeEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnContextActionChange(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}
func (e *Listeners) onServerConfig(event *ServerConfigEvent) {
event.Client.volatile.Lock()
for item := e.head; item != nil; item = item.next {
event.Client.volatile.Unlock()
item.listener.OnServerConfig(event)
event.Client.volatile.Lock()
}
event.Client.volatile.Unlock()
}

13
gumble/gumble/message.go Normal file
View File

@ -0,0 +1,13 @@
package gumble
// Message is data that be encoded and sent to the server. The following
// types implement this interface:
// AccessTokens
// ACL
// BanList
// RegisteredUsers
// TextMessage
// VoiceTarget
type Message interface {
writeMessage(client *Client) error
}

View File

@ -0,0 +1,33 @@
package gumble
// Permission is a bitmask of permissions given to a certain user.
type Permission int
// Permissions that can be applied in any channel.
const (
PermissionWrite Permission = 1 << iota
PermissionTraverse
PermissionEnter
PermissionSpeak
PermissionMuteDeafen
PermissionMove
PermissionMakeChannel
PermissionLinkChannel
PermissionWhisper
PermissionTextMessage
PermissionMakeTemporaryChannel
)
// Permissions that can only be applied in the root channel.
const (
PermissionKick Permission = 0x10000 << iota
PermissionBan
PermissionRegister
PermissionRegisterSelf
)
// Has returns true if the Permission p contains Permission o has part of its
// bitmask.
func (p Permission) Has(o Permission) bool {
return p&o == o
}

108
gumble/gumble/ping.go Normal file
View File

@ -0,0 +1,108 @@
package gumble
import (
"crypto/rand"
"encoding/binary"
"errors"
"io"
"net"
"sync"
"time"
)
// PingResponse contains information about a server that responded to a UDP
// ping packet.
type PingResponse struct {
// The address of the pinged server.
Address *net.UDPAddr
// The round-trip time from the client to the server.
Ping time.Duration
// The server's version. Only the Version field and SemanticVersion method of
// the value will be valid.
Version Version
// The number users currently connected to the server.
ConnectedUsers int
// The maximum number of users that can connect to the server.
MaximumUsers int
// The maximum audio bitrate per user for the server.
MaximumBitrate int
}
// Ping sends a UDP ping packet to the given server. If interval is positive,
// the packet is retransmitted at every interval.
//
// Returns a PingResponse and nil on success. The function will return nil and
// an error if a valid response is not received after the given timeout.
func Ping(address string, interval, timeout time.Duration) (*PingResponse, error) {
if timeout < 0 {
return nil, errors.New("gumble: timeout must be positive")
}
deadline := time.Now().Add(timeout)
conn, err := net.DialTimeout("udp", address, timeout)
if err != nil {
return nil, err
}
defer conn.Close()
conn.SetReadDeadline(deadline)
var (
idsLock sync.Mutex
ids = make(map[string]time.Time)
)
buildSendPacket := func() {
var packet [12]byte
if _, err := rand.Read(packet[4:]); err != nil {
return
}
id := string(packet[4:])
idsLock.Lock()
ids[id] = time.Now()
idsLock.Unlock()
conn.Write(packet[:])
}
if interval > 0 {
end := make(chan struct{})
defer close(end)
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
buildSendPacket()
case <-end:
return
}
}
}()
}
buildSendPacket()
for {
var incoming [24]byte
if _, err := io.ReadFull(conn, incoming[:]); err != nil {
return nil, err
}
id := string(incoming[4:12])
idsLock.Lock()
sendTime, ok := ids[id]
idsLock.Unlock()
if !ok {
continue
}
return &PingResponse{
Address: conn.RemoteAddr().(*net.UDPAddr),
Ping: time.Since(sendTime),
Version: Version{
Version: binary.BigEndian.Uint32(incoming[0:]),
},
ConnectedUsers: int(binary.BigEndian.Uint32(incoming[12:])),
MaximumUsers: int(binary.BigEndian.Uint32(incoming[16:])),
MaximumBitrate: int(binary.BigEndian.Uint32(incoming[20:])),
}, nil
}
}

61
gumble/gumble/reject.go Normal file
View File

@ -0,0 +1,61 @@
package gumble
import (
"strconv"
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// RejectType describes why a client connection was rejected by the server.
type RejectType int
// The possible reason why a client connection was rejected by the server.
const (
RejectNone RejectType = RejectType(MumbleProto.Reject_None)
RejectVersion RejectType = RejectType(MumbleProto.Reject_WrongVersion)
RejectUserName RejectType = RejectType(MumbleProto.Reject_InvalidUsername)
RejectUserCredentials RejectType = RejectType(MumbleProto.Reject_WrongUserPW)
RejectServerPassword RejectType = RejectType(MumbleProto.Reject_WrongServerPW)
RejectUsernameInUse RejectType = RejectType(MumbleProto.Reject_UsernameInUse)
RejectServerFull RejectType = RejectType(MumbleProto.Reject_ServerFull)
RejectNoCertificate RejectType = RejectType(MumbleProto.Reject_NoCertificate)
RejectAuthenticatorFail RejectType = RejectType(MumbleProto.Reject_AuthenticatorFail)
)
// RejectError is returned by DialWithDialer when the server rejects the client
// connection.
type RejectError struct {
Type RejectType
Reason string
}
// Error implements error.
func (e RejectError) Error() string {
var msg string
switch e.Type {
case RejectNone:
msg = "none"
case RejectVersion:
msg = "wrong client version"
case RejectUserName:
msg = "invalid username"
case RejectUserCredentials:
msg = "incorrect user credentials"
case RejectServerPassword:
msg = "incorrect server password"
case RejectUsernameInUse:
msg = "username in use"
case RejectServerFull:
msg = "server full"
case RejectNoCertificate:
msg = "no certificate"
case RejectAuthenticatorFail:
msg = "authenticator fail"
default:
msg = "unknown type " + strconv.Itoa(int(e.Type))
}
if e.Reason != "" {
msg += ": " + e.Reason
}
return msg
}

36
gumble/gumble/rpwmutex.go Normal file
View File

@ -0,0 +1,36 @@
package gumble
import "sync"
// rpwMutex is a reader-preferred RWMutex.
type rpwMutex struct {
w sync.Mutex
r sync.Mutex
n int
}
func (m *rpwMutex) Lock() {
m.w.Lock()
}
func (m *rpwMutex) Unlock() {
m.w.Unlock()
}
func (m *rpwMutex) RLock() {
m.r.Lock()
m.n++
if m.n == 1 {
m.w.Lock()
}
m.r.Unlock()
}
func (m *rpwMutex) RUnlock() {
m.r.Lock()
m.n--
if m.n == 0 {
m.w.Unlock()
}
m.r.Unlock()
}

View File

@ -0,0 +1,45 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// TextMessage is a chat message that can be received from and sent to the
// server.
type TextMessage struct {
// User who sent the message (can be nil).
Sender *User
// Users that receive the message.
Users []*User
// Channels that receive the message.
Channels []*Channel
// Channels that receive the message and send it recursively to sub-channels.
Trees []*Channel
// Chat message.
Message string
}
func (t *TextMessage) writeMessage(client *Client) error {
packet := MumbleProto.TextMessage{
Message: &t.Message,
}
if t.Users != nil {
packet.Session = make([]uint32, len(t.Users))
for i, user := range t.Users {
packet.Session[i] = user.Session
}
}
if t.Channels != nil {
packet.ChannelId = make([]uint32, len(t.Channels))
for i, channel := range t.Channels {
packet.ChannelId[i] = channel.ID
}
}
if t.Trees != nil {
packet.TreeId = make([]uint32, len(t.Trees))
for i, channel := range t.Trees {
packet.TreeId[i] = channel.ID
}
}
return client.Conn.WriteProto(&packet)
}

242
gumble/gumble/user.go Normal file
View File

@ -0,0 +1,242 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
"git.2mb.codes/~cmb/go-openal/openal"
"github.com/golang/protobuf/proto"
)
// User represents a user that is currently connected to the server.
type User struct {
// The user's unique session ID.
Session uint32
// The user's ID. Contains an invalid value if the user is not registered.
UserID uint32
// The user's name.
Name string
// The channel that the user is currently in.
Channel *Channel
// Has the user has been muted?
Muted bool
// Has the user been deafened?
Deafened bool
// Has the user been suppressed?
Suppressed bool
// Has the user been muted by him/herself?
SelfMuted bool
// Has the user been deafened by him/herself?
SelfDeafened bool
// Is the user a priority speaker in the channel?
PrioritySpeaker bool
// Is the user recording audio?
Recording bool
// The user's comment. Contains the empty string if the user does not have a
// comment, or if the comment needs to be requested.
Comment string
// The user's comment hash. nil if User.Comment has been populated.
CommentHash []byte
// The hash of the user's certificate (can be empty).
Hash string
// The user's texture (avatar). nil if the user does not have a
// texture, or if the texture needs to be requested.
Texture []byte
// The user's texture hash. nil if User.Texture has been populated.
TextureHash []byte
// The user's stats. Contains nil if the stats have not yet been requested.
Stats *UserStats
client *Client
decoder AudioDecoder
AudioSource *openal.Source
Boost uint16
Volume float32
}
func (u *User) GetClient() *Client {
return u.client
}
// SetTexture sets the user's texture.
func (u *User) SetTexture(texture []byte) {
packet := MumbleProto.UserState{
Session: &u.Session,
Texture: texture,
}
u.client.Conn.WriteProto(&packet)
}
// SetPrioritySpeaker sets if the user is a priority speaker in the channel.
func (u *User) SetPrioritySpeaker(prioritySpeaker bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
PrioritySpeaker: &prioritySpeaker,
}
u.client.Conn.WriteProto(&packet)
}
// SetRecording sets if the user is recording audio.
func (u *User) SetRecording(recording bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
Recording: &recording,
}
u.client.Conn.WriteProto(&packet)
}
// IsRegistered returns true if the user's certificate has been registered with
// the server. A registered user will have a valid user ID.
func (u *User) IsRegistered() bool {
return u.UserID > 0
}
// Register will register the user with the server. If the client has
// permission to do so, the user will shortly be given a UserID.
func (u *User) Register() {
packet := MumbleProto.UserState{
Session: &u.Session,
UserId: proto.Uint32(0),
}
u.client.Conn.WriteProto(&packet)
}
// SetComment will set the user's comment to the given string. The user's
// comment will be erased if the comment is set to the empty string.
func (u *User) SetComment(comment string) {
packet := MumbleProto.UserState{
Session: &u.Session,
Comment: &comment,
}
u.client.Conn.WriteProto(&packet)
}
// Move will move the user to the given channel.
func (u *User) Move(channel *Channel) {
packet := MumbleProto.UserState{
Session: &u.Session,
ChannelId: &channel.ID,
}
u.client.Conn.WriteProto(&packet)
}
// Kick will kick the user from the server.
func (u *User) Kick(reason string) {
packet := MumbleProto.UserRemove{
Session: &u.Session,
Reason: &reason,
}
u.client.Conn.WriteProto(&packet)
}
// Ban will ban the user from the server.
func (u *User) Ban(reason string) {
packet := MumbleProto.UserRemove{
Session: &u.Session,
Reason: &reason,
Ban: proto.Bool(true),
}
u.client.Conn.WriteProto(&packet)
}
// SetMuted sets whether the user can transmit audio or not.
func (u *User) SetMuted(muted bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
Mute: &muted,
}
u.client.Conn.WriteProto(&packet)
}
// SetSuppressed sets whether the user is suppressed by the server or not.
func (u *User) SetSuppressed(supressed bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
Suppress: &supressed,
}
u.client.Conn.WriteProto(&packet)
}
// SetDeafened sets whether the user can receive audio or not.
func (u *User) SetDeafened(muted bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
Deaf: &muted,
}
u.client.Conn.WriteProto(&packet)
}
// SetSelfMuted sets whether the user can transmit audio or not.
//
// This method should only be called on Client.Self().
func (u *User) SetSelfMuted(muted bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
SelfMute: &muted,
}
u.client.Conn.WriteProto(&packet)
}
// SetSelfDeafened sets whether the user can receive audio or not.
//
// This method should only be called on Client.Self().
func (u *User) SetSelfDeafened(muted bool) {
packet := MumbleProto.UserState{
Session: &u.Session,
SelfDeaf: &muted,
}
u.client.Conn.WriteProto(&packet)
}
// RequestStats requests that the user's stats be sent to the client.
func (u *User) RequestStats() {
packet := MumbleProto.UserStats{
Session: &u.Session,
}
u.client.Conn.WriteProto(&packet)
}
// RequestTexture requests that the user's actual texture (i.e. non-hashed) be
// sent to the client.
func (u *User) RequestTexture() {
packet := MumbleProto.RequestBlob{
SessionTexture: []uint32{u.Session},
}
u.client.Conn.WriteProto(&packet)
}
// RequestComment requests that the user's actual comment (i.e. non-hashed) be
// sent to the client.
func (u *User) RequestComment() {
packet := MumbleProto.RequestBlob{
SessionComment: []uint32{u.Session},
}
u.client.Conn.WriteProto(&packet)
}
// Send will send a text message to the user.
func (u *User) Send(message string) {
textMessage := TextMessage{
Users: []*User{u},
Message: message,
}
u.client.Send(&textMessage)
}
// SetPlugin sets the user's plugin data.
//
// Plugins are currently only used for positional audio. Clients will receive
// positional audio information from other users if their plugin context is the
// same. The official Mumble client sets the context to:
//
// PluginShortName + "\x00" + AdditionalContextInformation
func (u *User) SetPlugin(context []byte, identity string) {
packet := MumbleProto.UserState{
Session: &u.Session,
PluginContext: context,
PluginIdentity: &identity,
}
u.client.Conn.WriteProto(&packet)
}

74
gumble/gumble/userlist.go Normal file
View File

@ -0,0 +1,74 @@
package gumble
import (
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// RegisteredUser represents a registered user on the server.
type RegisteredUser struct {
// The registered user's ID.
UserID uint32
// The registered user's name.
Name string
// The last time the user was seen by the server.
LastSeen time.Time
// The last channel the user was seen in.
LastChannel *Channel
changed bool
deregister bool
}
// SetName sets the new name for the user.
func (r *RegisteredUser) SetName(name string) {
r.Name = name
r.changed = true
}
// Deregister will remove the registered user from the server.
func (r *RegisteredUser) Deregister() {
r.deregister = true
}
// Register will keep the user registered on the server. This is only useful if
// Deregister() was called on the registered user.
func (r *RegisteredUser) Register() {
r.deregister = false
}
// ACLUser returns an ACLUser for the given registered user.
func (r *RegisteredUser) ACLUser() *ACLUser {
return &ACLUser{
UserID: r.UserID,
Name: r.Name,
}
}
// RegisteredUsers is a list of users who are registered on the server.
//
// Whenever a registered user is changed, it does not come into effect until
// the registered user list is sent back to the server.
type RegisteredUsers []*RegisteredUser
func (r RegisteredUsers) writeMessage(client *Client) error {
packet := MumbleProto.UserList{}
for _, user := range r {
if user.deregister || user.changed {
userListUser := &MumbleProto.UserList_User{
UserId: &user.UserID,
}
if !user.deregister {
userListUser.Name = &user.Name
}
packet.Users = append(packet.Users, userListUser)
}
}
if len(packet.Users) <= 0 {
return nil
}
return client.Conn.WriteProto(&packet)
}

34
gumble/gumble/users.go Normal file
View File

@ -0,0 +1,34 @@
package gumble
import (
// "git.2mb.codes/~cmb/go-openal/openal"
)
// Users is a map of server users.
//
// When accessed through client.Users, it contains all users currently on the
// server. When accessed through a specific channel
// (e.g. client.Channels[0].Users), it contains only the users in the
// channel.
type Users map[uint32]*User
// create adds a new user with the given session to the collection. If a user
// with the given session already exists, it is overwritten.
func (u Users) create(session uint32) *User {
user := &User{
Session: session,
}
u[session] = user
return user
}
// Find returns the user with the given name. nil is returned if no user exists
// with the given name.
func (u Users) Find(name string) *User {
for _, user := range u {
if user.Name == name {
return user
}
}
return nil
}

View File

@ -0,0 +1,62 @@
package gumble
import (
"crypto/x509"
"net"
"time"
)
// UserStats contains additional information about a user.
type UserStats struct {
// The owner of the stats.
User *User
// Stats about UDP packets sent from the client.
FromClient UserStatsUDP
// Stats about UDP packets sent by the server.
FromServer UserStatsUDP
// Number of UDP packets sent by the user.
UDPPackets uint32
// Average UDP ping.
UDPPingAverage float32
// UDP ping variance.
UDPPingVariance float32
// Number of TCP packets sent by the user.
TCPPackets uint32
// Average TCP ping.
TCPPingAverage float32
// TCP ping variance.
TCPPingVariance float32
// The user's version.
Version Version
// When the user connected to the server.
Connected time.Time
// How long the user has been idle.
Idle time.Duration
// How much bandwidth the user is current using.
Bandwidth int
// The user's certificate chain.
Certificates []*x509.Certificate
// Does the user have a strong certificate? A strong certificate is one that
// is not self signed, nor expired, etc.
StrongCertificate bool
// A list of CELT versions supported by the user's client.
CELTVersions []int32
// Does the user's client supports the Opus audio codec?
Opus bool
// The user's IP address.
IP net.IP
}
// UserStatsUDP contains stats about UDP packets that have been sent to or from
// the server.
type UserStatsUDP struct {
Good uint32
Late uint32
Lost uint32
Resync uint32
}

View File

@ -0,0 +1 @@
package varint // import "git.2mb.codes/~cmb/barnard/gumble/gumble/varint"

View File

@ -0,0 +1,52 @@
package varint
import (
"encoding/binary"
)
// Decode reads the first varint encoded number from the given buffer.
//
// On success, the function returns the varint as an int64, and the number of
// bytes read (0 if there was an error).
func Decode(b []byte) (int64, int) {
if len(b) == 0 {
return 0, 0
}
// 0xxxxxxx 7-bit positive number
if (b[0] & 0x80) == 0 {
return int64(b[0]), 1
}
// 10xxxxxx + 1 byte 14-bit positive number
if (b[0]&0xC0) == 0x80 && len(b) >= 2 {
return int64(b[0]&0x3F)<<8 | int64(b[1]), 2
}
// 110xxxxx + 2 bytes 21-bit positive number
if (b[0]&0xE0) == 0xC0 && len(b) >= 3 {
return int64(b[0]&0x1F)<<16 | int64(b[1])<<8 | int64(b[2]), 3
}
// 1110xxxx + 3 bytes 28-bit positive number
if (b[0]&0xF0) == 0xE0 && len(b) >= 4 {
return int64(b[0]&0xF)<<24 | int64(b[1])<<16 | int64(b[2])<<8 | int64(b[3]), 4
}
// 111100__ + int (32-bit) 32-bit positive number
if (b[0]&0xFC) == 0xF0 && len(b) >= 5 {
return int64(binary.BigEndian.Uint32(b[1:])), 5
}
// 111101__ + long (64-bit) 64-bit number
if (b[0]&0xFC) == 0xF4 && len(b) >= 9 {
return int64(binary.BigEndian.Uint64(b[1:])), 9
}
// 111110__ + varint Negative recursive varint
if b[0]&0xFC == 0xF8 {
if v, n := Decode(b[1:]); n > 0 {
return -v, n + 1
}
return 0, 0
}
// 111111xx Byte-inverted negative two bit number (~xx)
if b[0]&0xFC == 0xFC {
return ^int64(b[0] & 0x03), 1
}
return 0, 0
}

View File

@ -0,0 +1,32 @@
package varint // import "git.2mb.codes/~cmb/barnard/gumble/gumble/varint"
import "testing"
func TestRange(t *testing.T) {
fn := func(i int64) {
var b [MaxVarintLen]byte
size := Encode(b[:], i)
if size == 0 {
t.Error("Encode returned size 0\n")
}
s := b[:size]
val, size := Decode(s)
if size == 0 {
t.Error("Decode return size 0\n")
}
if i != val {
t.Errorf("Encoded %d (%v) equals decoded %d\n", i, s, val)
}
}
for i := int64(-10000); i <= 10000; i++ {
fn(i)
}
fn(134342525)
fn(10282934828342)
fn(1028293482834200000)
}

View File

@ -0,0 +1,64 @@
package varint
import (
"encoding/binary"
"math"
)
// MaxVarintLen is the maximum number of bytes required to encode a varint
// number.
const MaxVarintLen = 10
// Encode encodes the given value to varint format.
func Encode(b []byte, value int64) int {
// 111111xx Byte-inverted negative two bit number (~xx)
if value <= -1 && value >= -4 {
b[0] = 0xFC | byte(^value&0xFF)
return 1
}
// 111110__ + varint Negative recursive varint
if value < 0 {
b[0] = 0xF8
return 1 + Encode(b[1:], -value)
}
// 0xxxxxxx 7-bit positive number
if value <= 0x7F {
b[0] = byte(value)
return 1
}
// 10xxxxxx + 1 byte 14-bit positive number
if value <= 0x3FFF {
b[0] = byte(((value >> 8) & 0x3F) | 0x80)
b[1] = byte(value & 0xFF)
return 2
}
// 110xxxxx + 2 bytes 21-bit positive number
if value <= 0x1FFFFF {
b[0] = byte((value>>16)&0x1F | 0xC0)
b[1] = byte((value >> 8) & 0xFF)
b[2] = byte(value & 0xFF)
return 3
}
// 1110xxxx + 3 bytes 28-bit positive number
if value <= 0xFFFFFFF {
b[0] = byte((value>>24)&0xF | 0xE0)
b[1] = byte((value >> 16) & 0xFF)
b[2] = byte((value >> 8) & 0xFF)
b[3] = byte(value & 0xFF)
return 4
}
// 111100__ + int (32-bit) 32-bit positive number
if value <= math.MaxInt32 {
b[0] = 0xF0
binary.BigEndian.PutUint32(b[1:], uint32(value))
return 5
}
// 111101__ + long (64-bit) 64-bit number
if value <= math.MaxInt64 {
b[0] = 0xF4
binary.BigEndian.PutUint64(b[1:], uint64(value))
return 9
}
return 0
}

24
gumble/gumble/version.go Normal file
View File

@ -0,0 +1,24 @@
package gumble
// Version represents a Mumble client or server version.
type Version struct {
// The semantic version information as a single unsigned integer.
//
// Bits 0-15 are the major version, bits 16-23 are the minor version, and
// bits 24-31 are the patch version.
Version uint32
// The name of the client.
Release string
// The operating system name.
OS string
// The operating system version.
OSVersion string
}
// SemanticVersion returns the version's semantic version components.
func (v *Version) SemanticVersion() (major uint16, minor, patch uint8) {
major = uint16(v.Version>>16) & 0xFFFF
minor = uint8(v.Version>>8) & 0xFF
patch = uint8(v.Version) & 0xFF
return
}

View File

@ -0,0 +1,76 @@
package gumble
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble/MumbleProto"
)
// VoiceTargetLoopback is a special voice target which causes any audio sent to
// the server to be returned to the client.
//
// Its ID should not be modified, and it does not have to to be sent to the
// server before use.
var VoiceTargetLoopback *VoiceTarget = &VoiceTarget{
ID: 31,
}
type voiceTargetChannel struct {
channel *Channel
links, recursive bool
group string
}
// VoiceTarget represents a set of users and/or channels that the client can
// whisper to.
type VoiceTarget struct {
// The voice target ID. This value must be in the range [1, 30].
ID uint32
users []*User
channels []*voiceTargetChannel
}
// Clear removes all users and channels from the voice target.
func (v *VoiceTarget) Clear() {
v.users = nil
v.channels = nil
}
// AddUser adds a user to the voice target.
func (v *VoiceTarget) AddUser(user *User) {
v.users = append(v.users, user)
}
// AddChannel adds a user to the voice target. If group is non-empty, only
// users belonging to that ACL group will be targeted.
func (v *VoiceTarget) AddChannel(channel *Channel, recursive, links bool, group string) {
v.channels = append(v.channels, &voiceTargetChannel{
channel: channel,
links: links,
recursive: recursive,
group: group,
})
}
func (v *VoiceTarget) writeMessage(client *Client) error {
packet := MumbleProto.VoiceTarget{
Id: &v.ID,
Targets: make([]*MumbleProto.VoiceTarget_Target, 0, len(v.users)+len(v.channels)),
}
for _, user := range v.users {
packet.Targets = append(packet.Targets, &MumbleProto.VoiceTarget_Target{
Session: []uint32{user.Session},
})
}
for _, vtChannel := range v.channels {
target := &MumbleProto.VoiceTarget_Target{
ChannelId: &vtChannel.channel.ID,
Links: &vtChannel.links,
Children: &vtChannel.recursive,
}
if vtChannel.group != "" {
target.Group = &vtChannel.group
}
packet.Targets = append(packet.Targets, target)
}
return client.Conn.WriteProto(&packet)
}

View File

@ -0,0 +1,103 @@
package gumbleffmpeg // import "git.2mb.codes/~cmb/barnard/gumble/gumbleffmpeg"
import (
"io"
"os/exec"
)
// Source is a Stream source.
type Source interface {
// must include the -i <filename>
arguments() []string
start(*exec.Cmd) error
done()
}
// sourceFile
type sourceFile string
// SourceFile is standard file source.
func SourceFile(filename string) Source {
return sourceFile(filename)
}
func (s sourceFile) arguments() []string {
return []string{"-i", string(s)}
}
func (sourceFile) start(*exec.Cmd) error {
return nil
}
func (sourceFile) done() {
}
// sourceReader
type sourceReader struct {
r io.ReadCloser
}
// SourceReader is a ReadCloser source.
func SourceReader(r io.ReadCloser) Source {
return &sourceReader{r}
}
func (*sourceReader) arguments() []string {
return []string{"-i", "-"}
}
func (s *sourceReader) start(cmd *exec.Cmd) error {
cmd.Stdin = s.r
return nil
}
func (s *sourceReader) done() {
s.r.Close()
}
// sourceExec
type sourceExec struct {
name string
arg []string
cmd *exec.Cmd
}
// SourceExec uses the output of the given command and arguments as source
// data.
func SourceExec(name string, arg ...string) Source {
return &sourceExec{
name: name,
arg: arg,
}
}
func (*sourceExec) arguments() []string {
return []string{"-i", "-"}
}
func (s *sourceExec) start(cmd *exec.Cmd) error {
s.cmd = exec.Command(s.name, s.arg...)
r, err := s.cmd.StdoutPipe()
if err != nil {
return err
}
cmd.Stdin = r
if err := s.cmd.Start(); err != nil {
cmd.Stdin = nil
return err
}
return nil
}
func (s *sourceExec) done() {
if s.cmd != nil {
if p := s.cmd.Process; p != nil {
p.Kill()
}
s.cmd.Wait()
}
}

View File

@ -0,0 +1,203 @@
package gumbleffmpeg // import "git.2mb.codes/~cmb/barnard/gumble/gumbleffmpeg"
import (
"encoding/binary"
"errors"
"io"
"os/exec"
"strconv"
"sync"
"sync/atomic"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// State represents the state of a Stream.
type State int32
// Valid states of Stream.
const (
StateInitial State = iota + 1
StatePlaying
StatePaused
StateStopped
)
// Stream is an audio stream that encodes media through ffmpeg and sends it to
// the server.
//
// A stream can only be used once; it cannot be started after it is stopped.
type Stream struct {
// Command to execute to play the file. Defaults to "ffmpeg".
Command string
// Playback volume (can be changed while the source is playing).
Volume float32
// Audio source (cannot be changed after stream starts).
Source Source
// Starting offset.
Offset time.Duration
client *gumble.Client
cmd *exec.Cmd
pipe io.ReadCloser
pause chan struct{}
elapsed int64
state State
l sync.Mutex
wg sync.WaitGroup
}
// New returns a new Stream for the given gumble Client and Source.
func New(client *gumble.Client, source Source) *Stream {
return &Stream{
client: client,
Volume: 1.0,
Source: source,
Command: "ffmpeg",
pause: make(chan struct{}),
state: StateInitial,
}
}
// Play begins playing
func (s *Stream) Play() error {
s.l.Lock()
defer s.l.Unlock()
switch s.state {
case StatePaused:
s.state = StatePlaying
go s.process()
return nil
case StatePlaying:
return errors.New("gumbleffmpeg: stream already playing")
case StateStopped:
return errors.New("gumbleffmpeg: stream has stopped")
}
// fresh stream
if s.Source == nil {
return errors.New("gumbleffmpeg: nil source")
}
args := s.Source.arguments()
if s.Offset > 0 {
args = append([]string{"-ss", strconv.FormatFloat(s.Offset.Seconds(), 'f', -1, 64)}, args...)
}
args = append(args, "-ac", strconv.Itoa(gumble.AudioChannels), "-ar", strconv.Itoa(gumble.AudioSampleRate), "-f", "s16le", "-")
cmd := exec.Command(s.Command, args...)
var err error
s.pipe, err = cmd.StdoutPipe()
if err != nil {
return err
}
if err := s.Source.start(cmd); err != nil {
return err
}
if err := cmd.Start(); err != nil {
s.Source.done()
return err
}
s.wg.Add(1)
s.cmd = cmd
s.state = StatePlaying
go s.process()
return nil
}
// State returns the state of the stream.
func (s *Stream) State() State {
s.l.Lock()
defer s.l.Unlock()
return s.state
}
// Pause pauses a playing stream.
func (s *Stream) Pause() error {
s.l.Lock()
if s.state != StatePlaying {
s.l.Unlock()
return errors.New("gumbleffmpeg: stream is not playing")
}
s.state = StatePaused
s.l.Unlock()
s.pause <- struct{}{}
return nil
}
// Stop stops the stream.
func (s *Stream) Stop() error {
s.l.Lock()
switch s.state {
case StateStopped, StateInitial:
s.l.Unlock()
return errors.New("gumbleffmpeg: stream is not playing nor paused")
}
s.cleanup()
s.Wait()
return nil
}
// Wait returns once the stream has stopped playing.
func (s *Stream) Wait() {
s.wg.Wait()
}
// Elapsed returns the amount of audio that has been played by the stream.
func (s *Stream) Elapsed() time.Duration {
return time.Duration(atomic.LoadInt64(&s.elapsed))
}
func (s *Stream) process() {
// s.state has been set to StatePlaying
interval := s.client.Config.AudioInterval
frameSize := s.client.Config.AudioFrameSize()
byteBuffer := make([]byte, frameSize*2)
outgoing := s.client.AudioOutgoing()
defer close(outgoing)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-s.pause:
return
case <-ticker.C:
if _, err := io.ReadFull(s.pipe, byteBuffer); err != nil {
s.l.Lock()
s.cleanup()
return
}
int16Buffer := make([]int16, frameSize)
for i := range int16Buffer {
float := float32(int16(binary.LittleEndian.Uint16(byteBuffer[i*2 : (i+1)*2])))
int16Buffer[i] = int16(s.Volume * float)
}
atomic.AddInt64(&s.elapsed, int64(interval))
outgoing <- gumble.AudioBuffer(int16Buffer)
}
}
}
func (s *Stream) cleanup() {
defer s.l.Unlock()
// s.l has been acquired
if s.state == StateStopped {
return
}
s.cmd.Process.Kill()
s.cmd.Wait()
s.Source.done()
for len(s.pause) > 0 {
<-s.pause
}
s.state = StateStopped
s.wg.Done()
}

View File

@ -0,0 +1,300 @@
package gumbleopenal
import (
"encoding/binary"
"errors"
"os/exec"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"git.2mb.codes/~cmb/go-openal/openal"
)
const (
maxBufferSize = 11520 // Max frame size (2880) * bytes per stereo sample (4)
)
var (
ErrState = errors.New("gumbleopenal: invalid state")
ErrMic = errors.New("gumbleopenal: microphone disconnected or misconfigured")
ErrInputDevice = errors.New("gumbleopenal: invalid input device or parameters")
ErrOutputDevice = errors.New("gumbleopenal: invalid output device or parameters")
)
func beep() {
cmd := exec.Command("beep")
cmdout, err := cmd.Output()
if err != nil {
panic(err)
}
if cmdout != nil {
}
}
type Stream struct {
client *gumble.Client
link gumble.Detacher
deviceSource *openal.CaptureDevice
sourceFrameSize int
micVolume float32
sourceStop chan bool
deviceSink *openal.Device
contextSink *openal.Context
}
func New(client *gumble.Client, inputDevice *string, outputDevice *string, test bool) (*Stream, error) {
frmsz := 480
if !test {
frmsz = client.Config.AudioFrameSize()
}
// Always use mono for input device
idev := openal.CaptureOpenDevice(*inputDevice, gumble.AudioSampleRate, openal.FormatMono16, uint32(frmsz))
if idev == nil {
return nil, ErrInputDevice
}
odev := openal.OpenDevice(*outputDevice)
if odev == nil {
idev.CaptureCloseDevice()
return nil, ErrOutputDevice
}
if test {
idev.CaptureCloseDevice()
odev.CloseDevice()
return nil, nil
}
s := &Stream{
client: client,
sourceFrameSize: frmsz,
micVolume: 1.0,
}
s.deviceSource = idev
if s.deviceSource == nil {
return nil, ErrInputDevice
}
s.deviceSink = odev
if s.deviceSink == nil {
return nil, ErrOutputDevice
}
s.contextSink = s.deviceSink.CreateContext()
if s.contextSink == nil {
s.Destroy()
return nil, ErrOutputDevice
}
s.contextSink.Activate()
return s, nil
}
func (s *Stream) AttachStream(client *gumble.Client) {
s.link = client.Config.AttachAudio(s)
}
func (s *Stream) Destroy() {
if s.link != nil {
s.link.Detach()
}
if s.deviceSource != nil {
s.StopSource()
s.deviceSource.CaptureCloseDevice()
s.deviceSource = nil
}
if s.deviceSink != nil {
s.contextSink.Destroy()
s.deviceSink.CloseDevice()
s.contextSink = nil
s.deviceSink = nil
}
}
func (s *Stream) StartSource(inputDevice *string) error {
if s.sourceStop != nil {
return ErrState
}
if s.deviceSource == nil {
return ErrMic
}
s.deviceSource.CaptureStart()
s.sourceStop = make(chan bool)
go s.sourceRoutine(inputDevice)
return nil
}
func (s *Stream) StopSource() error {
if s.deviceSource == nil {
return ErrMic
}
s.deviceSource.CaptureStop()
if s.sourceStop == nil {
return ErrState
}
close(s.sourceStop)
s.sourceStop = nil
return nil
}
func (s *Stream) GetMicVolume() float32 {
return s.micVolume
}
func (s *Stream) SetMicVolume(change float32, relative bool) {
var val float32
if relative {
val = s.GetMicVolume() + change
} else {
val = change
}
if val >= 1 {
val = 1.0
}
if val <= 0 {
val = 0
}
s.micVolume = val
}
func (s *Stream) OnAudioStream(e *gumble.AudioStreamEvent) {
go func(e *gumble.AudioStreamEvent) {
var source = openal.NewSource()
e.User.AudioSource = &source
e.User.AudioSource.SetGain(e.User.Volume)
bufferCount := e.Client.Config.Buffers
if bufferCount < 64 {
bufferCount = 64
}
emptyBufs := openal.NewBuffers(bufferCount)
reclaim := func() {
if n := source.BuffersProcessed(); n > 0 {
reclaimedBufs := make(openal.Buffers, n)
source.UnqueueBuffers(reclaimedBufs)
emptyBufs = append(emptyBufs, reclaimedBufs...)
}
}
var raw [maxBufferSize]byte
for packet := range e.C {
var boost uint16 = uint16(1)
samples := len(packet.AudioBuffer)
if samples > cap(raw)/2 {
continue
}
boost = e.User.Boost
// Check if sample count suggests stereo data
// If it's not a multiple of 2, it must be mono
// If it's more than standard frameSize, it's likely stereo
isStereo := samples > gumble.AudioDefaultFrameSize && samples%2 == 0
format := openal.FormatMono16
if isStereo {
format = openal.FormatStereo16
// Adjust samples to represent stereo frame count
samples = samples / 2
}
// Process samples
rawPtr := 0
if isStereo {
// Process stereo samples as pairs
for i := 0; i < samples*2; i += 2 {
// Process left channel
sample := packet.AudioBuffer[i]
if boost > 1 {
sample = int16((int32(sample) * int32(boost)))
}
binary.LittleEndian.PutUint16(raw[rawPtr:], uint16(sample))
rawPtr += 2
// Process right channel
sample = packet.AudioBuffer[i+1]
if boost > 1 {
sample = int16((int32(sample) * int32(boost)))
}
binary.LittleEndian.PutUint16(raw[rawPtr:], uint16(sample))
rawPtr += 2
}
} else {
// Process mono samples
for i := 0; i < samples; i++ {
sample := packet.AudioBuffer[i]
if boost > 1 {
sample = int16((int32(sample) * int32(boost)))
}
binary.LittleEndian.PutUint16(raw[rawPtr:], uint16(sample))
rawPtr += 2
}
}
reclaim()
if len(emptyBufs) == 0 {
continue
}
last := len(emptyBufs) - 1
buffer := emptyBufs[last]
emptyBufs = emptyBufs[:last]
// Set buffer data with correct format
buffer.SetData(format, raw[:rawPtr], gumble.AudioSampleRate)
source.QueueBuffer(buffer)
if source.State() != openal.Playing {
source.Play()
}
}
reclaim()
emptyBufs.Delete()
source.Delete()
}(e)
}
func (s *Stream) sourceRoutine(inputDevice *string) {
interval := s.client.Config.AudioInterval
frameSize := s.client.Config.AudioFrameSize()
if frameSize != s.sourceFrameSize {
s.deviceSource.CaptureCloseDevice()
s.sourceFrameSize = frameSize
// Always use mono for input
s.deviceSource = openal.CaptureOpenDevice(*inputDevice, gumble.AudioSampleRate, openal.FormatMono16, uint32(s.sourceFrameSize))
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
stop := s.sourceStop
outgoing := s.client.AudioOutgoing()
defer close(outgoing)
for {
select {
case <-stop:
return
case <-ticker.C:
buff := s.deviceSource.CaptureSamples(uint32(frameSize))
if len(buff) != frameSize*2 {
continue
}
int16Buffer := make([]int16, frameSize)
for i := range int16Buffer {
sample := int16(binary.LittleEndian.Uint16(buff[i*2:]))
if s.micVolume != 1.0 {
sample = int16(float32(sample) * s.micVolume)
}
int16Buffer[i] = sample
}
outgoing <- gumble.AudioBuffer(int16Buffer)
}
}
}

55
gumble/gumbleutil/acl.go Normal file
View File

@ -0,0 +1,55 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// UserGroups fetches the group names the given user belongs to in the given
// channel. The slice of group names sent via the returned channel. On error,
// the returned channel is closed without without sending a slice.
func UserGroups(client *gumble.Client, user *gumble.User, channel *gumble.Channel) <-chan []string {
ch := make(chan []string)
if !user.IsRegistered() {
close(ch)
return ch
}
var detacher gumble.Detacher
listener := Listener{
Disconnect: func(e *gumble.DisconnectEvent) {
detacher.Detach()
close(ch)
},
ChannelChange: func(e *gumble.ChannelChangeEvent) {
if e.Channel == channel && e.Type.Has(gumble.ChannelChangeRemoved) {
detacher.Detach()
close(ch)
}
},
PermissionDenied: func(e *gumble.PermissionDeniedEvent) {
if e.Channel == channel && e.Type == gumble.PermissionDeniedPermission && (e.Permission&gumble.PermissionWrite) != 0 {
detacher.Detach()
close(ch)
}
},
ACL: func(e *gumble.ACLEvent) {
if e.ACL.Channel != channel {
return
}
var names []string
for _, g := range e.ACL.Groups {
if (g.UsersAdd[user.UserID] != nil || g.UsersInherited[user.UserID] != nil) && g.UsersRemove[user.UserID] == nil {
names = append(names, g.Name)
}
}
detacher.Detach()
ch <- names
close(ch)
},
}
detacher = client.Config.Attach(&listener)
channel.RequestACL()
return ch
}

View File

@ -0,0 +1,27 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
var autoBitrate = &Listener{
Connect: func(e *gumble.ConnectEvent) {
if e.MaximumBitrate != nil {
const safety = 5
interval := e.Client.Config.AudioInterval
dataBytes := (*e.MaximumBitrate / (8 * (int(time.Second/interval) + safety))) - 32 - 10
e.Client.Config.AudioDataBytes = dataBytes
}
},
}
// AutoBitrate is a gumble.EventListener that automatically sets the client's
// AudioDataBytes to suitable value, based on the server's bitrate.
var AutoBitrate gumble.EventListener
func init() {
AutoBitrate = autoBitrate
}

View File

@ -0,0 +1,18 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// ChannelPath returns a slice of channel names, starting from the root channel
// to the given channel.
func ChannelPath(channel *gumble.Channel) []string {
var pieces []string
for ; channel != nil; channel = channel.Parent {
pieces = append(pieces, channel.Name)
}
for i := 0; i < (len(pieces) / 2); i++ {
pieces[len(pieces)-1-i], pieces[i] = pieces[i], pieces[len(pieces)-1-i]
}
return pieces
}

2
gumble/gumbleutil/doc.go Normal file
View File

@ -0,0 +1,2 @@
// Package gumbleutil provides extras that can make working with gumble easier.
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"

View File

@ -0,0 +1,100 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// Listener is a struct that implements the gumble.EventListener interface. The
// corresponding event function in the struct is called if it is non-nil.
type Listener struct {
Connect func(e *gumble.ConnectEvent)
Disconnect func(e *gumble.DisconnectEvent)
TextMessage func(e *gumble.TextMessageEvent)
UserChange func(e *gumble.UserChangeEvent)
ChannelChange func(e *gumble.ChannelChangeEvent)
PermissionDenied func(e *gumble.PermissionDeniedEvent)
UserList func(e *gumble.UserListEvent)
ACL func(e *gumble.ACLEvent)
BanList func(e *gumble.BanListEvent)
ContextActionChange func(e *gumble.ContextActionChangeEvent)
ServerConfig func(e *gumble.ServerConfigEvent)
}
var _ gumble.EventListener = (*Listener)(nil)
// OnConnect implements gumble.EventListener.OnConnect.
func (l Listener) OnConnect(e *gumble.ConnectEvent) {
if l.Connect != nil {
l.Connect(e)
}
}
// OnDisconnect implements gumble.EventListener.OnDisconnect.
func (l Listener) OnDisconnect(e *gumble.DisconnectEvent) {
if l.Disconnect != nil {
l.Disconnect(e)
}
}
// OnTextMessage implements gumble.EventListener.OnTextMessage.
func (l Listener) OnTextMessage(e *gumble.TextMessageEvent) {
if l.TextMessage != nil {
l.TextMessage(e)
}
}
// OnUserChange implements gumble.EventListener.OnUserChange.
func (l Listener) OnUserChange(e *gumble.UserChangeEvent) {
if l.UserChange != nil {
l.UserChange(e)
}
}
// OnChannelChange implements gumble.EventListener.OnChannelChange.
func (l Listener) OnChannelChange(e *gumble.ChannelChangeEvent) {
if l.ChannelChange != nil {
l.ChannelChange(e)
}
}
// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied.
func (l Listener) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
if l.PermissionDenied != nil {
l.PermissionDenied(e)
}
}
// OnUserList implements gumble.EventListener.OnUserList.
func (l Listener) OnUserList(e *gumble.UserListEvent) {
if l.UserList != nil {
l.UserList(e)
}
}
// OnACL implements gumble.EventListener.OnACL.
func (l Listener) OnACL(e *gumble.ACLEvent) {
if l.ACL != nil {
l.ACL(e)
}
}
// OnBanList implements gumble.EventListener.OnBanList.
func (l Listener) OnBanList(e *gumble.BanListEvent) {
if l.BanList != nil {
l.BanList(e)
}
}
// OnContextActionChange implements gumble.EventListener.OnContextActionChange.
func (l Listener) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
if l.ContextActionChange != nil {
l.ContextActionChange(e)
}
}
// OnServerConfig implements gumble.EventListener.OnServerConfig.
func (l Listener) OnServerConfig(e *gumble.ServerConfigEvent) {
if l.ServerConfig != nil {
l.ServerConfig(e)
}
}

View File

@ -0,0 +1,80 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// ListenerFunc is a single listener function that implements the
// gumble.EventListener interface. This is useful if you would like to use a
// type-switch for handling the different event types.
//
// Example:
// handler := func(e interface{}) {
// switch e.(type) {
// case *gumble.ConnectEvent:
// println("Connected")
// case *gumble.DisconnectEvent:
// println("Disconnected")
// // ...
// }
// }
//
// client.Attach(gumbleutil.ListenerFunc(handler))
type ListenerFunc func(e interface{})
var _ gumble.EventListener = ListenerFunc(nil)
// OnConnect implements gumble.EventListener.OnConnect.
func (lf ListenerFunc) OnConnect(e *gumble.ConnectEvent) {
lf(e)
}
// OnDisconnect implements gumble.EventListener.OnDisconnect.
func (lf ListenerFunc) OnDisconnect(e *gumble.DisconnectEvent) {
lf(e)
}
// OnTextMessage implements gumble.EventListener.OnTextMessage.
func (lf ListenerFunc) OnTextMessage(e *gumble.TextMessageEvent) {
lf(e)
}
// OnUserChange implements gumble.EventListener.OnUserChange.
func (lf ListenerFunc) OnUserChange(e *gumble.UserChangeEvent) {
lf(e)
}
// OnChannelChange implements gumble.EventListener.OnChannelChange.
func (lf ListenerFunc) OnChannelChange(e *gumble.ChannelChangeEvent) {
lf(e)
}
// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied.
func (lf ListenerFunc) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
lf(e)
}
// OnUserList implements gumble.EventListener.OnUserList.
func (lf ListenerFunc) OnUserList(e *gumble.UserListEvent) {
lf(e)
}
// OnACL implements gumble.EventListener.OnACL.
func (lf ListenerFunc) OnACL(e *gumble.ACLEvent) {
lf(e)
}
// OnBanList implements gumble.EventListener.OnBanList.
func (lf ListenerFunc) OnBanList(e *gumble.BanListEvent) {
lf(e)
}
// OnContextActionChange implements gumble.EventListener.OnContextActionChange.
func (lf ListenerFunc) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
lf(e)
}
// OnServerConfig implements gumble.EventListener.OnServerConfig.
func (lf ListenerFunc) OnServerConfig(e *gumble.ServerConfigEvent) {
lf(e)
}

79
gumble/gumbleutil/main.go Normal file
View File

@ -0,0 +1,79 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"crypto/tls"
"flag"
"fmt"
"net"
"os"
"strconv"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// Main aids in the creation of a basic command line gumble bot. It accepts the
// following flag arguments:
// --server
// --username
// --password
// --insecure
// --certificate
// --key
func Main(listeners ...gumble.EventListener) {
server := flag.String("server", "localhost:64738", "Mumble server address")
username := flag.String("username", "gumble-bot", "client username")
password := flag.String("password", "", "client password")
insecure := flag.Bool("insecure", false, "skip server certificate verification")
certificateFile := flag.String("certificate", "", "user certificate file (PEM)")
keyFile := flag.String("key", "", "user certificate key file (PEM)")
if !flag.Parsed() {
flag.Parse()
}
host, port, err := net.SplitHostPort(*server)
if err != nil {
host = *server
port = strconv.Itoa(gumble.DefaultPort)
}
keepAlive := make(chan bool)
config := gumble.NewConfig()
config.Username = *username
config.Password = *password
config.Address = net.JoinHostPort(host, port)
var tlsConfig tls.Config
if *insecure {
tlsConfig.InsecureSkipVerify = true
}
if *certificateFile != "" {
if *keyFile == "" {
keyFile = certificateFile
}
if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
os.Exit(1)
} else {
tlsConfig.Certificates = append(tlsConfig.Certificates, certificate)
}
}
config.Attach(AutoBitrate)
for _, listener := range listeners {
config.Attach(listener)
}
config.Attach(Listener{
Disconnect: func(e *gumble.DisconnectEvent) {
keepAlive <- true
},
})
_, err = gumble.DialWithDialer(new(net.Dialer), config, &tlsConfig)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
os.Exit(1)
}
<-keepAlive
}

View File

@ -0,0 +1,45 @@
package gumbleutil // import "git.2mb.codes/~cmb/barnard/gumble/gumbleutil"
import (
"bytes"
"encoding/xml"
"strings"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
)
// PlainText returns the Message string without HTML tags or entities.
func PlainText(tm *gumble.TextMessage) string {
d := xml.NewDecoder(strings.NewReader(tm.Message))
d.Strict = false
d.AutoClose = xml.HTMLAutoClose
d.Entity = xml.HTMLEntity
var b bytes.Buffer
newline := false
for {
t, _ := d.Token()
if t == nil {
break
}
switch node := t.(type) {
case xml.CharData:
if len(node) > 0 {
b.Write(node)
newline = false
}
case xml.StartElement:
switch node.Name.Local {
case "address", "article", "aside", "audio", "blockquote", "canvas", "dd", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video":
if !newline {
b.WriteByte('\n')
newline = true
}
case "br":
b.WriteByte('\n')
newline = true
}
}
}
return b.String()
}

92
gumble/opus/opus.go Normal file
View File

@ -0,0 +1,92 @@
package opus
import (
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"github.com/hraban/opus"
)
var Codec gumble.AudioCodec
const (
ID = 4
VoiceChannels = 1 // Force mono for voice transmission
)
func init() {
Codec = &generator{}
gumble.RegisterAudioCodec(4, Codec)
}
// generator
type generator struct {
}
func (*generator) ID() int {
return ID
}
func (*generator) NewEncoder() gumble.AudioEncoder {
// Force mono for voice transmission
e, _ := opus.NewEncoder(gumble.AudioSampleRate, VoiceChannels, opus.AppVoIP)
e.SetBitrateToMax()
return &Encoder{
e,
}
}
func (*generator) NewDecoder() gumble.AudioDecoder {
// Create decoder with stereo support
d, _ := opus.NewDecoder(gumble.AudioSampleRate, gumble.AudioChannels)
return &Decoder{
d,
}
}
// encoder
type Encoder struct {
*opus.Encoder
}
func (*Encoder) ID() int {
return ID
}
func (e *Encoder) Encode(pcm []int16, _, maxDataBytes int) ([]byte, error) {
buf := make([]byte, maxDataBytes)
n, err := e.Encoder.Encode(pcm, buf)
if err != nil {
return []byte{}, err
}
return buf[:n], nil
}
func (e *Encoder) Reset() {
e.Encoder.Reset()
}
// decoder
type Decoder struct {
*opus.Decoder
}
func (*Decoder) ID() int {
return ID
}
func (d *Decoder) Decode(data []byte, frameSize int) ([]int16, error) {
// Allocate buffer for stereo - frameSize is per channel
pcm := make([]int16, frameSize * gumble.AudioChannels)
// Decode the data
n, err := d.Decoder.Decode(data, pcm)
if err != nil {
return []int16{}, err
}
// Return the exact number of samples decoded
return pcm[:n * gumble.AudioChannels], nil
}
func (d *Decoder) Reset() {
d.Decoder.Reset()
}

203
main.go Normal file
View File

@ -0,0 +1,203 @@
package main
import _ "net/http/pprof"
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"strings"
"syscall"
//"gopkg.in/alessio/shellescape.v1"
//"github.com/google/shlex"
"crypto/tls"
"flag"
"github.com/alessio/shellescape"
"git.2mb.codes/~cmb/barnard/config"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
_ "git.2mb.codes/~cmb/barnard/gumble/opus"
"git.2mb.codes/~cmb/barnard/uiterm"
"git.2mb.codes/~cmb/go-openal/openal"
)
func show_devs(name string, args []string) {
if args == nil {
fmt.Printf("no items for %s\n", name)
}
fmt.Printf("%s\n", name)
for i := 0; i < len(args); i++ {
fmt.Printf("%s\n", args[i])
}
}
func do_list_devices() {
odevs := openal.GetStrings(openal.AllDevicesSpecifier)
if odevs != nil && len(odevs) > 0 {
show_devs("All outputs:", odevs)
} else {
odevs = openal.GetStrings(openal.DeviceSpecifier)
show_devs("All outputs:", odevs)
}
idevs := openal.GetStrings(openal.CaptureDeviceSpecifier)
show_devs("Inputs:", idevs)
}
func setup_notify_runner(notify_command string) chan []string {
t := make(chan []string)
var do_nothing = false
var err error
if err != nil {
}
if notify_command == "" {
do_nothing = true
}
go func(events chan []string, cmd_template string, dummy bool) {
for {
event := <-events
if !dummy {
t := string(cmd_template)
t = strings.ReplaceAll(t, "%event", shellescape.Quote(event[0]))
t = strings.ReplaceAll(t, "%who", shellescape.Quote(event[1]))
t = strings.ReplaceAll(t, "%what", shellescape.Quote(event[2]))
cmd := "/bin/sh"
args := []string{"-c", t}
x := exec.Command(cmd, args...)
x.Run()
} //if we actually have a command to run
} //for
}(t, notify_command, do_nothing)
return t
}
func setup_fifo(fn string) (chan string, error) {
t := make(chan string)
if fn == "" {
return t, nil
}
os.Remove(fn)
err := syscall.Mkfifo(fn, 0600)
if err != nil {
return t, err
}
file, err := os.OpenFile(fn, os.O_RDWR, os.ModeNamedPipe)
if err != nil {
return t, err
}
go func(fh io.Reader, out chan string) {
reader := bufio.NewReader(fh)
for {
line, err := reader.ReadBytes('\n')
if err == nil {
out <- strings.TrimSpace(string(line))
}
}
}(file, t)
return t, nil
}
func main() {
// Command line flags
server := flag.String("server", "localhost:64738", "the server to connect to")
username := flag.String("username", "", "the username of the client")
password := flag.String("password", "", "the password of the server")
insecure := flag.Bool("insecure", false, "skip server certificate verification")
certificate := flag.String("certificate", "", "PEM encoded certificate and private key")
cfgfn := flag.String("config", "~/.barnard.yaml", "Path to YAML formatted configuration file")
list_devices := flag.Bool("list_devices", false, "do not connect; instead, list available audio devices and exit")
fifo := flag.String("fifo", "", "path of a FIFO from which to read commands")
serverSet := false
usernameSet := false
buffers := flag.Int("buffers", 16, "number of audio buffers to use")
profile := flag.Bool("profile", false, "add http server to serve profiles")
flag.Parse()
if *profile == true {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
}
userConfig := config.NewConfig(cfgfn)
flag.CommandLine.Visit(func(theFlag *flag.Flag) {
switch theFlag.Name {
case "server":
serverSet = true
case "username":
usernameSet = true
}
})
if !serverSet {
server = userConfig.GetDefaultServer()
}
if !usernameSet {
username = userConfig.GetUsername()
}
if os.Getenv("ALSOFT_LOGLEVEL") == "" {
os.Setenv("ALSOFT_LOGLEVEL", "0")
}
if *list_devices {
do_list_devices()
os.Exit(0)
}
if !strings.Contains(*server, ":") {
*server = (*server + ":64738")
}
// Initialize
b := Barnard{
Config: gumble.NewConfig(),
UserConfig: userConfig,
Address: *server,
}
b.Config.Buffers = *buffers
b.Hotkeys = b.UserConfig.GetHotkeys()
b.UserConfig.SaveConfig()
b.Config.Username = *username
b.Config.Password = *password
if *insecure {
b.TLSConfig.InsecureSkipVerify = true
}
if *certificate != "" {
cert, err := tls.LoadX509KeyPair(*certificate, *certificate)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
b.TLSConfig.Certificates = append(b.TLSConfig.Certificates, cert)
}
reader, err := setup_fifo(*fifo)
if err != nil {
b.exitMessage = err.Error()
b.exitStatus = 1
handle_error(b)
}
b.notifyChannel = setup_notify_runner(*b.UserConfig.GetNotifyCommand())
b.Ui = uiterm.New(&b)
b.Ui.Run(reader)
handle_error(b)
}
func handle_raw_error(e error) {
fmt.Fprintf(os.Stderr, "%s\n", e.Error())
os.Exit(1)
}
func handle_error(b Barnard) {
if b.exitMessage != "" {
fmt.Fprintf(os.Stderr, "%s\n", b.exitMessage)
}
os.Exit(b.exitStatus)
}

323
ui.go Normal file
View File

@ -0,0 +1,323 @@
package main
import (
"fmt"
"github.com/nsf/termbox-go"
"os/exec"
"strings"
"time"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"git.2mb.codes/~cmb/barnard/uiterm"
"github.com/kennygrant/sanitize"
)
const (
uiViewLogo = "logo"
uiViewTop = "top"
uiViewStatus = "status"
uiViewInput = "input"
uiViewInputStatus = "inputstatus"
uiViewOutput = "output"
uiViewTree = "tree"
)
func Beep() {
cmd := exec.Command("beep")
cmdout, err := cmd.Output()
if err != nil {
panic(err)
}
if cmdout != nil {
}
}
func esc(str string) string {
return sanitize.HTML(str)
}
func (b *Barnard) Notify(event string, who string, what string) {
b.notifyChannel <- []string{event, who, what}
}
func (b *Barnard) Beep() {
Beep()
}
func (b *Barnard) SetSelectedUser(user *gumble.User) {
b.selectedUser = user
if user == nil {
if len(b.UiInput.Text) > 0 {
}
b.UpdateInputStatus(fmt.Sprintf("[%s]", b.Client.Self.Channel.Name))
} else {
b.UpdateInputStatus(fmt.Sprintf("[@%s]", user.Name))
}
}
func (b *Barnard) GetInputStatus() string {
return b.UiInputStatus.Text
}
func (b *Barnard) UpdateInputStatus(status string) {
if len(status) > 20 {
status = status[:17] + "..." + "]"
}
b.UiInputStatus.Text = status
b.UiTree.Rebuild()
b.Ui.Refresh()
}
func (b *Barnard) AddOutputLine(line string) {
now := time.Now()
b.UiOutput.AddLine(fmt.Sprintf("[%02d:%02d:%02d] %s", now.Hour(), now.Minute(), now.Second(), line))
}
func (b *Barnard) AddOutputMessage(sender *gumble.User, message string) {
if sender == nil {
b.AddOutputLine(message)
} else {
b.AddOutputLine(fmt.Sprintf("%s: %s", sender.Name, strings.TrimSpace(esc(message))))
}
}
func (b *Barnard) AddOutputPrivateMessage(source *gumble.User, dest *gumble.User, message string) {
var sender string
if source == nil {
sender = "Server"
} else {
sender = source.Name
}
b.AddOutputLine(fmt.Sprintf("pm/%s/%s: %s", sender, dest.Name, strings.TrimSpace(esc(message))))
}
func (b *Barnard) OnTimestampToggle(ui *uiterm.Ui, key uiterm.Key) {
b.UiOutput.ToggleTimestamps()
}
func (b *Barnard) UpdateGeneralStatus(text string, notice bool) {
// if (b.UiStatus.Text == text) {
//return
//}
if notice {
b.UiStatus.Fg = uiterm.ColorWhite | uiterm.AttrBold
b.UiStatus.Bg = uiterm.ColorRed
} else {
b.UiStatus.Fg = uiterm.ColorBlack
b.UiStatus.Bg = uiterm.ColorWhite
}
b.UiStatus.Text = text
b.Ui.Refresh()
}
func (b *Barnard) OnVoiceToggle(ui *uiterm.Ui, key uiterm.Key) {
b.setTransmit(ui, 2)
}
func (b *Barnard) CommandLog(ui *uiterm.Ui, cmd string) {
b.AddOutputLine("command " + cmd)
}
func (b *Barnard) CommandTalk(ui *uiterm.Ui, cmd string) {
b.setTransmit(ui, 2)
}
func (b *Barnard) CommandMicUp(ui *uiterm.Ui, cmd string) {
b.setTransmit(ui, 1)
}
func (b *Barnard) CommandMicDown(ui *uiterm.Ui, cmd string) {
b.setTransmit(ui, 0)
}
func (b *Barnard) setTransmit(ui *uiterm.Ui, val int) {
if b.Tx && val == 1 {
return
}
if b.Tx == false && val == 0 {
return
}
if b.Tx {
b.Notify("micdown", "me", "")
b.Tx = false
b.UpdateGeneralStatus(" Idle ", false)
b.Stream.StopSource()
} else if b.Connected == false {
b.Notify("error", "me", "no tx while disconnected")
b.Tx = false
b.UpdateGeneralStatus("no tx while disconnected", true)
} else {
b.Tx = true
err := b.Stream.StartSource(b.UserConfig.GetInputDevice())
if err != nil {
b.Notify("error", "me", err.Error())
b.UpdateGeneralStatus(err.Error(), true)
} else {
b.Notify("micup", "me", "")
b.UpdateGeneralStatus(" Tx ", true)
} //if error transmit
} //not transmitting
} //func
func (b *Barnard) OnMicVolumeDown(ui *uiterm.Ui, key uiterm.Key) {
b.Stream.SetMicVolume(-0.1, true)
b.UserConfig.SetMicVolume(b.Stream.GetMicVolume())
}
func (b *Barnard) OnMicVolumeUp(ui *uiterm.Ui, key uiterm.Key) {
b.Stream.SetMicVolume(0.1, true)
b.UserConfig.SetMicVolume(b.Stream.GetMicVolume())
}
func (b *Barnard) OnQuitPress(ui *uiterm.Ui, key uiterm.Key) {
b.Client.Disconnect()
b.Ui.Close()
}
func (b *Barnard) CommandExit(ui *uiterm.Ui, cmd string) {
b.Client.Disconnect()
b.Ui.Close()
}
func (b *Barnard) OnClearPress(ui *uiterm.Ui, key uiterm.Key) {
b.UiOutput.Clear()
}
func (b *Barnard) OnScrollOutputUp(ui *uiterm.Ui, key uiterm.Key) {
b.UiOutput.ScrollUp()
}
func (b *Barnard) OnScrollOutputDown(ui *uiterm.Ui, key uiterm.Key) {
b.UiOutput.ScrollDown()
}
func (b *Barnard) OnScrollOutputTop(ui *uiterm.Ui, key uiterm.Key) {
b.UiOutput.ScrollTop()
}
func (b *Barnard) OnScrollOutputBottom(ui *uiterm.Ui, key uiterm.Key) {
b.UiOutput.ScrollBottom()
}
func (b *Barnard) OnFocusPress(ui *uiterm.Ui, key uiterm.Key) {
active := b.Ui.Active()
if active == uiViewInput {
b.Ui.SetActive(uiViewTree)
} else if active == uiViewTree {
b.Ui.SetActive(uiViewInput)
}
width, height := termbox.Size()
b.OnUiResize(ui, width, height)
ui.Refresh()
}
func (b *Barnard) OnTextInput(ui *uiterm.Ui, textbox *uiterm.Textbox, text string) {
if text == "" {
return
}
if b.Client != nil && b.Client.Self != nil {
if b.selectedUser != nil {
b.selectedUser.Send(text)
b.AddOutputPrivateMessage(b.Client.Self, b.selectedUser, text)
} else {
b.Client.Self.Channel.Send(text, false)
b.AddOutputMessage(b.Client.Self, text)
}
}
}
func (b *Barnard) GotoChat() {
b.OnFocusPress(b.Ui, uiterm.KeyTab)
}
func (b *Barnard) OnUiDoneInitialize(ui *uiterm.Ui) {
b.start()
}
func (b *Barnard) OnUiInitialize(ui *uiterm.Ui) {
ui.Add(uiViewLogo, &uiterm.Label{
Text: "Barnard ",
Fg: uiterm.ColorWhite | uiterm.AttrBold,
Bg: uiterm.ColorMagenta,
})
// ui.Add(uiViewTop, &uiterm.Label{
// Fg: uiterm.ColorWhite,
// Bg: uiterm.ColorBlue,
// })
b.UiStatus = uiterm.Label{
Text: " Idle ",
Fg: uiterm.ColorBlack,
Bg: uiterm.ColorWhite,
}
ui.Add(uiViewStatus, &b.UiStatus)
b.UiInput = uiterm.Textbox{
Fg: uiterm.ColorWhite,
Bg: uiterm.ColorBlack,
Input: b.OnTextInput,
}
ui.Add(uiViewInput, &b.UiInput)
b.UiInputStatus = uiterm.Label{
Fg: uiterm.ColorBlack,
Bg: uiterm.ColorWhite,
}
ui.Add(uiViewInputStatus, &b.UiInputStatus)
b.UiOutput = uiterm.Textview{
Fg: uiterm.ColorWhite,
Bg: uiterm.ColorBlack,
}
ui.Add(uiViewOutput, &b.UiOutput)
b.UiTree = uiterm.Tree{
Generator: b.TreeItemBuild,
KeyListener: b.TreeItemKeyPress,
CharacterListener: b.TreeItemCharacter,
Fg: uiterm.ColorWhite,
Bg: uiterm.ColorBlack,
}
ui.Add(uiViewTree, &b.UiTree)
//add this to see what your commands are coming in as raw strings
// b.Ui.AddCommandListener(b.CommandLog, "*")
b.Ui.AddCommandListener(b.CommandMicUp, "micup")
b.Ui.AddCommandListener(b.CommandMicDown, "micdown")
b.Ui.AddCommandListener(b.CommandTalk, "toggle")
b.Ui.AddCommandListener(b.CommandTalk, "talk")
b.Ui.AddCommandListener(b.CommandExit, "exit")
b.Ui.AddKeyListener(b.OnFocusPress, b.Hotkeys.SwitchViews)
b.Ui.AddKeyListener(b.OnVoiceToggle, b.Hotkeys.Talk)
b.Ui.AddKeyListener(b.OnTimestampToggle, b.Hotkeys.ToggleTimestamps)
b.Ui.AddKeyListener(b.OnQuitPress, b.Hotkeys.Exit)
b.Ui.AddKeyListener(b.OnScrollOutputUp, b.Hotkeys.ScrollUp)
b.Ui.AddKeyListener(b.OnScrollOutputDown, b.Hotkeys.ScrollDown)
b.Ui.AddKeyListener(b.OnScrollOutputTop, b.Hotkeys.ScrollToTop)
b.Ui.AddKeyListener(b.OnScrollOutputBottom, b.Hotkeys.ScrollToBottom)
b.Ui.SetActive(uiViewInput)
b.UiTree.Rebuild()
b.Ui.Refresh()
}
func (b *Barnard) OnUiResize(ui *uiterm.Ui, width, height int) {
treeHeight := 0
outputHeight := 0
active := b.Ui.Active()
if active == uiViewTree {
treeHeight = height - 4
outputHeight = 0
} else {
treeHeight = 0
outputHeight = height - 4
}
// ui.SetBounds(uiViewLogo, 0, 0, 9, 1)
ui.SetBounds(uiViewOutput, 0, 1, width, outputHeight+1)
ui.SetBounds(uiViewTree, 0, 1, width, treeHeight+1)
ui.SetBounds(uiViewStatus, 0, height-2, width, height-1)
ui.SetBounds(uiViewInputStatus, 0, height-1, len(b.GetInputStatus()), height)
//setting this to inputStatus+1 will leave one space between inputStatus and input box
//x starts at 0, so 10 chars of text will go from 0 to 9, there'll be a space at char 10, and we'll start at (10+1)=11
ui.SetBounds(uiViewInput, len(b.GetInputStatus())+1, height-1, width, height)
}

176
ui_tree.go Normal file
View File

@ -0,0 +1,176 @@
package main
import (
//"math"
// "fmt"
"git.2mb.codes/~cmb/barnard/gumble/gumble"
"git.2mb.codes/~cmb/barnard/uiterm"
"sort"
)
type TreeItem struct {
User *gumble.User
Channel *gumble.Channel
}
func (ti TreeItem) String() string {
if ti.User != nil {
return ti.User.Name
}
if ti.Channel != nil {
return "#" + ti.Channel.Name
}
return ""
}
func (ti TreeItem) TreeItemStyle(fg, bg uiterm.Attribute, active bool) (uiterm.Attribute, uiterm.Attribute) {
if ti.Channel != nil {
fg |= uiterm.AttrBold
}
if active {
fg, bg = bg, fg
}
return fg, bg
}
func (b *Barnard) TreeItemCharacter(ui *uiterm.Ui, tree *uiterm.Tree, item uiterm.TreeItem, ch rune) {
}
func (b *Barnard) changeVolume(users []*gumble.User, change float32) {
for _, u := range users {
au := u.AudioSource
if au == nil {
continue
}
var boost uint16
var cv float32
var ng float32
var curboost float32
curboost = float32((u.Boost - 1)) / 10
cv = au.GetGain() + curboost
ng = cv + change
boost = uint16(1)
//b.AddOutputLine(fmt.Sprintf("cv %.2f change %.2f ng %.2f",cv,change,ng))
if ng > 1.0 {
//1.0 will give volume of one and boost of 1
//1.1 will give volume of 1 and boost of 2
//b.AddOutputLine(fmt.Sprintf("partperc %.2f",(ng*10)))
perc := uint16((ng * 10)) - 10
perc += 1
boost = perc
ng = 1.0
}
if ng < 0 {
ng = 0.0
}
//b.AddOutputLine(fmt.Sprintf("boost %d ng %.2f",boost,ng))
u.Boost = boost
u.Volume = ng
au.SetGain(ng)
b.UserConfig.UpdateConfig(u)
}
b.UserConfig.SaveConfig()
}
func makeUsersArray(users gumble.Users) []*gumble.User {
t := make([]*gumble.User, 0, len(users))
for _, u := range users {
t = append(t, u)
}
return t
}
func (b *Barnard) TreeItemKeyPress(ui *uiterm.Ui, tree *uiterm.Tree, item uiterm.TreeItem, key uiterm.Key) {
treeItem := item.(TreeItem)
if key == uiterm.KeyEnter {
if treeItem.Channel != nil {
b.Client.Self.Move(treeItem.Channel)
b.SetSelectedUser(nil)
b.GotoChat()
}
if treeItem.User != nil {
if b.selectedUser == treeItem.User {
b.SetSelectedUser(nil)
b.GotoChat()
} else {
b.SetSelectedUser(treeItem.User)
b.GotoChat()
} //select
} //if user and not selected
} //if enter key
if treeItem.Channel != nil {
var c = treeItem.Channel
if key == *b.Hotkeys.VolumeDown {
b.changeVolume(makeUsersArray(c.Users), -0.1)
}
if key == *b.Hotkeys.VolumeUp {
b.changeVolume(makeUsersArray(c.Users), 0.1)
}
} //set volume
if treeItem.User != nil {
var u = treeItem.User
if key == *b.Hotkeys.VolumeDown {
b.changeVolume([]*gumble.User{u}, -0.1)
}
if key == *b.Hotkeys.VolumeUp {
b.changeVolume([]*gumble.User{u}, 0.1)
}
} //user highlighted
} //func
func (b *Barnard) TreeItemBuild(item uiterm.TreeItem) []uiterm.TreeItem {
if b.Client == nil {
return nil
}
var treeItem TreeItem
if ti, ok := item.(TreeItem); !ok {
root := b.Client.Channels[0]
if root == nil {
return nil
}
return []uiterm.TreeItem{
TreeItem{
Channel: root,
},
}
} else {
treeItem = ti
}
if treeItem.User != nil {
return nil
}
users := []uiterm.TreeItem{}
ul := []*gumble.User{}
for _, user := range treeItem.Channel.Users {
ul = append(ul, user)
var u = ul[len(ul)-1]
_ = u
}
sort.Slice(ul, func(i, j int) bool {
return ul[i].Name < ul[j].Name
})
for _, user := range ul {
users = append(users, TreeItem{
User: user,
})
}
channels := []uiterm.TreeItem{}
cl := []*gumble.Channel{}
for _, subchannel := range treeItem.Channel.Children {
cl = append(cl, subchannel)
}
sort.Slice(cl, func(i, j int) bool {
return cl[i].Name < cl[j].Name
})
for _, subchannel := range cl {
channels = append(channels, TreeItem{
Channel: subchannel,
})
}
return append(users, channels...)
}

25
uiterm/attributes.go Normal file
View File

@ -0,0 +1,25 @@
package uiterm
/*
* Source: https://godoc.org/github.com/nsf/termbox-go
*/
type Attribute int
const (
ColorDefault Attribute = iota
ColorBlack
ColorRed
ColorGreen
ColorYellow
ColorBlue
ColorMagenta
ColorCyan
ColorWhite
)
const (
AttrBold Attribute = 1 << (iota + 4)
AttrUnderline
AttrReverse
)

1
uiterm/doc.go Normal file
View File

@ -0,0 +1 @@
package uiterm // import "git.2mb.codes/~cmb/barnard/uiterm"

253
uiterm/key_enumer.go Normal file
View File

@ -0,0 +1,253 @@
// Code generated by "enumer -type=Key -trimprefix=Key -yaml -json -transform=snake"; DO NOT EDIT.
//
package uiterm
import (
"encoding/json"
"fmt"
)
const (
_KeyName_0 = "ctrl_tildectrl_actrl_bctrl_cctrl_dctrl_ectrl_fctrl_gbackspacetabctrl_jctrl_kctrl_lenterctrl_nctrl_octrl_pctrl_qctrl_rctrl_sctrl_tctrl_uctrl_vctrl_wctrl_xctrl_yctrl_zescctrl4ctrl5ctrl6ctrl7space"
_KeyName_1 = "backspace2"
_KeyName_2 = "mouse_rightmouse_middlemouse_leftarrow_rightarrow_leftarrow_downarrow_uppgdnpgupendhomedeleteinsertf12f11f10f9f8f7f6f5f4f3f2f1alt_ctrl_tildealt_ctrl_aalt_ctrl_balt_ctrl_calt_ctrl_dalt_ctrl_ealt_ctrl_falt_ctrl_galt_backspacealt_tabalt_ctrl_jalt_ctrl_kalt_ctrl_lalt_enteralt_ctrl_nalt_ctrl_oalt_ctrl_palt_ctrl_qalt_ctrl_ralt_ctrl_salt_ctrl_talt_ctrl_ualt_ctrl_valt_ctrl_walt_ctrl_xalt_ctrl_yalt_ctrl_zalt_escalt_ctrl4alt_ctrl5alt_ctrl6alt_ctrl7alt_space"
_KeyName_3 = "alt_aalt_balt_calt_dalt_ealt_falt_galt_halt_ialt_jalt_kalt_lalt_malt_nalt_oalt_palt_qalt_ralt_salt_talt_ualt_valt_walt_xalt_yalt_z"
_KeyName_4 = "alt_backspace2"
_KeyName_5 = "alt_arrow_rightalt_arrow_leftalt_arrow_downalt_arrow_upalt_pgdnalt_pgupalt_endalt_homealt_deletealt_insertalt_f12alt_f11alt_f10alt_f9alt_f8alt_f7alt_f6alt_f5alt_f4alt_f3alt_f2alt_f1"
)
var (
_KeyIndex_0 = [...]uint8{0, 10, 16, 22, 28, 34, 40, 46, 52, 61, 64, 70, 76, 82, 87, 93, 99, 105, 111, 117, 123, 129, 135, 141, 147, 153, 159, 165, 168, 173, 178, 183, 188, 193}
_KeyIndex_1 = [...]uint8{0, 10}
_KeyIndex_2 = [...]uint16{0, 11, 23, 33, 44, 54, 64, 72, 76, 80, 83, 87, 93, 99, 102, 105, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 140, 150, 160, 170, 180, 190, 200, 210, 223, 230, 240, 250, 260, 269, 279, 289, 299, 309, 319, 329, 339, 349, 359, 369, 379, 389, 399, 406, 415, 424, 433, 442, 451}
_KeyIndex_3 = [...]uint8{0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130}
_KeyIndex_4 = [...]uint8{0, 14}
_KeyIndex_5 = [...]uint8{0, 15, 29, 43, 55, 63, 71, 78, 86, 96, 106, 113, 120, 127, 133, 139, 145, 151, 157, 163, 169, 175, 181}
)
func (i Key) String() string {
switch {
case 0 <= i && i <= 32:
return _KeyName_0[_KeyIndex_0[i]:_KeyIndex_0[i+1]]
case i == 127:
return _KeyName_1
case 65511 <= i && i <= 65568:
i -= 65511
return _KeyName_2[_KeyIndex_2[i]:_KeyIndex_2[i+1]]
case 65633 <= i && i <= 65658:
i -= 65633
return _KeyName_3[_KeyIndex_3[i]:_KeyIndex_3[i+1]]
case i == 65663:
return _KeyName_4
case 131050 <= i && i <= 131071:
i -= 131050
return _KeyName_5[_KeyIndex_5[i]:_KeyIndex_5[i+1]]
default:
return fmt.Sprintf("Key(%d)", i)
}
}
var _KeyValues = []Key{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 127, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536, 65537, 65538, 65539, 65540, 65541, 65542, 65543, 65544, 65545, 65546, 65547, 65548, 65549, 65550, 65551, 65552, 65553, 65554, 65555, 65556, 65557, 65558, 65559, 65560, 65561, 65562, 65563, 65564, 65565, 65566, 65567, 65568, 65633, 65634, 65635, 65636, 65637, 65638, 65639, 65640, 65641, 65642, 65643, 65644, 65645, 65646, 65647, 65648, 65649, 65650, 65651, 65652, 65653, 65654, 65655, 65656, 65657, 65658, 65663, 131050, 131051, 131052, 131053, 131054, 131055, 131056, 131057, 131058, 131059, 131060, 131061, 131062, 131063, 131064, 131065, 131066, 131067, 131068, 131069, 131070, 131071}
var _KeyNameToValueMap = map[string]Key{
_KeyName_0[0:10]: 0,
_KeyName_0[10:16]: 1,
_KeyName_0[16:22]: 2,
_KeyName_0[22:28]: 3,
_KeyName_0[28:34]: 4,
_KeyName_0[34:40]: 5,
_KeyName_0[40:46]: 6,
_KeyName_0[46:52]: 7,
_KeyName_0[52:61]: 8,
_KeyName_0[61:64]: 9,
_KeyName_0[64:70]: 10,
_KeyName_0[70:76]: 11,
_KeyName_0[76:82]: 12,
_KeyName_0[82:87]: 13,
_KeyName_0[87:93]: 14,
_KeyName_0[93:99]: 15,
_KeyName_0[99:105]: 16,
_KeyName_0[105:111]: 17,
_KeyName_0[111:117]: 18,
_KeyName_0[117:123]: 19,
_KeyName_0[123:129]: 20,
_KeyName_0[129:135]: 21,
_KeyName_0[135:141]: 22,
_KeyName_0[141:147]: 23,
_KeyName_0[147:153]: 24,
_KeyName_0[153:159]: 25,
_KeyName_0[159:165]: 26,
_KeyName_0[165:168]: 27,
_KeyName_0[168:173]: 28,
_KeyName_0[173:178]: 29,
_KeyName_0[178:183]: 30,
_KeyName_0[183:188]: 31,
_KeyName_0[188:193]: 32,
_KeyName_1[0:10]: 127,
_KeyName_2[0:11]: 65511,
_KeyName_2[11:23]: 65512,
_KeyName_2[23:33]: 65513,
_KeyName_2[33:44]: 65514,
_KeyName_2[44:54]: 65515,
_KeyName_2[54:64]: 65516,
_KeyName_2[64:72]: 65517,
_KeyName_2[72:76]: 65518,
_KeyName_2[76:80]: 65519,
_KeyName_2[80:83]: 65520,
_KeyName_2[83:87]: 65521,
_KeyName_2[87:93]: 65522,
_KeyName_2[93:99]: 65523,
_KeyName_2[99:102]: 65524,
_KeyName_2[102:105]: 65525,
_KeyName_2[105:108]: 65526,
_KeyName_2[108:110]: 65527,
_KeyName_2[110:112]: 65528,
_KeyName_2[112:114]: 65529,
_KeyName_2[114:116]: 65530,
_KeyName_2[116:118]: 65531,
_KeyName_2[118:120]: 65532,
_KeyName_2[120:122]: 65533,
_KeyName_2[122:124]: 65534,
_KeyName_2[124:126]: 65535,
_KeyName_2[126:140]: 65536,
_KeyName_2[140:150]: 65537,
_KeyName_2[150:160]: 65538,
_KeyName_2[160:170]: 65539,
_KeyName_2[170:180]: 65540,
_KeyName_2[180:190]: 65541,
_KeyName_2[190:200]: 65542,
_KeyName_2[200:210]: 65543,
_KeyName_2[210:223]: 65544,
_KeyName_2[223:230]: 65545,
_KeyName_2[230:240]: 65546,
_KeyName_2[240:250]: 65547,
_KeyName_2[250:260]: 65548,
_KeyName_2[260:269]: 65549,
_KeyName_2[269:279]: 65550,
_KeyName_2[279:289]: 65551,
_KeyName_2[289:299]: 65552,
_KeyName_2[299:309]: 65553,
_KeyName_2[309:319]: 65554,
_KeyName_2[319:329]: 65555,
_KeyName_2[329:339]: 65556,
_KeyName_2[339:349]: 65557,
_KeyName_2[349:359]: 65558,
_KeyName_2[359:369]: 65559,
_KeyName_2[369:379]: 65560,
_KeyName_2[379:389]: 65561,
_KeyName_2[389:399]: 65562,
_KeyName_2[399:406]: 65563,
_KeyName_2[406:415]: 65564,
_KeyName_2[415:424]: 65565,
_KeyName_2[424:433]: 65566,
_KeyName_2[433:442]: 65567,
_KeyName_2[442:451]: 65568,
_KeyName_3[0:5]: 65633,
_KeyName_3[5:10]: 65634,
_KeyName_3[10:15]: 65635,
_KeyName_3[15:20]: 65636,
_KeyName_3[20:25]: 65637,
_KeyName_3[25:30]: 65638,
_KeyName_3[30:35]: 65639,
_KeyName_3[35:40]: 65640,
_KeyName_3[40:45]: 65641,
_KeyName_3[45:50]: 65642,
_KeyName_3[50:55]: 65643,
_KeyName_3[55:60]: 65644,
_KeyName_3[60:65]: 65645,
_KeyName_3[65:70]: 65646,
_KeyName_3[70:75]: 65647,
_KeyName_3[75:80]: 65648,
_KeyName_3[80:85]: 65649,
_KeyName_3[85:90]: 65650,
_KeyName_3[90:95]: 65651,
_KeyName_3[95:100]: 65652,
_KeyName_3[100:105]: 65653,
_KeyName_3[105:110]: 65654,
_KeyName_3[110:115]: 65655,
_KeyName_3[115:120]: 65656,
_KeyName_3[120:125]: 65657,
_KeyName_3[125:130]: 65658,
_KeyName_4[0:14]: 65663,
_KeyName_5[0:15]: 131050,
_KeyName_5[15:29]: 131051,
_KeyName_5[29:43]: 131052,
_KeyName_5[43:55]: 131053,
_KeyName_5[55:63]: 131054,
_KeyName_5[63:71]: 131055,
_KeyName_5[71:78]: 131056,
_KeyName_5[78:86]: 131057,
_KeyName_5[86:96]: 131058,
_KeyName_5[96:106]: 131059,
_KeyName_5[106:113]: 131060,
_KeyName_5[113:120]: 131061,
_KeyName_5[120:127]: 131062,
_KeyName_5[127:133]: 131063,
_KeyName_5[133:139]: 131064,
_KeyName_5[139:145]: 131065,
_KeyName_5[145:151]: 131066,
_KeyName_5[151:157]: 131067,
_KeyName_5[157:163]: 131068,
_KeyName_5[163:169]: 131069,
_KeyName_5[169:175]: 131070,
_KeyName_5[175:181]: 131071,
}
// KeyString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func KeyString(s string) (Key, error) {
if val, ok := _KeyNameToValueMap[s]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to Key values", s)
}
// KeyValues returns all values of the enum
func KeyValues() []Key {
return _KeyValues
}
// IsAKey returns "true" if the value is listed in the enum definition. "false" otherwise
func (i Key) IsAKey() bool {
for _, v := range _KeyValues {
if i == v {
return true
}
}
return false
}
// MarshalJSON implements the json.Marshaler interface for Key
func (i Key) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface for Key
func (i *Key) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("Key should be a string, got %s", data)
}
var err error
*i, err = KeyString(s)
return err
}
// MarshalYAML implements a YAML Marshaler for Key
func (i Key) MarshalYAML() (interface{}, error) {
return i.String(), nil
}
// UnmarshalYAML implements a YAML Unmarshaler for Key
func (i *Key) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
var err error
*i, err = KeyString(s)
return err
}

186
uiterm/keys.go Normal file
View File

@ -0,0 +1,186 @@
package uiterm
//go:generate enumer -type=Key -trimprefix=Key -yaml -json -transform=snake
/*
* Source: https://godoc.org/github.com/nsf/termbox-go
*/
type Key uint32
const (
KeyF1 Key = 0xFFFF - iota
KeyF2
KeyF3
KeyF4
KeyF5
KeyF6
KeyF7
KeyF8
KeyF9
KeyF10
KeyF11
KeyF12
KeyInsert
KeyDelete
KeyHome
KeyEnd
KeyPgup
KeyPgdn
KeyArrowUp
KeyArrowDown
KeyArrowLeft
KeyArrowRight
MouseLeft
MouseMiddle
MouseRight
)
const (
KeyCtrlTilde Key = 0x00
KeyCtrl2 Key = 0x00
KeyCtrlSpace Key = 0x00
KeyCtrlA Key = 0x01
KeyCtrlB Key = 0x02
KeyCtrlC Key = 0x03
KeyCtrlD Key = 0x04
KeyCtrlE Key = 0x05
KeyCtrlF Key = 0x06
KeyCtrlG Key = 0x07
KeyBackspace Key = 0x08
KeyCtrlH Key = 0x08
KeyTab Key = 0x09
KeyCtrlI Key = 0x09
KeyCtrlJ Key = 0x0A
KeyCtrlK Key = 0x0B
KeyCtrlL Key = 0x0C
KeyEnter Key = 0x0D
KeyCtrlM Key = 0x0D
KeyCtrlN Key = 0x0E
KeyCtrlO Key = 0x0F
KeyCtrlP Key = 0x10
KeyCtrlQ Key = 0x11
KeyCtrlR Key = 0x12
KeyCtrlS Key = 0x13
KeyCtrlT Key = 0x14
KeyCtrlU Key = 0x15
KeyCtrlV Key = 0x16
KeyCtrlW Key = 0x17
KeyCtrlX Key = 0x18
KeyCtrlY Key = 0x19
KeyCtrlZ Key = 0x1A
KeyEsc Key = 0x1B
KeyCtrlLsqBracket Key = 0x1B
KeyCtrl3 Key = 0x1B
KeyCtrl4 Key = 0x1C
KeyCtrlBackslash Key = 0x1C
KeyCtrl5 Key = 0x1D
KeyCtrlRsqBracket Key = 0x1D
KeyCtrl6 Key = 0x1E
KeyCtrl7 Key = 0x1F
KeyCtrlSlash Key = 0x1F
KeyCtrlUnderscore Key = 0x1F
KeySpace Key = 0x20
KeyBackspace2 Key = 0x7F
KeyCtrl8 Key = 0x7F
)
//##altkeys##
const(
KeyAltF1 Key = KeyF1 + (1<<16)
KeyAltF2 Key = KeyF2 + (1<<16)
KeyAltF3 Key = KeyF3 + (1<<16)
KeyAltF4 Key = KeyF4 + (1<<16)
KeyAltF5 Key = KeyF5 + (1<<16)
KeyAltF6 Key = KeyF6 + (1<<16)
KeyAltF7 Key = KeyF7 + (1<<16)
KeyAltF8 Key = KeyF8 + (1<<16)
KeyAltF9 Key = KeyF9 + (1<<16)
KeyAltF10 Key = KeyF10 + (1<<16)
KeyAltF11 Key = KeyF11 + (1<<16)
KeyAltF12 Key = KeyF12 + (1<<16)
KeyAltInsert Key = KeyInsert + (1<<16)
KeyAltDelete Key = KeyDelete + (1<<16)
KeyAltHome Key = KeyHome + (1<<16)
KeyAltEnd Key = KeyEnd + (1<<16)
KeyAltPgup Key = KeyPgup + (1<<16)
KeyAltPgdn Key = KeyPgdn + (1<<16)
KeyAltArrowUp Key = KeyArrowUp + (1<<16)
KeyAltArrowDown Key = KeyArrowDown + (1<<16)
KeyAltArrowLeft Key = KeyArrowLeft + (1<<16)
KeyAltArrowRight Key = KeyArrowRight + (1<<16)
KeyAltCtrlTilde Key = KeyCtrlTilde + (1<<16)
KeyAltCtrl2 Key = KeyCtrl2 + (1<<16)
KeyAltCtrlSpace Key = KeyCtrlSpace + (1<<16)
KeyAltCtrlA Key = KeyCtrlA + (1<<16)
KeyAltCtrlB Key = KeyCtrlB + (1<<16)
KeyAltCtrlC Key = KeyCtrlC + (1<<16)
KeyAltCtrlD Key = KeyCtrlD + (1<<16)
KeyAltCtrlE Key = KeyCtrlE + (1<<16)
KeyAltCtrlF Key = KeyCtrlF + (1<<16)
KeyAltCtrlG Key = KeyCtrlG + (1<<16)
KeyAltBackspace Key = KeyBackspace + (1<<16)
KeyAltCtrlH Key = KeyCtrlH + (1<<16)
KeyAltTab Key = KeyTab + (1<<16)
KeyAltCtrlI Key = KeyCtrlI + (1<<16)
KeyAltCtrlJ Key = KeyCtrlJ + (1<<16)
KeyAltCtrlK Key = KeyCtrlK + (1<<16)
KeyAltCtrlL Key = KeyCtrlL + (1<<16)
KeyAltEnter Key = KeyEnter + (1<<16)
KeyAltCtrlM Key = KeyCtrlM + (1<<16)
KeyAltCtrlN Key = KeyCtrlN + (1<<16)
KeyAltCtrlO Key = KeyCtrlO + (1<<16)
KeyAltCtrlP Key = KeyCtrlP + (1<<16)
KeyAltCtrlQ Key = KeyCtrlQ + (1<<16)
KeyAltCtrlR Key = KeyCtrlR + (1<<16)
KeyAltCtrlS Key = KeyCtrlS + (1<<16)
KeyAltCtrlT Key = KeyCtrlT + (1<<16)
KeyAltCtrlU Key = KeyCtrlU + (1<<16)
KeyAltCtrlV Key = KeyCtrlV + (1<<16)
KeyAltCtrlW Key = KeyCtrlW + (1<<16)
KeyAltCtrlX Key = KeyCtrlX + (1<<16)
KeyAltCtrlY Key = KeyCtrlY + (1<<16)
KeyAltCtrlZ Key = KeyCtrlZ + (1<<16)
KeyAltEsc Key = KeyEsc + (1<<16)
KeyAltCtrlLsqBracket Key = KeyCtrlLsqBracket + (1<<16)
KeyAltCtrl3 Key = KeyCtrl3 + (1<<16)
KeyAltCtrl4 Key = KeyCtrl4 + (1<<16)
KeyAltCtrlBackslash Key = KeyCtrlBackslash + (1<<16)
KeyAltCtrl5 Key = KeyCtrl5 + (1<<16)
KeyAltCtrlRsqBracket Key = KeyCtrlRsqBracket + (1<<16)
KeyAltCtrl6 Key = KeyCtrl6 + (1<<16)
KeyAltCtrl7 Key = KeyCtrl7 + (1<<16)
KeyAltCtrlSlash Key = KeyCtrlSlash + (1<<16)
KeyAltCtrlUnderscore Key = KeyCtrlUnderscore + (1<<16)
KeyAltSpace Key = KeySpace + (1<<16)
KeyAltBackspace2 Key = KeyBackspace2 + (1<<16)
KeyAltCtrl8 Key = KeyCtrl8 + (1<<16)
KeyAltA Key = 0x61 + (1<<16)
KeyAltB Key = 0x62 + (1<<16)
KeyAltC Key = 0x63 + (1<<16)
KeyAltD Key = 0x64 + (1<<16)
KeyAltE Key = 0x65 + (1<<16)
KeyAltF Key = 0x66 + (1<<16)
KeyAltG Key = 0x67 + (1<<16)
KeyAltH Key = 0x68 + (1<<16)
KeyAltI Key = 0x69 + (1<<16)
KeyAltJ Key = 0x6a + (1<<16)
KeyAltK Key = 0x6b + (1<<16)
KeyAltL Key = 0x6c + (1<<16)
KeyAltM Key = 0x6d + (1<<16)
KeyAltN Key = 0x6e + (1<<16)
KeyAltO Key = 0x6f + (1<<16)
KeyAltP Key = 0x70 + (1<<16)
KeyAltQ Key = 0x71 + (1<<16)
KeyAltR Key = 0x72 + (1<<16)
KeyAltS Key = 0x73 + (1<<16)
KeyAltT Key = 0x74 + (1<<16)
KeyAltU Key = 0x75 + (1<<16)
KeyAltV Key = 0x76 + (1<<16)
KeyAltW Key = 0x77 + (1<<16)
KeyAltX Key = 0x78 + (1<<16)
KeyAltY Key = 0x79 + (1<<16)
KeyAltZ Key = 0x7a + (1<<16)
)

54
uiterm/label.go Normal file
View File

@ -0,0 +1,54 @@
package uiterm
import (
"strings"
"github.com/nsf/termbox-go"
)
type Label struct {
Text string
Fg, Bg Attribute
ui *Ui
x0, y0, x1, y1 int
}
func (l *Label) uiInitialize(ui *Ui) {
l.ui = ui
}
func (l *Label) uiSetActive(active bool) {
}
func (l *Label) uiSetBounds(x0, y0, x1, y1 int) {
l.x0 = x0
l.y0 = y0
l.x1 = x1
l.y1 = y1
l.uiDraw()
}
func (l *Label) uiDraw() {
l.ui.beginDraw()
defer l.ui.endDraw()
reader := strings.NewReader(l.Text)
for y := l.y0; y < l.y1; y++ {
for x := l.x0; x < l.x1; x++ {
var chr rune
if ch, _, err := reader.ReadRune(); err != nil {
chr = ' '
} else {
chr = ch
}
termbox.SetCell(x, y, chr, termbox.Attribute(l.Fg), termbox.Attribute(l.Bg))
}
}
}
func (l *Label) uiKeyEvent(key Key) {
}
func (l *Label) uiCharacterEvent(chr rune) {
}

138
uiterm/textbox.go Normal file
View File

@ -0,0 +1,138 @@
package uiterm
import (
"strings"
// "unicode/utf8"
"github.com/nsf/termbox-go"
)
type Textbox struct {
Text string
Fg, Bg Attribute
Input func(ui *Ui, textbox *Textbox, text string)
ui *Ui
active bool
x0, y0, x1, y1 int
pos int
}
func (t *Textbox) uiInitialize(ui *Ui) {
t.ui = ui
t.pos = 0
}
func (t *Textbox) uiSetActive(active bool) {
t.active = active
t.uiDraw()
}
func (t *Textbox) uiSetBounds(x0, y0, x1, y1 int) {
t.x0 = x0
t.y0 = y0
t.x1 = x1
t.y1 = y1
t.uiDraw()
}
func (t *Textbox) uiDraw() {
t.ui.beginDraw()
defer t.ui.endDraw()
reader := strings.NewReader(t.Text)
if t.pos < 0 {
t.pos = 0
}
if t.pos > len(t.Text) {
t.pos = len(t.Text)
}
for y := t.y0; y < t.y1; y++ {
for x := t.x0; x < t.x1; x++ {
var chr rune
if ch, _, err := reader.ReadRune(); err != nil {
chr = ' '
} else {
chr = ch
}
termbox.SetCell(x, y, chr, termbox.Attribute(t.Fg), termbox.Attribute(t.Bg))
}
}
if t.active {
var x = 0
var y = 0
var idx = -1
var flag = false
for y = t.y0; y < t.y1; y++ {
for x = t.x0; x < t.x1; x++ {
idx += 1
if idx == t.pos {
flag = true
}
if flag == true {
break
}
}
if flag == true {
break
}
}
termbox.SetCursor(x, y)
}
}
func (t *Textbox) uiKeyEvent(key Key) {
redraw := false
switch key {
case KeyHome:
t.pos = 0
redraw = true
case KeyEnd:
t.pos = len(t.Text)
redraw = true
case KeyArrowLeft:
t.pos -= 1
redraw = true
case KeyArrowRight:
t.pos += 1
redraw = true
case KeyCtrlC:
t.Text = ""
t.pos = 0
redraw = true
case KeyEnter:
if t.Input != nil {
t.Input(t.ui, t, t.Text)
}
t.Text = ""
t.pos = 0
redraw = true
case KeySpace:
t.uiCharacterEvent(' ')
case KeyBackspace:
case KeyBackspace2:
if len(t.Text) > 0 {
if t.pos > 0 {
t.Text = t.Text[:t.pos-1] + t.Text[t.pos:]
t.pos -= 1
}
}
// if r, size := utf8.DecodeLastRuneInString(t.Text); r != utf8.RuneError {
// t.Text = t.Text[:len(t.Text)-size]
//t.pos-=size
redraw = true
// }
// }
}
if redraw {
t.uiDraw()
}
}
func (t *Textbox) uiCharacterEvent(chr rune) {
var s = string(chr)
t.Text = t.Text[:t.pos] + s + t.Text[t.pos:]
t.pos += len(s)
t.uiDraw()
}

160
uiterm/textview.go Normal file
View File

@ -0,0 +1,160 @@
package uiterm
import (
"strings"
"github.com/nsf/termbox-go"
)
type Textview struct {
Lines []string
CurrentLine int
Fg, Bg Attribute
showTimestamps bool
parsedLines []string
ui *Ui
x0, y0, x1, y1 int
}
func (t *Textview) uiInitialize(ui *Ui) {
t.ui = ui
t.showTimestamps = true
}
func (t *Textview) ToggleTimestamps() {
if t.showTimestamps == true {
t.showTimestamps = false
} else {
t.showTimestamps = true
}
t.updateParsedLines()
t.uiDraw()
}
func (t *Textview) uiSetActive(active bool) {
}
func (t *Textview) uiSetBounds(x0, y0, x1, y1 int) {
t.x0 = x0
t.y0 = y0
t.x1 = x1
t.y1 = y1
t.updateParsedLines()
t.uiDraw()
}
func (t *Textview) ScrollUp() {
if newLine := t.CurrentLine + 1; newLine < len(t.parsedLines) {
t.CurrentLine = newLine
}
t.uiDraw()
}
func (t *Textview) ScrollDown() {
if newLine := t.CurrentLine - 1; newLine >= 0 {
t.CurrentLine = newLine
}
t.uiDraw()
}
func (t *Textview) ScrollTop() {
if newLine := len(t.parsedLines) - 1; newLine > 0 {
t.CurrentLine = newLine
} else {
t.CurrentLine = 0
}
t.uiDraw()
}
func (t *Textview) ScrollBottom() {
t.CurrentLine = 0
t.uiDraw()
}
func (t *Textview) updateParsedLines() {
width := t.x1 - t.x0
if t.Lines == nil || width <= 0 {
t.parsedLines = nil
return
}
parsed := make([]string, 0, len(t.Lines))
for _, line := range t.Lines {
var l = line
if t.showTimestamps == false {
l = strings.TrimSpace(strings.Split(line, "]")[1])
}
current := ""
chars := 0
reader := strings.NewReader(l)
for {
if chars >= width {
parsed = append(parsed, current)
chars = 0
current = ""
}
if reader.Len() <= 0 {
if chars > 0 {
parsed = append(parsed, current)
}
break
}
if ch, _, err := reader.ReadRune(); err == nil {
current = current + string(ch)
chars++
}
}
}
t.parsedLines = parsed
}
func (t *Textview) AddLine(line string) {
t.Lines = append(t.Lines, line)
t.updateParsedLines()
t.uiDraw()
}
func (t *Textview) Clear() {
t.Lines = nil
t.CurrentLine = 0
t.parsedLines = nil
t.uiDraw()
}
func (t *Textview) uiDraw() {
t.ui.beginDraw()
defer t.ui.endDraw()
var reader *strings.Reader
writeableLines := t.y1 - t.y0
lineNum := 0
if writeableLines < len(t.parsedLines) {
lineNum = len(t.parsedLines) - writeableLines
}
//Beep()
for y := t.y0; y < writeableLines; y++ {
if lineNum < len(t.parsedLines) {
reader = strings.NewReader(t.parsedLines[lineNum])
} else {
reader = nil
}
for x := t.x0; x < t.x1; x++ {
var chr rune = ' '
if reader != nil {
if ch, _, err := reader.ReadRune(); err == nil {
chr = ch
} //no err
} //reader != nil
termbox.SetCell(x, y, chr, termbox.Attribute(t.Fg), termbox.Attribute(t.Bg))
} //each x
lineNum++
} //each y
} //func
func (t *Textview) uiKeyEvent(key Key) {
}
func (t *Textview) uiCharacterEvent(chr rune) {
}

185
uiterm/tree.go Normal file
View File

@ -0,0 +1,185 @@
package uiterm
import (
"strings"
"github.com/nsf/termbox-go"
)
type TreeItem interface {
TreeItemStyle(fg, bg Attribute, active bool) (Attribute, Attribute)
String() string
}
type renderedTreeItem struct {
//String string
Level int
Item TreeItem
}
type Tree struct {
Fg, Bg Attribute
Generator func(item TreeItem) []TreeItem
KeyListener func(ui *Ui, tree *Tree, item TreeItem, key Key)
CharacterListener func(ui *Ui, tree *Tree, item TreeItem, chr rune)
lines []renderedTreeItem
activeLine int
ui *Ui
active bool
x0, y0, x1, y1 int
}
func bounded(i, lower, upper int) int {
if i < lower {
return lower
}
if i > upper {
return upper
}
return i
}
func (t *Tree) uiInitialize(ui *Ui) {
t.ui = ui
}
func (t *Tree) uiSetActive(active bool) {
t.active = active
t.uiDraw()
}
func (t *Tree) uiSetBounds(x0, y0, x1, y1 int) {
t.x0 = x0
t.y0 = y0
t.x1 = x1
t.y1 = y1
t.uiDraw()
}
func (t *Tree) Rebuild() {
if t.Generator == nil {
t.lines = []renderedTreeItem{}
return
}
lines := []renderedTreeItem{}
for _, item := range t.Generator(nil) {
children := t.rebuild_rec(item, 0)
if children != nil {
lines = append(lines, children...)
}
}
t.lines = lines
t.SetActiveLine(0, true)
t.uiDraw()
}
func (t *Tree) rebuild_rec(parent TreeItem, level int) []renderedTreeItem {
if parent == nil {
return nil
}
lines := []renderedTreeItem{
renderedTreeItem{
Level: level,
Item: parent,
},
}
for _, item := range t.Generator(parent) {
children := t.rebuild_rec(item, level+1)
if children != nil {
lines = append(lines, children...)
}
}
return lines
}
func (t *Tree) uiDraw() {
t.ui.beginDraw()
defer t.ui.endDraw()
if t.lines == nil {
t.Rebuild()
}
if t.y1-t.y0 <= 0 {
return
}
var line = t.activeLine
var height = t.y1 - t.y0
var startline = 0
//var total = len(t.lines)
//I'd welcome a better algorithm for this; for that matter, I'd love a book or reference for all sorts of GUI algorithms.
//if (startline+height) < line {
for startline = 0; (startline + height) <= line; startline += height {
}
//}
//if startline+height >= total {
//var rem=(startline+height)-total
//startline-=rem
//}
if startline < 0 {
startline = 0
}
line = startline
for y := t.y0; y < t.y1; y++ {
var reader *strings.Reader
var item TreeItem
level := 0
if line < len(t.lines) {
item = t.lines[line].Item
level = t.lines[line].Level
reader = strings.NewReader(item.String())
}
for x := t.x0; x < t.x1; x++ {
var chr rune = ' '
fg := t.Fg
bg := t.Bg
dx := x - t.x0
dy := y - t.y0
if reader != nil && level*2 <= dx {
if ch, _, err := reader.ReadRune(); err == nil {
chr = ch
fg, bg = item.TreeItemStyle(fg, bg, t.active && t.activeLine == dy)
}
}
termbox.SetCell(x, y, chr, termbox.Attribute(fg), termbox.Attribute(bg))
}
if t.activeLine == (line) {
termbox.SetCursor(t.x0, y)
}
line++
}
}
func (t *Tree) SetActiveLine(num int, relative bool) {
if relative {
t.activeLine = bounded(t.activeLine+num, 0, len(t.lines)-1)
} else {
t.activeLine = bounded(num, 0, len(t.lines)-1)
}
}
func (t *Tree) uiKeyEvent(key Key) {
var runHandler = true
switch key {
case KeyArrowUp:
t.SetActiveLine(-1, true)
runHandler = false
case KeyArrowDown:
t.SetActiveLine(1, true)
runHandler = false
}
if runHandler == true && t.KeyListener != nil {
t.KeyListener(t.ui, t, t.lines[t.activeLine].Item, key)
}
t.uiDraw()
}
func (t *Tree) uiCharacterEvent(ch rune) {
if t.CharacterListener != nil {
t.CharacterListener(t.ui, t, t.lines[t.activeLine].Item, ch)
}
}

218
uiterm/ui.go Normal file
View File

@ -0,0 +1,218 @@
package uiterm
import (
"errors"
"strings"
"sync/atomic"
"github.com/nsf/termbox-go"
)
type KeyListener func(ui *Ui, key Key)
type CommandListener func(ui *Ui, cmd string)
type UiManager interface {
OnUiInitialize(ui *Ui)
OnUiDoneInitialize(ui *Ui)
OnUiResize(ui *Ui, width, height int)
}
type Ui struct {
Fg, Bg Attribute
close chan bool
manager UiManager
drawCount int32
elements map[string]*uiElement
activeElement *uiElement
keyListeners map[Key][]KeyListener
commandListeners map[string][]CommandListener
}
type uiElement struct {
Name string
X0, Y0, X1, Y1 int
View View
}
func New(manager UiManager) *Ui {
ui := &Ui{
close: make(chan bool, 10),
elements: make(map[string]*uiElement),
manager: manager,
keyListeners: make(map[Key][]KeyListener),
commandListeners: make(map[string][]CommandListener),
}
return ui
}
func (ui *Ui) Close() {
if termbox.IsInit {
ui.close <- true
}
}
func (ui *Ui) Refresh() {
if termbox.IsInit {
ui.beginDraw()
defer ui.endDraw()
termbox.Clear(termbox.Attribute(ui.Fg), termbox.Attribute(ui.Bg))
termbox.HideCursor()
for _, element := range ui.elements {
element.View.uiDraw()
}
}
}
func (ui *Ui) beginDraw() {
atomic.AddInt32(&ui.drawCount, 1)
}
func (ui *Ui) endDraw() {
if count := atomic.AddInt32(&ui.drawCount, -1); count == 0 {
termbox.Flush()
}
}
func (ui *Ui) Active() string {
return ui.activeElement.Name
}
func (ui *Ui) SetActive(name string) {
element, _ := ui.elements[name]
if ui.activeElement != nil {
ui.activeElement.View.uiSetActive(false)
}
ui.activeElement = element
if element != nil {
element.View.uiSetActive(true)
}
}
func (ui *Ui) Run(cmds chan string) error {
if termbox.IsInit {
return nil
}
if err := termbox.Init(); err != nil {
return nil
}
defer termbox.Close()
termbox.SetInputMode(termbox.InputAlt)
events := make(chan termbox.Event)
go func() {
for {
events <- termbox.PollEvent()
}
}()
ui.manager.OnUiInitialize(ui)
ui.manager.OnUiDoneInitialize(ui)
width, height := termbox.Size()
ui.manager.OnUiResize(ui, width, height)
ui.Refresh()
for {
select {
case <-ui.close:
return nil
case cmd := <-cmds:
ui.onCommandEvent(cmd)
case event := <-events:
switch event.Type {
case termbox.EventResize:
ui.manager.OnUiResize(ui, event.Width, event.Height)
ui.Refresh()
case termbox.EventKey:
var k = uint32(event.Key)
if event.Ch != 0 && event.Mod != 0 {
k = uint32(event.Ch)
}
if event.Ch != 0 && event.Mod == 0 {
ui.onCharacterEvent(event.Ch)
} else {
if event.Mod > 0 {
k = k + (uint32(event.Mod) << 16)
}
ui.onKeyEvent(Key(k))
}
}
}
}
}
func (ui *Ui) onCharacterEvent(ch rune) {
if ui.activeElement != nil {
ui.activeElement.View.uiCharacterEvent(ch)
}
}
func (ui *Ui) onKeyEvent(key Key) {
if ui.keyListeners[key] != nil {
for _, listener := range ui.keyListeners[key] {
listener(ui, key)
}
}
if ui.activeElement != nil {
ui.activeElement.View.uiKeyEvent(key)
}
}
func (ui *Ui) onCommandEvent(cmd string) {
ta := strings.SplitN(cmd, " ", 2)
t := ta[0]
rest := ""
if len(ta) == 2 {
rest = ta[1]
}
if ui.commandListeners[t] != nil {
for _, listener := range ui.commandListeners[t] {
listener(ui, rest)
}
}
if ui.commandListeners["*"] != nil {
for _, listener := range ui.commandListeners["*"] {
listener(ui, cmd)
}
}
// if ui.activeElement != nil {
// ui.activeElement.View.uiKeyEvent(key)
// }
}
func (ui *Ui) Add(name string, view View) error {
if _, ok := ui.elements[name]; ok {
return errors.New("view already exists")
}
ui.elements[name] = &uiElement{
Name: name,
View: view,
}
view.uiInitialize(ui)
return nil
}
func (ui *Ui) SetBounds(name string, x0, y0, x1, y1 int) error {
element, ok := ui.elements[name]
if !ok {
return errors.New("view does not exist")
}
element.X0, element.Y0, element.X1, element.Y1 = x0, y0, x1, y1
element.View.uiSetBounds(x0, y0, x1, y1)
return nil
}
func (ui *Ui) AddKeyListener(listener KeyListener, key *Key) {
if key != nil {
ui.keyListeners[*key] = append(ui.keyListeners[*key], listener)
}
}
func (ui *Ui) AddCommandListener(listener CommandListener, cmd string) {
//if cmd!=nil {
ui.commandListeners[cmd] = append(ui.commandListeners[cmd], listener)
//}
}

11
uiterm/view.go Normal file
View File

@ -0,0 +1,11 @@
package uiterm
type View interface {
uiInitialize(ui *Ui)
uiSetActive(active bool)
uiSetBounds(x0, y0, x1, y1 int)
uiDraw()
uiKeyEvent(key Key)
uiCharacterEvent(ch rune)
// commandEvent(cmd string)
}