Compare commits
160 Commits
Author | SHA1 | Date | |
---|---|---|---|
101aa6a10f | |||
399364af01 | |||
660f7fd955 | |||
43be41b8a5 | |||
92eaa3c613 | |||
17fd86726d | |||
393574d57d | |||
10c94b0128 | |||
8aebafd531 | |||
70602b8c6c | |||
832b3945d9 | |||
7eeef74f4c | |||
c708585a0b | |||
6393531ac5 | |||
549dad7261 | |||
b883905f8a | |||
91e0fae1d9 | |||
9a2618f42b | |||
6bb99ed3cc | |||
6e11c28d3e | |||
f6f564913a | |||
40deb997ea | |||
59118109bd | |||
971eb4e8f7 | |||
1c70d9484e | |||
6a8c07f93a | |||
0ef6a6038a | |||
dd521103c9 | |||
b04ea04062 | |||
1774e525b3 | |||
d502e3ce74 | |||
80e52829fa | |||
c61aa8020a | |||
d2d63836d4 | |||
e0ad25b2c6 | |||
cc669f1be0 | |||
5bf86601e6 | |||
b7484363dc | |||
5264dc9d8a | |||
8649e562dc | |||
905b962e0b | |||
07c863b251 | |||
69f2c7ad89 | |||
e2c7b8c7b9 | |||
c6821a7090 | |||
b1125f3727 | |||
c7af8d6afa | |||
1025d8a2ed | |||
3f3d7a4c58 | |||
80f0af8723 | |||
730cff1148 | |||
0e3481b593 | |||
abacc9af8b | |||
d837cbd0ff | |||
3f7abce427 | |||
b6bcc3cda6 | |||
07d9436e1e | |||
5c1c238453 | |||
02fb415260 | |||
d866268a7a | |||
98d73e81c0 | |||
47821879fa | |||
7c16b1e00f | |||
29043f63b6 | |||
87d626cd1d | |||
201cf83afe | |||
35de611fd1 | |||
5c02bb98bf | |||
c1f915ae31 | |||
faae146a86 | |||
4a6c6b4b2a | |||
fafacc92eb | |||
b5f5ae2483 | |||
cdfb015638 | |||
435fe04ab3 | |||
4e73882bf1 | |||
f2d9b29baa | |||
eaf9113c92 | |||
194571e132 | |||
f34b33c1a2 | |||
2552a7645e | |||
5dab623793 | |||
95f1570796 | |||
85848ee317 | |||
385499e642 | |||
59ee192bf8 | |||
2771602e5c | |||
38cd5fabee | |||
4bc2a0ff42 | |||
d46e83b735 | |||
a37fce2849 | |||
764d776524 | |||
7c9798b6b1 | |||
70b0645f2e | |||
88606e0a0c | |||
91708da5fc | |||
867d150a6d | |||
9259a85e69 | |||
546d87ca0b | |||
b73f7070e4 | |||
bec2c15ac9 | |||
d4c7de3916 | |||
47346182f0 | |||
aa1351f815 | |||
997b057a21 | |||
fb7fc2443f | |||
43cda4e2fb | |||
dbd3888fe1 | |||
6eb3ff412d | |||
4c66edc170 | |||
a7d48e8059 | |||
41cb597f03 | |||
a9071d629a | |||
9173c8f19a | |||
6350b19478 | |||
8b13c94b22 | |||
add523f8a5 | |||
5c3df55b72 | |||
5f69ab67df | |||
e7d2bd0be6 | |||
9ac6188707 | |||
3d109dc1b4 | |||
c45a48966d | |||
263812f98f | |||
b7999a4db2 | |||
38e5398cb9 | |||
a4e91541cf | |||
5e227da0c4 | |||
59e1281960 | |||
01e49e23b5 | |||
2f30162add | |||
3be52e7ab8 | |||
c85442d39f | |||
61b167ef66 | |||
c449669793 | |||
0c2283a831 | |||
50d9873ec1 | |||
0b5f54b5b2 | |||
ec581076ef | |||
c71575faed | |||
35785a1a28 | |||
832eb7cbf1 | |||
65504cf537 | |||
6fa1c30fb7 | |||
d18872aa5f | |||
5f94f3f893 | |||
b03c94f75d | |||
e9905cbc39 | |||
fdee03cc99 | |||
cb98be1891 | |||
80edd1b9a9 | |||
91ad30ae27 | |||
168ad39076 | |||
0a62579814 | |||
3da0e4720e | |||
dad0d91d01 | |||
92635fe395 | |||
fbc089569d | |||
2296eb96ef | |||
30d9dd04bb |
26
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: npm
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
directory: "/frontend/web"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: npm
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
directory: "/frontend/extension"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "gomod"
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
14
.github/workflows/backend-tests.yml
vendored
@ -12,10 +12,10 @@ jobs:
|
||||
go-static-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.21
|
||||
go-version: 1.22
|
||||
check-latest: true
|
||||
cache: true
|
||||
- name: Verify go.mod is tidy
|
||||
@ -23,7 +23,7 @@ jobs:
|
||||
go mod tidy
|
||||
git diff --exit-code
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v3
|
||||
uses: golangci/golangci-lint-action@v4
|
||||
with:
|
||||
version: v1.54.1
|
||||
args: --verbose --timeout=3m
|
||||
@ -32,10 +32,10 @@ jobs:
|
||||
go-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.21
|
||||
go-version: 1.22
|
||||
check-latest: true
|
||||
cache: true
|
||||
- name: Run all tests
|
||||
|
@ -10,10 +10,10 @@ jobs:
|
||||
build-and-push-release-image:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Extract build args
|
||||
# Extract version from branch name
|
||||
@ -22,20 +22,20 @@ jobs:
|
||||
echo "VERSION=${GITHUB_REF_NAME#release/}" >> $GITHUB_ENV
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: yourselfhosted
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
install: true
|
||||
|
||||
- name: Build and Push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./
|
||||
file: ./Dockerfile
|
||||
|
10
.github/workflows/build-and-push-test-image.yml
vendored
@ -8,27 +8,27 @@ jobs:
|
||||
build-and-push-test-image:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: yourselfhosted
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
install: true
|
||||
version: v0.9.1
|
||||
|
||||
- name: Build and Push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./
|
||||
file: ./Dockerfile
|
||||
|
33
.github/workflows/build-artifacts.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
name: Build artifacts
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "*"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.22
|
||||
check-latest: true
|
||||
cache: true
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v5
|
||||
with:
|
||||
# either 'goreleaser' (default) or 'goreleaser-pro'
|
||||
distribution: goreleaser
|
||||
# 'latest', 'nightly', or a semver
|
||||
version: latest
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
20
.github/workflows/extension-test.yml
vendored
@ -14,19 +14,17 @@ jobs:
|
||||
eslint-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: pnpm/action-setup@v2.2.4
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3.0.0
|
||||
with:
|
||||
version: 8
|
||||
- uses: actions/setup-node@v3
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
cache: pnpm
|
||||
cache-dependency-path: "frontend/extension/pnpm-lock.yaml"
|
||||
- run: pnpm install
|
||||
working-directory: frontend/extension
|
||||
- run: pnpm type-gen
|
||||
working-directory: frontend/extension
|
||||
- name: Run eslint check
|
||||
run: pnpm lint
|
||||
working-directory: frontend/extension
|
||||
@ -34,19 +32,17 @@ jobs:
|
||||
extension-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: pnpm/action-setup@v2.2.4
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3.0.0
|
||||
with:
|
||||
version: 8
|
||||
- uses: actions/setup-node@v3
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
cache: pnpm
|
||||
cache-dependency-path: "frontend/extension/pnpm-lock.yaml"
|
||||
- run: pnpm install
|
||||
working-directory: frontend/extension
|
||||
- run: pnpm type-gen
|
||||
working-directory: frontend/extension
|
||||
- name: Run extension build
|
||||
run: pnpm build
|
||||
working-directory: frontend/extension
|
||||
|
20
.github/workflows/frontend-test.yml
vendored
@ -14,19 +14,17 @@ jobs:
|
||||
eslint-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: pnpm/action-setup@v2.2.4
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3.0.0
|
||||
with:
|
||||
version: 8
|
||||
- uses: actions/setup-node@v3
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
cache: pnpm
|
||||
cache-dependency-path: "frontend/web/pnpm-lock.yaml"
|
||||
- run: pnpm install
|
||||
working-directory: frontend/web
|
||||
- run: pnpm type-gen
|
||||
working-directory: frontend/web
|
||||
- name: Run eslint check
|
||||
run: pnpm lint
|
||||
working-directory: frontend/web
|
||||
@ -34,19 +32,17 @@ jobs:
|
||||
frontend-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: pnpm/action-setup@v2.2.4
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3.0.0
|
||||
with:
|
||||
version: 8
|
||||
- uses: actions/setup-node@v3
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
cache: pnpm
|
||||
cache-dependency-path: "frontend/web/pnpm-lock.yaml"
|
||||
- run: pnpm install
|
||||
working-directory: frontend/web
|
||||
- run: pnpm type-gen
|
||||
working-directory: frontend/web
|
||||
- name: Run frontend build
|
||||
run: pnpm build
|
||||
working-directory: frontend/web
|
||||
|
2
.github/workflows/proto-linter.yml
vendored
@ -17,7 +17,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup buf
|
||||
|
4
.gitignore
vendored
@ -10,3 +10,7 @@ build
|
||||
.DS_Store
|
||||
|
||||
node_modules
|
||||
|
||||
.env
|
||||
|
||||
dist/
|
||||
|
@ -29,7 +29,7 @@ issues:
|
||||
linters-settings:
|
||||
goimports:
|
||||
# Put imports beginning with prefix after 3rd-party packages.
|
||||
local-prefixes: github.com/boojack/slash
|
||||
local-prefixes: github.com/yourselfhosted/slash
|
||||
revive:
|
||||
# Default to run all linters so that new rules in the future could automatically be added to the static check.
|
||||
enable-all-rules: true
|
||||
@ -65,6 +65,10 @@ linters-settings:
|
||||
disabled: true
|
||||
- name: early-return
|
||||
disabled: true
|
||||
- name: use-any
|
||||
disabled: true
|
||||
- name: var-naming
|
||||
disabled: true
|
||||
- name: exported
|
||||
arguments:
|
||||
- "disableStutteringCheck"
|
||||
|
38
.goreleaser.yaml
Normal file
@ -0,0 +1,38 @@
|
||||
version: 1
|
||||
|
||||
before:
|
||||
hooks:
|
||||
# You may remove this if you don't use go modules.
|
||||
- go mod tidy
|
||||
|
||||
builds:
|
||||
- env:
|
||||
- CGO_ENABLED=0
|
||||
main: ./bin/slash
|
||||
binary: slash
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
|
||||
archives:
|
||||
- format: tar.gz
|
||||
# this name template makes the OS and Arch compatible with the results of `uname`.
|
||||
name_template: >-
|
||||
{{ .ProjectName }}_{{ .Tag }}_{{ .Os }}_{{ .Arch }}
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- "^docs:"
|
||||
- "^test:"
|
||||
|
||||
checksum:
|
||||
disable: true
|
||||
|
||||
release:
|
||||
draft: true
|
||||
replace_existing_draft: true
|
||||
make_latest: true
|
||||
mode: replace
|
||||
skip_upload: false
|
@ -6,16 +6,16 @@ COPY . .
|
||||
|
||||
WORKDIR /frontend-build/frontend/web
|
||||
|
||||
RUN corepack enable && pnpm i --frozen-lockfile && pnpm type-gen
|
||||
RUN corepack enable && pnpm i --frozen-lockfile
|
||||
|
||||
RUN pnpm build
|
||||
|
||||
# Build backend exec file.
|
||||
FROM golang:1.21-alpine AS backend
|
||||
FROM golang:1.22-alpine AS backend
|
||||
WORKDIR /backend-build
|
||||
|
||||
COPY . .
|
||||
COPY --from=frontend /frontend-build/frontend/web/dist ./server/dist
|
||||
COPY --from=frontend /frontend-build/frontend/web/dist /backend-build/server/route/frontend/dist
|
||||
|
||||
RUN CGO_ENABLED=0 go build -o slash ./bin/slash/main.go
|
||||
|
||||
|
21
README.md
@ -1,19 +1,19 @@
|
||||
# Slash
|
||||
|
||||
<img align="right" src="./resources/logo.png" height="64px" alt="logo">
|
||||
|
||||
**Slash** is an open source, self-hosted bookmarks and link sharing platform. It allows you to organize your links with tags, and share them with custom shortened URLs. Slash also supports team sharing of link libraries for easy collaboration.
|
||||
**Slash** is an open source, self-hosted links shortener and sharing platform. It allows you to organize your links with tags, and share them with custom shortened URLs. Slash also supports team sharing of link libraries for easy collaboration.
|
||||
|
||||
🧩 Browser extension(v1.0.0) now available! - [Chrome Web Store](https://chrome.google.com/webstore/detail/slash/ebaiehmkammnacjadffpicipfckgeobg), [Firefox Add-on](https://addons.mozilla.org/firefox/addon/your-slash/)
|
||||
|
||||
<a href="https://demo.slash.yourselfhosted.com">Live Demo</a> • <a href="https://discord.gg/QZqUuUAhDV">Discord</a>
|
||||
Getting started with Slash's [Shortcuts](https://github.com/yourselfhosted/slash/blob/main/docs/getting-started/shortcuts.md) and [Collections](https://github.com/yourselfhosted/slash/blob/main/docs/getting-started/collections.md).
|
||||
|
||||
[👉 Join our Discord 💬](https://discord.gg/QZqUuUAhDV)
|
||||
|
||||
<p>
|
||||
<a href="https://hub.docker.com/r/yourselfhosted/slash"><img alt="Docker pull" src="https://img.shields.io/docker/pulls/yourselfhosted/slash.svg"/></a>
|
||||
<a href="https://github.com/boojack/slash/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/boojack/slash?logo=github"/></a>
|
||||
<a href="https://discord.gg/QZqUuUAhDV"><img alt="Discord" src="https://img.shields.io/badge/discord-chat-5865f2?logo=discord&logoColor=f5f5f5" /></a>
|
||||
</p>
|
||||
|
||||

|
||||

|
||||
|
||||
## Background
|
||||
|
||||
@ -23,10 +23,11 @@ That's why we developed Slash, a solution that transforms these links into easil
|
||||
|
||||
## Features
|
||||
|
||||
- Create customizable `/s/` short links for any URL.
|
||||
- Create customizable `s/` short links for any URL.
|
||||
- Share short links public or only with your teammates.
|
||||
- View analytics on link traffic and sources.
|
||||
- Easy access to your shortcuts with browser extension.
|
||||
- Share your shortcuts with Collection to anyone, on any browser.
|
||||
- Open source self-hosted solution.
|
||||
|
||||
## Deploy with Docker in seconds
|
||||
@ -35,15 +36,15 @@ That's why we developed Slash, a solution that transforms these links into easil
|
||||
docker run -d --name slash -p 5231:5231 -v ~/.slash/:/var/opt/slash yourselfhosted/slash:latest
|
||||
```
|
||||
|
||||
Learn more in [Self-hosting Slash with Docker](https://github.com/boojack/slash/blob/main/docs/install.md).
|
||||
Learn more in [Self-hosting Slash with Docker](https://github.com/yourselfhosted/slash/blob/main/docs/install.md).
|
||||
|
||||
## Browser Extension
|
||||
|
||||
Slash provides a browser extension to help you use your shortcuts in the search bar to go to the corresponding URL.
|
||||
|
||||

|
||||

|
||||
|
||||
Learn more in [The Browser Extension of Slash](https://github.com/boojack/slash/blob/main/docs/install-browser-extension.md).
|
||||
Learn more in [The Browser Extension of Slash](https://github.com/yourselfhosted/slash/blob/main/docs/install-browser-extension.md).
|
||||
|
||||
### Chromium based browsers
|
||||
|
||||
|
@ -1,12 +0,0 @@
|
||||
package v1
|
||||
|
||||
type ActivityShorcutCreatePayload struct {
|
||||
ShortcutID int32 `json:"shortcutId"`
|
||||
}
|
||||
|
||||
type ActivityShorcutViewPayload struct {
|
||||
ShortcutID int32 `json:"shortcutId"`
|
||||
IP string `json:"ip"`
|
||||
Referer string `json:"referer"`
|
||||
UserAgent string `json:"userAgent"`
|
||||
}
|
@ -1,131 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/mssola/useragent"
|
||||
"golang.org/x/exp/slices"
|
||||
|
||||
"github.com/boojack/slash/server/metric"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
type ReferenceInfo struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type DeviceInfo struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type BrowserInfo struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type AnalysisData struct {
|
||||
ReferenceData []ReferenceInfo `json:"referenceData"`
|
||||
DeviceData []DeviceInfo `json:"deviceData"`
|
||||
BrowserData []BrowserInfo `json:"browserData"`
|
||||
}
|
||||
|
||||
func (s *APIV1Service) registerAnalyticsRoutes(g *echo.Group) {
|
||||
g.GET("/shortcut/:shortcutId/analytics", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
shortcutID, err := strconv.Atoi(c.Param("shortcutId"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("shortcutId"))).SetInternal(err)
|
||||
}
|
||||
activities, err := s.Store.ListActivities(ctx, &store.FindActivity{
|
||||
Type: store.ActivityShortcutView,
|
||||
Where: []string{fmt.Sprintf("json_extract(payload, '$.shortcutId') = %d", shortcutID)},
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get activities, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
referenceMap := make(map[string]int)
|
||||
deviceMap := make(map[string]int)
|
||||
browserMap := make(map[string]int)
|
||||
for _, activity := range activities {
|
||||
payload := &ActivityShorcutViewPayload{}
|
||||
if err := json.Unmarshal([]byte(activity.Payload), payload); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal payload, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
if _, ok := referenceMap[payload.Referer]; !ok {
|
||||
referenceMap[payload.Referer] = 0
|
||||
}
|
||||
referenceMap[payload.Referer]++
|
||||
|
||||
ua := useragent.New(payload.UserAgent)
|
||||
deviceName := ua.OSInfo().Name
|
||||
browserName, _ := ua.Browser()
|
||||
|
||||
if _, ok := deviceMap[deviceName]; !ok {
|
||||
deviceMap[deviceName] = 0
|
||||
}
|
||||
deviceMap[deviceName]++
|
||||
|
||||
if _, ok := browserMap[browserName]; !ok {
|
||||
browserMap[browserName] = 0
|
||||
}
|
||||
browserMap[browserName]++
|
||||
}
|
||||
|
||||
metric.Enqueue("shortcut analytics")
|
||||
return c.JSON(http.StatusOK, &AnalysisData{
|
||||
ReferenceData: mapToReferenceInfoSlice(referenceMap),
|
||||
DeviceData: mapToDeviceInfoSlice(deviceMap),
|
||||
BrowserData: mapToBrowserInfoSlice(browserMap),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func mapToReferenceInfoSlice(m map[string]int) []ReferenceInfo {
|
||||
referenceInfoSlice := make([]ReferenceInfo, 0)
|
||||
for key, value := range m {
|
||||
referenceInfoSlice = append(referenceInfoSlice, ReferenceInfo{
|
||||
Name: key,
|
||||
Count: value,
|
||||
})
|
||||
}
|
||||
slices.SortFunc(referenceInfoSlice, func(i, j ReferenceInfo) int {
|
||||
return i.Count - j.Count
|
||||
})
|
||||
return referenceInfoSlice
|
||||
}
|
||||
|
||||
func mapToDeviceInfoSlice(m map[string]int) []DeviceInfo {
|
||||
deviceInfoSlice := make([]DeviceInfo, 0)
|
||||
for key, value := range m {
|
||||
deviceInfoSlice = append(deviceInfoSlice, DeviceInfo{
|
||||
Name: key,
|
||||
Count: value,
|
||||
})
|
||||
}
|
||||
slices.SortFunc(deviceInfoSlice, func(i, j DeviceInfo) int {
|
||||
return i.Count - j.Count
|
||||
})
|
||||
return deviceInfoSlice
|
||||
}
|
||||
|
||||
func mapToBrowserInfoSlice(m map[string]int) []BrowserInfo {
|
||||
browserInfoSlice := make([]BrowserInfo, 0)
|
||||
for key, value := range m {
|
||||
browserInfoSlice = append(browserInfoSlice, BrowserInfo{
|
||||
Name: key,
|
||||
Count: value,
|
||||
})
|
||||
}
|
||||
slices.SortFunc(browserInfoSlice, func(i, j BrowserInfo) int {
|
||||
return i.Count - j.Count
|
||||
})
|
||||
return browserInfoSlice
|
||||
}
|
211
api/v1/auth.go
@ -1,211 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/boojack/slash/api/auth"
|
||||
storepb "github.com/boojack/slash/proto/gen/store"
|
||||
"github.com/boojack/slash/server/metric"
|
||||
"github.com/boojack/slash/server/service/license"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
type SignInRequest struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type SignUpRequest struct {
|
||||
Nickname string `json:"nickname"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (s *APIV1Service) registerAuthRoutes(g *echo.Group, secret string) {
|
||||
g.POST("/auth/signin", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
signin := &SignInRequest{}
|
||||
if err := json.NewDecoder(c.Request().Body).Decode(signin); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("malformatted signin request, err: %s", err))
|
||||
}
|
||||
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
Email: &signin.Email,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find user by email %s", signin.Email)).SetInternal(err)
|
||||
}
|
||||
if user == nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("user not found with email %s", signin.Email))
|
||||
} else if user.RowStatus == store.Archived {
|
||||
return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("user has been archived with email %s", signin.Email))
|
||||
}
|
||||
|
||||
// Compare the stored hashed password, with the hashed version of the password that was received.
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(signin.Password)); err != nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "unmatched email and password")
|
||||
}
|
||||
|
||||
accessToken, err := auth.GenerateAccessToken(user.Email, user.ID, time.Now().Add(auth.AccessTokenDuration), []byte(secret))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to generate tokens, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if err := s.UpsertAccessTokenToStore(ctx, user, accessToken); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to upsert access token, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
cookieExp := time.Now().Add(auth.CookieExpDuration)
|
||||
setTokenCookie(c, auth.AccessTokenCookieName, accessToken, cookieExp)
|
||||
metric.Enqueue("user sign in")
|
||||
return c.JSON(http.StatusOK, convertUserFromStore(user))
|
||||
})
|
||||
|
||||
g.POST("/auth/signup", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
enableSignUpSetting, err := s.Store.GetWorkspaceSetting(ctx, &store.FindWorkspaceSetting{
|
||||
Key: storepb.WorkspaceSettingKey_WORKSAPCE_SETTING_ENABLE_SIGNUP,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get workspace setting, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if enableSignUpSetting != nil && !enableSignUpSetting.GetEnableSignup() {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "sign up has been disabled")
|
||||
}
|
||||
|
||||
if !s.LicenseService.IsFeatureEnabled(license.FeatureTypeUnlimitedAccounts) {
|
||||
userList, err := s.Store.ListUsers(ctx, &store.FindUser{})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to list users").SetInternal(err)
|
||||
}
|
||||
if len(userList) >= 5 {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Maximum number of users reached")
|
||||
}
|
||||
}
|
||||
|
||||
signup := &SignUpRequest{}
|
||||
if err := json.NewDecoder(c.Request().Body).Decode(signup); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("malformatted signup request, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
passwordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate password hash").SetInternal(err)
|
||||
}
|
||||
|
||||
create := &store.User{
|
||||
Email: signup.Email,
|
||||
Nickname: signup.Nickname,
|
||||
PasswordHash: string(passwordHash),
|
||||
}
|
||||
existingUsers, err := s.Store.ListUsers(ctx, &store.FindUser{})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find existing users, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
// The first user to sign up is an admin by default.
|
||||
if len(existingUsers) == 0 {
|
||||
create.Role = store.RoleAdmin
|
||||
} else {
|
||||
create.Role = store.RoleUser
|
||||
}
|
||||
|
||||
user, err := s.Store.CreateUser(ctx, create)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to create user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
accessToken, err := auth.GenerateAccessToken(user.Email, user.ID, time.Now().Add(auth.AccessTokenDuration), []byte(secret))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to generate tokens, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if err := s.UpsertAccessTokenToStore(ctx, user, accessToken); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to upsert access token, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
cookieExp := time.Now().Add(auth.CookieExpDuration)
|
||||
setTokenCookie(c, auth.AccessTokenCookieName, accessToken, cookieExp)
|
||||
metric.Enqueue("user sign up")
|
||||
return c.JSON(http.StatusOK, convertUserFromStore(user))
|
||||
})
|
||||
|
||||
g.POST("/auth/logout", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
RemoveTokensAndCookies(c)
|
||||
accessToken := findAccessToken(c)
|
||||
userID, _ := getUserIDFromAccessToken(accessToken, secret)
|
||||
userAccessTokens, err := s.Store.GetUserAccessTokens(ctx, userID)
|
||||
// Auto remove the current access token from the user access tokens.
|
||||
if err == nil && len(userAccessTokens) != 0 {
|
||||
accessTokens := []*storepb.AccessTokensUserSetting_AccessToken{}
|
||||
for _, userAccessToken := range userAccessTokens {
|
||||
if accessToken != userAccessToken.AccessToken {
|
||||
accessTokens = append(accessTokens, userAccessToken)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := s.Store.UpsertUserSetting(ctx, &storepb.UserSetting{
|
||||
UserId: userID,
|
||||
Key: storepb.UserSettingKey_USER_SETTING_ACCESS_TOKENS,
|
||||
Value: &storepb.UserSetting_AccessTokens{
|
||||
AccessTokens: &storepb.AccessTokensUserSetting{
|
||||
AccessTokens: accessTokens,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to upsert user setting, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
}
|
||||
c.Response().WriteHeader(http.StatusOK)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *APIV1Service) UpsertAccessTokenToStore(ctx context.Context, user *store.User, accessToken string) error {
|
||||
userAccessTokens, err := s.Store.GetUserAccessTokens(ctx, user.ID)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get user access tokens")
|
||||
}
|
||||
userAccessToken := storepb.AccessTokensUserSetting_AccessToken{
|
||||
AccessToken: accessToken,
|
||||
Description: "Account sign in",
|
||||
}
|
||||
userAccessTokens = append(userAccessTokens, &userAccessToken)
|
||||
if _, err := s.Store.UpsertUserSetting(ctx, &storepb.UserSetting{
|
||||
UserId: user.ID,
|
||||
Key: storepb.UserSettingKey_USER_SETTING_ACCESS_TOKENS,
|
||||
Value: &storepb.UserSetting_AccessTokens{
|
||||
AccessTokens: &storepb.AccessTokensUserSetting{
|
||||
AccessTokens: userAccessTokens,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to upsert user setting, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveTokensAndCookies removes the jwt token from the cookies.
|
||||
func RemoveTokensAndCookies(c echo.Context) {
|
||||
cookieExp := time.Now().Add(-1 * time.Hour)
|
||||
setTokenCookie(c, auth.AccessTokenCookieName, "", cookieExp)
|
||||
}
|
||||
|
||||
// setTokenCookie sets the token to the cookie.
|
||||
func setTokenCookie(c echo.Context, name, token string, expiration time.Time) {
|
||||
cookie := new(http.Cookie)
|
||||
cookie.Name = name
|
||||
cookie.Value = token
|
||||
cookie.Expires = expiration
|
||||
cookie.Path = "/"
|
||||
// Http-only helps mitigate the risk of client side script accessing the protected cookie.
|
||||
cookie.HttpOnly = true
|
||||
cookie.SameSite = http.SameSiteStrictMode
|
||||
c.SetCookie(cookie)
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
package v1
|
||||
|
||||
// RowStatus is the status for a row.
|
||||
type RowStatus string
|
||||
|
||||
const (
|
||||
// Normal is the status for a normal row.
|
||||
Normal RowStatus = "NORMAL"
|
||||
// Archived is the status for an archived row.
|
||||
Archived RowStatus = "ARCHIVED"
|
||||
)
|
||||
|
||||
func (s RowStatus) String() string {
|
||||
return string(s)
|
||||
}
|
133
api/v1/jwt.go
@ -1,133 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/boojack/slash/api/auth"
|
||||
"github.com/boojack/slash/internal/util"
|
||||
storepb "github.com/boojack/slash/proto/gen/store"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// The key name used to store user id in the context
|
||||
// user id is extracted from the jwt token subject field.
|
||||
userIDContextKey = "user-id"
|
||||
)
|
||||
|
||||
func extractTokenFromHeader(c echo.Context) (string, error) {
|
||||
authHeader := c.Request().Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
authHeaderParts := strings.Fields(authHeader)
|
||||
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
|
||||
return "", errors.New("Authorization header format must be Bearer {token}")
|
||||
}
|
||||
|
||||
return authHeaderParts[1], nil
|
||||
}
|
||||
|
||||
func findAccessToken(c echo.Context) string {
|
||||
// Check the HTTP request header first.
|
||||
accessToken, _ := extractTokenFromHeader(c)
|
||||
if accessToken == "" {
|
||||
// Check the cookie.
|
||||
cookie, _ := c.Cookie(auth.AccessTokenCookieName)
|
||||
if cookie != nil {
|
||||
accessToken = cookie.Value
|
||||
}
|
||||
}
|
||||
return accessToken
|
||||
}
|
||||
|
||||
// JWTMiddleware validates the access token.
|
||||
func JWTMiddleware(s *APIV1Service, next echo.HandlerFunc, secret string) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
path := c.Request().URL.Path
|
||||
method := c.Request().Method
|
||||
|
||||
// Pass auth and profile endpoints.
|
||||
if util.HasPrefixes(path, "/api/v1/auth", "/api/v1/workspace/profile") {
|
||||
return next(c)
|
||||
}
|
||||
|
||||
accessToken := findAccessToken(c)
|
||||
if accessToken == "" {
|
||||
// When the request is not authenticated, we allow the user to access the shortcut endpoints for those public shortcuts.
|
||||
if util.HasPrefixes(path, "/s/", "/api/v1/user/") && method == http.MethodGet {
|
||||
return next(c)
|
||||
}
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token")
|
||||
}
|
||||
|
||||
userID, err := getUserIDFromAccessToken(accessToken, secret)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Invalid or expired access token")
|
||||
}
|
||||
|
||||
accessTokens, err := s.Store.GetUserAccessTokens(ctx, userID)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get user access tokens.").WithInternal(err)
|
||||
}
|
||||
if !validateAccessToken(accessToken, accessTokens) {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Invalid access token.")
|
||||
}
|
||||
|
||||
// Even if there is no error, we still need to make sure the user still exists.
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Server error to find user ID: %d", userID)).SetInternal(err)
|
||||
}
|
||||
if user == nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("Failed to find user ID: %d", userID))
|
||||
}
|
||||
|
||||
// Stores userID into context.
|
||||
c.Set(userIDContextKey, userID)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
|
||||
func getUserIDFromAccessToken(accessToken, secret string) (int32, error) {
|
||||
claims := &auth.ClaimsMessage{}
|
||||
_, err := jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
|
||||
if t.Method.Alg() != jwt.SigningMethodHS256.Name {
|
||||
return nil, errors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
|
||||
}
|
||||
if kid, ok := t.Header["kid"].(string); ok {
|
||||
if kid == "v1" {
|
||||
return []byte(secret), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
|
||||
})
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, "Invalid or expired access token")
|
||||
}
|
||||
// We either have a valid access token or we will attempt to generate new access token.
|
||||
userID, err := util.ConvertStringToInt32(claims.Subject)
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, "Malformed ID in the token")
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func validateAccessToken(accessTokenString string, userAccessTokens []*storepb.AccessTokensUserSetting_AccessToken) bool {
|
||||
for _, userAccessToken := range userAccessTokens {
|
||||
if accessTokenString == userAccessToken.AccessToken {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
@ -1,118 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
storepb "github.com/boojack/slash/proto/gen/store"
|
||||
"github.com/boojack/slash/server/metric"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
func (s *APIV1Service) registerRedirectorRoutes(g *echo.Group) {
|
||||
g.GET("/*", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
if len(c.ParamValues()) == 0 {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "invalid shortcut name")
|
||||
}
|
||||
|
||||
shortcutName := c.ParamValues()[0]
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
Name: &shortcutName,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return c.Redirect(http.StatusSeeOther, fmt.Sprintf("/404?shortcut=%s", shortcutName))
|
||||
}
|
||||
if shortcut.Visibility != storepb.Visibility_PUBLIC {
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
|
||||
}
|
||||
if shortcut.Visibility == storepb.Visibility_PRIVATE && shortcut.CreatorId != userID {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.createShortcutViewActivity(c, shortcut); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to create activity, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
metric.Enqueue("shortcut redirect")
|
||||
return redirectToShortcut(c, shortcut)
|
||||
})
|
||||
}
|
||||
|
||||
func redirectToShortcut(c echo.Context, shortcut *storepb.Shortcut) error {
|
||||
isValidURL := isValidURLString(shortcut.Link)
|
||||
if shortcut.OgMetadata == nil || (shortcut.OgMetadata.Title == "" && shortcut.OgMetadata.Description == "" && shortcut.OgMetadata.Image == "") {
|
||||
if isValidURL {
|
||||
return c.Redirect(http.StatusSeeOther, shortcut.Link)
|
||||
}
|
||||
return c.String(http.StatusOK, shortcut.Link)
|
||||
}
|
||||
|
||||
htmlTemplate := `<html><head>%s</head><body>%s</body></html>`
|
||||
metadataList := []string{
|
||||
fmt.Sprintf(`<title>%s</title>`, shortcut.OgMetadata.Title),
|
||||
fmt.Sprintf(`<meta name="description" content="%s" />`, shortcut.OgMetadata.Description),
|
||||
fmt.Sprintf(`<meta property="og:title" content="%s" />`, shortcut.OgMetadata.Title),
|
||||
fmt.Sprintf(`<meta property="og:description" content="%s" />`, shortcut.OgMetadata.Description),
|
||||
fmt.Sprintf(`<meta property="og:image" content="%s" />`, shortcut.OgMetadata.Image),
|
||||
`<meta property="og:type" content="website" />`,
|
||||
// Twitter related metadata.
|
||||
fmt.Sprintf(`<meta name="twitter:title" content="%s" />`, shortcut.OgMetadata.Title),
|
||||
fmt.Sprintf(`<meta name="twitter:description" content="%s" />`, shortcut.OgMetadata.Description),
|
||||
fmt.Sprintf(`<meta name="twitter:image" content="%s" />`, shortcut.OgMetadata.Image),
|
||||
`<meta name="twitter:card" content="summary_large_image" />`,
|
||||
}
|
||||
if isValidURL {
|
||||
metadataList = append(metadataList, fmt.Sprintf(`<meta property="og:url" content="%s" />`, shortcut.Link))
|
||||
}
|
||||
body := ""
|
||||
if isValidURL {
|
||||
body = fmt.Sprintf(`<script>window.location.href = "%s";</script>`, shortcut.Link)
|
||||
} else {
|
||||
body = html.EscapeString(shortcut.Link)
|
||||
}
|
||||
htmlString := fmt.Sprintf(htmlTemplate, strings.Join(metadataList, ""), body)
|
||||
return c.HTML(http.StatusOK, htmlString)
|
||||
}
|
||||
|
||||
func (s *APIV1Service) createShortcutViewActivity(c echo.Context, shortcut *storepb.Shortcut) error {
|
||||
payload := &ActivityShorcutViewPayload{
|
||||
ShortcutID: shortcut.Id,
|
||||
IP: c.RealIP(),
|
||||
Referer: c.Request().Referer(),
|
||||
UserAgent: c.Request().UserAgent(),
|
||||
}
|
||||
payloadStr, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to marshal activity payload")
|
||||
}
|
||||
activity := &store.Activity{
|
||||
CreatorID: BotID,
|
||||
Type: store.ActivityShortcutView,
|
||||
Level: store.ActivityInfo,
|
||||
Payload: string(payloadStr),
|
||||
}
|
||||
_, err = s.Store.CreateActivity(c.Request().Context(), activity)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to create activity")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isValidURLString(s string) bool {
|
||||
_, err := url.ParseRequestURI(s)
|
||||
return err == nil
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
package v1
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsValidURLString(t *testing.T) {
|
||||
tests := []struct {
|
||||
link string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
link: "https://google.com",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
link: "http://google.com",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
link: "google.com",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
link: "mailto:email@example.com",
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
if isValidURLString(test.link) != test.expected {
|
||||
t.Errorf("isValidURLString(%s) = %v, expected %v", test.link, !test.expected, test.expected)
|
||||
}
|
||||
}
|
||||
}
|
@ -1,383 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/boojack/slash/internal/util"
|
||||
storepb "github.com/boojack/slash/proto/gen/store"
|
||||
"github.com/boojack/slash/server/metric"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
// Visibility is the type of a shortcut visibility.
|
||||
type Visibility string
|
||||
|
||||
const (
|
||||
// VisibilityPublic is the PUBLIC visibility.
|
||||
VisibilityPublic Visibility = "PUBLIC"
|
||||
// VisibilityWorkspace is the WORKSPACE visibility.
|
||||
VisibilityWorkspace Visibility = "WORKSPACE"
|
||||
// VisibilityPrivate is the PRIVATE visibility.
|
||||
VisibilityPrivate Visibility = "PRIVATE"
|
||||
)
|
||||
|
||||
func (v Visibility) String() string {
|
||||
return string(v)
|
||||
}
|
||||
|
||||
type OpenGraphMetadata struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Image string `json:"image"`
|
||||
}
|
||||
|
||||
type Shortcut struct {
|
||||
ID int32 `json:"id"`
|
||||
|
||||
// Standard fields
|
||||
CreatorID int32 `json:"creatorId"`
|
||||
Creator *User `json:"creator"`
|
||||
CreatedTs int64 `json:"createdTs"`
|
||||
UpdatedTs int64 `json:"updatedTs"`
|
||||
RowStatus RowStatus `json:"rowStatus"`
|
||||
|
||||
// Domain specific fields
|
||||
Name string `json:"name"`
|
||||
Link string `json:"link"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Visibility Visibility `json:"visibility"`
|
||||
Tags []string `json:"tags"`
|
||||
View int `json:"view"`
|
||||
OpenGraphMetadata *OpenGraphMetadata `json:"openGraphMetadata"`
|
||||
}
|
||||
|
||||
type CreateShortcutRequest struct {
|
||||
Name string `json:"name"`
|
||||
Link string `json:"link"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Visibility Visibility `json:"visibility"`
|
||||
Tags []string `json:"tags"`
|
||||
OpenGraphMetadata *OpenGraphMetadata `json:"openGraphMetadata"`
|
||||
}
|
||||
|
||||
type PatchShortcutRequest struct {
|
||||
RowStatus *RowStatus `json:"rowStatus"`
|
||||
Name *string `json:"name"`
|
||||
Link *string `json:"link"`
|
||||
Title *string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Visibility *Visibility `json:"visibility"`
|
||||
Tags []string `json:"tags"`
|
||||
OpenGraphMetadata *OpenGraphMetadata `json:"openGraphMetadata"`
|
||||
}
|
||||
|
||||
func (s *APIV1Service) registerShortcutRoutes(g *echo.Group) {
|
||||
g.POST("/shortcut", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
create := &CreateShortcutRequest{}
|
||||
if err := json.NewDecoder(c.Request().Body).Decode(create); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("malformatted post shortcut request, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcut := &storepb.Shortcut{
|
||||
CreatorId: userID,
|
||||
Name: create.Name,
|
||||
Link: create.Link,
|
||||
Title: create.Title,
|
||||
Description: create.Description,
|
||||
Visibility: convertVisibilityToStorepb(create.Visibility),
|
||||
Tags: create.Tags,
|
||||
OgMetadata: &storepb.OpenGraphMetadata{},
|
||||
}
|
||||
if create.OpenGraphMetadata != nil {
|
||||
shortcut.OgMetadata = &storepb.OpenGraphMetadata{
|
||||
Title: create.OpenGraphMetadata.Title,
|
||||
Description: create.OpenGraphMetadata.Description,
|
||||
Image: create.OpenGraphMetadata.Image,
|
||||
}
|
||||
}
|
||||
shortcut, err := s.Store.CreateShortcut(ctx, shortcut)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to create shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
if err := s.createShortcutCreateActivity(ctx, shortcut); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to create shortcut activity, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcutMessage, err := s.composeShortcut(ctx, convertShortcutFromStorepb(shortcut))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to compose shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
metric.Enqueue("shortcut create")
|
||||
return c.JSON(http.StatusOK, shortcutMessage)
|
||||
})
|
||||
|
||||
g.PATCH("/shortcut/:shortcutId", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
shortcutID, err := util.ConvertStringToInt32(c.Param("shortcutId"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut ID is not a number: %s", c.Param("shortcutId"))).SetInternal(err)
|
||||
}
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
ID: &shortcutID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("not found shortcut with id: %d", shortcutID))
|
||||
}
|
||||
if shortcut.CreatorId != userID && currentUser.Role != store.RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "unauthorized to update shortcut")
|
||||
}
|
||||
|
||||
patch := &PatchShortcutRequest{}
|
||||
if err := json.NewDecoder(c.Request().Body).Decode(patch); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("failed to decode patch shortcut request, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcutUpdate := &store.UpdateShortcut{
|
||||
ID: shortcutID,
|
||||
Name: patch.Name,
|
||||
Link: patch.Link,
|
||||
Title: patch.Title,
|
||||
Description: patch.Description,
|
||||
}
|
||||
if patch.RowStatus != nil {
|
||||
shortcutUpdate.RowStatus = (*store.RowStatus)(patch.RowStatus)
|
||||
}
|
||||
if patch.Visibility != nil {
|
||||
shortcutUpdate.Visibility = (*store.Visibility)(patch.Visibility)
|
||||
}
|
||||
if patch.Tags != nil {
|
||||
tag := strings.Join(patch.Tags, " ")
|
||||
shortcutUpdate.Tag = &tag
|
||||
}
|
||||
if patch.OpenGraphMetadata != nil {
|
||||
shortcutUpdate.OpenGraphMetadata = &store.OpenGraphMetadata{
|
||||
Title: patch.OpenGraphMetadata.Title,
|
||||
Description: patch.OpenGraphMetadata.Description,
|
||||
Image: patch.OpenGraphMetadata.Image,
|
||||
}
|
||||
}
|
||||
shortcut, err = s.Store.UpdateShortcut(ctx, shortcutUpdate)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to patch shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcutMessage, err := s.composeShortcut(ctx, convertShortcutFromStorepb(shortcut))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to compose shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, shortcutMessage)
|
||||
})
|
||||
|
||||
g.GET("/shortcut", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
|
||||
find := &store.FindShortcut{}
|
||||
if tag := c.QueryParam("tag"); tag != "" {
|
||||
find.Tag = &tag
|
||||
}
|
||||
|
||||
list := []*storepb.Shortcut{}
|
||||
find.VisibilityList = []store.Visibility{store.VisibilityWorkspace, store.VisibilityPublic}
|
||||
visibleShortcutList, err := s.Store.ListShortcuts(ctx, find)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch shortcut list, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
list = append(list, visibleShortcutList...)
|
||||
|
||||
find.VisibilityList = []store.Visibility{store.VisibilityPrivate}
|
||||
find.CreatorID = &userID
|
||||
privateShortcutList, err := s.Store.ListShortcuts(ctx, find)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch private shortcut list, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
list = append(list, privateShortcutList...)
|
||||
|
||||
shortcutMessageList := []*Shortcut{}
|
||||
for _, shortcut := range list {
|
||||
shortcutMessage, err := s.composeShortcut(ctx, convertShortcutFromStorepb(shortcut))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to compose shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
shortcutMessageList = append(shortcutMessageList, shortcutMessage)
|
||||
}
|
||||
return c.JSON(http.StatusOK, shortcutMessageList)
|
||||
})
|
||||
|
||||
g.GET("/shortcut/:id", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
shortcutID, err := util.ConvertStringToInt32(c.Param("id"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("id"))).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
ID: &shortcutID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch shortcut by id, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("not found shortcut with id: %d", shortcutID))
|
||||
}
|
||||
|
||||
shortcutMessage, err := s.composeShortcut(ctx, convertShortcutFromStorepb(shortcut))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to compose shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, shortcutMessage)
|
||||
})
|
||||
|
||||
g.DELETE("/shortcut/:id", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
shortcutID, err := util.ConvertStringToInt32(c.Param("id"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("shortcut id is not a number: %s", c.Param("id"))).SetInternal(err)
|
||||
}
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
ID: &shortcutID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch shortcut by id, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("not found shortcut with id: %d", shortcutID))
|
||||
}
|
||||
if shortcut.CreatorId != userID && currentUser.Role != store.RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "Unauthorized to delete shortcut")
|
||||
}
|
||||
|
||||
err = s.Store.DeleteShortcut(ctx, &store.DeleteShortcut{ID: shortcutID})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to delete shortcut, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, true)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *APIV1Service) composeShortcut(ctx context.Context, shortcut *Shortcut) (*Shortcut, error) {
|
||||
if shortcut == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &shortcut.CreatorID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Failed to get creator")
|
||||
}
|
||||
if user == nil {
|
||||
return nil, errors.New("Creator not found")
|
||||
}
|
||||
shortcut.Creator = convertUserFromStore(user)
|
||||
|
||||
activityList, err := s.Store.ListActivities(ctx, &store.FindActivity{
|
||||
Type: store.ActivityShortcutView,
|
||||
Level: store.ActivityInfo,
|
||||
Where: []string{fmt.Sprintf("json_extract(payload, '$.shortcutId') = %d", shortcut.ID)},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Failed to list activities")
|
||||
}
|
||||
shortcut.View = len(activityList)
|
||||
|
||||
return shortcut, nil
|
||||
}
|
||||
|
||||
func convertShortcutFromStorepb(shortcut *storepb.Shortcut) *Shortcut {
|
||||
return &Shortcut{
|
||||
ID: shortcut.Id,
|
||||
CreatedTs: shortcut.CreatedTs,
|
||||
UpdatedTs: shortcut.UpdatedTs,
|
||||
CreatorID: shortcut.CreatorId,
|
||||
RowStatus: RowStatus(shortcut.RowStatus.String()),
|
||||
Name: shortcut.Name,
|
||||
Link: shortcut.Link,
|
||||
Title: shortcut.Title,
|
||||
Description: shortcut.Description,
|
||||
Visibility: Visibility(shortcut.Visibility.String()),
|
||||
Tags: shortcut.Tags,
|
||||
OpenGraphMetadata: &OpenGraphMetadata{
|
||||
Title: shortcut.OgMetadata.Title,
|
||||
Description: shortcut.OgMetadata.Description,
|
||||
Image: shortcut.OgMetadata.Image,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func convertVisibilityToStorepb(visibility Visibility) storepb.Visibility {
|
||||
switch visibility {
|
||||
case VisibilityPublic:
|
||||
return storepb.Visibility_PUBLIC
|
||||
case VisibilityWorkspace:
|
||||
return storepb.Visibility_WORKSPACE
|
||||
case VisibilityPrivate:
|
||||
return storepb.Visibility_PRIVATE
|
||||
default:
|
||||
return storepb.Visibility_PUBLIC
|
||||
}
|
||||
}
|
||||
|
||||
func (s *APIV1Service) createShortcutCreateActivity(ctx context.Context, shortcut *storepb.Shortcut) error {
|
||||
payload := &ActivityShorcutCreatePayload{
|
||||
ShortcutID: shortcut.Id,
|
||||
}
|
||||
payloadStr, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to marshal activity payload")
|
||||
}
|
||||
activity := &store.Activity{
|
||||
CreatorID: shortcut.CreatorId,
|
||||
Type: store.ActivityShortcutCreate,
|
||||
Level: store.ActivityInfo,
|
||||
Payload: string(payloadStr),
|
||||
}
|
||||
_, err = s.Store.CreateActivity(ctx, activity)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to create activity")
|
||||
}
|
||||
return nil
|
||||
}
|
340
api/v1/user.go
@ -1,340 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/boojack/slash/internal/util"
|
||||
"github.com/boojack/slash/server/metric"
|
||||
"github.com/boojack/slash/server/service/license"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// BotID is the id of bot.
|
||||
BotID = 0
|
||||
)
|
||||
|
||||
// Role is the type of a role.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
// RoleAdmin is the ADMIN role.
|
||||
RoleAdmin Role = "ADMIN"
|
||||
// RoleUser is the USER role.
|
||||
RoleUser Role = "USER"
|
||||
)
|
||||
|
||||
func (r Role) String() string {
|
||||
switch r {
|
||||
case RoleAdmin:
|
||||
return "ADMIN"
|
||||
case RoleUser:
|
||||
return "USER"
|
||||
}
|
||||
return "USER"
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int32 `json:"id"`
|
||||
|
||||
// Standard fields
|
||||
CreatedTs int64 `json:"createdTs"`
|
||||
UpdatedTs int64 `json:"updatedTs"`
|
||||
RowStatus RowStatus `json:"rowStatus"`
|
||||
|
||||
// Domain specific fields
|
||||
Email string `json:"email"`
|
||||
Nickname string `json:"nickname"`
|
||||
Role Role `json:"role"`
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Email string `json:"email"`
|
||||
Nickname string `json:"nickname"`
|
||||
Password string `json:"password"`
|
||||
Role Role `json:"role"`
|
||||
}
|
||||
|
||||
func (create CreateUserRequest) Validate() error {
|
||||
if create.Email != "" && !validateEmail(create.Email) {
|
||||
return errors.New("invalid email format")
|
||||
}
|
||||
if create.Nickname != "" && len(create.Nickname) < 3 {
|
||||
return errors.New("nickname is too short, minimum length is 3")
|
||||
}
|
||||
if len(create.Password) < 3 {
|
||||
return errors.New("password is too short, minimum length is 3")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type PatchUserRequest struct {
|
||||
RowStatus *RowStatus `json:"rowStatus"`
|
||||
Email *string `json:"email"`
|
||||
Nickname *string `json:"nickname"`
|
||||
Password *string `json:"password"`
|
||||
Role *Role `json:"role"`
|
||||
}
|
||||
|
||||
func (s *APIV1Service) registerUserRoutes(g *echo.Group) {
|
||||
g.POST("/user", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
|
||||
}
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user by id").SetInternal(err)
|
||||
}
|
||||
if currentUser == nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Missing auth session")
|
||||
}
|
||||
if currentUser.Role != store.RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized to create user")
|
||||
}
|
||||
|
||||
if !s.LicenseService.IsFeatureEnabled(license.FeatureTypeUnlimitedAccounts) {
|
||||
userList, err := s.Store.ListUsers(ctx, &store.FindUser{})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to list users").SetInternal(err)
|
||||
}
|
||||
if len(userList) >= 5 {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Maximum number of users reached")
|
||||
}
|
||||
}
|
||||
|
||||
userCreate := &CreateUserRequest{}
|
||||
if err := json.NewDecoder(c.Request().Body).Decode(userCreate); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post user request").SetInternal(err)
|
||||
}
|
||||
if err := userCreate.Validate(); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "Invalid user create format").SetInternal(err)
|
||||
}
|
||||
|
||||
passwordHash, err := bcrypt.GenerateFromPassword([]byte(userCreate.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
|
||||
}
|
||||
|
||||
user, err := s.Store.CreateUser(ctx, &store.User{
|
||||
Role: store.Role(userCreate.Role),
|
||||
Email: userCreate.Email,
|
||||
Nickname: userCreate.Nickname,
|
||||
PasswordHash: string(passwordHash),
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create user").SetInternal(err)
|
||||
}
|
||||
|
||||
userMessage := convertUserFromStore(user)
|
||||
metric.Enqueue("user create")
|
||||
return c.JSON(http.StatusOK, userMessage)
|
||||
})
|
||||
|
||||
g.GET("/user", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
list, err := s.Store.ListUsers(ctx, &store.FindUser{})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to list users, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
userList := []*User{}
|
||||
for _, user := range list {
|
||||
userList = append(userList, convertUserFromStore(user))
|
||||
}
|
||||
return c.JSON(http.StatusOK, userList)
|
||||
})
|
||||
|
||||
// GET /api/user/me is used to check if the user is logged in.
|
||||
g.GET("/user/me", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing auth session")
|
||||
}
|
||||
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, convertUserFromStore(user))
|
||||
})
|
||||
|
||||
g.GET("/user/:id", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
userID, err := util.ConvertStringToInt32(c.Param("id"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err)
|
||||
}
|
||||
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
userMessage := convertUserFromStore(user)
|
||||
userID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
userMessage.Email = ""
|
||||
}
|
||||
return c.JSON(http.StatusOK, userMessage)
|
||||
})
|
||||
|
||||
g.PATCH("/user/:id", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
userID, err := util.ConvertStringToInt32(c.Param("id"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err)
|
||||
}
|
||||
currentUserID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: ¤tUserID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, "failed to find current user").SetInternal(err)
|
||||
}
|
||||
if currentUser == nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
if currentUser.ID != userID && currentUser.Role != store.RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "access forbidden for current session user").SetInternal(err)
|
||||
}
|
||||
|
||||
userPatch := &PatchUserRequest{}
|
||||
if err := json.NewDecoder(c.Request().Body).Decode(userPatch); err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("failed to decode request body, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
updateUser := &store.UpdateUser{
|
||||
ID: userID,
|
||||
}
|
||||
if userPatch.Email != nil {
|
||||
if !validateEmail(*userPatch.Email) {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("invalid email format: %s", *userPatch.Email))
|
||||
}
|
||||
updateUser.Email = userPatch.Email
|
||||
}
|
||||
if userPatch.Nickname != nil {
|
||||
updateUser.Nickname = userPatch.Nickname
|
||||
}
|
||||
if userPatch.Password != nil && *userPatch.Password != "" {
|
||||
passwordHash, err := bcrypt.GenerateFromPassword([]byte(*userPatch.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to hash password, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
passwordHashStr := string(passwordHash)
|
||||
updateUser.PasswordHash = &passwordHashStr
|
||||
}
|
||||
if userPatch.RowStatus != nil {
|
||||
rowStatus := store.RowStatus(*userPatch.RowStatus)
|
||||
updateUser.RowStatus = &rowStatus
|
||||
}
|
||||
if userPatch.Role != nil {
|
||||
adminRole := store.RoleAdmin
|
||||
adminUsers, err := s.Store.ListUsers(ctx, &store.FindUser{
|
||||
Role: &adminRole,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to list admin users, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if len(adminUsers) == 1 && adminUsers[0].ID == userID && *userPatch.Role != RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, "cannot remove admin role from the last admin user")
|
||||
}
|
||||
role := store.Role(*userPatch.Role)
|
||||
updateUser.Role = &role
|
||||
}
|
||||
|
||||
user, err := s.Store.UpdateUser(ctx, updateUser)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, convertUserFromStore(user))
|
||||
})
|
||||
|
||||
g.DELETE("/user/:id", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
currentUserID, ok := c.Get(userIDContextKey).(int32)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing user in session")
|
||||
}
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: ¤tUserID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find current session user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if currentUser == nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("current session user not found with ID: %d", currentUserID)).SetInternal(err)
|
||||
}
|
||||
if currentUser.Role != store.RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "access forbidden for current session user").SetInternal(err)
|
||||
}
|
||||
|
||||
userID, err := util.ConvertStringToInt32(c.Param("id"))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user id is not a number: %s", c.Param("id"))).SetInternal(err)
|
||||
}
|
||||
user, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if user == nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user not found with ID: %d", userID)).SetInternal(err)
|
||||
}
|
||||
if user.Role == store.RoleAdmin {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("cannot delete admin user with ID: %d", userID)).SetInternal(err)
|
||||
}
|
||||
|
||||
if err := s.Store.DeleteUser(ctx, &store.DeleteUser{
|
||||
ID: userID,
|
||||
}); err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete user, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, true)
|
||||
})
|
||||
}
|
||||
|
||||
// validateEmail validates the email.
|
||||
func validateEmail(email string) bool {
|
||||
if _, err := mail.ParseAddress(email); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// convertUserFromStore converts a store user to a user.
|
||||
func convertUserFromStore(user *store.User) *User {
|
||||
return &User{
|
||||
ID: user.ID,
|
||||
CreatedTs: user.CreatedTs,
|
||||
UpdatedTs: user.UpdatedTs,
|
||||
RowStatus: RowStatus(user.RowStatus),
|
||||
Email: user.Email,
|
||||
Nickname: user.Nickname,
|
||||
Role: Role(user.Role),
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UserSettingKey string
|
||||
|
||||
const (
|
||||
// UserSettingLocaleKey is the key type for user locale.
|
||||
UserSettingLocaleKey UserSettingKey = "locale"
|
||||
)
|
||||
|
||||
// String returns the string format of UserSettingKey type.
|
||||
func (k UserSettingKey) String() string {
|
||||
return string(k)
|
||||
}
|
||||
|
||||
var (
|
||||
UserSettingLocaleValue = []string{"en", "zh"}
|
||||
)
|
||||
|
||||
type UserSetting struct {
|
||||
UserID int
|
||||
Key UserSettingKey `json:"key"`
|
||||
// Value is a JSON string with basic value.
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type UserSettingUpsert struct {
|
||||
UserID int
|
||||
Key UserSettingKey `json:"key"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (upsert UserSettingUpsert) Validate() error {
|
||||
if upsert.Key == UserSettingLocaleKey {
|
||||
localeValue := "en"
|
||||
err := json.Unmarshal([]byte(upsert.Value), &localeValue)
|
||||
if err != nil {
|
||||
return errors.New("failed to unmarshal user setting locale value")
|
||||
}
|
||||
|
||||
invalid := true
|
||||
for _, value := range UserSettingLocaleValue {
|
||||
if localeValue == value {
|
||||
invalid = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if invalid {
|
||||
return errors.New("invalid user setting locale value")
|
||||
}
|
||||
} else {
|
||||
return errors.New("invalid user setting key")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type UserSettingFind struct {
|
||||
UserID int
|
||||
|
||||
Key *UserSettingKey `json:"key"`
|
||||
}
|
41
api/v1/v1.go
@ -1,41 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"github.com/boojack/slash/server/profile"
|
||||
"github.com/boojack/slash/server/service/license"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
type APIV1Service struct {
|
||||
Profile *profile.Profile
|
||||
Store *store.Store
|
||||
LicenseService *license.LicenseService
|
||||
}
|
||||
|
||||
func NewAPIV1Service(profile *profile.Profile, store *store.Store, licenseService *license.LicenseService) *APIV1Service {
|
||||
return &APIV1Service{
|
||||
Profile: profile,
|
||||
Store: store,
|
||||
LicenseService: licenseService,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *APIV1Service) Start(apiGroup *echo.Group, secret string) {
|
||||
apiV1Group := apiGroup.Group("/api/v1")
|
||||
apiV1Group.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return JWTMiddleware(s, next, secret)
|
||||
})
|
||||
s.registerWorkspaceRoutes(apiV1Group)
|
||||
s.registerAuthRoutes(apiV1Group, secret)
|
||||
s.registerUserRoutes(apiV1Group)
|
||||
s.registerShortcutRoutes(apiV1Group)
|
||||
s.registerAnalyticsRoutes(apiV1Group)
|
||||
|
||||
redirectorGroup := apiGroup.Group("/s")
|
||||
redirectorGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return JWTMiddleware(s, next, secret)
|
||||
})
|
||||
s.registerRedirectorRoutes(redirectorGroup)
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
storepb "github.com/boojack/slash/proto/gen/store"
|
||||
"github.com/boojack/slash/server/profile"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
type WorkspaceProfile struct {
|
||||
Profile *profile.Profile `json:"profile"`
|
||||
DisallowSignUp bool `json:"disallowSignUp"`
|
||||
}
|
||||
|
||||
func (s *APIV1Service) registerWorkspaceRoutes(g *echo.Group) {
|
||||
g.GET("/workspace/profile", func(c echo.Context) error {
|
||||
ctx := c.Request().Context()
|
||||
workspaceProfile := WorkspaceProfile{
|
||||
Profile: s.Profile,
|
||||
DisallowSignUp: false,
|
||||
}
|
||||
|
||||
enableSignUpSetting, err := s.Store.GetWorkspaceSetting(ctx, &store.FindWorkspaceSetting{
|
||||
Key: storepb.WorkspaceSettingKey_WORKSAPCE_SETTING_ENABLE_SIGNUP,
|
||||
})
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to find workspace setting, err: %s", err)).SetInternal(err)
|
||||
}
|
||||
if enableSignUpSetting != nil {
|
||||
workspaceProfile.DisallowSignUp = !enableSignUpSetting.GetEnableSignup()
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, workspaceProfile)
|
||||
})
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
package v2
|
||||
|
||||
import "strings"
|
||||
|
||||
var allowedMethodsWhenUnauthorized = map[string]bool{
|
||||
"/slash.api.v2.WorkspaceService/GetWorkspaceProfile": true,
|
||||
"/slash.api.v2.WorkspaceService/GetWorkspaceSetting": true,
|
||||
"/slash.api.v2.ShortcutService/GetShortcut": true,
|
||||
"/slash.api.v2.CollectionService/GetCollectionByName": true,
|
||||
}
|
||||
|
||||
// isUnauthorizeAllowedMethod returns true if the method is allowed to be called when the user is not authorized.
|
||||
func isUnauthorizeAllowedMethod(methodName string) bool {
|
||||
if strings.HasPrefix(methodName, "/grpc.reflection") {
|
||||
return true
|
||||
}
|
||||
return allowedMethodsWhenUnauthorized[methodName]
|
||||
}
|
||||
|
||||
var allowedMethodsOnlyForAdmin = map[string]bool{
|
||||
"/slash.api.v2.UserService/CreateUser": true,
|
||||
"/slash.api.v2.UserService/DeleteUser": true,
|
||||
"/slash.api.v2.WorkspaceService/UpdateWorkspaceSetting": true,
|
||||
}
|
||||
|
||||
// isOnlyForAdminAllowedMethod returns true if the method is allowed to be called only by admin.
|
||||
func isOnlyForAdminAllowedMethod(methodName string) bool {
|
||||
return allowedMethodsOnlyForAdmin[methodName]
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
package v2
|
||||
|
||||
import (
|
||||
apiv2pb "github.com/boojack/slash/proto/gen/api/v2"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
func convertRowStatusFromStore(rowStatus store.RowStatus) apiv2pb.RowStatus {
|
||||
switch rowStatus {
|
||||
case store.Normal:
|
||||
return apiv2pb.RowStatus_NORMAL
|
||||
case store.Archived:
|
||||
return apiv2pb.RowStatus_ARCHIVED
|
||||
default:
|
||||
return apiv2pb.RowStatus_ROW_STATUS_UNSPECIFIED
|
||||
}
|
||||
}
|
@ -1,269 +0,0 @@
|
||||
package v2
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
apiv2pb "github.com/boojack/slash/proto/gen/api/v2"
|
||||
storepb "github.com/boojack/slash/proto/gen/store"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
func (s *APIV2Service) ListShortcuts(ctx context.Context, _ *apiv2pb.ListShortcutsRequest) (*apiv2pb.ListShortcutsResponse, error) {
|
||||
userID := ctx.Value(userIDContextKey).(int32)
|
||||
find := &store.FindShortcut{}
|
||||
find.VisibilityList = []store.Visibility{store.VisibilityWorkspace, store.VisibilityPublic}
|
||||
visibleShortcutList, err := s.Store.ListShortcuts(ctx, find)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to fetch visible shortcut list, err: %v", err)
|
||||
}
|
||||
|
||||
find.VisibilityList = []store.Visibility{store.VisibilityPrivate}
|
||||
find.CreatorID = &userID
|
||||
shortcutList, err := s.Store.ListShortcuts(ctx, find)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to fetch private shortcut list, err: %v", err)
|
||||
}
|
||||
|
||||
shortcutList = append(shortcutList, visibleShortcutList...)
|
||||
shortcuts := []*apiv2pb.Shortcut{}
|
||||
for _, shortcut := range shortcutList {
|
||||
composedShortcut, err := s.convertShortcutFromStorepb(ctx, shortcut)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to convert shortcut, err: %v", err)
|
||||
}
|
||||
shortcuts = append(shortcuts, composedShortcut)
|
||||
}
|
||||
|
||||
response := &apiv2pb.ListShortcutsResponse{
|
||||
Shortcuts: shortcuts,
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *APIV2Service) GetShortcut(ctx context.Context, request *apiv2pb.GetShortcutRequest) (*apiv2pb.GetShortcutResponse, error) {
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
ID: &request.Id,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to get shortcut by name: %v", err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "shortcut not found")
|
||||
}
|
||||
|
||||
userID, ok := ctx.Value(userIDContextKey).(int32)
|
||||
if ok {
|
||||
if shortcut.Visibility == storepb.Visibility_PRIVATE && shortcut.CreatorId != userID {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "Permission denied")
|
||||
}
|
||||
} else {
|
||||
if shortcut.Visibility != storepb.Visibility_PUBLIC {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "Permission denied")
|
||||
}
|
||||
}
|
||||
|
||||
composedShortcut, err := s.convertShortcutFromStorepb(ctx, shortcut)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to convert shortcut, err: %v", err)
|
||||
}
|
||||
response := &apiv2pb.GetShortcutResponse{
|
||||
Shortcut: composedShortcut,
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *APIV2Service) CreateShortcut(ctx context.Context, request *apiv2pb.CreateShortcutRequest) (*apiv2pb.CreateShortcutResponse, error) {
|
||||
userID := ctx.Value(userIDContextKey).(int32)
|
||||
shortcut := &storepb.Shortcut{
|
||||
CreatorId: userID,
|
||||
Name: request.Shortcut.Name,
|
||||
Link: request.Shortcut.Link,
|
||||
Title: request.Shortcut.Title,
|
||||
Tags: request.Shortcut.Tags,
|
||||
Description: request.Shortcut.Description,
|
||||
Visibility: storepb.Visibility(request.Shortcut.Visibility),
|
||||
OgMetadata: &storepb.OpenGraphMetadata{},
|
||||
}
|
||||
if request.Shortcut.OgMetadata != nil {
|
||||
shortcut.OgMetadata = &storepb.OpenGraphMetadata{
|
||||
Title: request.Shortcut.OgMetadata.Title,
|
||||
Description: request.Shortcut.OgMetadata.Description,
|
||||
Image: request.Shortcut.OgMetadata.Image,
|
||||
}
|
||||
}
|
||||
shortcut, err := s.Store.CreateShortcut(ctx, shortcut)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to create shortcut, err: %v", err)
|
||||
}
|
||||
if err := s.createShortcutCreateActivity(ctx, shortcut); err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to create activity, err: %v", err)
|
||||
}
|
||||
|
||||
composedShortcut, err := s.convertShortcutFromStorepb(ctx, shortcut)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to convert shortcut, err: %v", err)
|
||||
}
|
||||
response := &apiv2pb.CreateShortcutResponse{
|
||||
Shortcut: composedShortcut,
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *APIV2Service) UpdateShortcut(ctx context.Context, request *apiv2pb.UpdateShortcutRequest) (*apiv2pb.UpdateShortcutResponse, error) {
|
||||
if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "updateMask is required")
|
||||
}
|
||||
|
||||
userID := ctx.Value(userIDContextKey).(int32)
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to get current user, err: %v", err)
|
||||
}
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
ID: &request.Shortcut.Id,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to get shortcut by name: %v", err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "shortcut not found")
|
||||
}
|
||||
if shortcut.CreatorId != userID && currentUser.Role != store.RoleAdmin {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "Permission denied")
|
||||
}
|
||||
|
||||
update := &store.UpdateShortcut{}
|
||||
for _, path := range request.UpdateMask.Paths {
|
||||
switch path {
|
||||
case "link":
|
||||
update.Link = &request.Shortcut.Link
|
||||
case "title":
|
||||
update.Title = &request.Shortcut.Title
|
||||
case "tags":
|
||||
tag := strings.Join(request.Shortcut.Tags, " ")
|
||||
update.Tag = &tag
|
||||
case "description":
|
||||
update.Description = &request.Shortcut.Description
|
||||
case "visibility":
|
||||
visibility := store.Visibility(request.Shortcut.Visibility.String())
|
||||
update.Visibility = &visibility
|
||||
case "og_metadata":
|
||||
if request.Shortcut.OgMetadata != nil {
|
||||
update.OpenGraphMetadata = &store.OpenGraphMetadata{
|
||||
Title: request.Shortcut.OgMetadata.Title,
|
||||
Description: request.Shortcut.OgMetadata.Description,
|
||||
Image: request.Shortcut.OgMetadata.Image,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
shortcut, err = s.Store.UpdateShortcut(ctx, update)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to update shortcut, err: %v", err)
|
||||
}
|
||||
|
||||
composedShortcut, err := s.convertShortcutFromStorepb(ctx, shortcut)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to convert shortcut, err: %v", err)
|
||||
}
|
||||
response := &apiv2pb.UpdateShortcutResponse{
|
||||
Shortcut: composedShortcut,
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *APIV2Service) DeleteShortcut(ctx context.Context, request *apiv2pb.DeleteShortcutRequest) (*apiv2pb.DeleteShortcutResponse, error) {
|
||||
userID := ctx.Value(userIDContextKey).(int32)
|
||||
currentUser, err := s.Store.GetUser(ctx, &store.FindUser{
|
||||
ID: &userID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to get current user, err: %v", err)
|
||||
}
|
||||
shortcut, err := s.Store.GetShortcut(ctx, &store.FindShortcut{
|
||||
ID: &request.Id,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to get shortcut by name: %v", err)
|
||||
}
|
||||
if shortcut == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "shortcut not found")
|
||||
}
|
||||
if shortcut.CreatorId != userID && currentUser.Role != store.RoleAdmin {
|
||||
return nil, status.Errorf(codes.PermissionDenied, "Permission denied")
|
||||
}
|
||||
|
||||
err = s.Store.DeleteShortcut(ctx, &store.DeleteShortcut{
|
||||
ID: shortcut.Id,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to delete shortcut, err: %v", err)
|
||||
}
|
||||
response := &apiv2pb.DeleteShortcutResponse{}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *APIV2Service) createShortcutCreateActivity(ctx context.Context, shortcut *storepb.Shortcut) error {
|
||||
payload := &storepb.ActivityShorcutCreatePayload{
|
||||
ShortcutId: shortcut.Id,
|
||||
}
|
||||
payloadStr, err := protojson.Marshal(payload)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to marshal activity payload")
|
||||
}
|
||||
activity := &store.Activity{
|
||||
CreatorID: shortcut.CreatorId,
|
||||
Type: store.ActivityShortcutCreate,
|
||||
Level: store.ActivityInfo,
|
||||
Payload: string(payloadStr),
|
||||
}
|
||||
_, err = s.Store.CreateActivity(ctx, activity)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to create activity")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *APIV2Service) convertShortcutFromStorepb(ctx context.Context, shortcut *storepb.Shortcut) (*apiv2pb.Shortcut, error) {
|
||||
composedShortcut := &apiv2pb.Shortcut{
|
||||
Id: shortcut.Id,
|
||||
CreatorId: shortcut.CreatorId,
|
||||
CreatedTime: timestamppb.New(time.Unix(shortcut.CreatedTs, 0)),
|
||||
UpdatedTime: timestamppb.New(time.Unix(shortcut.UpdatedTs, 0)),
|
||||
RowStatus: apiv2pb.RowStatus(shortcut.RowStatus),
|
||||
Name: shortcut.Name,
|
||||
Link: shortcut.Link,
|
||||
Title: shortcut.Title,
|
||||
Tags: shortcut.Tags,
|
||||
Description: shortcut.Description,
|
||||
Visibility: apiv2pb.Visibility(shortcut.Visibility),
|
||||
OgMetadata: &apiv2pb.OpenGraphMetadata{
|
||||
Title: shortcut.OgMetadata.Title,
|
||||
Description: shortcut.OgMetadata.Description,
|
||||
Image: shortcut.OgMetadata.Image,
|
||||
},
|
||||
}
|
||||
|
||||
activityList, err := s.Store.ListActivities(ctx, &store.FindActivity{
|
||||
Type: store.ActivityShortcutView,
|
||||
Level: store.ActivityInfo,
|
||||
Where: []string{fmt.Sprintf("json_extract(payload, '$.shortcutId') = %d", composedShortcut.Id)},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Failed to list activities")
|
||||
}
|
||||
composedShortcut.ViewCount = int32(len(activityList))
|
||||
|
||||
return composedShortcut, nil
|
||||
}
|
113
api/v2/v2.go
@ -1,113 +0,0 @@
|
||||
package v2
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
|
||||
"github.com/improbable-eng/grpc-web/go/grpcweb"
|
||||
"github.com/labstack/echo/v4"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
apiv2pb "github.com/boojack/slash/proto/gen/api/v2"
|
||||
"github.com/boojack/slash/server/profile"
|
||||
"github.com/boojack/slash/server/service/license"
|
||||
"github.com/boojack/slash/store"
|
||||
)
|
||||
|
||||
type APIV2Service struct {
|
||||
apiv2pb.UnimplementedWorkspaceServiceServer
|
||||
apiv2pb.UnimplementedSubscriptionServiceServer
|
||||
apiv2pb.UnimplementedUserServiceServer
|
||||
apiv2pb.UnimplementedUserSettingServiceServer
|
||||
apiv2pb.UnimplementedShortcutServiceServer
|
||||
apiv2pb.UnimplementedCollectionServiceServer
|
||||
|
||||
Secret string
|
||||
Profile *profile.Profile
|
||||
Store *store.Store
|
||||
LicenseService *license.LicenseService
|
||||
|
||||
grpcServer *grpc.Server
|
||||
grpcServerPort int
|
||||
}
|
||||
|
||||
func NewAPIV2Service(secret string, profile *profile.Profile, store *store.Store, licenseService *license.LicenseService, grpcServerPort int) *APIV2Service {
|
||||
authProvider := NewGRPCAuthInterceptor(store, secret)
|
||||
grpcServer := grpc.NewServer(
|
||||
grpc.ChainUnaryInterceptor(
|
||||
authProvider.AuthenticationInterceptor,
|
||||
),
|
||||
)
|
||||
apiV2Service := &APIV2Service{
|
||||
Secret: secret,
|
||||
Profile: profile,
|
||||
Store: store,
|
||||
LicenseService: licenseService,
|
||||
grpcServer: grpcServer,
|
||||
grpcServerPort: grpcServerPort,
|
||||
}
|
||||
|
||||
apiv2pb.RegisterSubscriptionServiceServer(grpcServer, apiV2Service)
|
||||
apiv2pb.RegisterWorkspaceServiceServer(grpcServer, apiV2Service)
|
||||
apiv2pb.RegisterUserServiceServer(grpcServer, apiV2Service)
|
||||
apiv2pb.RegisterUserSettingServiceServer(grpcServer, apiV2Service)
|
||||
apiv2pb.RegisterShortcutServiceServer(grpcServer, apiV2Service)
|
||||
apiv2pb.RegisterCollectionServiceServer(grpcServer, apiV2Service)
|
||||
reflection.Register(grpcServer)
|
||||
|
||||
return apiV2Service
|
||||
}
|
||||
|
||||
func (s *APIV2Service) GetGRPCServer() *grpc.Server {
|
||||
return s.grpcServer
|
||||
}
|
||||
|
||||
// RegisterGateway registers the gRPC-Gateway with the given Echo instance.
|
||||
func (s *APIV2Service) RegisterGateway(ctx context.Context, e *echo.Echo) error {
|
||||
// Create a client connection to the gRPC Server we just started.
|
||||
// This is where the gRPC-Gateway proxies the requests.
|
||||
conn, err := grpc.DialContext(
|
||||
ctx,
|
||||
fmt.Sprintf(":%d", s.grpcServerPort),
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
gwMux := runtime.NewServeMux()
|
||||
if err := apiv2pb.RegisterSubscriptionServiceHandler(context.Background(), gwMux, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := apiv2pb.RegisterWorkspaceServiceHandler(context.Background(), gwMux, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := apiv2pb.RegisterUserServiceHandler(context.Background(), gwMux, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := apiv2pb.RegisterUserSettingServiceHandler(context.Background(), gwMux, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := apiv2pb.RegisterShortcutServiceHandler(context.Background(), gwMux, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := apiv2pb.RegisterCollectionServiceHandler(context.Background(), gwMux, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
e.Any("/api/v2/*", echo.WrapHandler(gwMux))
|
||||
|
||||
// GRPC web proxy.
|
||||
options := []grpcweb.Option{
|
||||
grpcweb.WithCorsForRegisteredEndpointsOnly(false),
|
||||
grpcweb.WithOriginFunc(func(origin string) bool {
|
||||
return true
|
||||
}),
|
||||
}
|
||||
wrappedGrpc := grpcweb.WrapServer(s.grpcServer, options...)
|
||||
e.Any("/slash.api.v2.*", echo.WrapHandler(wrappedGrpc))
|
||||
|
||||
return nil
|
||||
}
|
@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@ -10,15 +11,12 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"go.uber.org/zap"
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/boojack/slash/internal/log"
|
||||
"github.com/boojack/slash/server"
|
||||
"github.com/boojack/slash/server/metric"
|
||||
"github.com/boojack/slash/server/profile"
|
||||
"github.com/boojack/slash/store"
|
||||
"github.com/boojack/slash/store/db"
|
||||
"github.com/yourselfhosted/slash/server"
|
||||
"github.com/yourselfhosted/slash/server/metric"
|
||||
"github.com/yourselfhosted/slash/server/profile"
|
||||
"github.com/yourselfhosted/slash/store"
|
||||
"github.com/yourselfhosted/slash/store/db"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -30,29 +28,39 @@ var (
|
||||
mode string
|
||||
port int
|
||||
data string
|
||||
driver string
|
||||
dsn string
|
||||
enableMetric bool
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "slash",
|
||||
Short: `An open source, self-hosted bookmarks and link sharing platform.`,
|
||||
Run: func(_cmd *cobra.Command, _args []string) {
|
||||
Short: `An open source, self-hosted links shortener and sharing platform.`,
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
db := db.NewDB(serverProfile)
|
||||
if err := db.Open(ctx); err != nil {
|
||||
dbDriver, err := db.NewDBDriver(serverProfile)
|
||||
if err != nil {
|
||||
cancel()
|
||||
log.Error("failed to open database", zap.Error(err))
|
||||
slog.Error("failed to create db driver", err)
|
||||
return
|
||||
}
|
||||
if err := dbDriver.Migrate(ctx); err != nil {
|
||||
cancel()
|
||||
slog.Error("failed to migrate db", err)
|
||||
return
|
||||
}
|
||||
|
||||
storeInstance := store.New(db.DBInstance, serverProfile)
|
||||
storeInstance := store.New(dbDriver, serverProfile)
|
||||
s, err := server.NewServer(ctx, serverProfile, storeInstance)
|
||||
if err != nil {
|
||||
cancel()
|
||||
log.Error("failed to create server", zap.Error(err))
|
||||
slog.Error("failed to create server", err)
|
||||
return
|
||||
}
|
||||
|
||||
// nolint
|
||||
metric.NewMetricClient(s.Secret, *serverProfile)
|
||||
if serverProfile.Metric {
|
||||
// nolint
|
||||
metric.NewMetricClient(s.Secret, *serverProfile)
|
||||
}
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
// Trigger graceful shutdown on SIGINT or SIGTERM.
|
||||
@ -61,7 +69,7 @@ var (
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
sig := <-c
|
||||
log.Info(fmt.Sprintf("%s received.\n", sig.String()))
|
||||
slog.Info(fmt.Sprintf("%s received.\n", sig.String()))
|
||||
s.Shutdown(ctx)
|
||||
cancel()
|
||||
}()
|
||||
@ -70,7 +78,7 @@ var (
|
||||
|
||||
if err := s.Start(ctx); err != nil {
|
||||
if err != http.ErrServerClosed {
|
||||
log.Error("failed to start server", zap.Error(err))
|
||||
slog.Error("failed to start server", err)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
@ -82,7 +90,6 @@ var (
|
||||
)
|
||||
|
||||
func Execute() error {
|
||||
defer log.Sync()
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
|
||||
@ -92,6 +99,9 @@ func init() {
|
||||
rootCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "demo", `mode of server, can be "prod" or "dev" or "demo"`)
|
||||
rootCmd.PersistentFlags().IntVarP(&port, "port", "p", 8082, "port of server")
|
||||
rootCmd.PersistentFlags().StringVarP(&data, "data", "d", "", "data directory")
|
||||
rootCmd.PersistentFlags().StringVarP(&driver, "driver", "", "", "database driver")
|
||||
rootCmd.PersistentFlags().StringVarP(&dsn, "dsn", "", "", "database source name(aka. DSN)")
|
||||
rootCmd.PersistentFlags().BoolVarP(&enableMetric, "metric", "", true, "allow metric collection")
|
||||
|
||||
err := viper.BindPFlag("mode", rootCmd.PersistentFlags().Lookup("mode"))
|
||||
if err != nil {
|
||||
@ -105,9 +115,23 @@ func init() {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = viper.BindPFlag("driver", rootCmd.PersistentFlags().Lookup("driver"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = viper.BindPFlag("dsn", rootCmd.PersistentFlags().Lookup("dsn"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = viper.BindPFlag("metric", rootCmd.PersistentFlags().Lookup("metric"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
viper.SetDefault("mode", "demo")
|
||||
viper.SetDefault("port", 8082)
|
||||
viper.SetDefault("driver", "sqlite")
|
||||
viper.SetDefault("metric", true)
|
||||
viper.SetEnvPrefix("slash")
|
||||
}
|
||||
|
||||
@ -116,7 +140,7 @@ func initConfig() {
|
||||
var err error
|
||||
serverProfile, err = profile.GetProfile()
|
||||
if err != nil {
|
||||
log.Error("failed to get profile", zap.Error(err))
|
||||
slog.Error("failed to get profile", err)
|
||||
return
|
||||
}
|
||||
|
||||
@ -134,7 +158,7 @@ func printGreetings() {
|
||||
fmt.Printf("Version %s has been started on port %d\n", serverProfile.Version, serverProfile.Port)
|
||||
println("---")
|
||||
println("See more in:")
|
||||
fmt.Printf("👉GitHub: %s\n", "https://github.com/boojack/slash")
|
||||
fmt.Printf("👉GitHub: %s\n", "https://github.com/yourselfhosted/slash")
|
||||
println("---")
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 46 KiB |
BIN
docs/assets/demo.png
Normal file
After Width: | Height: | Size: 836 KiB |
@ -1,6 +1,6 @@
|
||||
# Slash Collections
|
||||
|
||||
**Slash Collections** introduces a feature to help you better organize and manage related Shortcuts within the Slash Shortcuts platform.
|
||||
**Slash Collections** introduces a feature to help you better organize and manage related Shortcuts.
|
||||
|
||||
## What is a Collection?
|
||||
|
||||
|
@ -44,7 +44,7 @@ Assume that docker compose is deployed in the `/opt/slash` directory.
|
||||
|
||||
```bash
|
||||
mkdir -p /opt/slash && cd /opt/slash
|
||||
curl -#LO https://github.com/boojack/slash/raw/main/docker-compose.yml
|
||||
curl -#LO https://github.com/yourselfhosted/slash/raw/main/docker-compose.yml
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
|
Before Width: | Height: | Size: 257 KiB After Width: | Height: | Size: 852 B |
@ -1,57 +1,54 @@
|
||||
{
|
||||
"name": "slash-extension",
|
||||
"displayName": "Slash",
|
||||
"version": "1.0.1",
|
||||
"description": "An open source, self-hosted bookmarks and link sharing platform. Save and share your links very easily.",
|
||||
"version": "1.0.8",
|
||||
"description": "An open source, self-hosted links shortener and sharing platform. Save and share your links very easily.",
|
||||
"scripts": {
|
||||
"dev": "plasmo dev",
|
||||
"build": "plasmo build",
|
||||
"package": "plasmo package",
|
||||
"lint": "eslint --ext .js,.ts,.tsx, src",
|
||||
"lint-fix": "eslint --ext .js,.ts,.tsx, src --fix",
|
||||
"type-gen": "cd ../../proto && buf generate"
|
||||
"postinstall": "cd ../../proto && buf generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.11.1",
|
||||
"@emotion/styled": "^11.11.0",
|
||||
"@mui/joy": "5.0.0-beta.14",
|
||||
"@plasmohq/storage": "^1.8.1",
|
||||
"axios": "^1.6.1",
|
||||
"classnames": "^2.3.2",
|
||||
"@emotion/react": "^11.11.4",
|
||||
"@emotion/styled": "^11.11.5",
|
||||
"@mui/joy": "5.0.0-beta.32",
|
||||
"@plasmohq/storage": "^1.10.0",
|
||||
"axios": "^1.6.8",
|
||||
"classnames": "^2.5.1",
|
||||
"lodash-es": "^4.17.21",
|
||||
"lucide-react": "^0.264.0",
|
||||
"plasmo": "^0.83.0",
|
||||
"lucide-react": "^0.312.0",
|
||||
"plasmo": "^0.85.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hot-toast": "^2.4.1",
|
||||
"zustand": "^4.4.6"
|
||||
"zustand": "^4.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@bufbuild/buf": "^1.27.2",
|
||||
"@trivago/prettier-plugin-sort-imports": "^4.2.1",
|
||||
"@types/chrome": "^0.0.241",
|
||||
"@types/lodash-es": "^4.17.11",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "^18.2.37",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@typescript-eslint/eslint-plugin": "^6.10.0",
|
||||
"@typescript-eslint/parser": "^6.10.0",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"eslint": "^8.53.0",
|
||||
"@bufbuild/buf": "^1.30.1",
|
||||
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
|
||||
"@types/chrome": "^0.0.266",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^20.12.7",
|
||||
"@types/react": "^18.2.79",
|
||||
"@types/react-dom": "^18.2.25",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^8.10.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react": "^7.34.1",
|
||||
"long": "^5.2.3",
|
||||
"postcss": "^8.4.31",
|
||||
"postcss": "^8.4.38",
|
||||
"prettier": "^2.8.8",
|
||||
"protobufjs": "^7.2.5",
|
||||
"tailwindcss": "^3.3.5",
|
||||
"typescript": "^5.2.2"
|
||||
"protobufjs": "^7.2.6",
|
||||
"tailwindcss": "^3.4.3",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"manifest": {
|
||||
"omnibox": {
|
||||
"keyword": "s/"
|
||||
},
|
||||
"permissions": [
|
||||
"activeTab",
|
||||
"storage",
|
||||
|
10477
frontend/extension/pnpm-lock.yaml
generated
@ -1,5 +1,4 @@
|
||||
import { Storage } from "@plasmohq/storage";
|
||||
import type { Shortcut } from "@/types/proto/api/v2/shortcut_service";
|
||||
|
||||
const storage = new Storage();
|
||||
const urlRegex = /https?:\/\/s\/(.+)/;
|
||||
@ -13,33 +12,14 @@ chrome.webRequest.onBeforeRequest.addListener(
|
||||
|
||||
const shortcutName = getShortcutNameFromUrl(param.url);
|
||||
if (shortcutName) {
|
||||
const shortcuts = (await storage.getItem<Shortcut[]>("shortcuts")) || [];
|
||||
const shortcut = shortcuts.find((shortcut) => shortcut.name === shortcutName);
|
||||
if (!shortcut) {
|
||||
return;
|
||||
}
|
||||
return chrome.tabs.update({ url: shortcut.link });
|
||||
const instanceUrl = (await storage.getItem<string>("domain")) || "";
|
||||
return chrome.tabs.update({ url: `${instanceUrl}/s/${shortcutName}` });
|
||||
}
|
||||
})();
|
||||
},
|
||||
{ urls: ["*://s/*", "*://*/search*"] }
|
||||
);
|
||||
|
||||
chrome.omnibox.onInputEntered.addListener(async (text, disposition) => {
|
||||
const shortcuts = (await storage.getItem<Shortcut[]>("shortcuts")) || [];
|
||||
const shortcut = shortcuts.find((shortcut) => shortcut.name === text);
|
||||
if (!shortcut) {
|
||||
return;
|
||||
}
|
||||
if (disposition === "currentTab") {
|
||||
chrome.tabs.update({ url: shortcut.link });
|
||||
} else if (disposition === "newForegroundTab") {
|
||||
chrome.tabs.create({ url: shortcut.link });
|
||||
} else if (disposition === "newBackgroundTab") {
|
||||
chrome.tabs.create({ url: shortcut.link, active: false });
|
||||
}
|
||||
});
|
||||
|
||||
const getShortcutNameFromUrl = (urlString: string) => {
|
||||
const matchResult = urlRegex.exec(urlString);
|
||||
if (matchResult === null) {
|
||||
|
@ -1,39 +1,27 @@
|
||||
import { Button, IconButton, Input, Modal, ModalDialog } from "@mui/joy";
|
||||
import { useStorage } from "@plasmohq/storage/hook";
|
||||
import axios from "axios";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { Visibility } from "@/types/proto/api/v2/common";
|
||||
import { CreateShortcutResponse, OpenGraphMetadata } from "@/types/proto/api/v2/shortcut_service";
|
||||
import { useStorageContext } from "@/context";
|
||||
import { useShortcutStore } from "@/stores";
|
||||
import type { Visibility } from "@/types/proto/api/v1/common";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import Icon from "./Icon";
|
||||
|
||||
const generateTempName = (length = 6) => {
|
||||
let result = "";
|
||||
const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
const charactersLength = characters.length;
|
||||
let counter = 0;
|
||||
while (counter < length) {
|
||||
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||
counter += 1;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
interface State {
|
||||
name: string;
|
||||
title: string;
|
||||
link: string;
|
||||
}
|
||||
|
||||
const CreateShortcutsButton = () => {
|
||||
const [domain] = useStorage("domain");
|
||||
const [accessToken] = useStorage("access_token");
|
||||
const [shortcuts, setShortcuts] = useStorage("shortcuts");
|
||||
const CreateShortcutButton = () => {
|
||||
const context = useStorageContext();
|
||||
const shortcutStore = useShortcutStore();
|
||||
const [state, setState] = useState<State>({
|
||||
name: "",
|
||||
title: "",
|
||||
link: "",
|
||||
});
|
||||
const [tag, setTag] = useState<string>("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
@ -54,7 +42,7 @@ const CreateShortcutsButton = () => {
|
||||
const tab = tabs[0];
|
||||
setState((state) => ({
|
||||
...state,
|
||||
name: generateTempName() + "-temp",
|
||||
name: "",
|
||||
title: tab.title || "",
|
||||
link: tab.url || "",
|
||||
}));
|
||||
@ -62,6 +50,18 @@ const CreateShortcutsButton = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const generateRandomName = () => {
|
||||
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
let name = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
name += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
setState((state) => ({
|
||||
...state,
|
||||
name,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleNameInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setState((state) => ({
|
||||
...state,
|
||||
@ -83,6 +83,11 @@ const CreateShortcutsButton = () => {
|
||||
}));
|
||||
};
|
||||
|
||||
const handleTagsInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const text = e.target.value as string;
|
||||
setTag(text);
|
||||
};
|
||||
|
||||
const handleSaveBtnClick = async () => {
|
||||
if (isLoading) {
|
||||
return;
|
||||
@ -94,25 +99,18 @@ const CreateShortcutsButton = () => {
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const {
|
||||
data: { shortcut },
|
||||
} = await axios.post<CreateShortcutResponse>(
|
||||
`${domain}/api/v2/shortcuts`,
|
||||
{
|
||||
const tags = tag.split(" ").filter(Boolean);
|
||||
await shortcutStore.createShortcut(
|
||||
context.instanceUrl,
|
||||
context.accessToken,
|
||||
Shortcut.fromPartial({
|
||||
name: state.name,
|
||||
title: state.title,
|
||||
link: state.link,
|
||||
visibility: Visibility.PRIVATE,
|
||||
ogMetadata: OpenGraphMetadata.fromPartial({}),
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
}
|
||||
tags,
|
||||
visibility: context.defaultVisibility as Visibility,
|
||||
})
|
||||
);
|
||||
|
||||
setShortcuts([shortcut, ...shortcuts]);
|
||||
toast.success("Shortcut created successfully");
|
||||
setShowModal(false);
|
||||
} catch (error: any) {
|
||||
@ -139,7 +137,18 @@ const CreateShortcutsButton = () => {
|
||||
<div className="overflow-x-hidden w-full flex flex-col justify-start items-center">
|
||||
<div className="w-full flex flex-row justify-start items-center mb-2">
|
||||
<span className="block w-12 mr-2 shrink-0">Name</span>
|
||||
<Input className="grow" type="text" placeholder="Unique shortcut name" value={state.name} onChange={handleNameInputChange} />
|
||||
<Input
|
||||
className="grow"
|
||||
type="text"
|
||||
placeholder="Unique shortcut name"
|
||||
value={state.name}
|
||||
onChange={handleNameInputChange}
|
||||
endDecorator={
|
||||
<IconButton size="sm" onClick={generateRandomName}>
|
||||
<Icon.RefreshCcw className="w-4 h-auto cursor-pointer" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-row justify-start items-center mb-2">
|
||||
<span className="block w-12 mr-2 shrink-0">Title</span>
|
||||
@ -150,11 +159,15 @@ const CreateShortcutsButton = () => {
|
||||
<Input
|
||||
className="grow"
|
||||
type="text"
|
||||
placeholder="https://github.com/boojack/slash"
|
||||
placeholder="e.g., https://github.com/yourselfhosted/slash"
|
||||
value={state.link}
|
||||
onChange={handleLinkInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-row justify-start items-center mb-2">
|
||||
<span className="block w-12 mr-2 shrink-0">Tags</span>
|
||||
<Input className="grow" type="text" placeholder="The tags of shortcut" value={tag} onChange={handleTagsInputChange} />
|
||||
</div>
|
||||
|
||||
<div className="w-full flex flex-row justify-end items-center mt-2 space-x-2">
|
||||
<Button color="neutral" variant="plain" onClick={() => setShowModal(false)}>
|
||||
@ -171,4 +184,4 @@ const CreateShortcutsButton = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateShortcutsButton;
|
||||
export default CreateShortcutButton;
|
@ -1,12 +1,12 @@
|
||||
import classNames from "classnames";
|
||||
import LogoBase64 from "data-base64:../..//assets/icon.png";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const Logo = ({ className }: Props) => {
|
||||
return <img className={classNames(className)} src={LogoBase64} alt="" />;
|
||||
return <Icon.CircleSlash className={classNames("dark:text-gray-500", className)} strokeWidth={1.5} />;
|
||||
};
|
||||
|
||||
export default Logo;
|
||||
|
@ -1,32 +1,23 @@
|
||||
import { IconButton } from "@mui/joy";
|
||||
import { useStorage } from "@plasmohq/storage/hook";
|
||||
import axios from "axios";
|
||||
import { useEffect } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { ListShortcutsResponse } from "@/types/proto/api/v2/shortcut_service";
|
||||
import { useStorageContext } from "@/context";
|
||||
import { useShortcutStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
const PullShortcutsButton = () => {
|
||||
const [domain] = useStorage("domain");
|
||||
const [accessToken] = useStorage("access_token");
|
||||
const [, setShortcuts] = useStorage("shortcuts");
|
||||
const context = useStorageContext();
|
||||
const shortcutStore = useShortcutStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (domain && accessToken) {
|
||||
if (context.instanceUrl && context.accessToken) {
|
||||
handlePullShortcuts(true);
|
||||
}
|
||||
}, [domain, accessToken]);
|
||||
}, [context]);
|
||||
|
||||
const handlePullShortcuts = async (silence = false) => {
|
||||
try {
|
||||
const {
|
||||
data: { shortcuts },
|
||||
} = await axios.get<ListShortcutsResponse>(`${domain}/api/v2/shortcuts`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
setShortcuts(shortcuts);
|
||||
await shortcutStore.fetchShortcutList(context.instanceUrl, context.accessToken);
|
||||
if (!silence) {
|
||||
toast.success("Shortcuts pulled");
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { useStorage } from "@plasmohq/storage/hook";
|
||||
import classNames from "classnames";
|
||||
import { getFaviconWithGoogleS2 } from "@/helpers/utils";
|
||||
import type { Shortcut } from "@/types/proto/api/v2/shortcut_service";
|
||||
import type { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -22,13 +22,13 @@ const ShortcutView = (props: Props) => {
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"group w-full px-3 py-2 flex flex-col justify-start items-start border rounded-lg hover:bg-gray-100 hover:shadow dark:border-zinc-800 dark:hover:bg-zinc-800"
|
||||
"group w-auto px-3 py-2 flex flex-col justify-start items-start border rounded-lg hover:bg-gray-100 hover:shadow dark:border-zinc-800 dark:hover:bg-zinc-800"
|
||||
)}
|
||||
>
|
||||
<div className="w-full flex flex-row justify-start items-center">
|
||||
<span className={classNames("w-5 h-5 flex justify-center items-center overflow-clip shrink-0")}>
|
||||
{favicon ? (
|
||||
<img className="w-full h-auto rounded-lg" src={favicon} decoding="async" loading="lazy" />
|
||||
<img className="w-full h-auto rounded" src={favicon} decoding="async" loading="lazy" />
|
||||
) : (
|
||||
<Icon.CircleSlash className="w-full h-auto text-gray-400" />
|
||||
)}
|
||||
@ -44,15 +44,14 @@ const ShortcutView = (props: Props) => {
|
||||
<div className="truncate">
|
||||
<span className="dark:text-gray-400">{shortcut.title}</span>
|
||||
{shortcut.title ? (
|
||||
<span className="text-gray-500">(s/{shortcut.name})</span>
|
||||
<span className="text-gray-500">({shortcut.name})</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-gray-400 dark:text-gray-500">s/</span>
|
||||
<span className="truncate dark:text-gray-400">{shortcut.name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<span className="hidden group-hover:block ml-1 cursor-pointer shrink-0">
|
||||
<span className="ml-1 cursor-pointer shrink-0 opacity-80">
|
||||
<Icon.ExternalLink className="w-4 h-auto text-gray-600" />
|
||||
</span>
|
||||
</button>
|
||||
|
@ -1,16 +1,24 @@
|
||||
import { useStorage } from "@plasmohq/storage/hook";
|
||||
import classNames from "classnames";
|
||||
import type { Shortcut } from "@/types/proto/api/v2/shortcut_service";
|
||||
import { useShortcutStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
import ShortcutView from "./ShortcutView";
|
||||
|
||||
const ShortcutsContainer = () => {
|
||||
const [shortcuts] = useStorage<Shortcut[]>("shortcuts", (v) => (v ? v : []));
|
||||
const shortcuts = useShortcutStore().getShortcutList();
|
||||
|
||||
return (
|
||||
<div className={classNames("w-full grid grid-cols-2 gap-2")}>
|
||||
{shortcuts.map((shortcut) => {
|
||||
return <ShortcutView key={shortcut.id} shortcut={shortcut} />;
|
||||
})}
|
||||
<div>
|
||||
<div className="w-full flex flex-row justify-start items-center mb-4">
|
||||
<a className="bg-blue-100 dark:bg-blue-500 dark:opacity-70 py-2 px-3 rounded-full border dark:border-blue-600 flex flex-row justify-start items-center cursor-pointer shadow">
|
||||
<Icon.AlertCircle className="w-4 h-auto" />
|
||||
<span className="mx-1 text-sm">Please make sure you have signed in your instance.</span>
|
||||
</a>
|
||||
</div>
|
||||
<div className={classNames("w-full flex flex-row justify-start items-start flex-wrap gap-2")}>
|
||||
{shortcuts.map((shortcut) => {
|
||||
return <ShortcutView key={shortcut.id} shortcut={shortcut} />;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
27
frontend/extension/src/context/context.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import { Visibility } from "@/types/proto/api/v1/common";
|
||||
|
||||
interface Context {
|
||||
instanceUrl?: string;
|
||||
accessToken?: string;
|
||||
defaultVisibility: string;
|
||||
setInstanceUrl: (instanceUrl: string) => void;
|
||||
setAccessToken: (accessToken: string) => void;
|
||||
setDefaultVisibility: (visibility: string) => void;
|
||||
}
|
||||
|
||||
export const StorageContext = createContext<Context>({
|
||||
instanceUrl: undefined,
|
||||
accessToken: undefined,
|
||||
defaultVisibility: Visibility.PRIVATE,
|
||||
setInstanceUrl: () => {},
|
||||
setAccessToken: () => {},
|
||||
setDefaultVisibility: () => {},
|
||||
});
|
||||
|
||||
const useStorageContext = () => {
|
||||
const context = useContext(StorageContext);
|
||||
return context;
|
||||
};
|
||||
|
||||
export default useStorageContext;
|
4
frontend/extension/src/context/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
import useStorageContext from "./context";
|
||||
import StorageContextProvider from "./provider";
|
||||
|
||||
export { useStorageContext, StorageContextProvider };
|
66
frontend/extension/src/context/provider.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
import { Storage } from "@plasmohq/storage";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Visibility } from "@/types/proto/api/v1/common";
|
||||
import { StorageContext } from "./context";
|
||||
|
||||
interface Props {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const StorageContextProvider = ({ children }: Props) => {
|
||||
const storage = new Storage();
|
||||
const [instanceUrl, setInstanceUrl] = useState<string | undefined>(undefined);
|
||||
const [accessToken, setAccessToken] = useState<string | undefined>(undefined);
|
||||
const [defaultVisibility, setDefaultVisibility] = useState<Visibility>(Visibility.PRIVATE);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
let instanceUrl = await storage.get("instance_url");
|
||||
const accessToken = await storage.get("access_token");
|
||||
const defaultVisibility = (await storage.get("default_visibility")) as Visibility;
|
||||
|
||||
// Migrate domain to instance_url.
|
||||
const domain = await storage.get("domain");
|
||||
if (domain) {
|
||||
instanceUrl = domain;
|
||||
await storage.remove("domain");
|
||||
await storage.set("instance_url", instanceUrl);
|
||||
}
|
||||
|
||||
setInstanceUrl(instanceUrl);
|
||||
setAccessToken(accessToken);
|
||||
setDefaultVisibility(defaultVisibility);
|
||||
setIsInitialized(true);
|
||||
})();
|
||||
|
||||
storage.watch({
|
||||
instance_url: (c) => {
|
||||
setInstanceUrl(c.newValue);
|
||||
},
|
||||
access_token: (c) => {
|
||||
setAccessToken(c.newValue);
|
||||
},
|
||||
default_visibility: (c) => {
|
||||
setDefaultVisibility(c.newValue as Visibility);
|
||||
},
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<StorageContext.Provider
|
||||
value={{
|
||||
instanceUrl,
|
||||
accessToken,
|
||||
defaultVisibility,
|
||||
setInstanceUrl: (instanceUrl: string) => storage.set("instance_url", instanceUrl),
|
||||
setAccessToken: (accessToken: string) => storage.set("access_token", accessToken),
|
||||
setDefaultVisibility: (visibility: Visibility) => storage.set("default_visibility", visibility),
|
||||
}}
|
||||
>
|
||||
{isInitialized && children}
|
||||
</StorageContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default StorageContextProvider;
|
@ -1,9 +1,3 @@
|
||||
import { isNull, isUndefined } from "lodash-es";
|
||||
|
||||
export const isNullorUndefined = (value: any) => {
|
||||
return isNull(value) || isUndefined(value);
|
||||
};
|
||||
|
||||
export const getFaviconWithGoogleS2 = (url: string) => {
|
||||
try {
|
||||
const urlObject = new URL(url);
|
||||
|
@ -1,14 +1,15 @@
|
||||
import { Button, CssVarsProvider, Divider, Input, Select, Option } from "@mui/joy";
|
||||
import { useStorage } from "@plasmohq/storage/hook";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Toaster, toast } from "react-hot-toast";
|
||||
import type { Shortcut } from "@/types/proto/api/v2/shortcut_service";
|
||||
import { useShortcutStore } from "@/stores";
|
||||
import Icon from "./components/Icon";
|
||||
import Logo from "./components/Logo";
|
||||
import PullShortcutsButton from "./components/PullShortcutsButton";
|
||||
import ShortcutsContainer from "./components/ShortcutsContainer";
|
||||
import { StorageContextProvider, useStorageContext } from "./context";
|
||||
import useColorTheme from "./hooks/useColorTheme";
|
||||
import "./style.css";
|
||||
import { Visibility } from "./types/proto/api/v1/common";
|
||||
|
||||
interface SettingState {
|
||||
domain: string;
|
||||
@ -32,21 +33,21 @@ const colorThemeOptions = [
|
||||
|
||||
const IndexOptions = () => {
|
||||
const { colorTheme, setColorTheme } = useColorTheme();
|
||||
const [domain, setDomain] = useStorage<string>("domain", (v) => (v ? v : ""));
|
||||
const [accessToken, setAccessToken] = useStorage<string>("access_token", (v) => (v ? v : ""));
|
||||
const context = useStorageContext();
|
||||
const [settingState, setSettingState] = useState<SettingState>({
|
||||
domain,
|
||||
accessToken,
|
||||
domain: context.instanceUrl || "",
|
||||
accessToken: context.accessToken || "",
|
||||
});
|
||||
const [shortcuts] = useStorage<Shortcut[]>("shortcuts", []);
|
||||
const isInitialized = domain && accessToken;
|
||||
const shortcutStore = useShortcutStore();
|
||||
const shortcuts = shortcutStore.getShortcutList();
|
||||
const isInitialized = context.instanceUrl && context.accessToken;
|
||||
|
||||
useEffect(() => {
|
||||
setSettingState({
|
||||
domain,
|
||||
accessToken,
|
||||
domain: context.instanceUrl || "",
|
||||
accessToken: context.accessToken || "",
|
||||
});
|
||||
}, [domain, accessToken]);
|
||||
}, [context]);
|
||||
|
||||
const setPartialSettingState = (partialSettingState: Partial<SettingState>) => {
|
||||
setSettingState((prevState) => ({
|
||||
@ -56,8 +57,8 @@ const IndexOptions = () => {
|
||||
};
|
||||
|
||||
const handleSaveSetting = () => {
|
||||
setDomain(settingState.domain);
|
||||
setAccessToken(settingState.accessToken);
|
||||
context.setInstanceUrl(settingState.domain);
|
||||
context.setAccessToken(settingState.accessToken);
|
||||
toast.success("Setting saved");
|
||||
};
|
||||
|
||||
@ -65,12 +66,16 @@ const IndexOptions = () => {
|
||||
setColorTheme(colorTheme as any);
|
||||
};
|
||||
|
||||
const handleDefaultVisibilitySelect = (value: Visibility) => {
|
||||
context.setDefaultVisibility(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="w-full px-4">
|
||||
<div className="w-full flex flex-row justify-center items-center">
|
||||
<a
|
||||
className="bg-yellow-100 dark:bg-yellow-500 dark:opacity-70 mt-12 py-2 px-3 rounded-full border dark:border-yellow-600 flex flex-row justify-start items-center cursor-pointer shadow hover:underline hover:text-blue-600"
|
||||
href="https://github.com/boojack/slash#browser-extension"
|
||||
href="https://github.com/yourselfhosted/slash#browser-extension"
|
||||
target="_blank"
|
||||
>
|
||||
<Icon.HelpCircle className="w-4 h-auto" />
|
||||
@ -79,7 +84,7 @@ const IndexOptions = () => {
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-lg mx-auto flex flex-col justify-start items-start mt-12">
|
||||
<div className="w-full max-w-lg mx-auto flex flex-col justify-start items-start py-12">
|
||||
<h2 className="flex flex-row justify-start items-center mb-6 text-2xl dark:text-gray-400">
|
||||
<Logo className="w-10 h-auto mr-2" />
|
||||
<span>Slash</span>
|
||||
@ -90,11 +95,11 @@ const IndexOptions = () => {
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<div className="w-full flex flex-col justify-start items-start mb-4">
|
||||
<div className="mb-2 text-base w-full flex flex-row justify-between items-center">
|
||||
<span className="dark:text-gray-400">Domain</span>
|
||||
{domain !== "" && (
|
||||
<span className="dark:text-gray-400">Instance URL</span>
|
||||
{context.instanceUrl !== "" && (
|
||||
<a
|
||||
className="text-sm flex flex-row justify-start items-center dark:text-gray-400 hover:underline hover:text-blue-600"
|
||||
href={domain}
|
||||
className="text-sm flex flex-row justify-start items-center underline text-blue-600 hover:opacity-80"
|
||||
href={context.instanceUrl}
|
||||
target="_blank"
|
||||
>
|
||||
<span className="mr-1">Go to my Slash</span>
|
||||
@ -106,7 +111,7 @@ const IndexOptions = () => {
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="The domain of your Slash instance"
|
||||
placeholder="The url of your Slash instance. e.g., https://slash.example.com"
|
||||
value={settingState.domain}
|
||||
onChange={(e) => setPartialSettingState({ domain: e.target.value })}
|
||||
/>
|
||||
@ -119,7 +124,7 @@ const IndexOptions = () => {
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="The access token of your Slash instance"
|
||||
placeholder="An available access token of your account."
|
||||
value={settingState.accessToken}
|
||||
onChange={(e) => setPartialSettingState({ accessToken: e.target.value })}
|
||||
/>
|
||||
@ -132,9 +137,9 @@ const IndexOptions = () => {
|
||||
|
||||
<Divider className="!my-6" />
|
||||
|
||||
<p className="text-base font-semibold leading-6 text-gray-900 dark:text-gray-500">Preference</p>
|
||||
<p className="text-base font-semibold leading-6 mb-2 text-gray-900 dark:text-gray-500">Preference</p>
|
||||
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="w-full flex flex-row justify-between items-center mb-2">
|
||||
<div className="flex flex-row justify-start items-center gap-x-1">
|
||||
<span className="dark:text-gray-400">Color Theme</span>
|
||||
</div>
|
||||
@ -148,6 +153,17 @@ const IndexOptions = () => {
|
||||
})}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="flex flex-row justify-start items-center gap-x-1">
|
||||
<span className="dark:text-gray-400">Default Visibility</span>
|
||||
</div>
|
||||
<Select defaultValue={context.defaultVisibility} onChange={(_, value) => handleDefaultVisibilitySelect(value as Visibility)}>
|
||||
<Option value={Visibility.PRIVATE}>Private</Option>
|
||||
<Option value={Visibility.WORKSPACE}>Workspace</Option>
|
||||
<Option value={Visibility.PUBLIC}>Public</Option>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isInitialized && (
|
||||
@ -169,10 +185,12 @@ const IndexOptions = () => {
|
||||
|
||||
const Options = () => {
|
||||
return (
|
||||
<CssVarsProvider>
|
||||
<IndexOptions />
|
||||
<Toaster position="top-right" />
|
||||
</CssVarsProvider>
|
||||
<StorageContextProvider>
|
||||
<CssVarsProvider>
|
||||
<IndexOptions />
|
||||
<Toaster position="top-center" />
|
||||
</CssVarsProvider>
|
||||
</StorageContextProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -1,21 +1,30 @@
|
||||
import { Button, CssVarsProvider, Divider, IconButton } from "@mui/joy";
|
||||
import { useStorage } from "@plasmohq/storage/hook";
|
||||
import { useEffect } from "react";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
import CreateShortcutsButton from "@/components/CreateShortcutsButton";
|
||||
import CreateShortcutButton from "@/components/CreateShortcutButton";
|
||||
import Icon from "@/components/Icon";
|
||||
import Logo from "@/components/Logo";
|
||||
import PullShortcutsButton from "@/components/PullShortcutsButton";
|
||||
import ShortcutsContainer from "@/components/ShortcutsContainer";
|
||||
import type { Shortcut } from "@/types/proto/api/v2/shortcut_service";
|
||||
import { useShortcutStore } from "@/stores";
|
||||
import { StorageContextProvider, useStorageContext } from "./context";
|
||||
import useColorTheme from "./hooks/useColorTheme";
|
||||
import "./style.css";
|
||||
|
||||
const IndexPopup = () => {
|
||||
useColorTheme();
|
||||
const [domain] = useStorage<string>("domain", "");
|
||||
const [accessToken] = useStorage<string>("access_token", "");
|
||||
const [shortcuts] = useStorage<Shortcut[]>("shortcuts", []);
|
||||
const isInitialized = domain && accessToken;
|
||||
const context = useStorageContext();
|
||||
const shortcutStore = useShortcutStore();
|
||||
const shortcuts = shortcutStore.getShortcutList();
|
||||
const isInitialized = context.instanceUrl && context.accessToken;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
shortcutStore.fetchShortcutList(context.instanceUrl, context.accessToken);
|
||||
}, [isInitialized]);
|
||||
|
||||
const handleSettingButtonClick = () => {
|
||||
chrome.runtime.openOptionsPage();
|
||||
@ -30,7 +39,7 @@ const IndexPopup = () => {
|
||||
<div className="w-full min-w-[512px] px-4 pt-4">
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="flex flex-row justify-start items-center dark:text-gray-400">
|
||||
<Logo className="w-6 h-auto mr-2" />
|
||||
<Logo className="w-6 h-auto mr-1" />
|
||||
<span className="">Slash</span>
|
||||
{isInitialized && (
|
||||
<>
|
||||
@ -41,7 +50,7 @@ const IndexPopup = () => {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div>{isInitialized && <CreateShortcutsButton />}</div>
|
||||
<div>{isInitialized && <CreateShortcutButton />}</div>
|
||||
</div>
|
||||
|
||||
<div className="w-full mt-4">
|
||||
@ -62,14 +71,21 @@ const IndexPopup = () => {
|
||||
<IconButton size="sm" variant="plain" color="neutral" onClick={handleSettingButtonClick}>
|
||||
<Icon.Settings className="w-5 h-auto text-gray-500 dark:text-gray-400" />
|
||||
</IconButton>
|
||||
<IconButton size="sm" variant="plain" color="neutral" component="a" href="https://github.com/boojack/slash" target="_blank">
|
||||
<IconButton
|
||||
size="sm"
|
||||
variant="plain"
|
||||
color="neutral"
|
||||
component="a"
|
||||
href="https://github.com/yourselfhosted/slash"
|
||||
target="_blank"
|
||||
>
|
||||
<Icon.Github className="w-5 h-auto text-gray-500 dark:text-gray-400" />
|
||||
</IconButton>
|
||||
</div>
|
||||
<div className="flex flex-row justify-end items-center">
|
||||
<a
|
||||
className="text-sm flex flex-row justify-start items-center text-gray-500 dark:text-gray-400 hover:underline hover:text-blue-600"
|
||||
href={domain}
|
||||
className="text-sm flex flex-row justify-start items-center underline text-blue-600 hover:opacity-80"
|
||||
href={context.instanceUrl}
|
||||
target="_blank"
|
||||
>
|
||||
<span className="mr-1">Go to my Slash</span>
|
||||
@ -81,10 +97,10 @@ const IndexPopup = () => {
|
||||
) : (
|
||||
<div className="w-full flex flex-col justify-start items-center">
|
||||
<Icon.Cookie strokeWidth={1} className="w-20 h-auto mb-4 text-gray-400" />
|
||||
<p className="dark:text-gray-400">Please set your domain and access token first.</p>
|
||||
<p className="dark:text-gray-400">Please set your instance URL and access token first.</p>
|
||||
<div className="w-full flex flex-row justify-center items-center py-4">
|
||||
<Button size="sm" color="primary" onClick={handleSettingButtonClick}>
|
||||
<Icon.Settings className="w-5 h-auto mr-1" /> Setting
|
||||
<Icon.Settings className="w-5 h-auto mr-1" /> Go to Setting
|
||||
</Button>
|
||||
<span className="mx-2 dark:text-gray-400">Or</span>
|
||||
<Button size="sm" variant="outlined" color="neutral" onClick={handleRefreshButtonClick}>
|
||||
@ -100,10 +116,12 @@ const IndexPopup = () => {
|
||||
|
||||
const Popup = () => {
|
||||
return (
|
||||
<CssVarsProvider>
|
||||
<IndexPopup />
|
||||
<Toaster position="top-right" />
|
||||
</CssVarsProvider>
|
||||
<StorageContextProvider>
|
||||
<CssVarsProvider>
|
||||
<IndexPopup />
|
||||
<Toaster position="top-center" />
|
||||
</CssVarsProvider>
|
||||
</StorageContextProvider>
|
||||
);
|
||||
};
|
||||
|
||||
|
3
frontend/extension/src/stores/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import useShortcutStore from "./shortcut";
|
||||
|
||||
export { useShortcutStore };
|
55
frontend/extension/src/stores/shortcut.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import axios from "axios";
|
||||
import { create } from "zustand";
|
||||
import { combine } from "zustand/middleware";
|
||||
import { CreateShortcutResponse, ListShortcutsResponse, Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
|
||||
interface State {
|
||||
shortcutMapById: Record<number, Shortcut>;
|
||||
}
|
||||
|
||||
const getDefaultState = (): State => {
|
||||
return {
|
||||
shortcutMapById: {},
|
||||
};
|
||||
};
|
||||
|
||||
const useShortcutStore = create(
|
||||
combine(getDefaultState(), (set, get) => ({
|
||||
fetchShortcutList: async (instanceUrl: string, accessToken: string) => {
|
||||
const {
|
||||
data: { shortcuts },
|
||||
} = await axios.get<ListShortcutsResponse>(`${instanceUrl}/api/v1/shortcuts`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
const shortcutMap = get().shortcutMapById;
|
||||
shortcuts.forEach((shortcut) => {
|
||||
shortcutMap[shortcut.id] = shortcut;
|
||||
});
|
||||
set({ shortcutMapById: shortcutMap });
|
||||
return shortcuts;
|
||||
},
|
||||
getShortcutList: () => {
|
||||
return Object.values(get().shortcutMapById);
|
||||
},
|
||||
createShortcut: async (instanceUrl: string, accessToken: string, create: Shortcut) => {
|
||||
const {
|
||||
data: { shortcut },
|
||||
} = await axios.post<CreateShortcutResponse>(`${instanceUrl}/api/v1/shortcuts`, create, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
if (!shortcut) {
|
||||
throw new Error(`Failed to create shortcut`);
|
||||
}
|
||||
const shortcutMap = get().shortcutMapById;
|
||||
shortcutMap[shortcut.id] = shortcut;
|
||||
set({ shortcutMapById: shortcutMap });
|
||||
return shortcut;
|
||||
},
|
||||
}))
|
||||
);
|
||||
|
||||
export default useShortcutStore;
|
@ -76,7 +76,8 @@
|
||||
"enable-user-signup": {
|
||||
"self": "Enable user signup",
|
||||
"description": "Once enabled, other users can signup."
|
||||
}
|
||||
},
|
||||
"default-visibility": "Default visibility"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -76,7 +76,8 @@
|
||||
"enable-user-signup": {
|
||||
"self": "启用用户注册",
|
||||
"description": "允许其他用户注册新账号"
|
||||
}
|
||||
},
|
||||
"default-visibility": "默认可见性"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,9 +2,10 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="/logo.png" type="image/*" />
|
||||
<link rel="icon" href="/logo.svg" type="image/*" />
|
||||
<meta name="theme-color" content="#FFFFFF" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
|
||||
<!-- slash.metadata -->
|
||||
<title>Slash</title>
|
||||
</head>
|
||||
<body>
|
||||
|
@ -6,51 +6,52 @@
|
||||
"serve": "vite preview",
|
||||
"lint": "eslint --ext .js,.ts,.tsx, src",
|
||||
"lint-fix": "eslint --ext .js,.ts,.tsx, src --fix",
|
||||
"type-gen": "cd ../../proto && buf generate"
|
||||
"postinstall": "cd ../../proto && buf generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.11.1",
|
||||
"@emotion/styled": "^11.11.0",
|
||||
"@mui/joy": "5.0.0-beta.14",
|
||||
"@emotion/react": "^11.11.4",
|
||||
"@emotion/styled": "^11.11.5",
|
||||
"@mui/joy": "5.0.0-beta.30",
|
||||
"@reduxjs/toolkit": "^1.9.7",
|
||||
"axios": "^1.6.0",
|
||||
"classnames": "^2.3.2",
|
||||
"classnames": "^2.5.1",
|
||||
"copy-to-clipboard": "^3.3.3",
|
||||
"dayjs": "^1.11.10",
|
||||
"i18next": "^23.6.0",
|
||||
"i18next": "^23.11.2",
|
||||
"lodash-es": "^4.17.21",
|
||||
"lucide-react": "^0.292.0",
|
||||
"nice-grpc-web": "^3.3.2",
|
||||
"lucide-react": "^0.312.0",
|
||||
"nice-grpc-web": "^3.3.3",
|
||||
"qrcode.react": "^3.1.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hot-toast": "^2.4.1",
|
||||
"react-i18next": "^13.3.1",
|
||||
"react-redux": "^8.1.3",
|
||||
"react-router-dom": "^6.18.0",
|
||||
"react-use": "^17.4.0",
|
||||
"tailwindcss": "^3.3.5",
|
||||
"zustand": "^4.4.6"
|
||||
"react-i18next": "^14.1.0",
|
||||
"react-router-dom": "^6.22.3",
|
||||
"react-use": "^17.5.0",
|
||||
"tailwindcss": "^3.4.3",
|
||||
"zustand": "^4.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@bufbuild/buf": "^1.27.2",
|
||||
"@trivago/prettier-plugin-sort-imports": "^4.2.1",
|
||||
"@types/lodash-es": "^4.17.11",
|
||||
"@types/react": "^18.2.37",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@typescript-eslint/eslint-plugin": "^6.10.0",
|
||||
"@typescript-eslint/parser": "^6.10.0",
|
||||
"@vitejs/plugin-react-swc": "^3.4.1",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"eslint": "^8.53.0",
|
||||
"eslint-config-prettier": "^8.10.0",
|
||||
"@bufbuild/buf": "^1.30.1",
|
||||
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/react": "^18.2.79",
|
||||
"@types/react-dom": "^18.2.25",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"@vitejs/plugin-react-swc": "^3.6.0",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react": "^7.34.1",
|
||||
"long": "^5.2.3",
|
||||
"postcss": "^8.4.31",
|
||||
"postcss": "^8.4.38",
|
||||
"prettier": "2.6.2",
|
||||
"protobufjs": "^7.2.5",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^4.5.0"
|
||||
"protobufjs": "^7.2.6",
|
||||
"typescript": "^5.4.5",
|
||||
"vite": "^5.2.9"
|
||||
},
|
||||
"resolutions": {
|
||||
"csstype": "3.1.2"
|
||||
}
|
||||
}
|
||||
|
6045
frontend/web/pnpm-lock.yaml
generated
Before Width: | Height: | Size: 257 KiB |
1
frontend/web/public/logo.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-slash"><line x1="9" x2="15" y1="15" y2="9"/><circle cx="12" cy="12" r="10"/></svg>frontend/web/public/logo.svg
|
After Width: | Height: | Size: 319 B |
@ -1,9 +1,8 @@
|
||||
import { useColorScheme } from "@mui/joy";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Outlet } from "react-router-dom";
|
||||
import DemoBanner from "./components/DemoBanner";
|
||||
import useUserStore from "./stores/v1/user";
|
||||
import useWorkspaceStore from "./stores/v1/workspace";
|
||||
import DemoBanner from "@/components/DemoBanner";
|
||||
import { useUserStore, useWorkspaceStore } from "@/stores";
|
||||
|
||||
function App() {
|
||||
const { mode: colorScheme } = useColorScheme();
|
||||
@ -16,7 +15,7 @@ function App() {
|
||||
try {
|
||||
await Promise.all([workspaceStore.fetchWorkspaceProfile(), workspaceStore.fetchWorkspaceSetting(), userStore.fetchCurrentUser()]);
|
||||
} catch (error) {
|
||||
// do nth
|
||||
// Do nothing.
|
||||
}
|
||||
setLoading(false);
|
||||
})();
|
||||
|
@ -21,11 +21,11 @@ const AboutDialog: React.FC<Props> = (props: Props) => {
|
||||
</div>
|
||||
<div className="max-w-full w-80 sm:w-96">
|
||||
<p>
|
||||
<span className="font-medium">Slash</span>: An open source, self-hosted bookmarks and link sharing platform.
|
||||
<span className="font-medium">Slash</span>: An open source, self-hosted links shortener and sharing platform.
|
||||
</p>
|
||||
<div className="mt-1">
|
||||
<span className="mr-2">See more in</span>
|
||||
<Link variant="plain" href="https://github.com/boojack/slash" target="_blank">
|
||||
<Link variant="plain" href="https://github.com/yourselfhosted/slash" target="_blank">
|
||||
GitHub
|
||||
</Link>
|
||||
</div>
|
||||
|
@ -45,7 +45,7 @@ const Alert: React.FC<Props> = (props: Props) => {
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-80 mb-4">
|
||||
<div className="flex flex-row justify-between items-center w-80">
|
||||
<span className="text-lg font-medium">{title}</span>
|
||||
<Button variant="plain" onClick={handleCloseBtnClick}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
|
@ -1,28 +1,29 @@
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import * as api from "../helpers/api";
|
||||
import { shortcutServiceClient } from "@/grpcweb";
|
||||
import { GetShortcutAnalyticsResponse } from "@/types/proto/api/v1/shortcut_service";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
shortcutId: ShortcutId;
|
||||
shortcutId: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const AnalyticsView: React.FC<Props> = (props: Props) => {
|
||||
const { shortcutId, className } = props;
|
||||
const { t } = useTranslation();
|
||||
const [analytics, setAnalytics] = useState<AnalysisData | null>(null);
|
||||
const [analytics, setAnalytics] = useState<GetShortcutAnalyticsResponse | null>(null);
|
||||
const [selectedDeviceTab, setSelectedDeviceTab] = useState<"os" | "browser">("browser");
|
||||
|
||||
useEffect(() => {
|
||||
api.getShortcutAnalytics(shortcutId).then(({ data }) => {
|
||||
setAnalytics(data);
|
||||
shortcutServiceClient.getShortcutAnalytics({ id: shortcutId }).then((response) => {
|
||||
setAnalytics(response);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={classNames("w-full", className)}>
|
||||
<div className={classNames("relative w-full", className)}>
|
||||
{analytics ? (
|
||||
<>
|
||||
<div className="w-full">
|
||||
@ -34,13 +35,13 @@ const AnalyticsView: React.FC<Props> = (props: Props) => {
|
||||
<span className="py-2 pr-2 text-right font-semibold text-sm text-gray-500">{t("analytics.visitors")}</span>
|
||||
</div>
|
||||
<div className="w-full divide-y divide-gray-200 dark:divide-zinc-800">
|
||||
{analytics.referenceData.length === 0 && (
|
||||
{analytics.references.length === 0 && (
|
||||
<div className="w-full flex flex-row justify-center items-center py-6 text-gray-400">
|
||||
<Icon.PackageOpen className="w-6 h-auto" />
|
||||
<p className="ml-2">No data found.</p>
|
||||
</div>
|
||||
)}
|
||||
{analytics.referenceData.map((reference) => (
|
||||
{analytics.references.map((reference) => (
|
||||
<div key={reference.name} className="w-full flex flex-row justify-between items-center">
|
||||
<span className="whitespace-nowrap py-2 px-2 text-sm truncate text-gray-900 dark:text-gray-500">
|
||||
{reference.name ? (
|
||||
@ -95,13 +96,13 @@ const AnalyticsView: React.FC<Props> = (props: Props) => {
|
||||
<span className="py-2 pr-2 text-right text-sm font-semibold text-gray-500">{t("analytics.visitors")}</span>
|
||||
</div>
|
||||
<div className="w-full divide-y divide-gray-200 dark:divide-zinc-800">
|
||||
{analytics.browserData.length === 0 && (
|
||||
{analytics.browsers.length === 0 && (
|
||||
<div className="w-full flex flex-row justify-center items-center py-6 text-gray-400">
|
||||
<Icon.PackageOpen className="w-6 h-auto" />
|
||||
<p className="ml-2">No data found.</p>
|
||||
</div>
|
||||
)}
|
||||
{analytics.browserData.map((reference) => (
|
||||
{analytics.browsers.map((reference) => (
|
||||
<div key={reference.name} className="w-full flex flex-row justify-between items-center">
|
||||
<span className="whitespace-nowrap py-2 px-2 text-sm text-gray-900 truncate dark:text-gray-500">
|
||||
{reference.name || "Unknown"}
|
||||
@ -118,13 +119,13 @@ const AnalyticsView: React.FC<Props> = (props: Props) => {
|
||||
<span className="py-2 pr-2 text-right text-sm font-semibold text-gray-500">{t("analytics.visitors")}</span>
|
||||
</div>
|
||||
<div className="w-full divide-y divide-gray-200">
|
||||
{analytics.deviceData.length === 0 && (
|
||||
{analytics.devices.length === 0 && (
|
||||
<div className="w-full flex flex-row justify-center items-center py-6 text-gray-400">
|
||||
<Icon.PackageOpen className="w-6 h-auto" />
|
||||
<p className="ml-2">No data found.</p>
|
||||
</div>
|
||||
)}
|
||||
{analytics.deviceData.map((device) => (
|
||||
{analytics.devices.map((device) => (
|
||||
<div key={device.name} className="w-full flex flex-row justify-between items-center">
|
||||
<span className="whitespace-nowrap py-2 px-2 text-sm text-gray-900 truncate">{device.name || "Unknown"}</span>
|
||||
<span className="whitespace-nowrap py-2 pr-2 text-sm text-gray-500 text-right shrink-0">{device.count}</span>
|
||||
@ -137,7 +138,7 @@ const AnalyticsView: React.FC<Props> = (props: Props) => {
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="py-12 w-full flex flex-row justify-center items-center opacity-80">
|
||||
<div className="absolute py-12 w-full flex flex-row justify-center items-center opacity-80">
|
||||
<Icon.Loader className="mr-2 w-5 h-auto animate-spin" />
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
|
@ -2,8 +2,8 @@ import { Button, Input, Modal, ModalDialog } from "@mui/joy";
|
||||
import { useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useUserStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -54,7 +54,7 @@ const ChangePasswordDialog: React.FC<Props> = (props: Props) => {
|
||||
toast("Password changed");
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
toast.error(error.response.data.message);
|
||||
toast.error(error.details);
|
||||
}
|
||||
requestState.setFinish();
|
||||
};
|
||||
@ -62,7 +62,7 @@ const ChangePasswordDialog: React.FC<Props> = (props: Props) => {
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-80 mb-4">
|
||||
<div className="flex flex-row justify-between items-center w-80">
|
||||
<span className="text-lg font-medium">Change Password</span>
|
||||
<Button variant="plain" onClick={handleCloseBtnClick}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
|
@ -7,11 +7,11 @@ import { Link } from "react-router-dom";
|
||||
import { absolutifyLink } from "@/helpers/utils";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
import useResponsiveWidth from "@/hooks/useResponsiveWidth";
|
||||
import { useAppSelector } from "@/stores";
|
||||
import useCollectionStore from "@/stores/v1/collection";
|
||||
import { Collection } from "@/types/proto/api/v2/collection_service";
|
||||
import { useCollectionStore, useShortcutStore, useUserStore } from "@/stores";
|
||||
import { Collection } from "@/types/proto/api/v1/collection_service";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import { showCommonDialog } from "./Alert";
|
||||
import CreateCollectionDialog from "./CreateCollectionDialog";
|
||||
import CreateCollectionDialog from "./CreateCollectionDrawer";
|
||||
import Icon from "./Icon";
|
||||
import ShortcutView from "./ShortcutView";
|
||||
import Dropdown from "./common/Dropdown";
|
||||
@ -25,12 +25,15 @@ const CollectionView = (props: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const { sm } = useResponsiveWidth();
|
||||
const navigateTo = useNavigateTo();
|
||||
const userStore = useUserStore();
|
||||
const currentUser = userStore.getCurrentUser();
|
||||
const collectionStore = useCollectionStore();
|
||||
const { shortcutList } = useAppSelector((state) => state.shortcut);
|
||||
const shortcutList = useShortcutStore().getShortcutList();
|
||||
const [showEditDialog, setShowEditDialog] = useState<boolean>(false);
|
||||
const shortcuts = collection.shortcutIds
|
||||
.map((shortcutId) => shortcutList.find((shortcut) => shortcut?.id === shortcutId))
|
||||
.filter(Boolean) as any as Shortcut[];
|
||||
const showAdminActions = currentUser.id === collection.creatorId;
|
||||
|
||||
const handleCopyCollectionLink = () => {
|
||||
copy(absolutifyLink(`/c/${collection.name}`));
|
||||
@ -57,37 +60,48 @@ const CollectionView = (props: Props) => {
|
||||
<div className={classNames("w-full flex flex-col justify-start items-start border rounded-lg hover:shadow dark:border-zinc-800")}>
|
||||
<div className="bg-gray-100 dark:bg-zinc-800 px-3 py-2 w-full flex flex-row justify-between items-center rounded-t-lg">
|
||||
<div className="w-auto flex flex-col justify-start items-start mr-2">
|
||||
<div className="w-full truncate" onClick={handleCopyCollectionLink}>
|
||||
<span className="leading-6 font-medium dark:text-gray-400">{collection.title}</span>
|
||||
<span className="ml-1 leading-6 text-gray-500 dark:text-gray-400">(c/{collection.name})</span>
|
||||
<div className="w-full truncate">
|
||||
<Link className="leading-6 font-medium dark:text-gray-400" to={`/c/${collection.name}`} unstable_viewTransition>
|
||||
{collection.title}
|
||||
</Link>
|
||||
<span className="ml-1 leading-6 text-gray-500 dark:text-gray-400" onClick={handleCopyCollectionLink}>
|
||||
(c/{collection.name})
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500">{collection.description}</p>
|
||||
</div>
|
||||
<div className="flex flex-row justify-end items-center shrink-0">
|
||||
<Link className="w-full text-gray-400 cursor-pointer hover:text-gray-500" to={`/c/${collection.name}`}>
|
||||
<Icon.Share className="w-4 h-auto mr-2" />
|
||||
<div className="flex flex-row justify-end items-center shrink-0 gap-2">
|
||||
<Link className="w-full text-gray-400 cursor-pointer hover:text-gray-500" to={`/c/${collection.name}`} target="_blank">
|
||||
<Icon.Share className="w-4 h-auto" />
|
||||
</Link>
|
||||
<Dropdown
|
||||
actionsClassName="!w-28 dark:text-gray-500"
|
||||
actions={
|
||||
<>
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left leading-8 cursor-pointer rounded hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60 dark:hover:bg-zinc-800"
|
||||
onClick={() => setShowEditDialog(true)}
|
||||
>
|
||||
<Icon.Edit className="w-4 h-auto mr-2" /> {t("common.edit")}
|
||||
{showAdminActions && (
|
||||
<Dropdown
|
||||
trigger={
|
||||
<button className="flex flex-row justify-center items-center rounded text-gray-400 cursor-pointer hover:text-gray-500">
|
||||
<Icon.MoreVertical className="w-4 h-auto" />
|
||||
</button>
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left leading-8 cursor-pointer rounded text-red-600 hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60 dark:hover:bg-zinc-800"
|
||||
onClick={() => {
|
||||
handleDeleteCollectionButtonClick();
|
||||
}}
|
||||
>
|
||||
<Icon.Trash className="w-4 h-auto mr-2" /> {t("common.delete")}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
></Dropdown>
|
||||
}
|
||||
actionsClassName="!w-28 text-sm"
|
||||
actions={
|
||||
<>
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
onClick={() => setShowEditDialog(true)}
|
||||
>
|
||||
<Icon.Edit className="w-4 h-auto mr-2" /> {t("common.edit")}
|
||||
</button>
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left text-red-600 dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
onClick={() => {
|
||||
handleDeleteCollectionButtonClick();
|
||||
}}
|
||||
>
|
||||
<Icon.Trash className="w-4 h-auto mr-2" /> {t("common.delete")}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
></Dropdown>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-full p-3 flex flex-row justify-start items-start flex-wrap gap-3">
|
||||
|
@ -3,8 +3,8 @@ import { useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { userServiceClient } from "@/grpcweb";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useUserStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -80,14 +80,14 @@ const CreateAccessTokenDialog: React.FC<Props> = (props: Props) => {
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
toast.error(error.response.data.message);
|
||||
toast.error(error.details);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-80 sm:w-96 mb-4">
|
||||
<div className="flex flex-row justify-between items-center w-80">
|
||||
<span className="text-lg font-medium">Create Access Token</span>
|
||||
<Button variant="plain" onClick={onClose}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
|
@ -1,14 +1,14 @@
|
||||
import { Button, Input, Modal, ModalDialog, Radio, RadioGroup } from "@mui/joy";
|
||||
import { Button, DialogActions, DialogContent, DialogTitle, Drawer, Input, ModalClose, Radio, RadioGroup } from "@mui/joy";
|
||||
import { isUndefined } from "lodash-es";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppSelector } from "@/stores";
|
||||
import useCollectionStore from "@/stores/v1/collection";
|
||||
import { Collection } from "@/types/proto/api/v2/collection_service";
|
||||
import { Visibility } from "@/types/proto/api/v2/common";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useCollectionStore, useShortcutStore, useWorkspaceStore } from "@/stores";
|
||||
import { Collection } from "@/types/proto/api/v1/collection_service";
|
||||
import { Visibility } from "@/types/proto/api/v1/common";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import { convertVisibilityFromPb } from "@/utils/visibility";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import Icon from "./Icon";
|
||||
import ShortcutView from "./ShortcutView";
|
||||
|
||||
@ -22,23 +22,50 @@ interface State {
|
||||
collectionCreate: Collection;
|
||||
}
|
||||
|
||||
const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
const CreateCollectionDrawer: React.FC<Props> = (props: Props) => {
|
||||
const { onClose, onConfirm, collectionId } = props;
|
||||
const { t } = useTranslation();
|
||||
const workspaceStore = useWorkspaceStore();
|
||||
const collectionStore = useCollectionStore();
|
||||
const { shortcutList } = useAppSelector((state) => state.shortcut);
|
||||
const shortcutList = useShortcutStore().getShortcutList();
|
||||
const [state, setState] = useState<State>({
|
||||
collectionCreate: Collection.fromPartial({
|
||||
visibility: Visibility.PRIVATE,
|
||||
}),
|
||||
});
|
||||
const [selectedShortcuts, setSelectedShortcuts] = useState<Shortcut[]>([]);
|
||||
const requestState = useLoading(false);
|
||||
const isCreating = isUndefined(collectionId);
|
||||
const loadingState = useLoading(!isCreating);
|
||||
const requestState = useLoading(false);
|
||||
const unselectedShortcuts = shortcutList
|
||||
.filter((shortcut) => (state.collectionCreate.visibility === Visibility.PUBLIC ? shortcut.visibility === "PUBLIC" : true))
|
||||
.filter((shortcut) => {
|
||||
if (state.collectionCreate.visibility === Visibility.PUBLIC) {
|
||||
return shortcut.visibility === Visibility.PUBLIC;
|
||||
} else if (state.collectionCreate.visibility === Visibility.WORKSPACE) {
|
||||
return shortcut.visibility === Visibility.PUBLIC || shortcut.visibility === Visibility.WORKSPACE;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
})
|
||||
.filter((shortcut) => !selectedShortcuts.find((selectedShortcut) => selectedShortcut.id === shortcut.id));
|
||||
|
||||
const setPartialState = (partialState: Partial<State>) => {
|
||||
setState({
|
||||
...state,
|
||||
...partialState,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (workspaceStore.setting.defaultVisibility !== Visibility.VISIBILITY_UNSPECIFIED) {
|
||||
setPartialState({
|
||||
collectionCreate: Object.assign(state.collectionCreate, {
|
||||
visibility: workspaceStore.setting.defaultVisibility,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
if (collectionId) {
|
||||
@ -55,17 +82,15 @@ const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
.map((shortcutId) => shortcutList.find((shortcut) => shortcut.id === shortcutId))
|
||||
.filter(Boolean) as Shortcut[]
|
||||
);
|
||||
loadingState.setFinish();
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [collectionId]);
|
||||
|
||||
const setPartialState = (partialState: Partial<State>) => {
|
||||
setState({
|
||||
...state,
|
||||
...partialState,
|
||||
});
|
||||
};
|
||||
if (loadingState.isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleNameInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setPartialState({
|
||||
@ -86,7 +111,7 @@ const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
const handleVisibilityInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setPartialState({
|
||||
collectionCreate: Object.assign(state.collectionCreate, {
|
||||
visibility: Number(e.target.value),
|
||||
visibility: e.target.value,
|
||||
}),
|
||||
});
|
||||
};
|
||||
@ -141,28 +166,22 @@ const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<span className="text-lg font-medium">{isCreating ? "Create Collection" : "Edit Collection"}</span>
|
||||
<Button variant="plain" onClick={onClose}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="overflow-y-auto overflow-x-hidden w-80 sm:w-96 max-w-full">
|
||||
<Drawer anchor="right" open={true} onClose={onClose}>
|
||||
<DialogTitle>{isCreating ? "Create Collection" : "Edit Collection"}</DialogTitle>
|
||||
<ModalClose />
|
||||
<DialogContent className="w-full max-w-full">
|
||||
<div className="overflow-y-auto w-full mt-2 px-4 pb-4 sm:w-[24rem]">
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">
|
||||
Name <span className="text-red-600">*</span>
|
||||
</span>
|
||||
<div className="relative w-full">
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="Should be an unique name and will be put in url"
|
||||
value={state.collectionCreate.name}
|
||||
onChange={handleNameInputChange}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="The memorable name of the collection"
|
||||
value={state.collectionCreate.name}
|
||||
onChange={handleNameInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">
|
||||
@ -195,6 +214,7 @@ const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
<div className="w-full flex flex-row justify-start items-center text-base">
|
||||
<RadioGroup orientation="horizontal" value={state.collectionCreate.visibility} onChange={handleVisibilityInputChange}>
|
||||
<Radio value={Visibility.PRIVATE} label={t(`shortcut.visibility.private.self`)} />
|
||||
<Radio value={Visibility.WORKSPACE} label={t(`shortcut.visibility.workspace.self`)} />
|
||||
<Radio value={Visibility.PUBLIC} label={t(`shortcut.visibility.public.self`)} />
|
||||
</RadioGroup>
|
||||
</div>
|
||||
@ -206,7 +226,7 @@ const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
<p className="mb-2">
|
||||
<span>Shortcuts</span>
|
||||
<span className="opacity-60">({selectedShortcuts.length})</span>
|
||||
{selectedShortcuts.length === 0 && <span className="ml-2 italic opacity-80 text-sm">Select a shortcut first</span>}
|
||||
{selectedShortcuts.length === 0 && <span className="ml-2 italic opacity-80 text-sm">(Select a shortcut first)</span>}
|
||||
</p>
|
||||
<div className="w-full py-1 px-px flex flex-row justify-start items-start flex-wrap overflow-hidden gap-2">
|
||||
{selectedShortcuts.map((shortcut) => {
|
||||
@ -241,19 +261,20 @@ const CreateCollectionDialog: React.FC<Props> = (props: Props) => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="w-full flex flex-row justify-end items-center mt-4 space-x-2">
|
||||
<Button color="neutral" variant="plain" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button color="primary" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={handleSaveBtnClick}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</ModalDialog>
|
||||
</Modal>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<div className="w-full flex flex-row justify-end items-center px-3 py-4 space-x-2">
|
||||
<Button color="neutral" variant="plain" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button color="primary" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={handleSaveBtnClick}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogActions>
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateCollectionDialog;
|
||||
export default CreateCollectionDrawer;
|
@ -1,57 +1,84 @@
|
||||
import { Button, Divider, Input, Modal, ModalDialog, Radio, RadioGroup, Textarea } from "@mui/joy";
|
||||
import {
|
||||
Button,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Divider,
|
||||
Drawer,
|
||||
Input,
|
||||
ModalClose,
|
||||
Radio,
|
||||
RadioGroup,
|
||||
Textarea,
|
||||
} from "@mui/joy";
|
||||
import classnames from "classnames";
|
||||
import { isUndefined, uniq } from "lodash-es";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppSelector } from "@/stores";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import { shortcutService } from "../services";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useWorkspaceStore, useShortcutStore } from "@/stores";
|
||||
import { getShortcutUpdateMask } from "@/stores/shortcut";
|
||||
import { Visibility } from "@/types/proto/api/v1/common";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import { convertVisibilityFromPb } from "@/utils/visibility";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
shortcutId?: ShortcutId;
|
||||
shortcutId?: number;
|
||||
initialShortcut?: Partial<Shortcut>;
|
||||
onClose: () => void;
|
||||
onConfirm?: () => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
shortcutCreate: ShortcutCreate;
|
||||
shortcutCreate: Shortcut;
|
||||
}
|
||||
|
||||
const visibilities: Visibility[] = ["PRIVATE", "WORKSPACE", "PUBLIC"];
|
||||
|
||||
const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
const CreateShortcutDrawer: React.FC<Props> = (props: Props) => {
|
||||
const { onClose, onConfirm, shortcutId, initialShortcut } = props;
|
||||
const { t } = useTranslation();
|
||||
const { shortcutList } = useAppSelector((state) => state.shortcut);
|
||||
const [state, setState] = useState<State>({
|
||||
shortcutCreate: {
|
||||
name: "",
|
||||
link: "",
|
||||
title: "",
|
||||
description: "",
|
||||
visibility: "PRIVATE",
|
||||
tags: [],
|
||||
openGraphMetadata: {
|
||||
shortcutCreate: Shortcut.fromPartial({
|
||||
visibility: Visibility.PUBLIC,
|
||||
ogMetadata: {
|
||||
title: "",
|
||||
description: "",
|
||||
image: "",
|
||||
},
|
||||
...initialShortcut,
|
||||
},
|
||||
}),
|
||||
});
|
||||
const [showAdditionalFields, setShowAdditionalFields] = useState<boolean>(false);
|
||||
const shortcutStore = useShortcutStore();
|
||||
const workspaceStore = useWorkspaceStore();
|
||||
const [showOpenGraphMetadata, setShowOpenGraphMetadata] = useState<boolean>(false);
|
||||
const shortcutList = shortcutStore.getShortcutList();
|
||||
const [tag, setTag] = useState<string>("");
|
||||
const tagSuggestions = uniq(shortcutList.map((shortcut) => shortcut.tags).flat());
|
||||
const requestState = useLoading(false);
|
||||
const isCreating = isUndefined(shortcutId);
|
||||
const loadingState = useLoading(!isCreating);
|
||||
const requestState = useLoading(false);
|
||||
|
||||
const setPartialState = (partialState: Partial<State>) => {
|
||||
setState({
|
||||
...state,
|
||||
...partialState,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (workspaceStore.setting.defaultVisibility !== Visibility.VISIBILITY_UNSPECIFIED) {
|
||||
setPartialState({
|
||||
shortcutCreate: Object.assign(state.shortcutCreate, {
|
||||
visibility: workspaceStore.setting.defaultVisibility,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (shortcutId) {
|
||||
const shortcut = shortcutService.getShortcutById(shortcutId);
|
||||
const shortcut = shortcutStore.getShortcutById(shortcutId);
|
||||
if (shortcut) {
|
||||
setState({
|
||||
...state,
|
||||
@ -61,20 +88,18 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
title: shortcut.title,
|
||||
description: shortcut.description,
|
||||
visibility: shortcut.visibility,
|
||||
openGraphMetadata: shortcut.openGraphMetadata,
|
||||
ogMetadata: shortcut.ogMetadata,
|
||||
}),
|
||||
});
|
||||
setTag(shortcut.tags.join(" "));
|
||||
loadingState.setFinish();
|
||||
}
|
||||
}
|
||||
}, [shortcutId]);
|
||||
|
||||
const setPartialState = (partialState: Partial<State>) => {
|
||||
setState({
|
||||
...state,
|
||||
...partialState,
|
||||
});
|
||||
};
|
||||
if (loadingState.isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleNameInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setPartialState({
|
||||
@ -124,8 +149,8 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
const handleOpenGraphMetadataImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setPartialState({
|
||||
shortcutCreate: Object.assign(state.shortcutCreate, {
|
||||
openGraphMetadata: {
|
||||
...state.shortcutCreate.openGraphMetadata,
|
||||
ogMetadata: {
|
||||
...state.shortcutCreate.ogMetadata,
|
||||
image: e.target.value,
|
||||
},
|
||||
}),
|
||||
@ -135,8 +160,8 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
const handleOpenGraphMetadataTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setPartialState({
|
||||
shortcutCreate: Object.assign(state.shortcutCreate, {
|
||||
openGraphMetadata: {
|
||||
...state.shortcutCreate.openGraphMetadata,
|
||||
ogMetadata: {
|
||||
...state.shortcutCreate.ogMetadata,
|
||||
title: e.target.value,
|
||||
},
|
||||
}),
|
||||
@ -146,8 +171,8 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
const handleOpenGraphMetadataDescriptionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setPartialState({
|
||||
shortcutCreate: Object.assign(state.shortcutCreate, {
|
||||
openGraphMetadata: {
|
||||
...state.shortcutCreate.openGraphMetadata,
|
||||
ogMetadata: {
|
||||
...state.shortcutCreate.ogMetadata,
|
||||
description: e.target.value,
|
||||
},
|
||||
}),
|
||||
@ -169,21 +194,19 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const tags = tag.split(" ").filter(Boolean);
|
||||
if (shortcutId) {
|
||||
await shortcutService.patchShortcut({
|
||||
id: shortcutId,
|
||||
name: state.shortcutCreate.name,
|
||||
link: state.shortcutCreate.link,
|
||||
title: state.shortcutCreate.title,
|
||||
description: state.shortcutCreate.description,
|
||||
visibility: state.shortcutCreate.visibility,
|
||||
tags: tag.split(" ").filter(Boolean),
|
||||
openGraphMetadata: state.shortcutCreate.openGraphMetadata,
|
||||
});
|
||||
} else {
|
||||
await shortcutService.createShortcut({
|
||||
const originShortcut = shortcutStore.getShortcutById(shortcutId);
|
||||
const updatingShortcut = {
|
||||
...state.shortcutCreate,
|
||||
tags: tag.split(" ").filter(Boolean),
|
||||
id: shortcutId,
|
||||
tags,
|
||||
};
|
||||
await shortcutStore.updateShortcut(updatingShortcut, getShortcutUpdateMask(originShortcut, updatingShortcut));
|
||||
} else {
|
||||
await shortcutStore.createShortcut({
|
||||
...state.shortcutCreate,
|
||||
tags,
|
||||
});
|
||||
}
|
||||
|
||||
@ -194,49 +217,63 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
toast.error(error.response.data.message);
|
||||
toast.error(error.details);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-80 sm:w-96">
|
||||
<span className="text-lg font-medium">{isCreating ? "Create Shortcut" : "Edit Shortcut"}</span>
|
||||
<Button variant="plain" onClick={onClose}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="overflow-y-auto overflow-x-hidden">
|
||||
<Drawer anchor="right" open={true} onClose={onClose}>
|
||||
<DialogTitle>{isCreating ? "Create Shortcut" : "Edit Shortcut"}</DialogTitle>
|
||||
<ModalClose />
|
||||
<DialogContent className="w-full max-w-full">
|
||||
<div className="overflow-y-auto w-full mt-2 px-4 pb-4 sm:w-[24rem]">
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">
|
||||
Name <span className="text-red-600">*</span>
|
||||
</span>
|
||||
<div className="relative w-full">
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="Should be an unique name and will be put in url"
|
||||
value={state.shortcutCreate.name}
|
||||
onChange={handleNameInputChange}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="The memorable name of the shortcut"
|
||||
value={state.shortcutCreate.name}
|
||||
onChange={handleNameInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">
|
||||
Destination URL <span className="text-red-600">*</span>
|
||||
Link <span className="text-red-600">*</span>
|
||||
</span>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="https://github.com/boojack/slash"
|
||||
placeholder="The destination link of the shortcut"
|
||||
value={state.shortcutCreate.link}
|
||||
onChange={handleLinkInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">Title</span>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="The title of the shortcut"
|
||||
value={state.shortcutCreate.title}
|
||||
onChange={handleTitleInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">Description</span>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="A short description of the shortcut"
|
||||
value={state.shortcutCreate.description}
|
||||
onChange={handleDescriptionInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2">Tags</span>
|
||||
<Input className="w-full" type="text" placeholder="github slash" value={tag} onChange={handleTagsInputChange} />
|
||||
<Input className="w-full" type="text" placeholder="The tags of shortcut" value={tag} onChange={handleTagsInputChange} />
|
||||
{tagSuggestions.length > 0 && (
|
||||
<div className="w-full flex flex-row justify-start items-start mt-2">
|
||||
<Icon.Asterisk className="w-4 h-auto shrink-0 mx-1 text-gray-400 dark:text-gray-500" />
|
||||
@ -258,57 +295,17 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
<span className="mb-2">Visibility</span>
|
||||
<div className="w-full flex flex-row justify-start items-center text-base">
|
||||
<RadioGroup orientation="horizontal" value={state.shortcutCreate.visibility} onChange={handleVisibilityInputChange}>
|
||||
{visibilities.map((visibility) => (
|
||||
<Radio key={visibility} value={visibility} label={t(`shortcut.visibility.${visibility.toLowerCase()}.self`)} />
|
||||
))}
|
||||
<Radio value={Visibility.PRIVATE} label={t(`shortcut.visibility.private.self`)} />
|
||||
<Radio value={Visibility.WORKSPACE} label={t(`shortcut.visibility.workspace.self`)} />
|
||||
<Radio value={Visibility.PUBLIC} label={t(`shortcut.visibility.public.self`)} />
|
||||
</RadioGroup>
|
||||
</div>
|
||||
<p className="mt-3 text-sm text-gray-500 w-full bg-gray-100 border border-gray-200 dark:bg-zinc-800 dark:border-zinc-700 dark:text-gray-400 px-2 py-1 rounded-md">
|
||||
{t(`shortcut.visibility.${state.shortcutCreate.visibility.toLowerCase()}.description`)}
|
||||
{t(`shortcut.visibility.${convertVisibilityFromPb(state.shortcutCreate.visibility).toLowerCase()}.description`)}
|
||||
</p>
|
||||
</div>
|
||||
<Divider className="text-gray-500">More</Divider>
|
||||
<div className="w-full flex flex-col justify-start items-start border rounded-md overflow-hidden my-3 dark:border-zinc-800">
|
||||
<div
|
||||
className={classnames(
|
||||
"w-full flex flex-row justify-between items-center px-2 py-1 cursor-pointer hover:bg-gray-100 dark:hover:bg-zinc-800",
|
||||
showAdditionalFields ? "bg-gray-100 border-b dark:bg-zinc-800 dark:border-b-zinc-700" : ""
|
||||
)}
|
||||
onClick={() => setShowAdditionalFields(!showAdditionalFields)}
|
||||
>
|
||||
<span className="text-sm">Additional fields</span>
|
||||
<button className="w-7 h-7 p-1 rounded-md">
|
||||
<Icon.ChevronDown className={classnames("w-4 h-auto text-gray-500", showAdditionalFields ? "transform rotate-180" : "")} />
|
||||
</button>
|
||||
</div>
|
||||
{showAdditionalFields && (
|
||||
<div className="w-full px-2 py-1">
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2 text-sm">Title</span>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="Title"
|
||||
size="sm"
|
||||
value={state.shortcutCreate.title}
|
||||
onChange={handleTitleInputChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<span className="mb-2 text-sm">Description</span>
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="Github repo for slash"
|
||||
size="sm"
|
||||
value={state.shortcutCreate.description}
|
||||
onChange={handleDescriptionInputChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start border rounded-md overflow-hidden dark:border-zinc-800">
|
||||
<div className="w-full flex flex-col justify-start items-start border rounded-md mt-3 overflow-hidden dark:border-zinc-800">
|
||||
<div
|
||||
className={classnames(
|
||||
"w-full flex flex-row justify-between items-center px-2 py-1 cursor-pointer hover:bg-gray-100 dark:hover:bg-zinc-800",
|
||||
@ -333,7 +330,7 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
type="text"
|
||||
placeholder="https://the.link.to/the/image.png"
|
||||
size="sm"
|
||||
value={state.shortcutCreate.openGraphMetadata.image}
|
||||
value={state.shortcutCreate.ogMetadata?.image}
|
||||
onChange={handleOpenGraphMetadataImageChange}
|
||||
/>
|
||||
</div>
|
||||
@ -342,9 +339,9 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
<Input
|
||||
className="w-full"
|
||||
type="text"
|
||||
placeholder="Slash - An open source, self-hosted bookmarks and link sharing platform"
|
||||
placeholder="Slash - An open source, self-hosted links shortener and sharing platform"
|
||||
size="sm"
|
||||
value={state.shortcutCreate.openGraphMetadata.title}
|
||||
value={state.shortcutCreate.ogMetadata?.title}
|
||||
onChange={handleOpenGraphMetadataTitleChange}
|
||||
/>
|
||||
</div>
|
||||
@ -352,29 +349,30 @@ const CreateShortcutDialog: React.FC<Props> = (props: Props) => {
|
||||
<span className="mb-2 text-sm">Description</span>
|
||||
<Textarea
|
||||
className="w-full"
|
||||
placeholder="An open source, self-hosted bookmarks and link sharing platform."
|
||||
placeholder="An open source, self-hosted links shortener and sharing platform."
|
||||
size="sm"
|
||||
maxRows={3}
|
||||
value={state.shortcutCreate.openGraphMetadata.description}
|
||||
value={state.shortcutCreate.ogMetadata?.description}
|
||||
onChange={handleOpenGraphMetadataDescriptionChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="w-full flex flex-row justify-end items-center mt-4 space-x-2">
|
||||
<Button color="neutral" variant="plain" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button color="primary" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={handleSaveBtnClick}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</ModalDialog>
|
||||
</Modal>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<div className="w-full flex flex-row justify-end items-center px-3 py-4 space-x-2">
|
||||
<Button color="neutral" variant="plain" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button color="primary" disabled={requestState.isLoading} loading={requestState.isLoading} onClick={handleSaveBtnClick}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogActions>
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateShortcutDialog;
|
||||
export default CreateShortcutDrawer;
|
@ -3,8 +3,9 @@ import { isUndefined } from "lodash-es";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useUserStore } from "@/stores";
|
||||
import { Role, User } from "@/types/proto/api/v1/user_service";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -14,11 +15,9 @@ interface Props {
|
||||
}
|
||||
|
||||
interface State {
|
||||
userCreate: UserCreate;
|
||||
userCreate: Pick<User, "email" | "nickname" | "password" | "role">;
|
||||
}
|
||||
|
||||
const roles: Role[] = ["USER", "ADMIN"];
|
||||
|
||||
const CreateUserDialog: React.FC<Props> = (props: Props) => {
|
||||
const { onClose, onConfirm, user } = props;
|
||||
const { t } = useTranslation();
|
||||
@ -28,7 +27,7 @@ const CreateUserDialog: React.FC<Props> = (props: Props) => {
|
||||
email: "",
|
||||
nickname: "",
|
||||
password: "",
|
||||
role: "USER",
|
||||
role: Role.USER,
|
||||
},
|
||||
});
|
||||
const requestState = useLoading(false);
|
||||
@ -95,7 +94,7 @@ const CreateUserDialog: React.FC<Props> = (props: Props) => {
|
||||
|
||||
try {
|
||||
if (user) {
|
||||
const userPatch: UserPatch = {
|
||||
const userPatch: Partial<User> = {
|
||||
id: user.id,
|
||||
};
|
||||
if (user.email !== state.userCreate.email) {
|
||||
@ -119,14 +118,14 @@ const CreateUserDialog: React.FC<Props> = (props: Props) => {
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
toast.error(error.response.data.message);
|
||||
toast.error(error.details);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-80 sm:w-96 mb-4">
|
||||
<div className="flex flex-row justify-between items-center w-80 sm:w-96">
|
||||
<span className="text-lg font-medium">{isCreating ? "Create User" : "Edit User"}</span>
|
||||
<Button variant="plain" onClick={onClose}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
@ -179,9 +178,8 @@ const CreateUserDialog: React.FC<Props> = (props: Props) => {
|
||||
</span>
|
||||
<div className="w-full flex flex-row justify-start items-center text-base">
|
||||
<RadioGroup orientation="horizontal" value={state.userCreate.role} onChange={handleRoleInputChange}>
|
||||
{roles.map((role) => (
|
||||
<Radio key={role} value={role} label={role} />
|
||||
))}
|
||||
<Radio value={Role.USER} label={"User"} />
|
||||
<Radio value={Role.ADMIN} label={"Admin"} />
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -1,4 +1,4 @@
|
||||
import useWorkspaceStore from "@/stores/v1/workspace";
|
||||
import { useWorkspaceStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
const DemoBanner: React.FC = () => {
|
||||
@ -10,10 +10,10 @@ const DemoBanner: React.FC = () => {
|
||||
return (
|
||||
<div className="z-10 relative flex flex-row items-center justify-center w-full py-2 text-sm sm:text-lg font-medium dark:text-gray-300 bg-white dark:bg-zinc-700 shadow">
|
||||
<div className="w-full max-w-8xl px-4 md:px-12 flex flex-row justify-between items-center gap-x-3">
|
||||
<span>✨🔗 Slash - An open source, self-hosted bookmarks and link sharing platform</span>
|
||||
<span>✨🔗 Slash - An open source, self-hosted links shortener and sharing platform</span>
|
||||
<a
|
||||
className="shadow flex flex-row justify-center items-center px-2 py-1 rounded-md text-sm sm:text-base text-white bg-blue-600 hover:bg-blue-700"
|
||||
href="https://github.com/boojack/slash#deploy-with-docker-in-seconds"
|
||||
href="https://github.com/yourselfhosted/slash#deploy-with-docker-in-seconds"
|
||||
target="_blank"
|
||||
>
|
||||
Install
|
||||
|
@ -2,8 +2,8 @@ import { Button, Input, Modal, ModalDialog } from "@mui/joy";
|
||||
import { useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useUserStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -50,7 +50,7 @@ const EditUserinfoDialog: React.FC<Props> = (props: Props) => {
|
||||
toast("User information updated");
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
toast.error(error.response.data.message);
|
||||
toast.error(error.details);
|
||||
}
|
||||
requestState.setFinish();
|
||||
};
|
||||
@ -58,7 +58,7 @@ const EditUserinfoDialog: React.FC<Props> = (props: Props) => {
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-80 mb-4">
|
||||
<div className="flex flex-row justify-between items-center w-80">
|
||||
<span className="text-lg font-medium">Edit Userinfo</span>
|
||||
<Button variant="plain" onClick={handleCloseBtnClick}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
|
@ -1,5 +1,6 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useViewStore from "../stores/v1/view";
|
||||
import { useViewStore } from "@/stores";
|
||||
import { convertVisibilityFromPb } from "@/utils/visibility";
|
||||
import Icon from "./Icon";
|
||||
import VisibilityIcon from "./VisibilityIcon";
|
||||
|
||||
@ -32,7 +33,7 @@ const FilterView = () => {
|
||||
onClick={() => viewStore.setFilter({ visibility: undefined })}
|
||||
>
|
||||
<VisibilityIcon className="w-4 h-auto mr-1" visibility={filter.visibility} />
|
||||
{t(`shortcut.visibility.${filter.visibility.toLowerCase()}.self`)}
|
||||
{t(`shortcut.visibility.${convertVisibilityFromPb(filter.visibility).toLowerCase()}.self`)}
|
||||
<Icon.X className="w-4 h-auto ml-1" />
|
||||
</button>
|
||||
)}
|
||||
|
@ -3,7 +3,8 @@ import { QRCodeCanvas } from "qrcode.react";
|
||||
import { useRef } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { absolutifyLink } from "../helpers/utils";
|
||||
import { absolutifyLink } from "@/helpers/utils";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -24,12 +25,12 @@ const GenerateQRCodeDialog: React.FC<Props> = (props: Props) => {
|
||||
const handleDownloadQRCodeClick = () => {
|
||||
const canvas = containerRef.current?.querySelector("canvas");
|
||||
if (!canvas) {
|
||||
toast.error("Failed to get qr code canvas");
|
||||
toast.error("Failed to get QR code canvas");
|
||||
return;
|
||||
}
|
||||
|
||||
const link = document.createElement("a");
|
||||
link.download = "filename.png";
|
||||
link.download = `${shortcut.title || shortcut.name}-qrcode.png`;
|
||||
link.href = canvas.toDataURL();
|
||||
link.click();
|
||||
handleCloseBtnClick();
|
||||
@ -38,7 +39,7 @@ const GenerateQRCodeDialog: React.FC<Props> = (props: Props) => {
|
||||
return (
|
||||
<Modal open={true}>
|
||||
<ModalDialog>
|
||||
<div className="flex flex-row justify-between items-center w-64 mb-4">
|
||||
<div className="flex flex-row justify-between items-center w-64">
|
||||
<span className="text-lg font-medium">QR Code</span>
|
||||
<Button variant="plain" onClick={handleCloseBtnClick}>
|
||||
<Icon.X className="w-5 h-auto text-gray-600" />
|
||||
@ -46,7 +47,7 @@ const GenerateQRCodeDialog: React.FC<Props> = (props: Props) => {
|
||||
</div>
|
||||
<div>
|
||||
<div ref={containerRef} className="w-full flex flex-row justify-center items-center mt-2 mb-6">
|
||||
<QRCodeCanvas value={shortcutLink} size={128} bgColor={"#ffffff"} fgColor={"#000000"} includeMargin={false} level={"L"} />
|
||||
<QRCodeCanvas value={shortcutLink} size={180} bgColor={"#ffffff"} fgColor={"#000000"} includeMargin={false} level={"L"} />
|
||||
</div>
|
||||
<div className="w-full flex flex-row justify-center items-center px-4">
|
||||
<Button className="w-full" color="neutral" onClick={handleDownloadQRCodeClick}>
|
||||
|
@ -2,10 +2,10 @@ import { Avatar } from "@mui/joy";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import useWorkspaceStore from "@/stores/v1/workspace";
|
||||
import { PlanType } from "@/types/proto/api/v2/subscription_service";
|
||||
import * as api from "../helpers/api";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import { authServiceClient } from "@/grpcweb";
|
||||
import { useWorkspaceStore, useUserStore } from "@/stores";
|
||||
import { PlanType } from "@/types/proto/api/v1/subscription_service";
|
||||
import { Role } from "@/types/proto/api/v1/user_service";
|
||||
import AboutDialog from "./AboutDialog";
|
||||
import Icon from "./Icon";
|
||||
import Dropdown from "./common/Dropdown";
|
||||
@ -17,21 +17,22 @@ const Header: React.FC = () => {
|
||||
const currentUser = useUserStore().getCurrentUser();
|
||||
const [showAboutDialog, setShowAboutDialog] = useState<boolean>(false);
|
||||
const profile = workspaceStore.profile;
|
||||
const isAdmin = currentUser.role === "ADMIN";
|
||||
const shouldShowRouterSwitch = location.pathname === "/" || location.pathname === "/collections";
|
||||
const isAdmin = currentUser.role === Role.ADMIN;
|
||||
const shouldShowRouterSwitch = location.pathname === "/shortcuts" || location.pathname === "/collections";
|
||||
const selectedSection = location.pathname === "/shortcuts" ? "Shortcuts" : location.pathname === "/collections" ? "Collections" : "";
|
||||
|
||||
const handleSignOutButtonClick = async () => {
|
||||
await api.signout();
|
||||
await authServiceClient.signOut({});
|
||||
window.location.href = "/auth";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full bg-gray-50 dark:bg-zinc-800 border-b border-b-gray-200 dark:border-b-zinc-800">
|
||||
<div className="w-full max-w-8xl mx-auto px-3 md:px-12 py-3 flex flex-row justify-between items-center">
|
||||
<div className="w-full max-w-8xl mx-auto px-4 sm:px-6 md:px-12 py-3 flex flex-row justify-between items-center">
|
||||
<div className="flex flex-row justify-start items-center shrink mr-2">
|
||||
<Link to="/" className="cursor-pointer flex flex-row justify-start items-center dark:text-gray-400">
|
||||
<img id="logo-img" src="/logo.png" className="w-7 h-auto mr-2 -mt-0.5 dark:opacity-80 rounded-full shadow" alt="" />
|
||||
<Link to="/" className="cursor-pointer flex flex-row justify-start items-center dark:text-gray-400" unstable_viewTransition>
|
||||
<Icon.CircleSlash className="w-7 h-auto dark:text-gray-500 mr-2" strokeWidth={1.5} />
|
||||
Slash
|
||||
</Link>
|
||||
{profile.plan === PlanType.PRO && (
|
||||
@ -41,11 +42,11 @@ const Header: React.FC = () => {
|
||||
)}
|
||||
{shouldShowRouterSwitch && (
|
||||
<>
|
||||
<span className="font-mono opacity-60 mx-1">/</span>
|
||||
<span className="font-mono opacity-60 mx-1 dark:text-gray-400">/</span>
|
||||
<Dropdown
|
||||
trigger={
|
||||
<button className="flex flex-row justify-end items-center cursor-pointer">
|
||||
<span className="dark:text-gray-400">{location.pathname === "/" ? "Shortcuts" : "Collections"}</span>
|
||||
<span className="dark:text-gray-400">{selectedSection}</span>
|
||||
<Icon.ChevronsUpDown className="ml-1 w-4 h-auto text-gray-600 dark:text-gray-400" />
|
||||
</button>
|
||||
}
|
||||
@ -53,14 +54,16 @@ const Header: React.FC = () => {
|
||||
actions={
|
||||
<>
|
||||
<Link
|
||||
to="/"
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
to="/shortcuts"
|
||||
unstable_viewTransition
|
||||
>
|
||||
<Icon.SquareSlash className="w-5 h-auto mr-2 opacity-70" /> Shortcuts
|
||||
</Link>
|
||||
<Link
|
||||
to="/collections"
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
to="/collections"
|
||||
unstable_viewTransition
|
||||
>
|
||||
<Icon.LibrarySquare className="w-5 h-auto mr-2 opacity-70" /> Collections
|
||||
</Link>
|
||||
@ -83,30 +86,32 @@ const Header: React.FC = () => {
|
||||
actions={
|
||||
<>
|
||||
<Link
|
||||
to="/setting/general"
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
to="/setting/general"
|
||||
unstable_viewTransition
|
||||
>
|
||||
<Icon.User className="w-4 h-auto mr-2" /> {t("user.profile")}
|
||||
<Icon.User className="w-5 h-auto mr-2 opacity-70" /> {t("user.profile")}
|
||||
</Link>
|
||||
{isAdmin && (
|
||||
<Link
|
||||
to="/setting/workspace"
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
to="/setting/workspace"
|
||||
unstable_viewTransition
|
||||
>
|
||||
<Icon.Settings className="w-4 h-auto mr-2" /> {t("settings.self")}
|
||||
<Icon.Settings className="w-5 h-auto mr-2 opacity-70" /> {t("settings.self")}
|
||||
</Link>
|
||||
)}
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
onClick={() => setShowAboutDialog(true)}
|
||||
>
|
||||
<Icon.Info className="w-4 h-auto mr-2" /> {t("common.about")}
|
||||
<Icon.Info className="w-5 h-auto mr-2 opacity-70" /> {t("common.about")}
|
||||
</button>
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left dark:text-gray-400 leading-8 cursor-pointer rounded hover:bg-gray-100 dark:hover:bg-zinc-800 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60"
|
||||
onClick={() => handleSignOutButtonClick()}
|
||||
>
|
||||
<Icon.LogOut className="w-4 h-auto mr-2" /> {t("auth.sign-out")}
|
||||
<Icon.LogOut className="w-5 h-auto mr-2 opacity-70" /> {t("auth.sign-out")}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
|
36
frontend/web/src/components/LinkFavicon.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
import { useState } from "react";
|
||||
import { useWorkspaceStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
url: string;
|
||||
}
|
||||
|
||||
const getFaviconUrlWithProvider = (url: string, provider: string) => {
|
||||
try {
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("domain", new URL(url).hostname);
|
||||
return new URL(`?${searchParams.toString()}`, provider).toString();
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const LinkFavicon = (props: Props) => {
|
||||
const { url } = props;
|
||||
const workspaceStore = useWorkspaceStore();
|
||||
const faviconProvider = workspaceStore.profile.faviconProvider || "https://www.google.com/s2/favicons";
|
||||
const [faviconUrl, setFaviconUrl] = useState<string>(getFaviconUrlWithProvider(url, faviconProvider));
|
||||
|
||||
const handleImgError = () => {
|
||||
setFaviconUrl("");
|
||||
};
|
||||
|
||||
return faviconUrl ? (
|
||||
<img className="w-full h-auto rounded" src={faviconUrl} decoding="async" loading="lazy" onError={handleImgError} />
|
||||
) : (
|
||||
<Icon.CircleSlash className="w-full h-auto text-gray-400" strokeWidth={1.5} />
|
||||
);
|
||||
};
|
||||
|
||||
export default LinkFavicon;
|
59
frontend/web/src/components/ResourceNameInput.tsx
Normal file
@ -0,0 +1,59 @@
|
||||
import { IconButton, Input } from "@mui/joy";
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
import { generateRandomString } from "@/helpers/utils";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
name: string;
|
||||
onChange: (name: string) => void;
|
||||
}
|
||||
|
||||
const ResourceNameInput = (props: Props) => {
|
||||
const { name, onChange } = props;
|
||||
const [modified, setModified] = useState(false);
|
||||
const [editingName, setEditingName] = useState(name || generateRandomString().toLowerCase());
|
||||
|
||||
useEffect(() => {
|
||||
onChange(editingName);
|
||||
}, [editingName]);
|
||||
|
||||
const handleNameInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!modified) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEditingName(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-start items-start mb-3">
|
||||
<div className={classNames("", modified ? "mb-2" : "flex flex-row justify-start items-center")}>
|
||||
<span>Name</span>
|
||||
{modified ? (
|
||||
<span className="text-red-600"> *</span>
|
||||
) : (
|
||||
<>
|
||||
<span>:</span>
|
||||
<span className="ml-1 font-mono font-medium">{editingName}</span>
|
||||
<div className="ml-1 flex flex-row justify-start items-center">
|
||||
<IconButton size="sm" variant="plain" color="neutral" onClick={() => setModified(true)}>
|
||||
<Icon.Edit className="w-4 h-auto text-gray-500 dark:text-gray-400" />
|
||||
</IconButton>
|
||||
<IconButton size="sm" variant="plain" color="neutral" onClick={() => setEditingName(generateRandomString().toLowerCase())}>
|
||||
<Icon.RefreshCcw className="w-4 h-auto text-gray-500 dark:text-gray-400" />
|
||||
</IconButton>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{modified && (
|
||||
<div className="relative w-full">
|
||||
<Input className="w-full" type="text" placeholder="An unique name" value={editingName} onChange={handleNameInputChange} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ResourceNameInput;
|
@ -1,10 +1,11 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
import { shortcutService } from "../services";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import { useShortcutStore, useUserStore } from "@/stores";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import { Role } from "@/types/proto/api/v1/user_service";
|
||||
import { showCommonDialog } from "./Alert";
|
||||
import CreateShortcutDialog from "./CreateShortcutDialog";
|
||||
import CreateShortcutDrawer from "./CreateShortcutDrawer";
|
||||
import GenerateQRCodeDialog from "./GenerateQRCodeDialog";
|
||||
import Icon from "./Icon";
|
||||
import Dropdown from "./common/Dropdown";
|
||||
@ -17,10 +18,11 @@ const ShortcutActionsDropdown = (props: Props) => {
|
||||
const { shortcut } = props;
|
||||
const { t } = useTranslation();
|
||||
const navigateTo = useNavigateTo();
|
||||
const shortcutStore = useShortcutStore();
|
||||
const currentUser = useUserStore().getCurrentUser();
|
||||
const [showEditDialog, setShowEditDialog] = useState<boolean>(false);
|
||||
const [showEditDrawer, setShowEditDrawer] = useState<boolean>(false);
|
||||
const [showQRCodeDialog, setShowQRCodeDialog] = useState<boolean>(false);
|
||||
const havePermission = currentUser.role === "ADMIN" || shortcut.creatorId === currentUser.id;
|
||||
const havePermission = currentUser.role === Role.ADMIN || shortcut.creatorId === currentUser.id;
|
||||
|
||||
const handleDeleteShortcutButtonClick = (shortcut: Shortcut) => {
|
||||
showCommonDialog({
|
||||
@ -28,7 +30,7 @@ const ShortcutActionsDropdown = (props: Props) => {
|
||||
content: `Are you sure to delete shortcut \`${shortcut.name}\`? You cannot undo this action.`,
|
||||
style: "danger",
|
||||
onConfirm: async () => {
|
||||
await shortcutService.deleteShortcutById(shortcut.id);
|
||||
await shortcutStore.deleteShortcut(shortcut.id);
|
||||
},
|
||||
});
|
||||
};
|
||||
@ -40,28 +42,28 @@ const ShortcutActionsDropdown = (props: Props) => {
|
||||
return (
|
||||
<>
|
||||
<Dropdown
|
||||
actionsClassName="!w-32 dark:text-gray-500"
|
||||
actionsClassName="!w-32 dark:text-gray-500 text-sm"
|
||||
actions={
|
||||
<>
|
||||
{havePermission && (
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left leading-8 cursor-pointer rounded hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60 dark:hover:bg-zinc-800"
|
||||
onClick={() => setShowEditDialog(true)}
|
||||
onClick={() => setShowEditDrawer(true)}
|
||||
>
|
||||
<Icon.Edit className="w-4 h-auto mr-2" /> {t("common.edit")}
|
||||
<Icon.Edit className="w-4 h-auto mr-2 opacity-70" /> {t("common.edit")}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left leading-8 cursor-pointer rounded hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60 dark:hover:bg-zinc-800"
|
||||
onClick={() => setShowQRCodeDialog(true)}
|
||||
>
|
||||
<Icon.QrCode className="w-4 h-auto mr-2" /> QR Code
|
||||
<Icon.QrCode className="w-4 h-auto mr-2 opacity-70" /> QR Code
|
||||
</button>
|
||||
<button
|
||||
className="w-full px-2 flex flex-row justify-start items-center text-left leading-8 cursor-pointer rounded hover:bg-gray-100 disabled:cursor-not-allowed disabled:bg-gray-100 disabled:opacity-60 dark:hover:bg-zinc-800"
|
||||
onClick={gotoAnalytics}
|
||||
>
|
||||
<Icon.BarChart2 className="w-4 h-auto mr-2" /> {t("analytics.self")}
|
||||
<Icon.BarChart2 className="w-4 h-auto mr-2 opacity-70" /> {t("analytics.self")}
|
||||
</button>
|
||||
{havePermission && (
|
||||
<button
|
||||
@ -70,18 +72,18 @@ const ShortcutActionsDropdown = (props: Props) => {
|
||||
handleDeleteShortcutButtonClick(shortcut);
|
||||
}}
|
||||
>
|
||||
<Icon.Trash className="w-4 h-auto mr-2" /> {t("common.delete")}
|
||||
<Icon.Trash className="w-4 h-auto mr-2 opacity-70" /> {t("common.delete")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
></Dropdown>
|
||||
|
||||
{showEditDialog && (
|
||||
<CreateShortcutDialog
|
||||
{showEditDrawer && (
|
||||
<CreateShortcutDrawer
|
||||
shortcutId={shortcut.id}
|
||||
onClose={() => setShowEditDialog(false)}
|
||||
onConfirm={() => setShowEditDialog(false)}
|
||||
onClose={() => setShowEditDrawer(false)}
|
||||
onConfirm={() => setShowEditDrawer(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
@ -1,12 +1,16 @@
|
||||
import { Tooltip } from "@mui/joy";
|
||||
import { Avatar, Tooltip } from "@mui/joy";
|
||||
import classNames from "classnames";
|
||||
import copy from "copy-to-clipboard";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import { absolutifyLink, getFaviconWithGoogleS2 } from "../helpers/utils";
|
||||
import useViewStore from "../stores/v1/view";
|
||||
import { absolutifyLink } from "@/helpers/utils";
|
||||
import { useUserStore, useViewStore } from "@/stores";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import { convertVisibilityFromPb } from "@/utils/visibility";
|
||||
import Icon from "./Icon";
|
||||
import LinkFavicon from "./LinkFavicon";
|
||||
import ShortcutActionsDropdown from "./ShortcutActionsDropdown";
|
||||
import VisibilityIcon from "./VisibilityIcon";
|
||||
|
||||
@ -17,9 +21,14 @@ interface Props {
|
||||
const ShortcutCard = (props: Props) => {
|
||||
const { shortcut } = props;
|
||||
const { t } = useTranslation();
|
||||
const userStore = useUserStore();
|
||||
const viewStore = useViewStore();
|
||||
const creator = userStore.getUserById(shortcut.creatorId);
|
||||
const shortcutLink = absolutifyLink(`/s/${shortcut.name}`);
|
||||
const favicon = getFaviconWithGoogleS2(shortcut.link);
|
||||
|
||||
useEffect(() => {
|
||||
userStore.getOrFetchUserById(shortcut.creatorId);
|
||||
}, []);
|
||||
|
||||
const handleCopyButtonClick = () => {
|
||||
copy(shortcutLink);
|
||||
@ -27,103 +36,113 @@ const ShortcutCard = (props: Props) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"group px-4 py-3 w-full flex flex-col justify-start items-start border rounded-lg hover:shadow dark:border-zinc-700"
|
||||
)}
|
||||
>
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="w-[calc(100%-16px)] flex flex-row justify-start items-center mr-1 shrink-0">
|
||||
<Link to={`/shortcut/${shortcut.id}`} className={classNames("w-8 h-8 flex justify-center items-center overflow-clip shrink-0")}>
|
||||
{favicon ? (
|
||||
<img className="w-full h-auto rounded-lg" src={favicon} decoding="async" loading="lazy" />
|
||||
) : (
|
||||
<Icon.CircleSlash className="w-full h-auto text-gray-400" />
|
||||
)}
|
||||
</Link>
|
||||
<div className="ml-1 w-[calc(100%-24px)] flex flex-col justify-start items-start">
|
||||
<div className="w-full flex flex-row justify-start items-center">
|
||||
<a
|
||||
className={classNames(
|
||||
"max-w-[calc(100%-36px)] flex flex-row px-1 mr-1 justify-start items-center cursor-pointer rounded-md hover:bg-gray-100 hover:shadow dark:hover:bg-zinc-800"
|
||||
)}
|
||||
target="_blank"
|
||||
href={shortcutLink}
|
||||
>
|
||||
<div className="truncate">
|
||||
<span className="dark:text-gray-400">{shortcut.title}</span>
|
||||
{shortcut.title ? (
|
||||
<span className="text-gray-500">(s/{shortcut.name})</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-gray-400 dark:text-gray-500">s/</span>
|
||||
<span className="truncate dark:text-gray-400">{shortcut.name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<span className="hidden group-hover:block ml-1 cursor-pointer shrink-0">
|
||||
<Icon.ExternalLink className="w-4 h-auto text-gray-600" />
|
||||
</span>
|
||||
</a>
|
||||
<Tooltip title="Copy" variant="solid" placement="top" arrow>
|
||||
<button
|
||||
className="hidden group-hover:block w-6 h-6 cursor-pointer rounded-md text-gray-500 hover:bg-gray-100 hover:shadow dark:hover:bg-zinc-800"
|
||||
onClick={() => handleCopyButtonClick()}
|
||||
>
|
||||
<Icon.Clipboard className="w-4 h-auto mx-auto" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"group px-4 py-3 w-full flex flex-col justify-start items-start border rounded-lg hover:shadow dark:border-zinc-700"
|
||||
)}
|
||||
>
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="w-[calc(100%-16px)] flex flex-row justify-start items-center mr-1 shrink-0">
|
||||
<Link
|
||||
className={classNames("w-8 h-8 flex justify-center items-center overflow-clip shrink-0")}
|
||||
to={`/shortcut/${shortcut.id}`}
|
||||
unstable_viewTransition
|
||||
>
|
||||
<LinkFavicon url={shortcut.link} />
|
||||
</Link>
|
||||
<div className="ml-2 w-[calc(100%-24px)] flex flex-col justify-start items-start">
|
||||
<div className="w-full flex flex-row justify-start items-center leading-tight">
|
||||
<a
|
||||
className="pl-1 pr-4 w-full text-sm truncate text-gray-400 dark:text-gray-500 hover:underline"
|
||||
href={shortcut.link}
|
||||
className={classNames(
|
||||
"max-w-[calc(100%-36px)] flex flex-row justify-start items-center mr-1 cursor-pointer hover:opacity-80 hover:underline"
|
||||
)}
|
||||
target="_blank"
|
||||
href={shortcutLink}
|
||||
>
|
||||
{shortcut.link}
|
||||
<div className="truncate">
|
||||
<span className="dark:text-gray-400">{shortcut.title}</span>
|
||||
{shortcut.title ? (
|
||||
<span className="text-gray-500">({shortcut.name})</span>
|
||||
) : (
|
||||
<span className="truncate dark:text-gray-400">{shortcut.name}</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="hidden group-hover:block ml-1 cursor-pointer shrink-0">
|
||||
<Icon.ExternalLink className="w-4 h-auto text-gray-600" />
|
||||
</span>
|
||||
</a>
|
||||
<Tooltip title="Copy" variant="solid" placement="top" arrow>
|
||||
<button
|
||||
className="hidden group-hover:block cursor-pointer text-gray-500 hover:opacity-80"
|
||||
onClick={() => handleCopyButtonClick()}
|
||||
>
|
||||
<Icon.Clipboard className="w-4 h-auto mx-auto" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-full pt-2 flex flex-row justify-end items-start">
|
||||
<ShortcutActionsDropdown shortcut={shortcut} />
|
||||
<a
|
||||
className="pr-4 leading-tight w-full text-sm truncate text-gray-400 dark:text-gray-500 hover:underline"
|
||||
href={shortcut.link}
|
||||
target="_blank"
|
||||
>
|
||||
{shortcut.link}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 w-full flex flex-row justify-start items-start gap-2 truncate">
|
||||
{shortcut.tags.map((tag) => {
|
||||
return (
|
||||
<span
|
||||
key={tag}
|
||||
className="max-w-[8rem] truncate text-gray-400 dark:text-gray-500 text-sm leading-4 cursor-pointer hover:opacity-80"
|
||||
onClick={() => viewStore.setFilter({ tag: tag })}
|
||||
>
|
||||
#{tag}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{shortcut.tags.length === 0 && <span className="text-gray-400 text-sm leading-4 italic">No tags</span>}
|
||||
</div>
|
||||
<div className="w-full flex mt-2 gap-2 overflow-x-auto">
|
||||
<Tooltip title={t(`shortcut.visibility.${shortcut.visibility.toLowerCase()}.description`)} variant="solid" placement="top" arrow>
|
||||
<div
|
||||
className="w-auto px-2 leading-6 flex flex-row justify-start items-center flex-nowrap whitespace-nowrap border rounded-full cursor-pointer text-gray-500 dark:text-gray-400 text-sm dark:border-zinc-700"
|
||||
onClick={() => viewStore.setFilter({ visibility: shortcut.visibility })}
|
||||
>
|
||||
<VisibilityIcon className="w-4 h-auto mr-1 opacity-60" visibility={shortcut.visibility} />
|
||||
{t(`shortcut.visibility.${shortcut.visibility.toLowerCase()}.self`)}
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title="View count" variant="solid" placement="top" arrow>
|
||||
<Link
|
||||
to={`/shortcut/${shortcut.id}#analytics`}
|
||||
className="w-auto px-2 leading-6 flex flex-row justify-start items-center flex-nowrap whitespace-nowrap border rounded-full cursor-pointer text-gray-500 dark:text-gray-400 text-sm dark:border-zinc-700"
|
||||
>
|
||||
<Icon.BarChart2 className="w-4 h-auto mr-1 opacity-80" />
|
||||
{t("shortcut.visits", { count: shortcut.view })}
|
||||
</Link>
|
||||
</Tooltip>
|
||||
<div className="h-full pt-2 flex flex-row justify-end items-start">
|
||||
<ShortcutActionsDropdown shortcut={shortcut} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
<div className="mt-2 w-full flex flex-row justify-start items-start gap-2 truncate">
|
||||
{shortcut.tags.map((tag) => {
|
||||
return (
|
||||
<span
|
||||
key={tag}
|
||||
className="max-w-[8rem] truncate text-gray-400 dark:text-gray-500 text-sm leading-4 cursor-pointer hover:opacity-80"
|
||||
onClick={() => viewStore.setFilter({ tag: tag })}
|
||||
>
|
||||
#{tag}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{shortcut.tags.length === 0 && <span className="text-gray-400 text-sm leading-4 italic">No tags</span>}
|
||||
</div>
|
||||
<div className="w-full mt-2 flex gap-2 overflow-x-auto">
|
||||
<Tooltip title={creator.nickname} variant="solid" placement="top" arrow>
|
||||
<Avatar
|
||||
className="dark:bg-zinc-800"
|
||||
sx={{
|
||||
"--Avatar-size": "24px",
|
||||
}}
|
||||
alt={creator.nickname.toUpperCase()}
|
||||
></Avatar>
|
||||
</Tooltip>
|
||||
<Tooltip
|
||||
title={t(`shortcut.visibility.${convertVisibilityFromPb(shortcut.visibility).toLowerCase()}.description`)}
|
||||
variant="solid"
|
||||
placement="top"
|
||||
arrow
|
||||
>
|
||||
<div
|
||||
className="w-auto leading-5 flex flex-row justify-start items-center flex-nowrap whitespace-nowrap cursor-pointer text-gray-400 text-sm"
|
||||
onClick={() => viewStore.setFilter({ visibility: shortcut.visibility })}
|
||||
>
|
||||
<VisibilityIcon className="w-4 h-auto mr-1 opacity-70" visibility={shortcut.visibility} />
|
||||
{t(`shortcut.visibility.${convertVisibilityFromPb(shortcut.visibility).toLowerCase()}.self`)}
|
||||
</div>
|
||||
</Tooltip>
|
||||
<Tooltip title="View count" variant="solid" placement="top" arrow>
|
||||
<Link
|
||||
className="w-auto leading-5 flex flex-row justify-start items-center flex-nowrap whitespace-nowrap cursor-pointer text-gray-400 text-sm"
|
||||
to={`/shortcut/${shortcut.id}#analytics`}
|
||||
unstable_viewTransition
|
||||
>
|
||||
<Icon.BarChart2 className="w-4 h-auto mr-1 opacity-70" />
|
||||
{t("shortcut.visits", { count: shortcut.viewCount })}
|
||||
</Link>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
35
frontend/web/src/components/ShortcutFrame.tsx
Normal file
@ -0,0 +1,35 @@
|
||||
import { Divider } from "@mui/joy";
|
||||
import classNames from "classnames";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import Icon from "./Icon";
|
||||
import LinkFavicon from "./LinkFavicon";
|
||||
|
||||
interface Props {
|
||||
shortcut: Shortcut;
|
||||
}
|
||||
|
||||
const ShortcutFrame = ({ shortcut }: Props) => {
|
||||
return (
|
||||
<div className="w-full h-full flex flex-col justify-center items-center p-8">
|
||||
<Link
|
||||
className="w-72 max-w-full border dark:border-zinc-900 dark:bg-zinc-900 p-6 pb-4 rounded-2xl shadow-xl dark:text-gray-400 hover:opacity-80"
|
||||
to={`/s/${shortcut.name}`}
|
||||
target="_blank"
|
||||
>
|
||||
<div className={classNames("w-12 h-12 flex justify-center items-center overflow-clip rounded-lg shrink-0")}>
|
||||
<LinkFavicon url={shortcut.link} />
|
||||
</div>
|
||||
<p className="text-lg font-medium leading-8 mt-2 truncate">{shortcut.title || shortcut.name}</p>
|
||||
<p className="text-gray-500 truncate">{shortcut.description}</p>
|
||||
<Divider className="!my-2" />
|
||||
<p className="text-gray-400 dark:text-gray-600 text-sm mt-2">
|
||||
<span className="leading-4">Open this site in a new tab</span>
|
||||
<Icon.ArrowUpRight className="inline-block ml-1 -mt-0.5 w-4 h-auto" />
|
||||
</p>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ShortcutFrame;
|
@ -1,7 +1,8 @@
|
||||
import classNames from "classnames";
|
||||
import { Link } from "react-router-dom";
|
||||
import { getFaviconWithGoogleS2 } from "../helpers/utils";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import Icon from "./Icon";
|
||||
import LinkFavicon from "./LinkFavicon";
|
||||
import ShortcutActionsDropdown from "./ShortcutActionsDropdown";
|
||||
|
||||
interface Props {
|
||||
@ -14,7 +15,6 @@ interface Props {
|
||||
|
||||
const ShortcutView = (props: Props) => {
|
||||
const { shortcut, className, showActions, alwaysShowLink, onClick } = props;
|
||||
const favicon = getFaviconWithGoogleS2(shortcut.link);
|
||||
|
||||
return (
|
||||
<div
|
||||
@ -25,21 +25,16 @@ const ShortcutView = (props: Props) => {
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className={classNames("w-5 h-5 flex justify-center items-center overflow-clip shrink-0")}>
|
||||
{favicon ? (
|
||||
<img className="w-full h-auto rounded-lg" src={favicon} decoding="async" loading="lazy" />
|
||||
) : (
|
||||
<Icon.CircleSlash className="w-full h-auto text-gray-400" />
|
||||
)}
|
||||
<LinkFavicon url={shortcut.link} />
|
||||
</div>
|
||||
<div className="ml-2 w-full truncate">
|
||||
{shortcut.title ? (
|
||||
<>
|
||||
<span className="dark:text-gray-400">{shortcut.title}</span>
|
||||
<span className="text-gray-500">(s/{shortcut.name})</span>
|
||||
<span className="text-gray-500">({shortcut.name})</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-gray-400 dark:text-gray-500">s/</span>
|
||||
<span className="dark:text-gray-400">{shortcut.name}</span>
|
||||
</>
|
||||
)}
|
||||
|
@ -1,6 +1,7 @@
|
||||
import classNames from "classnames";
|
||||
import { absolutifyLink } from "@/helpers/utils";
|
||||
import useViewStore from "../stores/v1/view";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
import { useViewStore } from "@/stores";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
import ShortcutCard from "./ShortcutCard";
|
||||
import ShortcutView from "./ShortcutView";
|
||||
|
||||
@ -10,12 +11,13 @@ interface Props {
|
||||
|
||||
const ShortcutsContainer: React.FC<Props> = (props: Props) => {
|
||||
const { shortcutList } = props;
|
||||
const navigateTo = useNavigateTo();
|
||||
const viewStore = useViewStore();
|
||||
const displayStyle = viewStore.displayStyle || "full";
|
||||
const ShortcutItemView = viewStore.displayStyle === "compact" ? ShortcutView : ShortcutCard;
|
||||
|
||||
const handleShortcutClick = (shortcut: Shortcut) => {
|
||||
window.open(absolutifyLink(`/s/${shortcut.name}`));
|
||||
navigateTo(`/shortcut/${shortcut.id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
|
@ -1,13 +1,12 @@
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppSelector } from "../stores";
|
||||
import useViewStore from "../stores/v1/view";
|
||||
import { useShortcutStore, useViewStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
|
||||
const ShortcutsNavigator = () => {
|
||||
const { t } = useTranslation();
|
||||
const viewStore = useViewStore();
|
||||
const { shortcutList } = useAppSelector((state) => state.shortcut);
|
||||
const shortcutList = useShortcutStore().getShortcutList();
|
||||
const tags = shortcutList.map((shortcut) => shortcut.tags).flat();
|
||||
const currentTab = viewStore.filter.tab || `tab:all`;
|
||||
const sortedTagMap = sortTags(tags);
|
||||
@ -18,7 +17,7 @@ const ShortcutsNavigator = () => {
|
||||
className={classNames(
|
||||
"flex flex-row justify-center items-center px-2 leading-7 text-sm dark:text-gray-400 rounded-md",
|
||||
currentTab === "tab:all"
|
||||
? "bg-gray-600 dark:bg-zinc-700 text-white dark:text-gray-400 shadow"
|
||||
? "bg-blue-700 dark:bg-blue-800 text-white dark:text-gray-400 shadow"
|
||||
: "hover:bg-gray-200 dark:hover:bg-zinc-700"
|
||||
)}
|
||||
onClick={() => viewStore.setFilter({ tab: "tab:all" })}
|
||||
@ -30,7 +29,7 @@ const ShortcutsNavigator = () => {
|
||||
className={classNames(
|
||||
"flex flex-row justify-center items-center px-2 leading-7 text-sm dark:text-gray-400 rounded-md",
|
||||
currentTab === "tab:mine"
|
||||
? "bg-gray-600 dark:bg-zinc-700 text-white dark:text-gray-400 shadow"
|
||||
? "bg-blue-700 dark:bg-blue-800 text-white dark:text-gray-400 shadow"
|
||||
: "hover:bg-gray-200 dark:hover:bg-zinc-700"
|
||||
)}
|
||||
onClick={() => viewStore.setFilter({ tab: "tab:mine" })}
|
||||
@ -44,7 +43,7 @@ const ShortcutsNavigator = () => {
|
||||
className={classNames(
|
||||
"flex flex-row justify-center items-center px-2 leading-7 text-sm dark:text-gray-400 rounded-md",
|
||||
currentTab === `tag:${tag}`
|
||||
? "bg-gray-600 dark:bg-zinc-700 text-white dark:text-gray-400 shadow"
|
||||
? "bg-blue-700 dark:bg-blue-800 text-white dark:text-gray-400 shadow"
|
||||
: "hover:bg-gray-200 dark:hover:bg-zinc-700"
|
||||
)}
|
||||
onClick={() => viewStore.setFilter({ tab: `tag:${tag}`, tag: undefined })}
|
||||
|
@ -11,18 +11,25 @@ const SubscriptionFAQ = () => {
|
||||
<Accordion>
|
||||
<AccordionSummary>Can I use the Free plan in my team?</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
Of course you can. In the free plan, you can invite up to 5 members to your team. If you need more, you can upgrade to the Pro
|
||||
plan.
|
||||
Of course you can. In the free plan, you can invite up to 5 members to your team. If you need more, you should upgrade to the
|
||||
Pro plan.
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
<Accordion>
|
||||
<AccordionSummary>How many devices can the license key be used on?</AccordionSummary>
|
||||
<AccordionDetails>{`It's unlimited for now, but please don't abuse it.`}</AccordionDetails>
|
||||
<AccordionDetails>{`It's unlimited for now, but please do not abuse it.`}</AccordionDetails>
|
||||
</Accordion>
|
||||
<Accordion>
|
||||
<AccordionSummary>{`Can I get a refund if Slash doesn't meet my needs?`}</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
Yes, absolutely! You can send a email to me at `yourselfhosted@gmail.com`. I will refund you as soon as possible.
|
||||
Yes, absolutely! You can contact us with `yourselfhosted@gmail.com`. I will refund you as soon as possible.
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
<Accordion>
|
||||
<AccordionSummary>Is there a Lifetime license?</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
{`As software requires someone to maintain it, so we won't sell a lifetime service, since humans are not immortal yet. But if you
|
||||
really want it, please contact us "yourselfhosted@gmail.com".`}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { Divider, Option, Select, Switch } from "@mui/joy";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useViewStore from "../stores/v1/view";
|
||||
import { useViewStore } from "@/stores";
|
||||
import Icon from "./Icon";
|
||||
import Dropdown from "./common/Dropdown";
|
||||
|
||||
@ -18,7 +18,7 @@ const ViewSetting = () => {
|
||||
<Icon.Settings2 className="w-4 h-auto text-gray-500" />
|
||||
</button>
|
||||
}
|
||||
actionsClassName="!mt-3 !-right-2"
|
||||
actionsClassName="!mt-3 !right-[unset] -left-24 -ml-2"
|
||||
actions={
|
||||
<div className="w-52 p-2 gap-2 flex flex-col justify-start items-start" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { Visibility } from "@/types/proto/api/v1/common";
|
||||
import Icon from "./Icon";
|
||||
|
||||
interface Props {
|
||||
@ -7,11 +8,11 @@ interface Props {
|
||||
|
||||
const VisibilityIcon = (props: Props) => {
|
||||
const { visibility, className } = props;
|
||||
if (visibility === "PRIVATE") {
|
||||
if (visibility === Visibility.PRIVATE) {
|
||||
return <Icon.Lock className={className || ""} />;
|
||||
} else if (visibility === "WORKSPACE") {
|
||||
} else if (visibility === Visibility.WORKSPACE) {
|
||||
return <Icon.Building2 className={className || ""} />;
|
||||
} else if (visibility === "PUBLIC") {
|
||||
} else if (visibility === Visibility.PUBLIC) {
|
||||
return <Icon.Globe2 className={className || ""} />;
|
||||
}
|
||||
return null;
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { ReactNode, useEffect, useRef, useState } from "react";
|
||||
import Icon from "../Icon";
|
||||
import Icon from "@/components/Icon";
|
||||
|
||||
interface Props {
|
||||
trigger?: ReactNode;
|
||||
|
@ -3,12 +3,12 @@ import copy from "copy-to-clipboard";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { showCommonDialog } from "@/components/Alert";
|
||||
import CreateAccessTokenDialog from "@/components/CreateAccessTokenDialog";
|
||||
import Icon from "@/components/Icon";
|
||||
import { userServiceClient } from "@/grpcweb";
|
||||
import { UserAccessToken } from "@/types/proto/api/v2/user_service";
|
||||
import useUserStore from "../../stores/v1/user";
|
||||
import { showCommonDialog } from "../Alert";
|
||||
import CreateAccessTokenDialog from "../CreateAccessTokenDialog";
|
||||
import Icon from "../Icon";
|
||||
import { useUserStore } from "@/stores";
|
||||
import { UserAccessToken } from "@/types/proto/api/v1/user_service";
|
||||
|
||||
const listAccessTokens = async (userId: number) => {
|
||||
const { accessTokens } = await userServiceClient.listUserAccessTokens({
|
||||
@ -64,7 +64,7 @@ const AccessTokenSection = () => {
|
||||
<div className="w-full">
|
||||
<div className="sm:flex sm:items-center">
|
||||
<div className="sm:flex-auto">
|
||||
<p className="text-base font-semibold leading-6 text-gray-900 dark:text-gray-500">Access Tokens</p>
|
||||
<p className="text-2xl shrink-0 font-semibold text-gray-900 dark:text-gray-500">Access Tokens</p>
|
||||
<p className="mt-2 text-sm text-gray-700 dark:text-gray-600">A list of all access tokens for your account.</p>
|
||||
</div>
|
||||
<div className="mt-4 sm:ml-16 sm:mt-0 sm:flex-none">
|
||||
|
@ -1,21 +1,22 @@
|
||||
import { Button } from "@mui/joy";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useUserStore from "../../stores/v1/user";
|
||||
import ChangePasswordDialog from "../ChangePasswordDialog";
|
||||
import EditUserinfoDialog from "../EditUserinfoDialog";
|
||||
import ChangePasswordDialog from "@/components/ChangePasswordDialog";
|
||||
import EditUserinfoDialog from "@/components/EditUserinfoDialog";
|
||||
import { useUserStore } from "@/stores";
|
||||
import { Role } from "@/types/proto/api/v1/user_service";
|
||||
|
||||
const AccountSection: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const currentUser = useUserStore().getCurrentUser();
|
||||
const [showEditUserinfoDialog, setShowEditUserinfoDialog] = useState<boolean>(false);
|
||||
const [showChangePasswordDialog, setShowChangePasswordDialog] = useState<boolean>(false);
|
||||
const isAdmin = currentUser.role === "ADMIN";
|
||||
const isAdmin = currentUser.role === Role.ADMIN;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full flex flex-col justify-start items-start gap-y-2">
|
||||
<p className="text-base font-semibold leading-6 text-gray-900 dark:text-gray-500">{t("common.account")}</p>
|
||||
<p className="text-2xl shrink-0 font-semibold text-gray-900 dark:text-gray-500">{t("common.account")}</p>
|
||||
<p className="flex flex-row justify-start items-center mt-2 dark:text-gray-400">
|
||||
<span className="text-xl">{currentUser.nickname}</span>
|
||||
{isAdmin && <span className="ml-2 bg-blue-600 text-white px-2 leading-6 text-sm rounded-full">Admin</span>}
|
||||
|
@ -2,10 +2,12 @@ import { Button, IconButton } from "@mui/joy";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useUserStore from "../../stores/v1/user";
|
||||
import { showCommonDialog } from "../Alert";
|
||||
import CreateUserDialog from "../CreateUserDialog";
|
||||
import Icon from "../Icon";
|
||||
import { showCommonDialog } from "@/components/Alert";
|
||||
import CreateUserDialog from "@/components/CreateUserDialog";
|
||||
import Icon from "@/components/Icon";
|
||||
import { useUserStore } from "@/stores";
|
||||
import { User } from "@/types/proto/api/v1/user_service";
|
||||
import { convertRoleFromPb } from "@/utils/user";
|
||||
|
||||
const MemberSection = () => {
|
||||
const { t } = useTranslation();
|
||||
@ -33,7 +35,7 @@ const MemberSection = () => {
|
||||
await userStore.deleteUser(user.id);
|
||||
toast.success(`User \`${user.nickname}\` deleted successfully`);
|
||||
} catch (error: any) {
|
||||
toast.error(`Failed to delete user \`${user.nickname}\`: ${error.response.data.message}`);
|
||||
toast.error(`Failed to delete user \`${user.nickname}\`: ${error.details}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
@ -45,7 +47,7 @@ const MemberSection = () => {
|
||||
<div className="w-full">
|
||||
<div className="sm:flex sm:items-center">
|
||||
<div className="sm:flex-auto">
|
||||
<p className="text-base font-semibold leading-6 text-gray-900 dark:text-gray-500">{t("user.self")}</p>
|
||||
<p className="text-2xl shrink-0 font-semibold text-gray-900 dark:text-gray-500">{t("user.self")}</p>
|
||||
<p className="mt-2 text-sm text-gray-700 dark:text-gray-600">
|
||||
A list of all the users in your workspace including their nickname, email and role.
|
||||
</p>
|
||||
@ -88,7 +90,7 @@ const MemberSection = () => {
|
||||
<tr key={user.email}>
|
||||
<td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm text-gray-900 dark:text-gray-500">{user.nickname}</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{user.email}</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{user.role}</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">{convertRoleFromPb(user.role)}</td>
|
||||
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm">
|
||||
<IconButton
|
||||
size="sm"
|
||||
|
@ -1,8 +1,8 @@
|
||||
import { Option, Select } from "@mui/joy";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { UserSetting, UserSetting_ColorTheme, UserSetting_Locale } from "@/types/proto/api/v2/user_setting_service";
|
||||
import useUserStore from "../../stores/v1/user";
|
||||
import BetaBadge from "../BetaBadge";
|
||||
import BetaBadge from "@/components/BetaBadge";
|
||||
import { useUserStore } from "@/stores";
|
||||
import { UserSetting, UserSetting_ColorTheme, UserSetting_Locale } from "@/types/proto/api/v1/user_setting_service";
|
||||
|
||||
const PreferenceSection: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@ -58,9 +58,9 @@ const PreferenceSection: React.FC = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full flex flex-col justify-start items-start gap-y-2">
|
||||
<p className="text-base font-semibold leading-6 text-gray-900 dark:text-gray-500">{t("settings.preference.self")}</p>
|
||||
<div className="w-full flex flex-col sm:flex-row justify-start items-start gap-4 sm:gap-x-16">
|
||||
<p className="sm:w-1/4 text-2xl shrink-0 font-semibold text-gray-900 dark:text-gray-500">{t("settings.preference.self")}</p>
|
||||
<div className="w-full sm:w-auto grow flex flex-col justify-start items-start gap-4">
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="flex flex-row justify-start items-center gap-x-1">
|
||||
<span className="dark:text-gray-400">{t("settings.preference.color-theme")}</span>
|
||||
@ -91,7 +91,7 @@ const PreferenceSection: React.FC = () => {
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -1,13 +1,14 @@
|
||||
import { Button, Checkbox, Textarea } from "@mui/joy";
|
||||
import { Button, Input, Select, Textarea, Option, Switch, Link } from "@mui/joy";
|
||||
import { isEqual } from "lodash-es";
|
||||
import { useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { workspaceServiceClient } from "@/grpcweb";
|
||||
import useWorkspaceStore from "@/stores/v1/workspace";
|
||||
import { WorkspaceSetting } from "@/types/proto/api/v2/workspace_service";
|
||||
import { useWorkspaceStore } from "@/stores";
|
||||
import { Visibility } from "@/types/proto/api/v1/common";
|
||||
import { WorkspaceSetting } from "@/types/proto/api/v1/workspace_service";
|
||||
|
||||
const WorkspaceSection: React.FC = () => {
|
||||
const WorkspaceSection = () => {
|
||||
const { t } = useTranslation();
|
||||
const workspaceStore = useWorkspaceStore();
|
||||
const [workspaceSetting, setWorkspaceSetting] = useState<WorkspaceSetting>(workspaceStore.setting);
|
||||
@ -21,6 +22,20 @@ const WorkspaceSection: React.FC = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const handleInstanceUrlChange = async (value: string) => {
|
||||
setWorkspaceSetting({
|
||||
...workspaceSetting,
|
||||
instanceUrl: value,
|
||||
});
|
||||
};
|
||||
|
||||
const handleFaviconProvierChange = async (value: string) => {
|
||||
setWorkspaceSetting({
|
||||
...workspaceSetting,
|
||||
faviconProvider: value,
|
||||
});
|
||||
};
|
||||
|
||||
const handleCustomStyleChange = async (value: string) => {
|
||||
setWorkspaceSetting({
|
||||
...workspaceSetting,
|
||||
@ -28,14 +43,30 @@ const WorkspaceSection: React.FC = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const handleDefaultVisibilityChange = async (value: Visibility) => {
|
||||
setWorkspaceSetting({
|
||||
...workspaceSetting,
|
||||
defaultVisibility: value,
|
||||
});
|
||||
};
|
||||
|
||||
const handleSaveWorkspaceSetting = async () => {
|
||||
const updateMask: string[] = [];
|
||||
if (!isEqual(originalWorkspaceSetting.current.enableSignup, workspaceSetting.enableSignup)) {
|
||||
updateMask.push("enable_signup");
|
||||
}
|
||||
if (!isEqual(originalWorkspaceSetting.current.instanceUrl, workspaceSetting.instanceUrl)) {
|
||||
updateMask.push("instance_url");
|
||||
}
|
||||
if (!isEqual(originalWorkspaceSetting.current.customStyle, workspaceSetting.customStyle)) {
|
||||
updateMask.push("custom_style");
|
||||
}
|
||||
if (!isEqual(originalWorkspaceSetting.current.defaultVisibility, workspaceSetting.defaultVisibility)) {
|
||||
updateMask.push("default_visibility");
|
||||
}
|
||||
if (!isEqual(originalWorkspaceSetting.current.faviconProvider, workspaceSetting.faviconProvider)) {
|
||||
updateMask.push("favicon_provider");
|
||||
}
|
||||
if (updateMask.length === 0) {
|
||||
toast.error("No changes made");
|
||||
return;
|
||||
@ -49,6 +80,7 @@ const WorkspaceSection: React.FC = () => {
|
||||
})
|
||||
).setting as WorkspaceSetting;
|
||||
setWorkspaceSetting(setting);
|
||||
await workspaceStore.fetchWorkspaceSetting();
|
||||
originalWorkspaceSetting.current = setting;
|
||||
toast.success("Workspace setting saved successfully");
|
||||
} catch (error: any) {
|
||||
@ -57,31 +89,75 @@ const WorkspaceSection: React.FC = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-start items-start space-y-4">
|
||||
<p className="text-base font-semibold leading-6 text-gray-900 dark:text-gray-500">{t("settings.workspace.self")}</p>
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<p className="mt-2 dark:text-gray-400">{t("settings.workspace.custom-style")}</p>
|
||||
<Textarea
|
||||
className="w-full mt-2"
|
||||
placeholder="* {font-family: ui-monospace Monaco Consolas;}"
|
||||
minRows={2}
|
||||
maxRows={5}
|
||||
value={workspaceSetting.customStyle}
|
||||
onChange={(event) => handleCustomStyleChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<Checkbox
|
||||
label={t("settings.workspace.enable-user-signup.self")}
|
||||
checked={workspaceSetting.enableSignup}
|
||||
onChange={(event) => handleEnableSignUpChange(event.target.checked)}
|
||||
/>
|
||||
<p className="mt-2 text-gray-500">{t("settings.workspace.enable-user-signup.description")}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button variant="outlined" color="neutral" disabled={!allowSave} onClick={handleSaveWorkspaceSetting}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
<div className="w-full flex flex-col sm:flex-row justify-start items-start gap-4 sm:gap-x-16">
|
||||
<p className="sm:w-1/4 text-2xl shrink-0 font-semibold text-gray-900 dark:text-gray-500">{t("settings.workspace.self")}</p>
|
||||
<div className="w-full sm:w-auto grow flex flex-col justify-start items-start gap-4">
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<p className="font-medium dark:text-gray-400">Instance URL</p>
|
||||
<Input
|
||||
className="w-full mt-2"
|
||||
placeholder="Your instance URL. Using for website SEO. Leave it empty if you don't want cawler to index your website."
|
||||
value={workspaceSetting.instanceUrl}
|
||||
onChange={(event) => handleInstanceUrlChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<p className="font-medium dark:text-gray-400">Favicon Provider</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
e.g.{" "}
|
||||
<Link className="!text-sm" href="https://github.com/yourselfhosted/favicons" target="_blank">
|
||||
yourselfhosted/favicons
|
||||
</Link>
|
||||
</p>
|
||||
<Input
|
||||
className="w-full mt-2"
|
||||
placeholder="The provider of favicon. Empty for default Google S2."
|
||||
value={workspaceSetting.faviconProvider}
|
||||
onChange={(event) => handleFaviconProvierChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<p className="mt-2 font-medium dark:text-gray-400">{t("settings.workspace.custom-style")}</p>
|
||||
<Textarea
|
||||
className="w-full mt-2"
|
||||
placeholder="* {font-family: ui-monospace Monaco Consolas;}"
|
||||
minRows={2}
|
||||
maxRows={5}
|
||||
value={workspaceSetting.customStyle}
|
||||
onChange={(event) => handleCustomStyleChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="w-full flex flex-col justify-start items-start">
|
||||
<p className="font-medium">{t("settings.workspace.enable-user-signup.self")}</p>
|
||||
<p className="text-gray-500">{t("settings.workspace.enable-user-signup.description")}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
size="lg"
|
||||
checked={workspaceSetting.enableSignup}
|
||||
onChange={(event) => handleEnableSignUpChange(event.target.checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-full flex flex-row justify-between items-center">
|
||||
<div className="flex flex-row justify-start items-center gap-x-1">
|
||||
<span className="font-medium dark:text-gray-400">{t("settings.workspace.default-visibility")}</span>
|
||||
</div>
|
||||
<Select
|
||||
defaultValue={workspaceSetting.defaultVisibility || Visibility.PRIVATE}
|
||||
onChange={(_, value) => handleDefaultVisibilityChange(value as Visibility)}
|
||||
>
|
||||
<Option value={Visibility.PRIVATE}>{t(`shortcut.visibility.private.self`)}</Option>
|
||||
<Option value={Visibility.WORKSPACE}>{t(`shortcut.visibility.workspace.self`)}</Option>
|
||||
<Option value={Visibility.PUBLIC}>{t(`shortcut.visibility.public.self`)}</Option>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Button variant="outlined" color="neutral" disabled={!allowSave} onClick={handleSaveWorkspaceSetting}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
3
frontend/web/src/css/joy-ui.css
Normal file
@ -0,0 +1,3 @@
|
||||
.MuiDrawer-content {
|
||||
@apply !w-auto;
|
||||
}
|
@ -1,10 +1,11 @@
|
||||
import { createChannel, createClientFactory, FetchTransport } from "nice-grpc-web";
|
||||
import { CollectionServiceDefinition } from "./types/proto/api/v2/collection_service";
|
||||
import { ShortcutServiceDefinition } from "./types/proto/api/v2/shortcut_service";
|
||||
import { SubscriptionServiceDefinition } from "./types/proto/api/v2/subscription_service";
|
||||
import { UserServiceDefinition } from "./types/proto/api/v2/user_service";
|
||||
import { UserSettingServiceDefinition } from "./types/proto/api/v2/user_setting_service";
|
||||
import { WorkspaceServiceDefinition } from "./types/proto/api/v2/workspace_service";
|
||||
import { AuthServiceDefinition } from "./types/proto/api/v1/auth_service";
|
||||
import { CollectionServiceDefinition } from "./types/proto/api/v1/collection_service";
|
||||
import { ShortcutServiceDefinition } from "./types/proto/api/v1/shortcut_service";
|
||||
import { SubscriptionServiceDefinition } from "./types/proto/api/v1/subscription_service";
|
||||
import { UserServiceDefinition } from "./types/proto/api/v1/user_service";
|
||||
import { UserSettingServiceDefinition } from "./types/proto/api/v1/user_setting_service";
|
||||
import { WorkspaceServiceDefinition } from "./types/proto/api/v1/workspace_service";
|
||||
|
||||
const address = import.meta.env.MODE === "development" ? "http://localhost:8082" : window.location.origin;
|
||||
|
||||
@ -17,9 +18,11 @@ const channel = createChannel(
|
||||
|
||||
const clientFactory = createClientFactory();
|
||||
|
||||
export const workspaceServiceClient = clientFactory.create(WorkspaceServiceDefinition, channel);
|
||||
|
||||
export const subscriptionServiceClient = clientFactory.create(SubscriptionServiceDefinition, channel);
|
||||
|
||||
export const workspaceServiceClient = clientFactory.create(WorkspaceServiceDefinition, channel);
|
||||
export const authServiceClient = clientFactory.create(AuthServiceDefinition, channel);
|
||||
|
||||
export const userServiceClient = clientFactory.create(UserServiceDefinition, channel);
|
||||
|
||||
|
@ -1,73 +0,0 @@
|
||||
import axios from "axios";
|
||||
import { userServiceClient } from "@/grpcweb";
|
||||
|
||||
export function signin(email: string, password: string) {
|
||||
return axios.post<User>("/api/v1/auth/signin", {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
}
|
||||
|
||||
export function signup(email: string, nickname: string, password: string) {
|
||||
return axios.post<User>("/api/v1/auth/signup", {
|
||||
email,
|
||||
nickname,
|
||||
password,
|
||||
});
|
||||
}
|
||||
|
||||
export function signout() {
|
||||
return axios.post("/api/v1/auth/logout");
|
||||
}
|
||||
|
||||
export function getMyselfUser() {
|
||||
return axios.get<User>("/api/v1/user/me");
|
||||
}
|
||||
|
||||
export function getUserList() {
|
||||
return axios.get<User[]>("/api/v1/user");
|
||||
}
|
||||
|
||||
export function getUserById(id: number) {
|
||||
return axios.get<User>(`/api/v1/user/${id}`);
|
||||
}
|
||||
|
||||
export function createUser(userCreate: UserCreate) {
|
||||
return axios.post<User>("/api/v1/user", userCreate);
|
||||
}
|
||||
|
||||
export function patchUser(userPatch: UserPatch) {
|
||||
return axios.patch<User>(`/api/v1/user/${userPatch.id}`, userPatch);
|
||||
}
|
||||
|
||||
export function deleteUser(userId: UserId) {
|
||||
return userServiceClient.deleteUser({ id: userId });
|
||||
}
|
||||
|
||||
export function getShortcutList(shortcutFind?: ShortcutFind) {
|
||||
const queryList = [];
|
||||
if (shortcutFind?.tag) {
|
||||
queryList.push(`tag=${shortcutFind.tag}`);
|
||||
}
|
||||
return axios.get<Shortcut[]>(`/api/v1/shortcut?${queryList.join("&")}`);
|
||||
}
|
||||
|
||||
export function getShortcutById(id: number) {
|
||||
return axios.get<Shortcut>(`/api/v1/shortcut/${id}`);
|
||||
}
|
||||
|
||||
export function createShortcut(shortcutCreate: ShortcutCreate) {
|
||||
return axios.post<Shortcut>("/api/v1/shortcut", shortcutCreate);
|
||||
}
|
||||
|
||||
export function getShortcutAnalytics(shortcutId: ShortcutId) {
|
||||
return axios.get<AnalysisData>(`/api/v1/shortcut/${shortcutId}/analytics`);
|
||||
}
|
||||
|
||||
export function patchShortcut(shortcutPatch: ShortcutPatch) {
|
||||
return axios.patch<Shortcut>(`/api/v1/shortcut/${shortcutPatch.id}`, shortcutPatch);
|
||||
}
|
||||
|
||||
export function deleteShortcutById(shortcutId: ShortcutId) {
|
||||
return axios.delete(`/api/v1/shortcut/${shortcutId}`);
|
||||
}
|
@ -1,24 +1,20 @@
|
||||
import { isNull, isUndefined } from "lodash-es";
|
||||
|
||||
export const isNullorUndefined = (value: any) => {
|
||||
return isNull(value) || isUndefined(value);
|
||||
};
|
||||
|
||||
export const absolutifyLink = (rel: string): string => {
|
||||
const anchor = document.createElement("a");
|
||||
anchor.setAttribute("href", rel);
|
||||
return anchor.href;
|
||||
};
|
||||
|
||||
export const releaseGuard = () => {
|
||||
return import.meta.env.MODE === "development";
|
||||
export const isURL = (str: string): boolean => {
|
||||
const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
|
||||
return urlRegex.test(str);
|
||||
};
|
||||
|
||||
export const getFaviconWithGoogleS2 = (url: string) => {
|
||||
try {
|
||||
const urlObject = new URL(url);
|
||||
return `https://www.google.com/s2/favicons?sz=128&domain=${urlObject.hostname}`;
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
export const generateRandomString = () => {
|
||||
const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let randomString = "";
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const randomIndex = Math.floor(Math.random() * characters.length);
|
||||
randomString += characters.charAt(randomIndex);
|
||||
}
|
||||
return randomString;
|
||||
};
|
||||
|
@ -3,11 +3,11 @@ import { isEqual } from "lodash-es";
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Outlet } from "react-router-dom";
|
||||
import Header from "@/components/Header";
|
||||
import Navigator from "@/components/Navigator";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
import { UserSetting_ColorTheme, UserSetting_Locale } from "@/types/proto/api/v2/user_setting_service";
|
||||
import Header from "../components/Header";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import { useUserStore } from "@/stores";
|
||||
import { UserSetting_ColorTheme, UserSetting_Locale } from "@/types/proto/api/v1/user_setting_service";
|
||||
|
||||
const Root: React.FC = () => {
|
||||
const navigateTo = useNavigateTo();
|
||||
@ -51,15 +51,13 @@ const Root: React.FC = () => {
|
||||
}, [currentUserSetting]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isInitialized && (
|
||||
<div className="w-full h-auto flex flex-col justify-start items-start dark:bg-zinc-900">
|
||||
<Header />
|
||||
<Navigator />
|
||||
<Outlet />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
isInitialized && (
|
||||
<div className="w-full h-auto flex flex-col justify-start items-start dark:bg-zinc-900">
|
||||
<Header />
|
||||
<Navigator />
|
||||
<Outlet />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -1,21 +1,18 @@
|
||||
import { CssVarsProvider } from "@mui/joy";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
import { Provider } from "react-redux";
|
||||
import { RouterProvider } from "react-router-dom";
|
||||
import "./css/index.css";
|
||||
import "./css/joy-ui.css";
|
||||
import "./i18n";
|
||||
import router from "./routers";
|
||||
import store from "./stores";
|
||||
|
||||
const container = document.getElementById("root");
|
||||
const root = createRoot(container as HTMLElement);
|
||||
|
||||
root.render(
|
||||
<Provider store={store}>
|
||||
<CssVarsProvider>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster position="top-center" />
|
||||
</CssVarsProvider>
|
||||
</Provider>
|
||||
<CssVarsProvider>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster position="top-center" />
|
||||
</CssVarsProvider>
|
||||
);
|
||||
|
@ -1,59 +1,67 @@
|
||||
import { Button } from "@mui/joy";
|
||||
import { Button, Input } from "@mui/joy";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useLocalStorage from "react-use/lib/useLocalStorage";
|
||||
import CollectionView from "@/components/CollectionView";
|
||||
import CreateCollectionDialog from "@/components/CreateCollectionDialog";
|
||||
import { shortcutService } from "@/services";
|
||||
import useCollectionStore from "@/stores/v1/collection";
|
||||
import FilterView from "../components/FilterView";
|
||||
import Icon from "../components/Icon";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import CreateCollectionDrawer from "@/components/CreateCollectionDrawer";
|
||||
import FilterView from "@/components/FilterView";
|
||||
import Icon from "@/components/Icon";
|
||||
import useLoading from "@/hooks/useLoading";
|
||||
import { useShortcutStore, useCollectionStore } from "@/stores";
|
||||
|
||||
interface State {
|
||||
showCreateCollectionDialog: boolean;
|
||||
showCreateCollectionDrawer: boolean;
|
||||
}
|
||||
|
||||
const CollectionDashboard: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const [, setLastVisited] = useLocalStorage<string>("lastVisited", "/shortcuts");
|
||||
const loadingState = useLoading();
|
||||
const shortcutStore = useShortcutStore();
|
||||
const collectionStore = useCollectionStore();
|
||||
const collections = collectionStore.getCollectionList();
|
||||
const [state, setState] = useState<State>({
|
||||
showCreateCollectionDialog: false,
|
||||
showCreateCollectionDrawer: false,
|
||||
});
|
||||
const [search, setSearch] = useState<string>("");
|
||||
const filteredCollections = collectionStore.getCollectionList().filter((collection) => {
|
||||
return (
|
||||
collection.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
collection.title.toLowerCase().includes(search.toLowerCase()) ||
|
||||
collection.description.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([shortcutService.getMyAllShortcuts(), collectionStore.fetchCollectionList()]).finally(() => {
|
||||
setLastVisited("/collections");
|
||||
Promise.all([shortcutStore.fetchShortcutList(), collectionStore.fetchCollectionList()]).finally(() => {
|
||||
loadingState.setFinish();
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setShowCreateCollectionDialog = (show: boolean) => {
|
||||
const setShowCreateCollectionDrawer = (show: boolean) => {
|
||||
setState({
|
||||
...state,
|
||||
showCreateCollectionDialog: show,
|
||||
showCreateCollectionDrawer: show,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mx-auto max-w-8xl w-full px-3 md:px-12 pt-4 pb-6 flex flex-col justify-start items-start">
|
||||
<div className="w-full flex flex-row justify-start items-start mb-4">
|
||||
<div className="bg-yellow-100 dark:bg-yellow-500 dark:opacity-70 py-2 px-3 rounded-full border dark:border-yellow-600 flex flex-row justify-start items-center cursor-pointer shadow">
|
||||
<Icon.LibrarySquare className="w-5 h-auto opacity-60" />
|
||||
<a
|
||||
className="hover:underline hover:text-blue-600"
|
||||
href="https://github.com/boojack/slash/blob/main/docs/getting-started/collections.md"
|
||||
target="_blank"
|
||||
>
|
||||
<span className="mx-1 text-sm">Collection is in Beta. Learn more in docs</span>
|
||||
<Icon.ExternalLink className="w-4 h-auto inline-block" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mx-auto max-w-8xl w-full px-4 sm:px-6 md:px-12 pt-4 pb-6 flex flex-col justify-start items-start">
|
||||
<div className="w-full flex flex-row justify-between items-center mb-4">
|
||||
<div>
|
||||
<Input
|
||||
className="w-32 mr-2"
|
||||
type="text"
|
||||
size="sm"
|
||||
placeholder={t("common.search")}
|
||||
startDecorator={<Icon.Search className="w-4 h-auto" />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-row justify-start items-center">
|
||||
<Button className="hover:shadow" variant="soft" size="sm" onClick={() => setShowCreateCollectionDialog(true)}>
|
||||
<Button className="hover:shadow" variant="soft" size="sm" onClick={() => setShowCreateCollectionDrawer(true)}>
|
||||
<Icon.Plus className="w-5 h-auto" />
|
||||
<span className="ml-0.5">{t("common.create")}</span>
|
||||
</Button>
|
||||
@ -65,24 +73,24 @@ const CollectionDashboard: React.FC = () => {
|
||||
<Icon.Loader className="mr-2 w-5 h-auto animate-spin" />
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
) : collections.length === 0 ? (
|
||||
) : filteredCollections.length === 0 ? (
|
||||
<div className="py-16 w-full flex flex-col justify-center items-center text-gray-400">
|
||||
<Icon.PackageOpen className="w-16 h-auto" strokeWidth="1" />
|
||||
<p className="mt-4">No collections found.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full flex flex-col justify-start items-start gap-3">
|
||||
{collections.map((collection) => {
|
||||
{filteredCollections.map((collection) => {
|
||||
return <CollectionView key={collection.id} collection={collection} />;
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{state.showCreateCollectionDialog && (
|
||||
<CreateCollectionDialog
|
||||
onClose={() => setShowCreateCollectionDialog(false)}
|
||||
onConfirm={() => setShowCreateCollectionDialog(false)}
|
||||
{state.showCreateCollectionDrawer && (
|
||||
<CreateCollectionDrawer
|
||||
onClose={() => setShowCreateCollectionDrawer(false)}
|
||||
onConfirm={() => setShowCreateCollectionDrawer(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
@ -2,19 +2,18 @@ import { Divider } from "@mui/joy";
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { useParams } from "react-router-dom";
|
||||
import Icon from "@/components/Icon";
|
||||
import ShortcutFrame from "@/components/ShortcutFrame";
|
||||
import ShortcutView from "@/components/ShortcutView";
|
||||
import useResponsiveWidth from "@/hooks/useResponsiveWidth";
|
||||
import useCollectionStore from "@/stores/v1/collection";
|
||||
import useShortcutStore from "@/stores/v1/shortcut";
|
||||
import useUserStore from "@/stores/v1/user";
|
||||
import { Collection } from "@/types/proto/api/v2/collection_service";
|
||||
import { Shortcut } from "@/types/proto/api/v2/shortcut_service";
|
||||
import { convertShortcutFromPb } from "@/utils/shortcut";
|
||||
import { useUserStore, useCollectionStore, useShortcutStore } from "@/stores";
|
||||
import { Collection } from "@/types/proto/api/v1/collection_service";
|
||||
import { Shortcut } from "@/types/proto/api/v1/shortcut_service";
|
||||
|
||||
const CollectionSpace = () => {
|
||||
const { collectionName } = useParams();
|
||||
const params = useParams();
|
||||
const collectionName = params["*"];
|
||||
const { sm } = useResponsiveWidth();
|
||||
const userStore = useUserStore();
|
||||
const collectionStore = useCollectionStore();
|
||||
@ -31,7 +30,6 @@ const CollectionSpace = () => {
|
||||
(async () => {
|
||||
try {
|
||||
const collection = await collectionStore.fetchCollectionByName(collectionName);
|
||||
await userStore.getOrFetchUserById(collection.creatorId);
|
||||
setCollection(collection);
|
||||
setShortcuts([]);
|
||||
for (const shortcutId of collection.shortcutIds) {
|
||||
@ -41,7 +39,7 @@ const CollectionSpace = () => {
|
||||
return [...shortcuts, shortcut];
|
||||
});
|
||||
} catch (error) {
|
||||
// do nth
|
||||
// Do nothing.
|
||||
}
|
||||
}
|
||||
document.title = `${collection.title} - Slash`;
|
||||
@ -70,26 +68,26 @@ const CollectionSpace = () => {
|
||||
<div className="w-full h-full sm:px-12 sm:py-10 sm:h-screen sm:bg-gray-100 dark:sm:bg-zinc-800">
|
||||
<div className="w-full h-full flex flex-row sm:border dark:sm:border-zinc-800 p-4 rounded-2xl bg-gray-50 dark:bg-zinc-900">
|
||||
<div className="w-full sm:w-56 sm:pr-4 flex flex-col justify-start items-start overflow-auto shrink-0">
|
||||
<div className="w-full sticky top-0 bg-gray-50 dark:bg-zinc-900">
|
||||
<div className="w-full sticky top-0 px-2">
|
||||
<div className="w-full flex flex-row justify-start items-center text-gray-800 dark:text-gray-300">
|
||||
<Icon.LibrarySquare className="w-5 h-auto mr-2 opacity-70" />
|
||||
<span className="text-lg">{collection.title}</span>
|
||||
<Icon.LibrarySquare className="w-5 h-auto mr-1 opacity-70 shrink-0" />
|
||||
<span className="text-lg truncate">{collection.title}</span>
|
||||
</div>
|
||||
<p className="text-gray-500 text-sm">{collection.description}</p>
|
||||
<Divider className="!my-2" />
|
||||
<p className="text-gray-500 text-sm truncate">{collection.description}</p>
|
||||
</div>
|
||||
<Divider className="!my-2" />
|
||||
<div className="w-full flex flex-col justify-start items-start gap-2 sm:gap-1 px-px">
|
||||
{shortcuts.map((shortcut) => {
|
||||
return (
|
||||
<ShortcutView
|
||||
className={classNames(
|
||||
"w-full py-2 cursor-pointer",
|
||||
"w-full py-2 cursor-pointer sm:!px-2",
|
||||
selectedShortcut?.id === shortcut.id
|
||||
? "bg-gray-100 dark:bg-zinc-800"
|
||||
: "sm:border-transparent dark:sm:border-transparent"
|
||||
)}
|
||||
key={shortcut.name}
|
||||
shortcut={convertShortcutFromPb(shortcut)}
|
||||
shortcut={shortcut}
|
||||
alwaysShowLink={!sm}
|
||||
onClick={() => handleShortcutClick(shortcut)}
|
||||
/>
|
||||
@ -100,30 +98,15 @@ const CollectionSpace = () => {
|
||||
{sm && (
|
||||
<div className="w-full h-full overflow-clip rounded-lg border dark:border-zinc-800 bg-white dark:bg-zinc-800">
|
||||
{selectedShortcut ? (
|
||||
<div className="w-full h-full flex flex-col justify-center items-center p-8">
|
||||
<Link
|
||||
className="w-72 max-w-full border dark:border-zinc-900 dark:bg-zinc-900 p-6 rounded-2xl shadow-xl dark:text-gray-400 hover:opacity-80"
|
||||
to={`/s/${selectedShortcut.name}`}
|
||||
target="_blank"
|
||||
>
|
||||
<Icon.Globe2Icon className="w-12 h-auto mb-1" strokeWidth={1} />
|
||||
<p className="text-lg font-medium leading-8">{selectedShortcut.title || selectedShortcut.name}</p>
|
||||
<p className="text-gray-500">{selectedShortcut.description}</p>
|
||||
<Divider className="!my-2" />
|
||||
<p className="text-gray-400 dark:text-gray-600 text-sm mt-2">
|
||||
<span className="leading-4">Open this site in a new tab</span>
|
||||
<Icon.ArrowUpRight className="inline-block ml-1 -mt-0.5 w-4 h-auto" />
|
||||
</p>
|
||||
</Link>
|
||||
</div>
|
||||
<ShortcutFrame key={selectedShortcut.id} shortcut={selectedShortcut} />
|
||||
) : (
|
||||
<div className="w-full h-full flex flex-col justify-center items-center p-8">
|
||||
<div className="w-72 max-w-full border dark:border-zinc-900 dark:bg-zinc-900 dark:text-gray-400 p-6 rounded-2xl shadow-xl">
|
||||
<Icon.AppWindow className="w-12 h-auto mb-2" strokeWidth={1} />
|
||||
<div className="w-72 max-w-full border dark:border-zinc-900 dark:bg-zinc-900 dark:text-gray-400 p-6 pb-4 rounded-2xl shadow-xl">
|
||||
<Icon.AppWindow className="w-12 h-auto mb-2 opacity-60" strokeWidth={1} />
|
||||
<p className="text-lg font-medium">Click on a tab in the Sidebar to get started.</p>
|
||||
<Divider className="!my-2" />
|
||||
<p className="text-gray-400 dark:text-gray-600 text-sm mt-2">
|
||||
Shared by <span className="italic font-medium">{creator.nickname}</span>
|
||||
<p className="text-gray-400 dark:text-gray-600 text-sm mt-2 italic">
|
||||
Shared by <span className="font-medium not-italic">{creator.nickname}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -1,93 +1,20 @@
|
||||
import { Button, Input } from "@mui/joy";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CreateShortcutDialog from "../components/CreateShortcutDialog";
|
||||
import FilterView from "../components/FilterView";
|
||||
import Icon from "../components/Icon";
|
||||
import ShortcutsContainer from "../components/ShortcutsContainer";
|
||||
import ShortcutsNavigator from "../components/ShortcutsNavigator";
|
||||
import ViewSetting from "../components/ViewSetting";
|
||||
import useLoading from "../hooks/useLoading";
|
||||
import { shortcutService } from "../services";
|
||||
import { useAppSelector } from "../stores";
|
||||
import useUserStore from "../stores/v1/user";
|
||||
import useViewStore, { getFilteredShortcutList, getOrderedShortcutList } from "../stores/v1/view";
|
||||
|
||||
interface State {
|
||||
showCreateShortcutDialog: boolean;
|
||||
}
|
||||
import { useEffect } from "react";
|
||||
import useLocalStorage from "react-use/lib/useLocalStorage";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
|
||||
const Home: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const loadingState = useLoading();
|
||||
const currentUser = useUserStore().getCurrentUser();
|
||||
const viewStore = useViewStore();
|
||||
const { shortcutList } = useAppSelector((state) => state.shortcut);
|
||||
const [state, setState] = useState<State>({
|
||||
showCreateShortcutDialog: false,
|
||||
});
|
||||
const filter = viewStore.filter;
|
||||
const filteredShortcutList = getFilteredShortcutList(shortcutList, filter, currentUser);
|
||||
const orderedShortcutList = getOrderedShortcutList(filteredShortcutList, viewStore.order);
|
||||
const [lastVisited] = useLocalStorage<string>("lastVisited", "/shortcuts");
|
||||
const navigateTo = useNavigateTo();
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([shortcutService.getMyAllShortcuts()]).finally(() => {
|
||||
loadingState.setFinish();
|
||||
});
|
||||
if (lastVisited === "/shortcuts" || lastVisited === "/collections") {
|
||||
navigateTo(lastVisited);
|
||||
} else {
|
||||
navigateTo("/shortcuts");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setShowCreateShortcutDialog = (show: boolean) => {
|
||||
setState({
|
||||
...state,
|
||||
showCreateShortcutDialog: show,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mx-auto max-w-8xl w-full px-3 md:px-12 pt-4 pb-6 flex flex-col justify-start items-start">
|
||||
<ShortcutsNavigator />
|
||||
<div className="w-full flex flex-row justify-between items-center mb-4">
|
||||
<div className="flex flex-row justify-start items-center">
|
||||
<Button className="hover:shadow" variant="soft" size="sm" onClick={() => setShowCreateShortcutDialog(true)}>
|
||||
<Icon.Plus className="w-5 h-auto" />
|
||||
<span className="hidden sm:block ml-0.5">{t("common.create")}</span>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-row justify-end items-center">
|
||||
<Input
|
||||
className="w-32 ml-2"
|
||||
type="text"
|
||||
size="sm"
|
||||
placeholder={t("common.search")}
|
||||
startDecorator={<Icon.Search className="w-4 h-auto" />}
|
||||
endDecorator={<ViewSetting />}
|
||||
value={filter.search}
|
||||
onChange={(e) => viewStore.setFilter({ search: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<FilterView />
|
||||
{loadingState.isLoading ? (
|
||||
<div className="py-12 w-full flex flex-row justify-center items-center opacity-80 dark:text-gray-500">
|
||||
<Icon.Loader className="mr-2 w-5 h-auto animate-spin" />
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
) : orderedShortcutList.length === 0 ? (
|
||||
<div className="py-16 w-full flex flex-col justify-center items-center text-gray-400">
|
||||
<Icon.PackageOpen className="w-16 h-auto" strokeWidth="1" />
|
||||
<p className="mt-4">No shortcuts found.</p>
|
||||
</div>
|
||||
) : (
|
||||
<ShortcutsContainer shortcutList={orderedShortcutList} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{state.showCreateShortcutDialog && (
|
||||
<CreateShortcutDialog onClose={() => setShowCreateShortcutDialog(false)} onConfirm={() => setShowCreateShortcutDialog(false)} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return <></>;
|
||||
};
|
||||
|
||||
export default Home;
|
||||
|
@ -1,61 +1,13 @@
|
||||
import { Button } from "@mui/joy";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import CreateShortcutDialog from "@/components/CreateShortcutDialog";
|
||||
import Icon from "@/components/Icon";
|
||||
import useNavigateTo from "@/hooks/useNavigateTo";
|
||||
import useUserStore from "@/stores/v1/user";
|
||||
|
||||
interface State {
|
||||
showCreateShortcutButton: boolean;
|
||||
}
|
||||
|
||||
const NotFound = () => {
|
||||
const location = useLocation();
|
||||
const navigateTo = useNavigateTo();
|
||||
const currentUser = useUserStore().getCurrentUser();
|
||||
const [state, setState] = useState<State>({
|
||||
showCreateShortcutButton: false,
|
||||
});
|
||||
const [showCreateShortcutDialog, setShowCreateShortcutDialog] = useState(false);
|
||||
const params = new URLSearchParams(location.search);
|
||||
|
||||
useEffect(() => {
|
||||
const shortcut = params.get("shortcut");
|
||||
if (currentUser && shortcut) {
|
||||
setState({
|
||||
...state,
|
||||
showCreateShortcutButton: true,
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-full h-full overflow-y-auto overflow-x-hidden bg-zinc-100 dark:bg-zinc-800">
|
||||
<div className="w-full h-full flex flex-col justify-center items-center">
|
||||
<Icon.Meh strokeWidth={1} className="w-20 h-auto opacity-80 dark:text-gray-300" />
|
||||
<p className="mt-4 mb-8 text-4xl font-mono dark:text-gray-300">404</p>
|
||||
{state.showCreateShortcutButton && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
startDecorator={<Icon.Plus className="w-5 h-auto" />}
|
||||
onClick={() => setShowCreateShortcutDialog(true)}
|
||||
>
|
||||
Create shortcut
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-full h-full overflow-y-auto overflow-x-hidden bg-zinc-100 dark:bg-zinc-800">
|
||||
<div className="w-full h-full flex flex-col justify-center items-center">
|
||||
<Icon.Meh strokeWidth={1} className="w-20 h-auto opacity-80 dark:text-gray-300" />
|
||||
<p className="mt-4 mb-8 text-4xl font-mono dark:text-gray-300">404</p>
|
||||
</div>
|
||||
|
||||
{showCreateShortcutDialog && (
|
||||
<CreateShortcutDialog
|
||||
initialShortcut={{ name: params.get("shortcut") || "" }}
|
||||
onClose={() => setShowCreateShortcutDialog(false)}
|
||||
onConfirm={() => navigateTo("/")}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|