1
0
mirror of https://github.com/garraflavatra/rolens.git synced 2025-01-18 13:07:58 +00:00

Hosts and settings

This commit is contained in:
Romein van Buren 2023-01-18 20:59:00 +01:00
parent 2603e6350e
commit b8f1f241f1
Signed by: romein
GPG Key ID: 0EFF8478ADDF6C49
12 changed files with 413 additions and 99 deletions

View File

@ -1,6 +1,6 @@
<script>
import { onMount } from 'svelte';
import { Hosts, OpenConnection } from '../wailsjs/go/app/App';
import { OpenConnection } from '../wailsjs/go/app/App';
import { Environment, WindowSetTitle } from '../wailsjs/runtime';
import BlankState from './components/blankstate.svelte';
import ContextMenu from './components/contextmenu.svelte';
@ -41,7 +41,6 @@
onMount(() => {
Environment().then(e => environment = e);
Hosts().then(h => hosts = h);
});
</script>
@ -52,7 +51,7 @@
{#if environment}
<main class:empty={!host || !connection}>
<AddressBar {hosts} bind:activeHostKey on:select={e => openConnection(e.detail)} bind:modalOpen={addressBarModalOpen} />
<AddressBar bind:hosts bind:activeHostKey on:select={e => openConnection(e.detail)} bind:modalOpen={addressBarModalOpen} />
{#if host && connection}
<Connection {hosts} bind:activeCollKey bind:activeDbKey {activeHostKey} />

View File

@ -5,6 +5,7 @@
export let show = false;
export let title = undefined;
export let contentPadding = true;
export let width = '80vw';
function keydown(event) {
if (event.key === 'Escape') {
@ -17,7 +18,7 @@
{#if show}
<div class="modal outer" on:mousedown|self={() => show = false} transition:fade>
<div class="inner" transition:fly={{ y: 100 }}>
<div class="inner" style:max-width={width || '80vw'} transition:fly={{ y: 100 }}>
{#if title}
<header>
<div class="title">{title}</div>
@ -55,7 +56,6 @@
}
.inner {
max-width: 80vw;
max-height: 80vh;
background-color: #fff;
margin-left: auto;

View File

@ -0,0 +1,72 @@
<script>
import { createEventDispatcher } from 'svelte';
import { AddHost } from '../../../wailsjs/go/app/App';
import Modal from '../../components/modal.svelte';
export let show = false;
const dispatch = createEventDispatcher('reload');
let form = {};
let error = '';
$: valid = validate(form);
$: if (show || !show) {
form = {};
}
function validate(form) {
return form.name && form.uri && true;
}
async function submit() {
if (!valid) {
return;
}
try {
await AddHost(JSON.stringify(form));
show = false;
dispatch('reload');
}
catch (e) {
error = e;
}
}
</script>
<Modal bind:show title="Create a new host">
<form on:submit|preventDefault={submit}>
<label class="field">
<span class="label">Label</span>
<input type="text" placeholder="mywebsite.com MongoDB" bind:value={form.name} />
</label>
<label class="field">
<span class="label">Connection string</span>
<input type="text" placeholder="mongodb://..." bind:value={form.uri} spellcheck="false" />
</label>
<div class="result">
<div>
{#if error}
<div class="error">{error}</div>
{/if}
</div>
<button class="btn" disabled={!valid} type="submit">Create</button>
</div>
</form>
</Modal>
<style>
form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.result {
display: flex;
justify-content: space-between;
align-items: center;
}
</style>

View File

@ -1,44 +1,83 @@
<script>
import Modal from '../../components/modal.svelte';
import { createEventDispatcher } from 'svelte';
import { createEventDispatcher, onMount } from 'svelte';
import Icon from '../../components/icon.svelte';
import { Hosts, RemoveHost } from '../../../wailsjs/go/app/App';
import Welcome from './welcome.svelte';
import CreateHostModal from './createhostmodal.svelte';
export let hosts = {};
export let activeHostKey = '';
export let modalOpen = false;
const dispatch = createEventDispatcher();
let error = '';
let createHostModalOpen = false;
$: host = hosts?.[activeHostKey];
$: if (!modalOpen) {
error = '';
}
function select(hostKey) {
activeHostKey = hostKey;
dispatch('select', hostKey);
}
async function getHosts() {
try {
const h = await Hosts();
hosts = h || {};
}
catch (e) {
error = e;
}
}
async function removeHost(hostKey) {
try {
await RemoveHost(hostKey);
await getHosts();
}
catch (e) {
error = e;
}
}
onMount(getHosts);
</script>
<Modal bind:show={modalOpen} title="Hosts">
<Modal bind:show={modalOpen} title={Object.keys(hosts).length && 'Hosts'} width="60vw">
{#if error}
<p class="error">
<strong>Oops!</strong> {error}
</p>
{/if}
{#if Object.keys(hosts).length}
<ul class="hosts">
{#each Object.entries(hosts) as [hostKey, host]}
<li>
<div class="host">
<!-- <div class="name">{host.name}</div> -->
<button class="btn" on:click={() => select(hostKey)} title="Connect to {host.name}">
<button class="btn secondary" on:click={() => select(hostKey)} title="Connect to {host.name}">
{host.name}
</button>
<button class="btn" title="Edit {host.name}">
<button class="btn secondary" title="Edit {host.name}">
<Icon name="edit" />
</button>
<button class="btn" title="Remove {host.name}">
<button class="btn secondary" title="Remove {host.name}" on:click={() => removeHost(hostKey)}>
<Icon name="x" />
</button>
</div>
</li>
{/each}
</ul>
{:else}
<Welcome on:createHost={() => createHostModalOpen = true} />
{/if}
</Modal>
<CreateHostModal bind:show={createHostModalOpen} on:reload={getHosts} />
<style>
.hosts {
display: grid;
@ -46,36 +85,32 @@
gap: 0.5rem;
}
.error {
color: #c00;
}
.host {
display: grid;
grid-template: 1fr 1fr / 1fr auto;
align-items: center;
width: 100%;
height: 100%;
border-radius: 10px;
overflow: hidden;
border: 1px solid #ccc;
}
.host button {
border-radius: 0;
background: #eee;
color: inherit;
border: none;
border-left: 1px solid #ccc;
}
.host button:hover {
background-color: #ddd;
}
.host button:first-child {
.host button:nth-child(1) {
border-right: none;
grid-row: 1 / 3;
height: 100%;
border: none;
background-color: #fff;
border-radius: 10px 0 0 10px;
}
.host button:first-child:hover {
background-color: #eee;
.host button:nth-child(2) {
border-top-right-radius: 10px;
border-bottom: none;
}
.host button:last-child {
border-top: 1px solid #ccc;
.host button:nth-child(3) {
border-bottom-right-radius: 10px;
}
</style>

View File

@ -27,7 +27,7 @@
</div>
</div>
<HostModal bind:modalOpen on:select {hosts} />
<HostModal bind:modalOpen bind:hosts on:select />
<style>
.addressbar {

View File

@ -0,0 +1,30 @@
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function createHost() {
dispatch('createHost');
}
</script>
<div class="welcome">
<p class="title">Welcome to Mongodup!</p>
<button class="btn" on:click={createHost}>Create your first host</button>
</div>
<style>
.welcome {
text-align: center;
padding: 2rem;
}
.title {
font-weight: 600;
font-size: 1.5rem;
}
.btn {
margin-top: 2rem;
}
</style>

View File

@ -4,6 +4,8 @@ import {app} from '../models';
import {primitive} from '../models';
import {map[string]app} from '../models';
export function AddHost(arg1:string):Promise<void>;
export function DropCollection(arg1:string,arg2:string,arg3:string):Promise<boolean>;
export function DropDatabase(arg1:string,arg2:string):Promise<boolean>;
@ -24,6 +26,8 @@ export function OpenConnection(arg1:string):Promise<Array<string>>;
export function OpenDatabase(arg1:string,arg2:string):Promise<Array<string>>;
export function RemoveHost(arg1:string):Promise<void>;
export function RemoveItems(arg1:string,arg2:string,arg3:string,arg4:string,arg5:boolean):Promise<number>;
export function UpdateItems(arg1:string,arg2:string,arg3:string,arg4:string):Promise<number>;

View File

@ -2,6 +2,10 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export function AddHost(arg1) {
return window['go']['app']['App']['AddHost'](arg1);
}
export function DropCollection(arg1, arg2, arg3) {
return window['go']['app']['App']['DropCollection'](arg1, arg2, arg3);
}
@ -42,6 +46,10 @@ export function OpenDatabase(arg1, arg2) {
return window['go']['app']['App']['OpenDatabase'](arg1, arg2);
}
export function RemoveHost(arg1) {
return window['go']['app']['App']['RemoveHost'](arg1);
}
export function RemoveItems(arg1, arg2, arg3, arg4, arg5) {
return window['go']['app']['App']['RemoveItems'](arg1, arg2, arg3, arg4, arg5);
}

23
go.mod
View File

@ -4,24 +4,14 @@ go 1.18
require github.com/wailsapp/wails/v2 v2.3.1
require (
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.1 // indirect
github.com/xdg-go/stringprep v1.0.3 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
)
require (
github.com/bep/debounce v1.2.1 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/google/uuid v1.1.2 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/google/uuid v1.1.2
github.com/imdario/mergo v0.3.12 // indirect
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/labstack/echo/v4 v4.9.0 // indirect
github.com/labstack/gommon v0.3.1 // indirect
github.com/leaanthony/go-ansi-parser v1.0.1 // indirect
@ -29,17 +19,24 @@ require (
github.com/leaanthony/slicer v1.5.0 // indirect
github.com/mattn/go-colorable v0.1.11 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/pkg/browser v0.0.0-20210706143420-7d21f8c997e2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/samber/lo v1.27.1 // indirect
github.com/tkrajina/go-reflector v0.5.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.1 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.1 // indirect
github.com/xdg-go/stringprep v1.0.3 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
go.mongodb.org/mongo-driver v1.11.1
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
golang.org/x/text v0.3.7 // indirect
)

View File

@ -1,58 +0,0 @@
package app
import (
"context"
"errors"
"fmt"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/mongo"
mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
)
type Host struct {
Name string `json:"name"`
URI string `json:"uri"`
}
var hosts = map[string]Host{
"localhost": {Name: "Localhost", URI: "mongodb://localhost:27017"},
"tig": {Name: "cmdb.myinfra.nl"},
"vbt": {Name: "vbtverhuurmakelaars.nl"},
}
func (a *App) Hosts() map[string]Host {
return hosts
}
func (a *App) connectToHost(hostKey string) (*mongo.Client, context.Context, func(), error) {
h := hosts[hostKey]
if len(h.URI) == 0 {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Invalid uri",
Message: "You haven't specified a valid uri for the selected host.",
})
return nil, nil, nil, errors.New("invalid uri")
}
client, err := mongo.NewClient(mongoOptions.Client().ApplyURI(h.URI))
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not connect",
Message: "Failed to establish a connection with " + h.Name,
})
return nil, nil, nil, errors.New("could not establish a connection with " + h.Name)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client.Connect(ctx)
return client, ctx, func() {
client.Disconnect(ctx)
cancel()
}, nil
}

190
internal/app/hosts.go Normal file
View File

@ -0,0 +1,190 @@
package app
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/google/uuid"
"github.com/wailsapp/wails/v2/pkg/runtime"
"go.mongodb.org/mongo-driver/mongo"
mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
)
// {
// "3b7e3926-03ce-4407-bc3f-85ed2f01ee42": {
// "name": "Localhost",
// "uri": "mongodb://localhost:27017"
// }
// }
type Host struct {
Name string `json:"name"`
URI string `json:"uri"`
}
func updateHostsFile(newData map[string]Host) error {
filePath, err := appDataFilePath("hosts.json")
if err != nil {
return err
}
jsonData, err := json.MarshalIndent(newData, "", "\t")
if err != nil {
return err
}
err = ioutil.WriteFile(filePath, jsonData, os.ModePerm)
return err
}
func (a *App) Hosts() (map[string]Host, error) {
filePath, err := appDataFilePath("hosts.json")
if err != nil {
fmt.Println(err.Error())
return nil, err
}
jsonData, err := ioutil.ReadFile(filePath)
if err != nil {
// It's ok if the file cannot be opened, for example if it is not accessible.
// Therefore no error is returned.
fmt.Println(err.Error())
return make(map[string]Host, 0), nil
}
if len(jsonData) == 0 {
return make(map[string]Host, 0), nil
} else {
var hosts map[string]Host
err = json.Unmarshal(jsonData, &hosts)
if err != nil {
fmt.Println(err.Error())
return nil, errors.New("host.json file contains malformatted JSON data")
}
return hosts, nil
}
}
func (a *App) AddHost(jsonData string) error {
hosts, err := a.Hosts()
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Could not retrieve hosts",
})
return errors.New("could not retrieve existing host list")
}
var newHost Host
err = json.Unmarshal([]byte(jsonData), &newHost)
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Malformed JSON",
})
return errors.New("could not retrieve existing host list")
}
id, err := uuid.NewRandom()
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Failed to generate a UUID",
})
return errors.New("could not generate a UUID")
}
fmt.Println(hosts)
hosts[id.String()] = newHost
err = updateHostsFile(hosts)
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Could not update host list",
})
return errors.New("could not update host list")
}
return nil
}
func (a *App) RemoveHost(key string) error {
hosts, err := a.Hosts()
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Could not retrieve hosts",
})
return errors.New("could not retrieve existing host list")
}
sure, _ := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Title: "Confirm",
Message: "Are you sure you want to remove " + key + "?",
Buttons: []string{"Yes", "No"},
DefaultButton: "Yes",
CancelButton: "No",
})
if sure != "Yes" {
return errors.New("operation aborted")
}
delete(hosts, key)
err = updateHostsFile(hosts)
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Could not update host list",
})
return errors.New("could not update host list")
}
return nil
}
func (a *App) connectToHost(hostKey string) (*mongo.Client, context.Context, func(), error) {
hosts, err := a.Hosts()
if err != nil {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Could not retrieve hosts",
})
return nil, nil, nil, errors.New("could not retrieve hosts")
}
h := hosts[hostKey]
if len(h.URI) == 0 {
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.InfoDialog,
Title: "Invalid uri",
Message: "You haven't specified a valid uri for the selected host.",
})
return nil, nil, nil, errors.New("invalid uri")
}
client, err := mongo.NewClient(mongoOptions.Client().ApplyURI(h.URI))
if err != nil {
fmt.Println(err.Error())
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Could not connect",
Message: "Failed to establish a connection with " + h.Name,
})
return nil, nil, nil, errors.New("could not establish a connection with " + h.Name)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client.Connect(ctx)
return client, ctx, func() {
client.Disconnect(ctx)
cancel()
}, nil
}

37
internal/app/settings.go Normal file
View File

@ -0,0 +1,37 @@
package app
import (
"errors"
"os"
"path/filepath"
"runtime"
)
func appDataDirectory() (string, error) {
var err error
homeDir, err := os.UserHomeDir()
prefDir := ""
switch runtime.GOOS {
case "windows":
prefDir = filepath.Join(homeDir, "/AppData/Local/Mongodup")
case "darwin":
prefDir = filepath.Join(homeDir, "/Library/Application Support/Mongodup")
case "linux":
prefDir = filepath.Join(homeDir, "/.config/Mongodup")
default:
err = errors.New("unsupported platform")
}
_ = os.MkdirAll(prefDir, os.ModePerm)
return prefDir, err
}
func appDataFilePath(filename string) (string, error) {
dir, err := appDataDirectory()
if err != nil {
return "", err
}
path := filepath.Join(dir, filename)
return path, nil
}