all
22
Securite/Linkwarden/.devcontainer/devcontainer.json
Normal file
@ -0,0 +1,22 @@
|
||||
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
|
||||
// README at: https://github.com/devcontainers/templates/tree/main/src/typescript-node
|
||||
{
|
||||
"name": "Node.js & TypeScript",
|
||||
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
|
||||
"image": "mcr.microsoft.com/devcontainers/typescript-node:1-20-bullseye",
|
||||
|
||||
// Features to add to the dev container. More info: https://containers.dev/features.
|
||||
// "features": {},
|
||||
|
||||
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||
// "forwardPorts": [],
|
||||
|
||||
// Use 'postCreateCommand' to run commands after the container is created.
|
||||
// "postCreateCommand": "yarn install",
|
||||
|
||||
// Configure tool-specific properties.
|
||||
// "customizations": {},
|
||||
|
||||
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
|
||||
"remoteUser": "root"
|
||||
}
|
7
Securite/Linkwarden/.dockerignore
Normal file
@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
pgdata
|
||||
.env
|
||||
.devcontainer
|
||||
docker-compose.yml
|
||||
Dockerfile
|
||||
README.md
|
391
Securite/Linkwarden/.env.sample
Normal file
@ -0,0 +1,391 @@
|
||||
NEXTAUTH_SECRET=very_sensitive_secret
|
||||
NEXTAUTH_URL=http://localhost:3000/api/v1/auth
|
||||
|
||||
# Manual installation database settings
|
||||
DATABASE_URL=postgresql://user:password@localhost:5432/linkwarden
|
||||
|
||||
# Docker installation database settings
|
||||
POSTGRES_PASSWORD=super_secret_password
|
||||
|
||||
# Additional Optional Settings
|
||||
PAGINATION_TAKE_COUNT=
|
||||
STORAGE_FOLDER=
|
||||
AUTOSCROLL_TIMEOUT=
|
||||
NEXT_PUBLIC_DISABLE_REGISTRATION=
|
||||
NEXT_PUBLIC_CREDENTIALS_ENABLED=
|
||||
DISABLE_NEW_SSO_USERS=
|
||||
RE_ARCHIVE_LIMIT=
|
||||
NEXT_PUBLIC_MAX_FILE_SIZE=
|
||||
MAX_LINKS_PER_USER=
|
||||
ARCHIVE_TAKE_COUNT=
|
||||
BROWSER_TIMEOUT=
|
||||
IGNORE_UNAUTHORIZED_CA=
|
||||
IGNORE_HTTPS_ERRORS=
|
||||
|
||||
# AWS S3 Settings
|
||||
SPACES_KEY=
|
||||
SPACES_SECRET=
|
||||
SPACES_ENDPOINT=
|
||||
SPACES_BUCKET_NAME=
|
||||
SPACES_REGION=
|
||||
SPACES_FORCE_PATH_STYLE=
|
||||
|
||||
# SMTP Settings
|
||||
NEXT_PUBLIC_EMAIL_PROVIDER=
|
||||
EMAIL_FROM=
|
||||
EMAIL_SERVER=
|
||||
|
||||
# Proxy settings
|
||||
PROXY=
|
||||
PROXY_USERNAME=
|
||||
PROXY_PASSWORD=
|
||||
PROXY_BYPASS=
|
||||
|
||||
# PDF archive settings
|
||||
PDF_MARGIN_TOP=
|
||||
PDF_MARGIN_BOTTOM=
|
||||
|
||||
#
|
||||
# SSO Providers
|
||||
#
|
||||
|
||||
# 42 School
|
||||
NEXT_PUBLIC_FORTYTWO_ENABLED=
|
||||
FORTYTWO_CUSTOM_NAME=
|
||||
FORTYTWO_CLIENT_ID=
|
||||
FORTYTWO_CLIENT_SECRET=
|
||||
|
||||
# Apple
|
||||
NEXT_PUBLIC_APPLE_ENABLED=
|
||||
APPLE_CUSTOM_NAME=
|
||||
APPLE_ID=
|
||||
APPLE_SECRET=
|
||||
|
||||
# Atlassian
|
||||
NEXT_PUBLIC_ATLASSIAN_ENABLED=
|
||||
ATLASSIAN_CUSTOM_NAME=
|
||||
ATLASSIAN_CLIENT_ID=
|
||||
ATLASSIAN_CLIENT_SECRET=
|
||||
ATLASSIAN_SCOPE=
|
||||
|
||||
# Auth0
|
||||
NEXT_PUBLIC_AUTH0_ENABLED=
|
||||
AUTH0_CUSTOM_NAME=
|
||||
AUTH0_ISSUER=
|
||||
AUTH0_CLIENT_SECRET=
|
||||
AUTH0_CLIENT_ID=
|
||||
|
||||
# Authentik
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED=
|
||||
AUTHENTIK_CUSTOM_NAME=
|
||||
AUTHENTIK_ISSUER=
|
||||
AUTHENTIK_CLIENT_ID=
|
||||
AUTHENTIK_CLIENT_SECRET=
|
||||
|
||||
# Battle.net
|
||||
NEXT_PUBLIC_BATTLENET_ENABLED=
|
||||
BATTLENET_CUSTOM_NAME=
|
||||
BATTLENET_CLIENT_ID=
|
||||
BATTLENET_CLIENT_SECRET=
|
||||
BATLLENET_ISSUER=
|
||||
|
||||
# Box
|
||||
NEXT_PUBLIC_BOX_ENABLED=
|
||||
BOX_CUSTOM_NAME=
|
||||
BOX_CLIENT_ID=
|
||||
BOX_CLIENT_SECRET=
|
||||
|
||||
# Bungie
|
||||
NEXT_PUBLIC_BUNGIE_ENABLED=
|
||||
BUNGIE_CUSTOM_NAME=
|
||||
BUNGIE_CLIENT_ID=
|
||||
BUNGIE_CLIENT_SECRET=
|
||||
BUNGIE_API_KEY=
|
||||
|
||||
# Cognito
|
||||
NEXT_PUBLIC_COGNITO_ENABLED=
|
||||
COGNITO_CUSTOM_NAME=
|
||||
COGNITO_CLIENT_ID=
|
||||
COGNITO_CLIENT_SECRET=
|
||||
COGNITO_ISSUER=
|
||||
|
||||
# Coinbase
|
||||
NEXT_PUBLIC_COINBASE_ENABLED=
|
||||
COINBASE_CUSTOM_NAME=
|
||||
COINBASE_CLIENT_ID=
|
||||
COINBASE_CLIENT_SECRET=
|
||||
|
||||
# Discord
|
||||
NEXT_PUBLIC_DISCORD_ENABLED=
|
||||
DISCORD_CUSTOM_NAME=
|
||||
DISCORD_CLIENT_ID=
|
||||
DISCORD_CLIENT_SECRET=
|
||||
|
||||
# Dropbox
|
||||
NEXT_PUBLIC_DROPBOX_ENABLED=
|
||||
DROPBOX_CUSTOM_NAME=
|
||||
DROPBOX_CLIENT_ID=
|
||||
DROPBOX_CLIENT_SECRET=
|
||||
|
||||
# DuendeIndentityServer6
|
||||
NEXT_PUBLIC_DUENDE_IDS6_ENABLED=
|
||||
DUENDE_IDS6_CUSTOM_NAME=
|
||||
DUENDE_IDS6_CLIENT_ID=
|
||||
DUENDE_IDS6_CLIENT_SECRET=
|
||||
DUENDE_IDS6_ISSUER=
|
||||
|
||||
# EVE Online
|
||||
NEXT_PUBLIC_EVEONLINE_ENABLED=
|
||||
EVEONLINE_CUSTOM_NAME=
|
||||
EVEONLINE_CLIENT_ID=
|
||||
EVEONLINE_CLIENT_SECRET=
|
||||
|
||||
# Facebook
|
||||
NEXT_PUBLIC_FACEBOOK_ENABLED=
|
||||
FACEBOOK_CUSTOM_NAME=
|
||||
FACEBOOK_CLIENT_ID=
|
||||
FACEBOOK_CLIENT_SECRET=
|
||||
|
||||
# FACEIT
|
||||
NEXT_PUBLIC_FACEIT_ENABLED=
|
||||
FACEIT_CUSTOM_NAME=
|
||||
FACEIT_CLIENT_ID=
|
||||
FACEIT_CLIENT_SECRET=
|
||||
|
||||
# Foursquare
|
||||
NEXT_PUBLIC_FOURSQUARE_ENABLED=
|
||||
FOURSQUARE_CUSTOM_NAME=
|
||||
FOURSQUARE_CLIENT_ID=
|
||||
FOURSQUARE_CLIENT_SECRET=
|
||||
FOURSQUARE_APIVERSION=
|
||||
|
||||
# Freshbooks
|
||||
NEXT_PUBLIC_FRESHBOOKS_ENABLED=
|
||||
FRESHBOOKS_CUSTOM_NAME=
|
||||
FRESHBOOKS_CLIENT_ID=
|
||||
FRESHBOOKS_CLIENT_SECRET=
|
||||
|
||||
# FusionAuth
|
||||
NEXT_PUBLIC_FUSIONAUTH_ENABLED=
|
||||
FUSIONAUTH_CUSTOM_NAME=
|
||||
FUSIONAUTH_CLIENT_ID=
|
||||
FUSIONAUTH_CLIENT_SECRET=
|
||||
FUSIONAUTH_ISSUER=
|
||||
FUSIONAUTH_TENANT_ID=
|
||||
|
||||
# GitHub
|
||||
NEXT_PUBLIC_GITHUB_ENABLED=
|
||||
GITHUB_CUSTOM_NAME=
|
||||
GITHUB_CLIENT_ID=
|
||||
GITHUB_CLIENT_SECRET=
|
||||
|
||||
# GitLab
|
||||
NEXT_PUBLIC_GITLAB_ENABLED=
|
||||
GITLAB_CUSTOM_NAME=
|
||||
GITLAB_CLIENT_ID=
|
||||
GITLAB_CLIENT_SECRET=
|
||||
|
||||
# Google
|
||||
NEXT_PUBLIC_GOOGLE_ENABLED=
|
||||
GOOGLE_CUSTOM_NAME=
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
|
||||
# HubSpot
|
||||
NEXT_PUBLIC_HUBSPOT_ENABLED=
|
||||
HUBSPOT_CUSTOM_NAME=
|
||||
HUBSPOT_CLIENT_ID=
|
||||
HUBSPOT_CLIENT_SECRET=
|
||||
|
||||
# IdentityServer4
|
||||
NEXT_PUBLIC_IDS4_ENABLED=
|
||||
IDS4_CUSTOM_NAME=
|
||||
IDS4_CLIENT_ID=
|
||||
IDS4_CLIENT_SECRET=
|
||||
IDS4_ISSUER=
|
||||
|
||||
# Kakao
|
||||
NEXT_PUBLIC_KAKAO_ENABLED=
|
||||
KAKAO_CUSTOM_NAME=
|
||||
KAKAO_CLIENT_ID=
|
||||
KAKAO_CLIENT_SECRET=
|
||||
|
||||
# Keycloak
|
||||
NEXT_PUBLIC_KEYCLOAK_ENABLED=
|
||||
KEYCLOAK_CUSTOM_NAME=
|
||||
KEYCLOAK_ISSUER=
|
||||
KEYCLOAK_CLIENT_ID=
|
||||
KEYCLOAK_CLIENT_SECRET=
|
||||
|
||||
# LINE
|
||||
NEXT_PUBLIC_LINE_ENABLED=
|
||||
LINE_CUSTOM_NAME=
|
||||
LINE_CLIENT_ID=
|
||||
LINE_CLIENT_SECRET=
|
||||
|
||||
# LinkedIn
|
||||
NEXT_PUBLIC_LINKEDIN_ENABLED=
|
||||
LINKEDIN_CUSTOM_NAME=
|
||||
LINKEDIN_CLIENT_ID=
|
||||
LINKEDIN_CLIENT_SECRET=
|
||||
|
||||
# Mailchimp
|
||||
NEXT_PUBLIC_MAILCHIMP_ENABLED=
|
||||
MAILCHIMP_CUSTOM_NAME=
|
||||
MAILCHIMP_CLIENT_ID=
|
||||
MAILCHIMP_CLIENT_SECRET=
|
||||
|
||||
# Mail.ru
|
||||
NEXT_PUBLIC_MAILRU_ENABLED=
|
||||
MAILRU_CUSTOM_NAME=
|
||||
MAILRU_CLIENT_ID=
|
||||
MAILRU_CLIENT_SECRET=
|
||||
|
||||
# Naver
|
||||
NEXT_PUBLIC_NAVER_ENABLED=
|
||||
NAVER_CUSTOM_NAME=
|
||||
NAVER_CLIENT_ID=
|
||||
NAVER_CLIENT_SECRET=
|
||||
|
||||
# Netlify
|
||||
NEXT_PUBLIC_NETLIFY_ENABLED=
|
||||
NETLIFY_CUSTOM_NAME=
|
||||
NETLIFY_CLIENT_ID=
|
||||
NETLIFY_CLIENT_SECRET=
|
||||
|
||||
# Okta
|
||||
NEXT_PUBLIC_OKTA_ENABLED=
|
||||
OKTA_CUSTOM_NAME=
|
||||
OKTA_CLIENT_ID=
|
||||
OKTA_CLIENT_SECRET=
|
||||
OKTA_ISSUER=
|
||||
|
||||
# OneLogin
|
||||
NEXT_PUBLIC_ONELOGIN_ENABLED=
|
||||
ONELOGIN_CUSTOM_NAME=
|
||||
ONELOGIN_CLIENT_ID=
|
||||
ONELOGIN_CLIENT_SECRET=
|
||||
ONELOGIN_ISSUER=
|
||||
|
||||
# Osso
|
||||
NEXT_PUBLIC_OSSO_ENABLED=
|
||||
OSSO_CUSTOM_NAME=
|
||||
OSSO_CLIENT_ID=
|
||||
OSSO_CLIENT_SECRET=
|
||||
OSSO_ISSUER=
|
||||
|
||||
# osu!
|
||||
NEXT_PUBLIC_OSU_ENABLED=
|
||||
OSU_CUSTOM_NAME=
|
||||
OSU_CLIENT_ID=
|
||||
OSU_CLIENT_SECRET=
|
||||
|
||||
# Patreon
|
||||
NEXT_PUBLIC_PATREON_ENABLED=
|
||||
PATREON_CUSTOM_NAME=
|
||||
PATREON_CLIENT_ID=
|
||||
PATREON_CLIENT_SECRET=
|
||||
|
||||
# Pinterest
|
||||
NEXT_PUBLIC_PINTEREST_ENABLED=
|
||||
PINTEREST_CUSTOM_NAME=
|
||||
PINTEREST_CLIENT_ID=
|
||||
PINTEREST_CLIENT_SECRET=
|
||||
|
||||
# Pipedrive
|
||||
NEXT_PUBLIC_PIPEDRIVE_ENABLED=
|
||||
PIPEDRIVE_CUSTOM_NAME=
|
||||
PIPEDRIVE_CLIENT_ID=
|
||||
PIPEDRIVE_CLIENT_SECRET=
|
||||
|
||||
# Reddit
|
||||
NEXT_PUBLIC_REDDIT_ENABLED=
|
||||
REDDIT_CUSTOM_NAME=
|
||||
REDDIT_CLIENT_ID=
|
||||
REDDIT_CLIENT_SECRET=
|
||||
|
||||
# Salesforce
|
||||
NEXT_PUBLIC_SALESFORCE_ENABLED=
|
||||
SALESFORCE_CUSTOM_NAME=
|
||||
SALESFORCE_CLIENT_ID=
|
||||
SALESFORCE_CLIENT_SECRET=
|
||||
|
||||
# Slack
|
||||
NEXT_PUBLIC_SLACK_ENABLED=
|
||||
SLACK_CUSTOM_NAME=
|
||||
SLACK_CLIENT_ID=
|
||||
SLACK_CLIENT_SECRET=
|
||||
|
||||
# Spotify
|
||||
NEXT_PUBLIC_SPOTIFY_ENABLED=
|
||||
SPOTIFY_CUSTOM_NAME=
|
||||
SPOTIFY_CLIENT_ID=
|
||||
SPOTIFY_CLIENT_SECRET=
|
||||
|
||||
# Strava
|
||||
NEXT_PUBLIC_STRAVA_ENABLED=
|
||||
STRAVA_CUSTOM_NAME=
|
||||
STRAVA_CLIENT_ID=
|
||||
STRAVA_CLIENT_SECRET=
|
||||
|
||||
# Todoist
|
||||
NEXT_PUBLIC_TODOIST_ENABLED=
|
||||
TODOIST_CUSTOM_NAME=
|
||||
TODOIST_CLIENT_ID=
|
||||
TODOIST_CLIENT_SECRET=
|
||||
|
||||
# Twitch
|
||||
NEXT_PUBLIC_TWITCH_ENABLED=
|
||||
TWITCH_CUSTOM_NAME=
|
||||
TWITCH_CLIENT_ID=
|
||||
TWITCH_CLIENT_SECRET=
|
||||
|
||||
# United Effects
|
||||
NEXT_PUBLIC_UNITED_EFFECTS_ENABLED=
|
||||
UNITED_EFFECTS_CUSTOM_NAME=
|
||||
UNITED_EFFECTS_CLIENT_ID=
|
||||
UNITED_EFFECTS_CLIENT_SECRET=
|
||||
UNITED_EFFECTS_ISSUER=
|
||||
|
||||
# VK
|
||||
NEXT_PUBLIC_VK_ENABLED=
|
||||
VK_CUSTOM_NAME=
|
||||
VK_CLIENT_ID=
|
||||
VK_CLIENT_SECRET=
|
||||
|
||||
# Wikimedia
|
||||
NEXT_PUBLIC_WIKIMEDIA_ENABLED=
|
||||
WIKIMEDIA_CUSTOM_NAME=
|
||||
WIKIMEDIA_CLIENT_ID=
|
||||
WIKIMEDIA_CLIENT_SECRET=
|
||||
|
||||
# Wordpress.com
|
||||
NEXT_PUBLIC_WORDPRESS_ENABLED=
|
||||
WORDPRESS_CUSTOM_NAME=
|
||||
WORDPRESS_CLIENT_ID=
|
||||
WORDPRESS_CLIENT_SECRET=
|
||||
|
||||
# Yandex
|
||||
NEXT_PUBLIC_YANDEX_ENABLED=
|
||||
YANDEX_CUSTOM_NAME=
|
||||
YANDEX_CLIENT_ID=
|
||||
YANDEX_CLIENT_SECRET=
|
||||
|
||||
# Zitadel
|
||||
NEXT_PUBLIC_ZITADEL_ENABLED=
|
||||
ZITADEL_CUSTOM_NAME=
|
||||
ZITADEL_CLIENT_ID=
|
||||
ZITADEL_CLIENT_SECRET=
|
||||
ZITADEL_ISSUER=
|
||||
|
||||
# Zoho
|
||||
NEXT_PUBLIC_ZOHO_ENABLED=
|
||||
ZOHO_CUSTOM_NAME=
|
||||
ZOHO_CLIENT_ID=
|
||||
ZOHO_CLIENT_SECRET=
|
||||
|
||||
# Zoom
|
||||
NEXT_PUBLIC_ZOOM_ENABLED=
|
||||
ZOOM_CUSTOM_NAME=
|
||||
ZOOM_CLIENT_ID=
|
||||
ZOOM_CLIENT_SECRET=
|
7
Securite/Linkwarden/.eslintrc.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "next/core-web-vitals",
|
||||
"rules": {
|
||||
"react-hooks/exhaustive-deps": "off",
|
||||
"@next/next/no-img-element": "off"
|
||||
}
|
||||
}
|
11
Securite/Linkwarden/.prettierignore
Normal file
@ -0,0 +1,11 @@
|
||||
node_modules
|
||||
.next
|
||||
public
|
||||
|
||||
*.lock
|
||||
*.log
|
||||
|
||||
.github
|
||||
|
||||
data
|
||||
pgdata
|
4
Securite/Linkwarden/.prettierrc.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"trailingComma": "es5",
|
||||
"tabWidth": 2
|
||||
}
|
1
Securite/Linkwarden/.vscode/settings.json
vendored
Normal file
@ -0,0 +1 @@
|
||||
{}
|
45
Securite/Linkwarden/ARCHITECTURE.md
Normal file
@ -0,0 +1,45 @@
|
||||
# Architecture
|
||||
|
||||
This is a summary of the architecture of Linkwarden. It's intended as a primer for collaborators to get a high-level understanding of the project.
|
||||
|
||||
When you start Linkwarden, there are mainly two components that run:
|
||||
|
||||
- The NextJS app, This is the main app and it's responsible for serving the frontend and handling the API routes.
|
||||
- [The Background Worker](https://github.com/linkwarden/linkwarden/blob/main/scripts/worker.ts), This is a separate `ts-node` process that runs in the background and is responsible for archiving links.
|
||||
|
||||
## Main Tech Stack
|
||||
|
||||
- [NextJS](https://github.com/vercel/next.js)
|
||||
- [TypeScript](https://github.com/microsoft/TypeScript)
|
||||
- [Tailwind](https://github.com/tailwindlabs/tailwindcss)
|
||||
- [DaisyUI](https://github.com/saadeghi/daisyui)
|
||||
- [Prisma](https://github.com/prisma/prisma)
|
||||
- [Playwright](https://github.com/microsoft/playwright)
|
||||
- [Zustand](https://github.com/pmndrs/zustand)
|
||||
|
||||
## Folder Structure
|
||||
|
||||
Here's a summary of the main files and folders in the project:
|
||||
|
||||
```
|
||||
linkwarden
|
||||
├── components # React components
|
||||
├── hooks # React reusable hooks
|
||||
├── layouts # Layouts for pages
|
||||
├── lib
|
||||
│ ├── api # Server-side functions (controllers, etc.)
|
||||
│ ├── client # Client-side functions
|
||||
│ └── shared # Shared functions between client and server
|
||||
├── pages # Pages and API routes
|
||||
├── prisma # Prisma schema and migrations
|
||||
├── scripts
|
||||
│ ├── migration # Scripts for breaking changes
|
||||
│ └── worker.ts # Background worker for archiving links
|
||||
├── store # Zustand stores
|
||||
├── styles # Styles
|
||||
└── types # TypeScript types
|
||||
```
|
||||
|
||||
## Versioning
|
||||
|
||||
We use semantic versioning for the project. You can track the changes from the [Releases](https://github.com/linkwarden/linkwarden/releases).
|
23
Securite/Linkwarden/Dockerfile
Normal file
@ -0,0 +1,23 @@
|
||||
FROM node:18.18-bullseye-slim
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
RUN mkdir /data
|
||||
|
||||
WORKDIR /data
|
||||
|
||||
COPY ./package.json ./yarn.lock ./playwright.config.ts ./
|
||||
|
||||
# Increase timeout to pass github actions arm64 build
|
||||
RUN --mount=type=cache,sharing=locked,target=/usr/local/share/.cache/yarn yarn install --network-timeout 10000000
|
||||
|
||||
RUN npx playwright install-deps && \
|
||||
apt-get clean && \
|
||||
yarn cache clean
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN yarn prisma generate && \
|
||||
yarn build
|
||||
|
||||
CMD yarn prisma migrate deploy && yarn start
|
3
Securite/Linkwarden/LICENSE
Normal file
@ -0,0 +1,3 @@
|
||||
Additional permission under GNU GPL version 3 section 7
|
||||
|
||||
If you modify this Program, or any covered work, by linking or combining it with [name of library] (or a modified version of that library), containing parts covered by the terms of [name of library's license], the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of [name of library] used as well as that of the covered work.
|
66
Securite/Linkwarden/README.md
Normal file
@ -0,0 +1,66 @@
|
||||

|
||||
URL :
|
||||
|
||||
# Linkwarden
|
||||
|
||||
|
||||
|
||||
# Téléchargement, Configuration et Lancement
|
||||
|
||||
## Téléchargement de Linkwarden
|
||||
|
||||
Saisir la commande pour télécharger la source
|
||||
```bash
|
||||
git clone https://git.tips-of-mine.fr/Tips-Of-Mine/Docker.git
|
||||
```
|
||||
|
||||
Saisir la commande pour vous rendre dans le dossier
|
||||
```bash
|
||||
cd Securite\Linkwarden
|
||||
```
|
||||
|
||||
## Modifier la configuration de Linkwarden
|
||||
|
||||
Saisir la commande pour vous rendre dans le dossier
|
||||
```bash
|
||||
cd Securite\Linkwarden
|
||||
```
|
||||
|
||||
Nous éditons le fichier de configuration
|
||||
```bash
|
||||
nano .env
|
||||
```
|
||||
|
||||
Nous modifions les variables dont nous avons besoin.
|
||||
|
||||
## Lancement de Linkwarden
|
||||
|
||||
Pour utiliser Linkwarden tout seul
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Pour utiliser Linkwarden avec Traefik
|
||||
```bash
|
||||
docker compose -f docker-compose-traefik.yml up -d
|
||||
```
|
||||
|
||||
# Utilisation
|
||||
|
||||
## Accueil
|
||||
|
||||
Ouvrir une page web avec l'url :
|
||||
Pour une utilisation tout seul
|
||||
|
||||
http://10.0.4.29:3000
|
||||
|
||||
Pour une utilisation avec Traefik
|
||||
|
||||
https://Linkwarden.10.0.4.29.traefik.me`)"
|
||||
|
||||
|
||||
# More info
|
||||
- more information on the website [Tips-Of-Mine](https://www.tips-of-mine.fr/)
|
||||
|
||||
# Buy me a coffe
|
||||
<a href='https://ko-fi.com/R5R2KNI3N' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi4.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
|
BIN
Securite/Linkwarden/assets/all_collections.jpg
Normal file
After Width: | Height: | Size: 251 KiB |
BIN
Securite/Linkwarden/assets/all_links.jpg
Normal file
After Width: | Height: | Size: 564 KiB |
BIN
Securite/Linkwarden/assets/dashboard.png
Normal file
After Width: | Height: | Size: 786 KiB |
BIN
Securite/Linkwarden/assets/light_dashboard.jpg
Normal file
After Width: | Height: | Size: 471 KiB |
BIN
Securite/Linkwarden/assets/list_view.jpg
Normal file
After Width: | Height: | Size: 394 KiB |
BIN
Securite/Linkwarden/assets/logo.png
Normal file
After Width: | Height: | Size: 79 KiB |
BIN
Securite/Linkwarden/assets/manage_team.jpg
Normal file
After Width: | Height: | Size: 226 KiB |
BIN
Securite/Linkwarden/assets/preserved_formats.jpg
Normal file
After Width: | Height: | Size: 301 KiB |
BIN
Securite/Linkwarden/assets/public_page.jpg
Normal file
After Width: | Height: | Size: 330 KiB |
BIN
Securite/Linkwarden/assets/readable_view.jpg
Normal file
After Width: | Height: | Size: 345 KiB |
BIN
Securite/Linkwarden/assets/star_repo.gif
Normal file
After Width: | Height: | Size: 2.4 MiB |
29
Securite/Linkwarden/components/AccentSubmitButton.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
type Props = {
|
||||
onClick?: Function;
|
||||
label: string;
|
||||
loading?: boolean;
|
||||
className?: string;
|
||||
type?: "button" | "submit" | "reset" | undefined;
|
||||
};
|
||||
|
||||
export default function AccentSubmitButton({
|
||||
onClick,
|
||||
label,
|
||||
loading,
|
||||
className,
|
||||
type,
|
||||
}: Props) {
|
||||
return (
|
||||
<button
|
||||
type={type ? type : undefined}
|
||||
className={`border primary-btn-gradient select-none duration-200 bg-black border-[oklch(var(--p))] hover:border-[#0070b5] rounded-lg text-center px-4 py-2 text-white active:scale-95 tracking-wider w-fit flex justify-center items-center gap-2 ${
|
||||
className || ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (loading !== undefined && !loading && onClick) onClick();
|
||||
}}
|
||||
>
|
||||
<p className="font-bold">{label}</p>
|
||||
</button>
|
||||
);
|
||||
}
|
33
Securite/Linkwarden/components/AnnouncementBar.tsx
Normal file
@ -0,0 +1,33 @@
|
||||
import Link from "next/link";
|
||||
import React, { MouseEventHandler } from "react";
|
||||
|
||||
type Props = {
|
||||
toggleAnnouncementBar: MouseEventHandler<HTMLButtonElement>;
|
||||
};
|
||||
|
||||
export default function AnnouncementBar({ toggleAnnouncementBar }: Props) {
|
||||
return (
|
||||
<div className="fixed w-full z-20 bg-base-200">
|
||||
<div className="w-full h-10 rainbow flex items-center justify-center">
|
||||
<div className="w-fit font-semibold">
|
||||
🎉️ See what's new in{" "}
|
||||
<Link
|
||||
href="https://blog.linkwarden.app/releases/v2.5"
|
||||
target="_blank"
|
||||
className="underline hover:opacity-50 duration-100"
|
||||
>
|
||||
Linkwarden v2.5
|
||||
</Link>
|
||||
! 🥳️
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="fixed right-3 hover:opacity-50 duration-100"
|
||||
onClick={toggleAnnouncementBar}
|
||||
>
|
||||
<i className="bi-x text-neutral text-2xl"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
26
Securite/Linkwarden/components/Checkbox.tsx
Normal file
@ -0,0 +1,26 @@
|
||||
import { ChangeEventHandler } from "react";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
state: boolean;
|
||||
className?: string;
|
||||
onClick: ChangeEventHandler<HTMLInputElement>;
|
||||
};
|
||||
|
||||
export default function Checkbox({ label, state, className, onClick }: Props) {
|
||||
return (
|
||||
<label
|
||||
className={`label cursor-pointer flex gap-2 justify-start ${
|
||||
className || ""
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={state}
|
||||
onChange={onClick}
|
||||
className="checkbox checkbox-primary"
|
||||
/>
|
||||
<span className="label-text">{label}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
54
Securite/Linkwarden/components/ClickAwayHandler.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
import React, { useRef, useEffect, ReactNode, RefObject } from "react";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
onClickOutside: Function;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
onMount?: (rect: DOMRect) => void;
|
||||
};
|
||||
|
||||
function useOutsideAlerter(
|
||||
ref: RefObject<HTMLElement>,
|
||||
onClickOutside: Function
|
||||
) {
|
||||
useEffect(() => {
|
||||
function handleClickOutside(event: Event) {
|
||||
if (
|
||||
ref.current &&
|
||||
!ref.current.contains(event.target as HTMLInputElement)
|
||||
) {
|
||||
onClickOutside(event);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [ref, onClickOutside]);
|
||||
}
|
||||
|
||||
export default function ClickAwayHandler({
|
||||
children,
|
||||
onClickOutside,
|
||||
className,
|
||||
style,
|
||||
onMount,
|
||||
}: Props) {
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useOutsideAlerter(wrapperRef, onClickOutside);
|
||||
|
||||
useEffect(() => {
|
||||
if (wrapperRef.current && onMount) {
|
||||
const rect = wrapperRef.current.getBoundingClientRect();
|
||||
onMount(rect); // Pass the bounding rectangle to the parent
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className={className} style={style}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
218
Securite/Linkwarden/components/CollectionCard.tsx
Normal file
@ -0,0 +1,218 @@
|
||||
import Link from "next/link";
|
||||
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import ProfilePhoto from "./ProfilePhoto";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import useLocalSettingsStore from "@/store/localSettings";
|
||||
import getPublicUserData from "@/lib/client/getPublicUserData";
|
||||
import useAccountStore from "@/store/account";
|
||||
import EditCollectionModal from "./ModalContent/EditCollectionModal";
|
||||
import EditCollectionSharingModal from "./ModalContent/EditCollectionSharingModal";
|
||||
import DeleteCollectionModal from "./ModalContent/DeleteCollectionModal";
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
|
||||
type Props = {
|
||||
collection: CollectionIncludingMembersAndLinkCount;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function CollectionCard({ collection, className }: Props) {
|
||||
const { settings } = useLocalSettingsStore();
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const formattedDate = new Date(collection.createdAt as string).toLocaleString(
|
||||
"en-US",
|
||||
{
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
}
|
||||
);
|
||||
|
||||
const permissions = usePermissions(collection.id as number);
|
||||
|
||||
const [collectionOwner, setCollectionOwner] = useState({
|
||||
id: null as unknown as number,
|
||||
name: "",
|
||||
username: "",
|
||||
image: "",
|
||||
archiveAsScreenshot: undefined as unknown as boolean,
|
||||
archiveAsPDF: undefined as unknown as boolean,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchOwner = async () => {
|
||||
if (collection && collection.ownerId !== account.id) {
|
||||
const owner = await getPublicUserData(collection.ownerId as number);
|
||||
setCollectionOwner(owner);
|
||||
} else if (collection && collection.ownerId === account.id) {
|
||||
setCollectionOwner({
|
||||
id: account.id as number,
|
||||
name: account.name,
|
||||
username: account.username as string,
|
||||
image: account.image as string,
|
||||
archiveAsScreenshot: account.archiveAsScreenshot as boolean,
|
||||
archiveAsPDF: account.archiveAsPDF as boolean,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
fetchOwner();
|
||||
}, [collection]);
|
||||
|
||||
const [editCollectionModal, setEditCollectionModal] = useState(false);
|
||||
const [editCollectionSharingModal, setEditCollectionSharingModal] =
|
||||
useState(false);
|
||||
const [deleteCollectionModal, setDeleteCollectionModal] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="dropdown dropdown-bottom dropdown-end absolute top-3 right-3 z-20">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-ghost btn-sm btn-square text-neutral"
|
||||
>
|
||||
<i className="bi-three-dots text-xl" title="More"></i>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box w-52 mt-1">
|
||||
{permissions === true ? (
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setEditCollectionModal(true);
|
||||
}}
|
||||
>
|
||||
Edit Collection Info
|
||||
</div>
|
||||
</li>
|
||||
) : undefined}
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setEditCollectionSharingModal(true);
|
||||
}}
|
||||
>
|
||||
{permissions === true ? "Share and Collaborate" : "View Team"}
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setDeleteCollectionModal(true);
|
||||
}}
|
||||
>
|
||||
{permissions === true ? "Delete Collection" : "Leave Collection"}
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center absolute bottom-3 left-3 z-10 btn px-2 btn-ghost rounded-full"
|
||||
onClick={() => setEditCollectionSharingModal(true)}
|
||||
>
|
||||
{collectionOwner.id ? (
|
||||
<ProfilePhoto
|
||||
src={collectionOwner.image || undefined}
|
||||
name={collectionOwner.name}
|
||||
/>
|
||||
) : undefined}
|
||||
{collection.members
|
||||
.sort((a, b) => (a.userId as number) - (b.userId as number))
|
||||
.map((e, i) => {
|
||||
return (
|
||||
<ProfilePhoto
|
||||
key={i}
|
||||
src={e.user.image ? e.user.image : undefined}
|
||||
name={e.user.name}
|
||||
className="-ml-3"
|
||||
/>
|
||||
);
|
||||
})
|
||||
.slice(0, 3)}
|
||||
{collection.members.length - 3 > 0 ? (
|
||||
<div className={`avatar drop-shadow-md placeholder -ml-3`}>
|
||||
<div className="bg-base-100 text-neutral rounded-full w-8 h-8 ring-2 ring-neutral-content">
|
||||
<span>+{collection.members.length - 3}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Link
|
||||
href={`/collections/${collection.id}`}
|
||||
style={{
|
||||
backgroundImage: `linear-gradient(45deg, ${collection.color}30 10%, ${
|
||||
settings.theme === "dark" ? "oklch(var(--b2))" : "oklch(var(--b2))"
|
||||
} 50%, ${
|
||||
settings.theme === "dark" ? "oklch(var(--b2))" : "oklch(var(--b2))"
|
||||
} 100%)`,
|
||||
}}
|
||||
className="card card-compact shadow-md hover:shadow-none duration-200 border border-neutral-content"
|
||||
>
|
||||
<div className="card-body flex flex-col justify-between min-h-[12rem]">
|
||||
<div className="flex justify-between">
|
||||
<p className="card-title break-words line-clamp-2 w-full">
|
||||
{collection.name}
|
||||
</p>
|
||||
<div className="w-8 h-8 ml-10"></div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end items-center">
|
||||
<div className="text-right">
|
||||
<div className="font-bold text-sm flex justify-end gap-1 items-center">
|
||||
{collection.isPublic ? (
|
||||
<i
|
||||
className="bi-globe2 drop-shadow text-neutral"
|
||||
title="This collection is being shared publicly."
|
||||
></i>
|
||||
) : undefined}
|
||||
<i
|
||||
className="bi-link-45deg text-lg text-neutral"
|
||||
title="This collection is being shared publicly."
|
||||
></i>
|
||||
{collection._count && collection._count.links}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-1 text-neutral">
|
||||
<p className="font-bold text-xs flex gap-1 items-center">
|
||||
<i
|
||||
className="bi-calendar3 text-neutral"
|
||||
title="This collection is being shared publicly."
|
||||
></i>
|
||||
{formattedDate}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
{editCollectionModal ? (
|
||||
<EditCollectionModal
|
||||
onClose={() => setEditCollectionModal(false)}
|
||||
activeCollection={collection}
|
||||
/>
|
||||
) : undefined}
|
||||
{editCollectionSharingModal ? (
|
||||
<EditCollectionSharingModal
|
||||
onClose={() => setEditCollectionSharingModal(false)}
|
||||
activeCollection={collection}
|
||||
/>
|
||||
) : undefined}
|
||||
{deleteCollectionModal ? (
|
||||
<DeleteCollectionModal
|
||||
onClose={() => setDeleteCollectionModal(false)}
|
||||
activeCollection={collection}
|
||||
/>
|
||||
) : undefined}
|
||||
</div>
|
||||
);
|
||||
}
|
365
Securite/Linkwarden/components/CollectionListing.tsx
Normal file
@ -0,0 +1,365 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import Tree, {
|
||||
mutateTree,
|
||||
moveItemOnTree,
|
||||
RenderItemParams,
|
||||
TreeItem,
|
||||
TreeData,
|
||||
ItemId,
|
||||
TreeSourcePosition,
|
||||
TreeDestinationPosition,
|
||||
} from "@atlaskit/tree";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import { Collection } from "@prisma/client";
|
||||
import Link from "next/link";
|
||||
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
||||
import { useRouter } from "next/router";
|
||||
import useAccountStore from "@/store/account";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
interface ExtendedTreeItem extends TreeItem {
|
||||
data: Collection;
|
||||
}
|
||||
|
||||
const CollectionListing = () => {
|
||||
const { collections, updateCollection } = useCollectionStore();
|
||||
const { account, updateAccount } = useAccountStore();
|
||||
|
||||
const router = useRouter();
|
||||
const currentPath = router.asPath;
|
||||
|
||||
const initialTree = useMemo(() => {
|
||||
if (collections.length > 0) {
|
||||
return buildTreeFromCollections(
|
||||
collections,
|
||||
router,
|
||||
account.collectionOrder
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}, [collections, router]);
|
||||
|
||||
const [tree, setTree] = useState(initialTree);
|
||||
|
||||
useEffect(() => {
|
||||
setTree(initialTree);
|
||||
}, [initialTree]);
|
||||
|
||||
useEffect(() => {
|
||||
if (account.username) {
|
||||
if (
|
||||
(!account.collectionOrder || account.collectionOrder.length === 0) &&
|
||||
collections.length > 0
|
||||
)
|
||||
updateAccount({
|
||||
...account,
|
||||
collectionOrder: collections
|
||||
.filter(
|
||||
(e) =>
|
||||
e.parentId === null ||
|
||||
!collections.find((i) => i.id === e.parentId)
|
||||
) // Filter out collections with non-null parentId
|
||||
.map((e) => e.id as number), // Use "as number" to assert that e.id is a number
|
||||
});
|
||||
else {
|
||||
const newCollectionOrder: number[] = [
|
||||
...(account.collectionOrder || []),
|
||||
];
|
||||
|
||||
// Start with collections that are in both account.collectionOrder and collections
|
||||
const existingCollectionIds = collections.map((c) => c.id as number);
|
||||
const filteredCollectionOrder = account.collectionOrder.filter((id) =>
|
||||
existingCollectionIds.includes(id)
|
||||
);
|
||||
|
||||
// Add new collections that are not in account.collectionOrder and meet the specific conditions
|
||||
collections.forEach((collection) => {
|
||||
if (
|
||||
!filteredCollectionOrder.includes(collection.id as number) &&
|
||||
(!collection.parentId || collection.ownerId === account.id)
|
||||
) {
|
||||
filteredCollectionOrder.push(collection.id as number);
|
||||
}
|
||||
});
|
||||
|
||||
// check if the newCollectionOrder is the same as the old one
|
||||
if (
|
||||
JSON.stringify(newCollectionOrder) !==
|
||||
JSON.stringify(account.collectionOrder)
|
||||
) {
|
||||
updateAccount({
|
||||
...account,
|
||||
collectionOrder: newCollectionOrder,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [collections]);
|
||||
|
||||
const onExpand = (movedCollectionId: ItemId) => {
|
||||
setTree((currentTree) =>
|
||||
mutateTree(currentTree!, movedCollectionId, { isExpanded: true })
|
||||
);
|
||||
};
|
||||
|
||||
const onCollapse = (movedCollectionId: ItemId) => {
|
||||
setTree((currentTree) =>
|
||||
mutateTree(currentTree as TreeData, movedCollectionId, {
|
||||
isExpanded: false,
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const onDragEnd = async (
|
||||
source: TreeSourcePosition,
|
||||
destination: TreeDestinationPosition | undefined
|
||||
) => {
|
||||
if (!destination || !tree) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
source.index === destination.index &&
|
||||
source.parentId === destination.parentId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const movedCollectionId = Number(
|
||||
tree.items[source.parentId].children[source.index]
|
||||
);
|
||||
|
||||
const movedCollection = collections.find((c) => c.id === movedCollectionId);
|
||||
|
||||
const destinationCollection = collections.find(
|
||||
(c) => c.id === Number(destination.parentId)
|
||||
);
|
||||
|
||||
if (
|
||||
(movedCollection?.ownerId !== account.id &&
|
||||
destination.parentId !== source.parentId) ||
|
||||
(destinationCollection?.ownerId !== account.id &&
|
||||
destination.parentId !== "root")
|
||||
) {
|
||||
return toast.error(
|
||||
"You can't make change to a collection you don't own."
|
||||
);
|
||||
}
|
||||
|
||||
setTree((currentTree) => moveItemOnTree(currentTree!, source, destination));
|
||||
|
||||
const updatedCollectionOrder = [...account.collectionOrder];
|
||||
|
||||
if (source.parentId !== destination.parentId) {
|
||||
await updateCollection({
|
||||
...movedCollection,
|
||||
parentId:
|
||||
destination.parentId && destination.parentId !== "root"
|
||||
? Number(destination.parentId)
|
||||
: destination.parentId === "root"
|
||||
? "root"
|
||||
: null,
|
||||
} as any);
|
||||
}
|
||||
|
||||
if (
|
||||
destination.index !== undefined &&
|
||||
destination.parentId === source.parentId &&
|
||||
source.parentId === "root"
|
||||
) {
|
||||
updatedCollectionOrder.includes(movedCollectionId) &&
|
||||
updatedCollectionOrder.splice(source.index, 1);
|
||||
|
||||
updatedCollectionOrder.splice(destination.index, 0, movedCollectionId);
|
||||
|
||||
await updateAccount({
|
||||
...account,
|
||||
collectionOrder: updatedCollectionOrder,
|
||||
});
|
||||
} else if (
|
||||
destination.index !== undefined &&
|
||||
destination.parentId === "root"
|
||||
) {
|
||||
updatedCollectionOrder.splice(destination.index, 0, movedCollectionId);
|
||||
|
||||
await updateAccount({
|
||||
...account,
|
||||
collectionOrder: updatedCollectionOrder,
|
||||
});
|
||||
} else if (
|
||||
source.parentId === "root" &&
|
||||
destination.parentId &&
|
||||
destination.parentId !== "root"
|
||||
) {
|
||||
updatedCollectionOrder.splice(source.index, 1);
|
||||
|
||||
await updateAccount({
|
||||
...account,
|
||||
collectionOrder: updatedCollectionOrder,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (!tree) {
|
||||
return <></>;
|
||||
} else
|
||||
return (
|
||||
<Tree
|
||||
tree={tree}
|
||||
renderItem={(itemProps) => renderItem({ ...itemProps }, currentPath)}
|
||||
onExpand={onExpand}
|
||||
onCollapse={onCollapse}
|
||||
onDragEnd={onDragEnd}
|
||||
isDragEnabled
|
||||
isNestingEnabled
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default CollectionListing;
|
||||
|
||||
const renderItem = (
|
||||
{ item, onExpand, onCollapse, provided }: RenderItemParams,
|
||||
currentPath: string
|
||||
) => {
|
||||
const collection = item.data;
|
||||
|
||||
return (
|
||||
<div ref={provided.innerRef} {...provided.draggableProps} className="mb-1">
|
||||
<div
|
||||
className={`${
|
||||
currentPath === `/collections/${collection.id}`
|
||||
? "bg-primary/20 is-active"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 flex gap-1 items-center pr-2 pl-1 rounded-md`}
|
||||
>
|
||||
{Icon(item as ExtendedTreeItem, onExpand, onCollapse)}
|
||||
|
||||
<Link
|
||||
href={`/collections/${collection.id}`}
|
||||
className="w-full"
|
||||
{...provided.dragHandleProps}
|
||||
>
|
||||
<div
|
||||
className={`py-1 cursor-pointer flex items-center gap-2 w-full rounded-md h-8 capitalize`}
|
||||
>
|
||||
<i
|
||||
className="bi-folder-fill text-2xl drop-shadow"
|
||||
style={{ color: collection.color }}
|
||||
></i>
|
||||
<p className="truncate w-full">{collection.name}</p>
|
||||
|
||||
{collection.isPublic ? (
|
||||
<i
|
||||
className="bi-globe2 text-sm text-black/50 dark:text-white/50 drop-shadow"
|
||||
title="This collection is being shared publicly."
|
||||
></i>
|
||||
) : undefined}
|
||||
<div className="drop-shadow text-neutral text-xs">
|
||||
{collection._count?.links}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const Icon = (
|
||||
item: ExtendedTreeItem,
|
||||
onExpand: (id: ItemId) => void,
|
||||
onCollapse: (id: ItemId) => void
|
||||
) => {
|
||||
if (item.children && item.children.length > 0) {
|
||||
return item.isExpanded ? (
|
||||
<button onClick={() => onCollapse(item.id)}>
|
||||
<div className="bi-caret-down-fill opacity-50 hover:opacity-100 duration-200"></div>
|
||||
</button>
|
||||
) : (
|
||||
<button onClick={() => onExpand(item.id)}>
|
||||
<div className="bi-caret-right-fill opacity-40 hover:opacity-100 duration-200"></div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
// return <span>•</span>;
|
||||
return <div></div>;
|
||||
};
|
||||
|
||||
const buildTreeFromCollections = (
|
||||
collections: CollectionIncludingMembersAndLinkCount[],
|
||||
router: ReturnType<typeof useRouter>,
|
||||
order?: number[]
|
||||
): TreeData => {
|
||||
if (order) {
|
||||
collections.sort((a: any, b: any) => {
|
||||
return order.indexOf(a.id) - order.indexOf(b.id);
|
||||
});
|
||||
}
|
||||
|
||||
const items: { [key: string]: ExtendedTreeItem } = collections.reduce(
|
||||
(acc: any, collection) => {
|
||||
acc[collection.id as number] = {
|
||||
id: collection.id,
|
||||
children: [],
|
||||
hasChildren: false,
|
||||
isExpanded: false,
|
||||
data: {
|
||||
id: collection.id,
|
||||
parentId: collection.parentId,
|
||||
name: collection.name,
|
||||
description: collection.description,
|
||||
color: collection.color,
|
||||
isPublic: collection.isPublic,
|
||||
ownerId: collection.ownerId,
|
||||
createdAt: collection.createdAt,
|
||||
updatedAt: collection.updatedAt,
|
||||
_count: {
|
||||
links: collection._count?.links,
|
||||
},
|
||||
},
|
||||
};
|
||||
return acc;
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
const activeCollectionId = Number(router.asPath.split("/collections/")[1]);
|
||||
|
||||
if (activeCollectionId) {
|
||||
for (const item in items) {
|
||||
const collection = items[item];
|
||||
if (Number(item) === activeCollectionId && collection.data.parentId) {
|
||||
// get all the parents of the active collection recursively until root and set isExpanded to true
|
||||
let parentId = collection.data.parentId || null;
|
||||
while (parentId && items[parentId]) {
|
||||
items[parentId].isExpanded = true;
|
||||
parentId = items[parentId].data.parentId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collections.forEach((collection) => {
|
||||
const parentId = collection.parentId;
|
||||
if (parentId && items[parentId] && collection.id) {
|
||||
items[parentId].children.push(collection.id);
|
||||
items[parentId].hasChildren = true;
|
||||
}
|
||||
});
|
||||
|
||||
const rootId = "root";
|
||||
items[rootId] = {
|
||||
id: rootId,
|
||||
children: (collections
|
||||
.filter(
|
||||
(c) =>
|
||||
c.parentId === null || !collections.find((i) => i.id === c.parentId)
|
||||
)
|
||||
.map((c) => c.id) || "") as unknown as string[],
|
||||
hasChildren: true,
|
||||
isExpanded: true,
|
||||
data: { name: "Root" } as Collection,
|
||||
};
|
||||
|
||||
return { rootId, items };
|
||||
};
|
21
Securite/Linkwarden/components/DashboardItem.tsx
Normal file
@ -0,0 +1,21 @@
|
||||
export default function dashboardItem({
|
||||
name,
|
||||
value,
|
||||
icon,
|
||||
}: {
|
||||
name: string;
|
||||
value: number;
|
||||
icon: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center">
|
||||
<div className="w-[4.7rem] aspect-square flex justify-center items-center bg-primary/20 rounded-xl select-none">
|
||||
<i className={`${icon} text-primary text-4xl drop-shadow`}></i>
|
||||
</div>
|
||||
<div className="ml-4 flex flex-col justify-center">
|
||||
<p className="text-neutral text-xs tracking-wider">{name}</p>
|
||||
<p className="font-thin text-6xl text-primary mt-0.5">{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
106
Securite/Linkwarden/components/Dropdown.tsx
Normal file
@ -0,0 +1,106 @@
|
||||
import Link from "next/link";
|
||||
import React, { MouseEventHandler, useEffect, useState } from "react";
|
||||
import ClickAwayHandler from "./ClickAwayHandler";
|
||||
|
||||
type MenuItem =
|
||||
| {
|
||||
name: string;
|
||||
onClick: MouseEventHandler;
|
||||
href?: string;
|
||||
}
|
||||
| {
|
||||
name: string;
|
||||
onClick?: MouseEventHandler;
|
||||
href: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
type Props = {
|
||||
onClickOutside: Function;
|
||||
className?: string;
|
||||
items: MenuItem[];
|
||||
points?: { x: number; y: number };
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
export default function Dropdown({
|
||||
points,
|
||||
onClickOutside,
|
||||
className,
|
||||
items,
|
||||
}: Props) {
|
||||
const [pos, setPos] = useState<{ x: number; y: number }>();
|
||||
const [dropdownHeight, setDropdownHeight] = useState<number>();
|
||||
const [dropdownWidth, setDropdownWidth] = useState<number>();
|
||||
|
||||
function convertRemToPixels(rem: number) {
|
||||
return (
|
||||
rem * parseFloat(getComputedStyle(document.documentElement).fontSize)
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (points) {
|
||||
let finalX = points.x;
|
||||
let finalY = points.y;
|
||||
|
||||
// Check for x-axis overflow (left side)
|
||||
if (dropdownWidth && points.x + dropdownWidth > window.innerWidth) {
|
||||
finalX = points.x - dropdownWidth;
|
||||
}
|
||||
|
||||
// Check for y-axis overflow (bottom side)
|
||||
if (dropdownHeight && points.y + dropdownHeight > window.innerHeight) {
|
||||
finalY =
|
||||
window.innerHeight -
|
||||
(dropdownHeight + (window.innerHeight - points.y));
|
||||
}
|
||||
|
||||
setPos({ x: finalX, y: finalY });
|
||||
}
|
||||
}, [points, dropdownHeight]);
|
||||
|
||||
return !points || pos ? (
|
||||
<ClickAwayHandler
|
||||
onMount={(e) => {
|
||||
setDropdownHeight(e.height);
|
||||
setDropdownWidth(e.width);
|
||||
}}
|
||||
style={
|
||||
points
|
||||
? {
|
||||
position: "fixed",
|
||||
top: `${pos?.y}px`,
|
||||
left: `${pos?.x}px`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onClickOutside={onClickOutside}
|
||||
className={`${
|
||||
className || ""
|
||||
} py-1 shadow-md border border-neutral-content bg-base-200 rounded-md flex flex-col z-20`}
|
||||
>
|
||||
{items.map((e, i) => {
|
||||
const inner = e && (
|
||||
<div className="cursor-pointer rounded-md">
|
||||
<div className="flex items-center gap-2 py-1 px-2 hover:bg-base-100 duration-100">
|
||||
<p className="select-none">{e.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return e && e.href ? (
|
||||
<Link key={i} href={e.href}>
|
||||
{inner}
|
||||
</Link>
|
||||
) : (
|
||||
e && (
|
||||
<div key={i} onClick={e.onClick}>
|
||||
{inner}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</ClickAwayHandler>
|
||||
) : null;
|
||||
}
|
134
Securite/Linkwarden/components/FilterSearchDropdown.tsx
Normal file
@ -0,0 +1,134 @@
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
import React from "react";
|
||||
|
||||
type Props = {
|
||||
setSearchFilter: Function;
|
||||
searchFilter: {
|
||||
name: boolean;
|
||||
url: boolean;
|
||||
description: boolean;
|
||||
textContent: boolean;
|
||||
tags: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export default function FilterSearchDropdown({
|
||||
setSearchFilter,
|
||||
searchFilter,
|
||||
}: Props) {
|
||||
return (
|
||||
<div className="dropdown dropdown-bottom dropdown-end">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-sm btn-square btn-ghost"
|
||||
>
|
||||
<i className="bi-funnel text-neutral text-2xl"></i>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-box w-56 mt-1">
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="search-filter-checkbox"
|
||||
className="checkbox checkbox-primary"
|
||||
checked={searchFilter.name}
|
||||
onChange={() => {
|
||||
setSearchFilter({ ...searchFilter, name: !searchFilter.name });
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">Name</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="search-filter-checkbox"
|
||||
className="checkbox checkbox-primary"
|
||||
checked={searchFilter.url}
|
||||
onChange={() => {
|
||||
setSearchFilter({ ...searchFilter, url: !searchFilter.url });
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">Link</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="search-filter-checkbox"
|
||||
className="checkbox checkbox-primary"
|
||||
checked={searchFilter.description}
|
||||
onChange={() => {
|
||||
setSearchFilter({
|
||||
...searchFilter,
|
||||
description: !searchFilter.description,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">Description</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="search-filter-checkbox"
|
||||
className="checkbox checkbox-primary"
|
||||
checked={searchFilter.tags}
|
||||
onChange={() => {
|
||||
setSearchFilter({
|
||||
...searchFilter,
|
||||
tags: !searchFilter.tags,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">Tags</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-between"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="search-filter-checkbox"
|
||||
className="checkbox checkbox-primary"
|
||||
checked={searchFilter.textContent}
|
||||
onChange={() => {
|
||||
setSearchFilter({
|
||||
...searchFilter,
|
||||
textContent: !searchFilter.textContent,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">Full Content</span>
|
||||
|
||||
<div className="ml-auto badge badge-sm badge-neutral">Slower</div>
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,130 @@
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { styles } from "./styles";
|
||||
import { Options } from "./types";
|
||||
import CreatableSelect from "react-select/creatable";
|
||||
import Select from "react-select";
|
||||
|
||||
type Props = {
|
||||
onChange: any;
|
||||
showDefaultValue?: boolean;
|
||||
defaultValue?:
|
||||
| {
|
||||
label: string;
|
||||
value?: number;
|
||||
}
|
||||
| undefined;
|
||||
creatable?: boolean;
|
||||
};
|
||||
|
||||
export default function CollectionSelection({
|
||||
onChange,
|
||||
defaultValue,
|
||||
showDefaultValue = true,
|
||||
creatable = true,
|
||||
}: Props) {
|
||||
const { collections } = useCollectionStore();
|
||||
const router = useRouter();
|
||||
|
||||
const [options, setOptions] = useState<Options[]>([]);
|
||||
|
||||
const collectionId = Number(router.query.id);
|
||||
|
||||
const activeCollection = collections.find((e) => {
|
||||
return e.id === collectionId;
|
||||
});
|
||||
|
||||
if (activeCollection && !defaultValue) {
|
||||
defaultValue = {
|
||||
value: activeCollection?.id,
|
||||
label: activeCollection?.name,
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const formatedCollections = collections.map((e) => {
|
||||
return {
|
||||
value: e.id,
|
||||
label: e.name,
|
||||
ownerId: e.ownerId,
|
||||
count: e._count,
|
||||
parentId: e.parentId,
|
||||
};
|
||||
});
|
||||
|
||||
setOptions(formatedCollections);
|
||||
}, [collections]);
|
||||
|
||||
const getParentNames = (parentId: number): string[] => {
|
||||
const parentNames = [];
|
||||
const parent = collections.find((e) => e.id === parentId);
|
||||
|
||||
if (parent) {
|
||||
parentNames.push(parent.name);
|
||||
if (parent.parentId) {
|
||||
parentNames.push(...getParentNames(parent.parentId));
|
||||
}
|
||||
}
|
||||
|
||||
// Have the top level parent at beginning
|
||||
return parentNames.reverse();
|
||||
};
|
||||
|
||||
const customOption = ({ data, innerProps }: any) => {
|
||||
return (
|
||||
<div
|
||||
{...innerProps}
|
||||
className="px-2 py-2 last:border-0 border-b border-neutral-content hover:bg-neutral-content cursor-pointer"
|
||||
>
|
||||
<div className="flex w-full justify-between items-center">
|
||||
<span>{data.label}</span>
|
||||
<span className="text-sm text-neutral">{data.count?.links}</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 dark:text-gray-300">
|
||||
{getParentNames(data?.parentId).length > 0 ? (
|
||||
<>
|
||||
{getParentNames(data.parentId).join(" > ")} {">"} {data.label}
|
||||
</>
|
||||
) : (
|
||||
data.label
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (creatable) {
|
||||
return (
|
||||
<CreatableSelect
|
||||
isClearable={false}
|
||||
className="react-select-container"
|
||||
classNamePrefix="react-select"
|
||||
onChange={onChange}
|
||||
options={options}
|
||||
styles={styles}
|
||||
defaultValue={showDefaultValue ? defaultValue : null}
|
||||
components={{
|
||||
Option: customOption,
|
||||
}}
|
||||
// menuPosition="fixed"
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<Select
|
||||
isClearable={false}
|
||||
className="react-select-container"
|
||||
classNamePrefix="react-select"
|
||||
onChange={onChange}
|
||||
options={options}
|
||||
styles={styles}
|
||||
defaultValue={showDefaultValue ? defaultValue : null}
|
||||
components={{
|
||||
Option: customOption,
|
||||
}}
|
||||
// menuPosition="fixed"
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
41
Securite/Linkwarden/components/InputSelect/TagSelection.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
import useTagStore from "@/store/tags";
|
||||
import { useEffect, useState } from "react";
|
||||
import CreatableSelect from "react-select/creatable";
|
||||
import { styles } from "./styles";
|
||||
import { Options } from "./types";
|
||||
|
||||
type Props = {
|
||||
onChange: any;
|
||||
defaultValue?: {
|
||||
value: number;
|
||||
label: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export default function TagSelection({ onChange, defaultValue }: Props) {
|
||||
const { tags } = useTagStore();
|
||||
|
||||
const [options, setOptions] = useState<Options[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const formatedCollections = tags.map((e) => {
|
||||
return { value: e.id, label: e.name };
|
||||
});
|
||||
|
||||
setOptions(formatedCollections);
|
||||
}, [tags]);
|
||||
|
||||
return (
|
||||
<CreatableSelect
|
||||
isClearable={false}
|
||||
className="react-select-container"
|
||||
classNamePrefix="react-select"
|
||||
onChange={onChange}
|
||||
options={options}
|
||||
styles={styles}
|
||||
defaultValue={defaultValue}
|
||||
// menuPosition="fixed"
|
||||
isMulti
|
||||
/>
|
||||
);
|
||||
}
|
69
Securite/Linkwarden/components/InputSelect/styles.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import { StylesConfig } from "react-select";
|
||||
|
||||
const font =
|
||||
"ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji";
|
||||
|
||||
export const styles: StylesConfig = {
|
||||
option: (styles, state) => ({
|
||||
...styles,
|
||||
fontFamily: font,
|
||||
cursor: "pointer",
|
||||
backgroundColor: state.isSelected ? "oklch(var(--p))" : "inherit",
|
||||
"&:hover": {
|
||||
backgroundColor: state.isSelected
|
||||
? "oklch(var(--p))"
|
||||
: "oklch(var(--nc))",
|
||||
},
|
||||
transition: "all 50ms",
|
||||
}),
|
||||
control: (styles, state) => ({
|
||||
...styles,
|
||||
fontFamily: font,
|
||||
borderRadius: "0.375rem",
|
||||
border: state.isFocused
|
||||
? "1px solid oklch(var(--p))"
|
||||
: "1px solid oklch(var(--nc))",
|
||||
boxShadow: "none",
|
||||
minHeight: "2.6rem",
|
||||
}),
|
||||
container: (styles, state) => ({
|
||||
...styles,
|
||||
height: "full",
|
||||
borderRadius: "0.375rem",
|
||||
lineHeight: "1.25rem",
|
||||
// "@media screen and (min-width: 1024px)": {
|
||||
// fontSize: "0.875rem",
|
||||
// },
|
||||
}),
|
||||
input: (styles) => ({
|
||||
...styles,
|
||||
cursor: "text",
|
||||
}),
|
||||
dropdownIndicator: (styles) => ({
|
||||
...styles,
|
||||
cursor: "pointer",
|
||||
}),
|
||||
placeholder: (styles) => ({
|
||||
...styles,
|
||||
borderColor: "black",
|
||||
}),
|
||||
multiValue: (styles) => {
|
||||
return {
|
||||
...styles,
|
||||
backgroundColor: "#0ea5e9",
|
||||
color: "white",
|
||||
};
|
||||
},
|
||||
multiValueLabel: (styles) => ({
|
||||
...styles,
|
||||
color: "white",
|
||||
}),
|
||||
multiValueRemove: (styles) => ({
|
||||
...styles,
|
||||
":hover": {
|
||||
color: "white",
|
||||
backgroundColor: "#38bdf8",
|
||||
},
|
||||
}),
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
};
|
4
Securite/Linkwarden/components/InputSelect/types.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export interface Options {
|
||||
label: string;
|
||||
value?: string | number;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
import LinkCard from "@/components/LinkViews/LinkCard";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import { link } from "fs";
|
||||
import { GridLoader } from "react-spinners";
|
||||
|
||||
export default function CardView({
|
||||
links,
|
||||
editMode,
|
||||
isLoading,
|
||||
}: {
|
||||
links: LinkIncludingShortenedCollectionAndTags[];
|
||||
editMode?: boolean;
|
||||
isLoading?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid min-[1900px]:grid-cols-4 xl:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
|
||||
{links.map((e, i) => {
|
||||
return (
|
||||
<LinkCard
|
||||
key={i}
|
||||
link={e}
|
||||
count={i}
|
||||
flipDropdown={i === links.length - 1}
|
||||
editMode={editMode}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{isLoading && links.length > 0 && (
|
||||
<GridLoader
|
||||
color="oklch(var(--p))"
|
||||
loading={true}
|
||||
size={20}
|
||||
className="fixed top-5 right-5 opacity-50 z-30"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
import LinkGrid from "@/components/LinkViews/LinkGrid";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
|
||||
export default function GridView({
|
||||
links,
|
||||
}: {
|
||||
links: LinkIncludingShortenedCollectionAndTags[];
|
||||
}) {
|
||||
return (
|
||||
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 grid-cols-1 gap-5">
|
||||
{links.map((e, i) => {
|
||||
return <LinkGrid link={e} count={i} key={i} />;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
import LinkList from "@/components/LinkViews/LinkList";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import { GridLoader } from "react-spinners";
|
||||
|
||||
export default function ListView({
|
||||
links,
|
||||
editMode,
|
||||
isLoading,
|
||||
}: {
|
||||
links: LinkIncludingShortenedCollectionAndTags[];
|
||||
editMode?: boolean;
|
||||
isLoading?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex gap-1 flex-col">
|
||||
{links.map((e, i) => {
|
||||
return (
|
||||
<LinkList
|
||||
key={i}
|
||||
link={e}
|
||||
count={i}
|
||||
flipDropdown={i === links.length - 1}
|
||||
editMode={editMode}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{isLoading && links.length > 0 && (
|
||||
<GridLoader
|
||||
color="oklch(var(--p))"
|
||||
loading={true}
|
||||
size={20}
|
||||
className="fixed top-5 right-5 opacity-50 z-30"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
248
Securite/Linkwarden/components/LinkViews/LinkCard.tsx
Normal file
@ -0,0 +1,248 @@
|
||||
import {
|
||||
ArchivedFormat,
|
||||
CollectionIncludingMembersAndLinkCount,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
|
||||
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
|
||||
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
|
||||
import Image from "next/image";
|
||||
import { previewAvailable } from "@/lib/shared/getArchiveValidity";
|
||||
import Link from "next/link";
|
||||
import LinkIcon from "./LinkComponents/LinkIcon";
|
||||
import useOnScreen from "@/hooks/useOnScreen";
|
||||
import { generateLinkHref } from "@/lib/client/generateLinkHref";
|
||||
import useAccountStore from "@/store/account";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
type Props = {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
count: number;
|
||||
className?: string;
|
||||
flipDropdown?: boolean;
|
||||
editMode?: boolean;
|
||||
};
|
||||
|
||||
export default function LinkCard({ link, flipDropdown, editMode }: Props) {
|
||||
const { collections } = useCollectionStore();
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const { links, getLink, setSelectedLinks, selectedLinks } = useLinkStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (!editMode) {
|
||||
setSelectedLinks([]);
|
||||
}
|
||||
}, [editMode]);
|
||||
|
||||
const handleCheckboxClick = (
|
||||
link: LinkIncludingShortenedCollectionAndTags
|
||||
) => {
|
||||
if (selectedLinks.includes(link)) {
|
||||
setSelectedLinks(selectedLinks.filter((e) => e !== link));
|
||||
} else {
|
||||
setSelectedLinks([...selectedLinks, link]);
|
||||
}
|
||||
};
|
||||
|
||||
let shortendURL;
|
||||
|
||||
try {
|
||||
shortendURL = new URL(link.url || "").host.toLowerCase();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
const [collection, setCollection] =
|
||||
useState<CollectionIncludingMembersAndLinkCount>(
|
||||
collections.find(
|
||||
(e) => e.id === link.collection.id
|
||||
) as CollectionIncludingMembersAndLinkCount
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setCollection(
|
||||
collections.find(
|
||||
(e) => e.id === link.collection.id
|
||||
) as CollectionIncludingMembersAndLinkCount
|
||||
);
|
||||
}, [collections, links]);
|
||||
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const isVisible = useOnScreen(ref);
|
||||
const permissions = usePermissions(collection?.id as number);
|
||||
|
||||
useEffect(() => {
|
||||
let interval: any;
|
||||
|
||||
if (
|
||||
isVisible &&
|
||||
!link.preview?.startsWith("archives") &&
|
||||
link.preview !== "unavailable"
|
||||
) {
|
||||
interval = setInterval(async () => {
|
||||
getLink(link.id as number);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
};
|
||||
}, [isVisible, link.preview]);
|
||||
|
||||
const [showInfo, setShowInfo] = useState(false);
|
||||
|
||||
const selectedStyle = selectedLinks.some(
|
||||
(selectedLink) => selectedLink.id === link.id
|
||||
)
|
||||
? "border-primary bg-base-300"
|
||||
: "border-neutral-content";
|
||||
|
||||
const selectable =
|
||||
editMode &&
|
||||
(permissions === true || permissions?.canCreate || permissions?.canDelete);
|
||||
|
||||
// window.open ('www.yourdomain.com', '_ blank');
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`${selectedStyle} border border-solid border-neutral-content bg-base-200 shadow-md hover:shadow-none duration-100 rounded-2xl relative`}
|
||||
onClick={() =>
|
||||
selectable
|
||||
? handleCheckboxClick(link)
|
||||
: editMode
|
||||
? toast.error(
|
||||
"You don't have permission to edit or delete this item."
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<div
|
||||
className="rounded-2xl cursor-pointer"
|
||||
onClick={() =>
|
||||
!editMode && window.open(generateLinkHref(link, account), "_blank")
|
||||
}
|
||||
>
|
||||
<div className="relative rounded-t-2xl h-40 overflow-hidden">
|
||||
{previewAvailable(link) ? (
|
||||
<Image
|
||||
src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true`}
|
||||
width={1280}
|
||||
height={720}
|
||||
alt=""
|
||||
className="rounded-t-2xl select-none object-cover z-10 h-40 w-full shadow opacity-80 scale-105"
|
||||
style={{ filter: "blur(2px)" }}
|
||||
draggable="false"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
target.style.display = "none";
|
||||
}}
|
||||
/>
|
||||
) : link.preview === "unavailable" ? (
|
||||
<div className="bg-gray-50 duration-100 h-40 bg-opacity-80"></div>
|
||||
) : (
|
||||
<div className="duration-100 h-40 bg-opacity-80 skeleton rounded-none"></div>
|
||||
)}
|
||||
<div className="absolute top-0 left-0 right-0 bottom-0 rounded-t-2xl flex items-center justify-center shadow rounded-md">
|
||||
<LinkIcon link={link} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr className="divider my-0 last:hidden border-t border-neutral-content h-[1px]" />
|
||||
|
||||
<div className="p-3 mt-1">
|
||||
<p className="truncate w-full pr-8 text-primary">
|
||||
{unescapeString(link.name || link.description) || link.url}
|
||||
</p>
|
||||
|
||||
<Link
|
||||
href={link.url || ""}
|
||||
target="_blank"
|
||||
title={link.url || ""}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="flex gap-1 item-center select-none text-neutral mt-1 hover:opacity-70 duration-100"
|
||||
>
|
||||
<i className="bi-link-45deg text-lg mt-[0.10rem] leading-none"></i>
|
||||
<p className="text-sm truncate">{shortendURL}</p>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<hr className="divider mt-2 mb-1 last:hidden border-t border-neutral-content h-[1px]" />
|
||||
|
||||
<div className="flex justify-between text-xs text-neutral px-3 pb-1">
|
||||
<div className="cursor-pointer w-fit">
|
||||
{collection && (
|
||||
<LinkCollection link={link} collection={collection} />
|
||||
)}
|
||||
</div>
|
||||
<LinkDate link={link} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showInfo && (
|
||||
<div className="p-3 absolute z-30 top-0 left-0 right-0 bottom-0 bg-base-200 rounded-2xl fade-in overflow-y-auto">
|
||||
<div
|
||||
onClick={() => setShowInfo(!showInfo)}
|
||||
className=" float-right btn btn-sm outline-none btn-circle btn-ghost z-10"
|
||||
>
|
||||
<i className="bi-x text-neutral text-2xl"></i>
|
||||
</div>
|
||||
<p className="text-neutral text-lg font-semibold">Description</p>
|
||||
|
||||
<hr className="divider my-2 last:hidden border-t border-neutral-content h-[1px]" />
|
||||
<p>
|
||||
{link.description ? (
|
||||
unescapeString(link.description)
|
||||
) : (
|
||||
<span className="text-neutral text-sm">
|
||||
No description provided.
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
{link.tags[0] && (
|
||||
<>
|
||||
<p className="text-neutral text-lg mt-3 font-semibold">Tags</p>
|
||||
|
||||
<hr className="divider my-2 last:hidden border-t border-neutral-content h-[1px]" />
|
||||
|
||||
<div className="flex gap-3 items-center flex-wrap mt-2 truncate relative">
|
||||
<div className="flex gap-1 items-center flex-wrap">
|
||||
{link.tags.map((e, i) => (
|
||||
<Link
|
||||
href={"/tags/" + e.id}
|
||||
key={i}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
|
||||
>
|
||||
#{e.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<LinkActions
|
||||
link={link}
|
||||
collection={collection}
|
||||
position="top-[10.75rem] right-3"
|
||||
toggleShowInfo={() => setShowInfo(!showInfo)}
|
||||
linkInfo={showInfo}
|
||||
flipDropdown={flipDropdown}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,177 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
CollectionIncludingMembersAndLinkCount,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import EditLinkModal from "@/components/ModalContent/EditLinkModal";
|
||||
import DeleteLinkModal from "@/components/ModalContent/DeleteLinkModal";
|
||||
import PreservedFormatsModal from "@/components/ModalContent/PreservedFormatsModal";
|
||||
import useLinkStore from "@/store/links";
|
||||
import { toast } from "react-hot-toast";
|
||||
import useAccountStore from "@/store/account";
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
|
||||
type Props = {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
collection: CollectionIncludingMembersAndLinkCount;
|
||||
position?: string;
|
||||
toggleShowInfo?: () => void;
|
||||
linkInfo?: boolean;
|
||||
flipDropdown?: boolean;
|
||||
};
|
||||
|
||||
export default function LinkActions({
|
||||
link,
|
||||
toggleShowInfo,
|
||||
position,
|
||||
linkInfo,
|
||||
flipDropdown,
|
||||
}: Props) {
|
||||
const permissions = usePermissions(link.collection.id as number);
|
||||
|
||||
const [editLinkModal, setEditLinkModal] = useState(false);
|
||||
const [deleteLinkModal, setDeleteLinkModal] = useState(false);
|
||||
const [preservedFormatsModal, setPreservedFormatsModal] = useState(false);
|
||||
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const { removeLink, updateLink } = useLinkStore();
|
||||
|
||||
const pinLink = async () => {
|
||||
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0];
|
||||
|
||||
const load = toast.loading("Applying...");
|
||||
|
||||
const response = await updateLink({
|
||||
...link,
|
||||
pinnedBy: isAlreadyPinned ? undefined : [{ id: account.id }],
|
||||
});
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
response.ok &&
|
||||
toast.success(`Link ${isAlreadyPinned ? "Unpinned!" : "Pinned!"}`);
|
||||
};
|
||||
|
||||
const deleteLink = async () => {
|
||||
const load = toast.loading("Deleting...");
|
||||
|
||||
const response = await removeLink(link.id as number);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
response.ok && toast.success(`Link Deleted.`);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`dropdown dropdown-left dropdown-end absolute ${
|
||||
position || "top-3 right-3"
|
||||
} z-20`}
|
||||
>
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-ghost btn-sm btn-square text-neutral"
|
||||
>
|
||||
<i title="More" className="bi-three-dots text-xl" />
|
||||
</div>
|
||||
<ul className="dropdown-content z-[20] menu shadow bg-base-200 border border-neutral-content rounded-box w-44 mr-1 translate-y-10">
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
pinLink();
|
||||
}}
|
||||
>
|
||||
{link?.pinnedBy && link.pinnedBy[0]
|
||||
? "Unpin"
|
||||
: "Pin to Dashboard"}
|
||||
</div>
|
||||
</li>
|
||||
{linkInfo !== undefined && toggleShowInfo ? (
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
toggleShowInfo();
|
||||
}}
|
||||
>
|
||||
{!linkInfo ? "Show" : "Hide"} Link Details
|
||||
</div>
|
||||
</li>
|
||||
) : undefined}
|
||||
{permissions === true || permissions?.canUpdate ? (
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setEditLinkModal(true);
|
||||
}}
|
||||
>
|
||||
Edit Link
|
||||
</div>
|
||||
</li>
|
||||
) : undefined}
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setPreservedFormatsModal(true);
|
||||
}}
|
||||
>
|
||||
Preserved Formats
|
||||
</div>
|
||||
</li>
|
||||
{permissions === true || permissions?.canDelete ? (
|
||||
<li>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(e) => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
e.shiftKey ? deleteLink() : setDeleteLinkModal(true);
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</div>
|
||||
</li>
|
||||
) : undefined}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{editLinkModal ? (
|
||||
<EditLinkModal
|
||||
onClose={() => setEditLinkModal(false)}
|
||||
activeLink={link}
|
||||
/>
|
||||
) : undefined}
|
||||
{deleteLinkModal ? (
|
||||
<DeleteLinkModal
|
||||
onClose={() => setDeleteLinkModal(false)}
|
||||
activeLink={link}
|
||||
/>
|
||||
) : undefined}
|
||||
{preservedFormatsModal ? (
|
||||
<PreservedFormatsModal
|
||||
onClose={() => setPreservedFormatsModal(false)}
|
||||
activeLink={link}
|
||||
/>
|
||||
) : undefined}
|
||||
{/* {expandedLink ? (
|
||||
<ExpandedLink onClose={() => setExpandedLink(false)} link={link} />
|
||||
) : undefined} */}
|
||||
</>
|
||||
);
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
import {
|
||||
CollectionIncludingMembersAndLinkCount,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import React from "react";
|
||||
|
||||
export default function LinkCollection({
|
||||
link,
|
||||
collection,
|
||||
}: {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
collection: CollectionIncludingMembersAndLinkCount;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={`/collections/${link.collection.id}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="flex items-center gap-1 max-w-full w-fit hover:opacity-70 duration-100 select-none"
|
||||
title={collection?.name}
|
||||
>
|
||||
<i
|
||||
className="bi-folder-fill text-lg drop-shadow"
|
||||
style={{ color: collection?.color }}
|
||||
></i>
|
||||
<p className="truncate capitalize">{collection?.name}</p>
|
||||
</Link>
|
||||
);
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import React from "react";
|
||||
|
||||
export default function LinkDate({
|
||||
link,
|
||||
}: {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
}) {
|
||||
const formattedDate = new Date(
|
||||
(link.importDate || link.createdAt) as string
|
||||
).toLocaleString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1 text-neutral">
|
||||
<i className="bi-calendar3 text-lg"></i>
|
||||
<p>{formattedDate}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import Image from "next/image";
|
||||
import isValidUrl from "@/lib/shared/isValidUrl";
|
||||
import React from "react";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function LinkGroupedIconURL({
|
||||
link,
|
||||
}: {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
}) {
|
||||
const url =
|
||||
isValidUrl(link.url || "") && link.url ? new URL(link.url) : undefined;
|
||||
|
||||
const [showFavicon, setShowFavicon] = React.useState<boolean>(true);
|
||||
|
||||
let shortendURL;
|
||||
|
||||
try {
|
||||
shortendURL = new URL(link.url || "").host.toLowerCase();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link href={link.url || ""} target="_blank">
|
||||
<div className="bg-white shadow-md rounded-md border-[2px] flex gap-1 item-center justify-center border-white select-none z-10 max-w-full">
|
||||
{link.url && url && showFavicon ? (
|
||||
<Image
|
||||
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${link.url}&size=32`}
|
||||
width={64}
|
||||
height={64}
|
||||
alt=""
|
||||
className="w-5 h-5 rounded"
|
||||
draggable="false"
|
||||
onError={() => {
|
||||
setShowFavicon(false);
|
||||
}}
|
||||
/>
|
||||
) : showFavicon === false ? (
|
||||
<i className="bi-link-45deg text-xl leading-none text-black"></i>
|
||||
) : link.type === "pdf" ? (
|
||||
<i className={`bi-file-earmark-pdf`}></i>
|
||||
) : link.type === "image" ? (
|
||||
<i className={`bi-file-earmark-image`}></i>
|
||||
) : undefined}
|
||||
<p className="truncate bg-white text-black mr-1">
|
||||
<p className="text-sm">{shortendURL}</p>
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import Image from "next/image";
|
||||
import isValidUrl from "@/lib/shared/isValidUrl";
|
||||
import React from "react";
|
||||
|
||||
export default function LinkIcon({
|
||||
link,
|
||||
width,
|
||||
}: {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
width?: string;
|
||||
}) {
|
||||
const url =
|
||||
isValidUrl(link.url || "") && link.url ? new URL(link.url) : undefined;
|
||||
|
||||
const iconClasses: string =
|
||||
"bg-white shadow rounded-md border-[2px] flex item-center justify-center border-white select-none z-10" +
|
||||
" " +
|
||||
(width || "w-12");
|
||||
|
||||
const [showFavicon, setShowFavicon] = React.useState<boolean>(true);
|
||||
|
||||
return (
|
||||
<>
|
||||
{link.url && url && showFavicon ? (
|
||||
<Image
|
||||
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${link.url}&size=32`}
|
||||
width={64}
|
||||
height={64}
|
||||
alt=""
|
||||
className={iconClasses}
|
||||
draggable="false"
|
||||
onError={() => {
|
||||
setShowFavicon(false);
|
||||
}}
|
||||
/>
|
||||
) : showFavicon === false ? (
|
||||
<div className={iconClasses}>
|
||||
<i className="bi-link-45deg text-4xl text-black"></i>
|
||||
</div>
|
||||
) : link.type === "pdf" ? (
|
||||
<i className={`bi-file-earmark-pdf ${iconClasses}`}></i>
|
||||
) : link.type === "image" ? (
|
||||
<i className={`bi-file-earmark-image ${iconClasses}`}></i>
|
||||
) : undefined}
|
||||
</>
|
||||
);
|
||||
}
|
111
Securite/Linkwarden/components/LinkViews/LinkGrid.tsx
Normal file
@ -0,0 +1,111 @@
|
||||
import {
|
||||
CollectionIncludingMembersAndLinkCount,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import { useEffect, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
|
||||
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
|
||||
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
|
||||
import LinkIcon from "@/components/LinkViews/LinkComponents/LinkIcon";
|
||||
import Link from "next/link";
|
||||
|
||||
type Props = {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
count: number;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function LinkGrid({ link }: Props) {
|
||||
const { collections } = useCollectionStore();
|
||||
|
||||
const { links } = useLinkStore();
|
||||
|
||||
let shortendURL;
|
||||
|
||||
try {
|
||||
shortendURL = new URL(link.url || "").host.toLowerCase();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
const [collection, setCollection] =
|
||||
useState<CollectionIncludingMembersAndLinkCount>(
|
||||
collections.find(
|
||||
(e) => e.id === link.collection.id
|
||||
) as CollectionIncludingMembersAndLinkCount
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setCollection(
|
||||
collections.find(
|
||||
(e) => e.id === link.collection.id
|
||||
) as CollectionIncludingMembersAndLinkCount
|
||||
);
|
||||
}, [collections, links]);
|
||||
|
||||
return (
|
||||
<div className="border border-solid border-neutral-content bg-base-200 shadow-md hover:shadow-none duration-100 rounded-2xl relative p-3">
|
||||
<div
|
||||
onClick={() => link.url && window.open(link.url || "", "_blank")}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<LinkIcon link={link} width="w-12 mb-3" />
|
||||
<p className="truncate w-full">
|
||||
{unescapeString(link.name || link.description) || link.url}
|
||||
</p>
|
||||
|
||||
<div className="mt-1 flex flex-col text-xs text-neutral">
|
||||
<div className="flex items-center gap-2">
|
||||
<LinkCollection link={link} collection={collection} />
|
||||
·
|
||||
{link.url ? (
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
window.open(link.url || "", "_blank");
|
||||
}}
|
||||
className="flex items-center hover:opacity-60 cursor-pointer duration-100"
|
||||
>
|
||||
<p className="truncate">{shortendURL}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="badge badge-primary badge-sm my-1">
|
||||
{link.type}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<LinkDate link={link} />
|
||||
</div>
|
||||
<p className="truncate">{unescapeString(link.description)}</p>
|
||||
{link.tags[0] ? (
|
||||
<div className="flex gap-3 items-center flex-wrap mt-2 truncate relative">
|
||||
<div className="flex gap-1 items-center flex-wrap">
|
||||
{link.tags.map((e, i) => (
|
||||
<Link
|
||||
href={"/tags/" + e.id}
|
||||
key={i}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
|
||||
>
|
||||
#{e.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : undefined}
|
||||
</div>
|
||||
|
||||
<LinkActions
|
||||
toggleShowInfo={() => {}}
|
||||
linkInfo={false}
|
||||
link={link}
|
||||
collection={collection}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
181
Securite/Linkwarden/components/LinkViews/LinkList.tsx
Normal file
@ -0,0 +1,181 @@
|
||||
import {
|
||||
CollectionIncludingMembersAndLinkCount,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import { useEffect, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
|
||||
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
|
||||
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
|
||||
import LinkIcon from "@/components/LinkViews/LinkComponents/LinkIcon";
|
||||
import Link from "next/link";
|
||||
import { isPWA } from "@/lib/client/utils";
|
||||
import { generateLinkHref } from "@/lib/client/generateLinkHref";
|
||||
import useAccountStore from "@/store/account";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
type Props = {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
count: number;
|
||||
className?: string;
|
||||
flipDropdown?: boolean;
|
||||
editMode?: boolean;
|
||||
};
|
||||
|
||||
export default function LinkCardCompact({
|
||||
link,
|
||||
flipDropdown,
|
||||
editMode,
|
||||
}: Props) {
|
||||
const { collections } = useCollectionStore();
|
||||
const { account } = useAccountStore();
|
||||
const { links, setSelectedLinks, selectedLinks } = useLinkStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (!editMode) {
|
||||
setSelectedLinks([]);
|
||||
}
|
||||
}, [editMode]);
|
||||
|
||||
const handleCheckboxClick = (
|
||||
link: LinkIncludingShortenedCollectionAndTags
|
||||
) => {
|
||||
const linkIndex = selectedLinks.findIndex(
|
||||
(selectedLink) => selectedLink.id === link.id
|
||||
);
|
||||
|
||||
if (linkIndex !== -1) {
|
||||
const updatedLinks = [...selectedLinks];
|
||||
updatedLinks.splice(linkIndex, 1);
|
||||
setSelectedLinks(updatedLinks);
|
||||
} else {
|
||||
setSelectedLinks([...selectedLinks, link]);
|
||||
}
|
||||
};
|
||||
|
||||
let shortendURL;
|
||||
|
||||
try {
|
||||
shortendURL = new URL(link.url || "").host.toLowerCase();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
const [collection, setCollection] =
|
||||
useState<CollectionIncludingMembersAndLinkCount>(
|
||||
collections.find(
|
||||
(e) => e.id === link.collection.id
|
||||
) as CollectionIncludingMembersAndLinkCount
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setCollection(
|
||||
collections.find(
|
||||
(e) => e.id === link.collection.id
|
||||
) as CollectionIncludingMembersAndLinkCount
|
||||
);
|
||||
}, [collections, links]);
|
||||
|
||||
const permissions = usePermissions(collection?.id as number);
|
||||
|
||||
const [showInfo, setShowInfo] = useState(false);
|
||||
|
||||
const selectedStyle = selectedLinks.some(
|
||||
(selectedLink) => selectedLink.id === link.id
|
||||
)
|
||||
? "border border-primary bg-base-300"
|
||||
: "border-transparent";
|
||||
|
||||
const selectable =
|
||||
editMode &&
|
||||
(permissions === true || permissions?.canCreate || permissions?.canDelete);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`${selectedStyle} border relative items-center flex ${
|
||||
!showInfo && !isPWA() ? "hover:bg-base-300 p-3" : "py-3"
|
||||
} duration-200 rounded-lg`}
|
||||
onClick={() =>
|
||||
selectable
|
||||
? handleCheckboxClick(link)
|
||||
: editMode
|
||||
? toast.error(
|
||||
"You don't have permission to edit or delete this item."
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{/* {showCheckbox &&
|
||||
editMode &&
|
||||
(permissions === true ||
|
||||
permissions?.canCreate ||
|
||||
permissions?.canDelete) && (
|
||||
<input
|
||||
type="checkbox"
|
||||
className="checkbox checkbox-primary my-auto mr-2"
|
||||
checked={selectedLinks.some(
|
||||
(selectedLink) => selectedLink.id === link.id
|
||||
)}
|
||||
onChange={() => handleCheckboxClick(link)}
|
||||
/>
|
||||
)} */}
|
||||
<div
|
||||
className="flex items-center cursor-pointer"
|
||||
onClick={() =>
|
||||
!editMode && window.open(generateLinkHref(link, account), "_blank")
|
||||
}
|
||||
>
|
||||
<div className="shrink-0">
|
||||
<LinkIcon link={link} width="sm:w-12 w-8 mt-1 sm:mt-0" />
|
||||
</div>
|
||||
|
||||
<div className="w-[calc(100%-56px)] ml-2">
|
||||
<p className="line-clamp-1 mr-8 text-primary select-none">
|
||||
{unescapeString(link.name || link.description) || link.url}
|
||||
</p>
|
||||
|
||||
<div className="mt-1 flex flex-col sm:flex-row sm:items-center gap-2 text-xs text-neutral">
|
||||
<div className="flex items-center gap-x-3 w-fit text-neutral flex-wrap">
|
||||
{collection ? (
|
||||
<LinkCollection link={link} collection={collection} />
|
||||
) : undefined}
|
||||
{link.url ? (
|
||||
<Link
|
||||
href={link.url || ""}
|
||||
target="_blank"
|
||||
title={link.url || ""}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="flex gap-1 item-center select-none text-neutral mt-1 hover:opacity-70 duration-100"
|
||||
>
|
||||
<i className="bi-link-45deg text-lg mt-[0.1rem] leading-none"></i>
|
||||
<p className="text-sm truncate">{shortendURL}</p>
|
||||
</Link>
|
||||
) : (
|
||||
<div className="badge badge-primary badge-sm my-1 select-none">
|
||||
{link.type}
|
||||
</div>
|
||||
)}
|
||||
<LinkDate link={link} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<LinkActions
|
||||
link={link}
|
||||
collection={collection}
|
||||
position="top-3 right-3"
|
||||
flipDropdown={flipDropdown}
|
||||
// toggleShowInfo={() => setShowInfo(!showInfo)}
|
||||
// linkInfo={showInfo}
|
||||
/>
|
||||
</div>
|
||||
<div className="divider my-0 last:hidden h-[1px]"></div>
|
||||
</>
|
||||
);
|
||||
}
|
7
Securite/Linkwarden/components/Loader.tsx
Normal file
@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div>
|
||||
<p>Loading...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
96
Securite/Linkwarden/components/MobileNavigation.tsx
Normal file
@ -0,0 +1,96 @@
|
||||
import { dropdownTriggerer, isIphone } from "@/lib/client/utils";
|
||||
import React from "react";
|
||||
import { useState } from "react";
|
||||
import NewLinkModal from "./ModalContent/NewLinkModal";
|
||||
import NewCollectionModal from "./ModalContent/NewCollectionModal";
|
||||
import UploadFileModal from "./ModalContent/UploadFileModal";
|
||||
import MobileNavigationButton from "./MobileNavigationButton";
|
||||
|
||||
type Props = {};
|
||||
|
||||
export default function MobileNavigation({}: Props) {
|
||||
const [newLinkModal, setNewLinkModal] = useState(false);
|
||||
const [newCollectionModal, setNewCollectionModal] = useState(false);
|
||||
const [uploadFileModal, setUploadFileModal] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`fixed bottom-0 left-0 right-0 z-30 duration-200 sm:hidden`}
|
||||
>
|
||||
<div
|
||||
className={`w-full flex bg-base-100 ${
|
||||
isIphone() ? "pb-5" : ""
|
||||
} border-solid border-t-neutral-content border-t`}
|
||||
>
|
||||
<MobileNavigationButton href={`/dashboard`} icon={"bi-house"} />
|
||||
<MobileNavigationButton
|
||||
href={`/links/pinned`}
|
||||
icon={"bi-pin-angle"}
|
||||
/>
|
||||
<div className="dropdown dropdown-top -mt-4">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className={`flex items-center btn btn-accent dark:border-violet-400 text-white btn-circle w-20 h-20 px-2 relative`}
|
||||
>
|
||||
<span>
|
||||
<i className="bi-plus text-5xl pointer-events-none"></i>
|
||||
</span>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box w-40 mb-1 -ml-12">
|
||||
<li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setNewLinkModal(true);
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
New Link
|
||||
</div>
|
||||
</li>
|
||||
{/* <li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setUploadFileModal(true);
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
Upload File
|
||||
</div>
|
||||
</li> */}
|
||||
<li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setNewCollectionModal(true);
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
New Collection
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<MobileNavigationButton href={`/links`} icon={"bi-link-45deg"} />
|
||||
<MobileNavigationButton href={`/collections`} icon={"bi-folder"} />
|
||||
</div>
|
||||
</div>
|
||||
{newLinkModal ? (
|
||||
<NewLinkModal onClose={() => setNewLinkModal(false)} />
|
||||
) : undefined}
|
||||
{newCollectionModal ? (
|
||||
<NewCollectionModal onClose={() => setNewCollectionModal(false)} />
|
||||
) : undefined}
|
||||
{uploadFileModal ? (
|
||||
<UploadFileModal onClose={() => setUploadFileModal(false)} />
|
||||
) : undefined}
|
||||
</>
|
||||
);
|
||||
}
|
45
Securite/Linkwarden/components/MobileNavigationButton.tsx
Normal file
@ -0,0 +1,45 @@
|
||||
import { isPWA } from "@/lib/client/utils";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function MobileNavigationButton({
|
||||
href,
|
||||
icon,
|
||||
}: {
|
||||
href: string;
|
||||
icon: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [active, setActive] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setActive(href === router.asPath);
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
className="w-full active:scale-[80%] duration-200 select-none"
|
||||
draggable="false"
|
||||
style={{ WebkitTouchCallout: "none" }}
|
||||
onContextMenu={(e) => {
|
||||
if (isPWA()) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
} else return null;
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={`py-2 cursor-pointer gap-2 w-full rounded-full capitalize flex items-center justify-center`}
|
||||
>
|
||||
<i
|
||||
className={`${icon} text-primary text-3xl drop-shadow duration-200 rounded-full w-14 h-14 text-center pt-[0.65rem] ${
|
||||
active || false ? "bg-primary/20" : ""
|
||||
}`}
|
||||
></i>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
67
Securite/Linkwarden/components/Modal.tsx
Normal file
@ -0,0 +1,67 @@
|
||||
import React, { MouseEventHandler, ReactNode, useEffect } from "react";
|
||||
import ClickAwayHandler from "@/components/ClickAwayHandler";
|
||||
import { Drawer } from "vaul";
|
||||
|
||||
type Props = {
|
||||
toggleModal: Function;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function Modal({ toggleModal, className, children }: Props) {
|
||||
const [drawerIsOpen, setDrawerIsOpen] = React.useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (window.innerWidth >= 640) {
|
||||
document.body.style.overflow = "hidden";
|
||||
document.body.style.position = "relative";
|
||||
return () => {
|
||||
document.body.style.overflow = "auto";
|
||||
document.body.style.position = "";
|
||||
};
|
||||
}
|
||||
}, []);
|
||||
|
||||
if (window.innerWidth < 640) {
|
||||
return (
|
||||
<Drawer.Root
|
||||
open={drawerIsOpen}
|
||||
onClose={() => setTimeout(() => toggleModal(), 100)}
|
||||
>
|
||||
<Drawer.Portal>
|
||||
<Drawer.Overlay className="fixed inset-0 bg-black/40" />
|
||||
<ClickAwayHandler onClickOutside={() => setDrawerIsOpen(false)}>
|
||||
<Drawer.Content className="flex flex-col rounded-t-2xl h-[90%] mt-24 fixed bottom-0 left-0 right-0 z-30">
|
||||
<div className="p-4 pb-32 bg-base-100 rounded-t-2xl flex-1 border-neutral-content border-t overflow-y-auto">
|
||||
<div className="mx-auto w-12 h-1.5 flex-shrink-0 rounded-full bg-neutral mb-5" />
|
||||
|
||||
{children}
|
||||
</div>
|
||||
</Drawer.Content>
|
||||
</ClickAwayHandler>
|
||||
</Drawer.Portal>
|
||||
</Drawer.Root>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<div className="overflow-y-auto pt-2 sm:py-2 fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex justify-center items-center fade-in z-40">
|
||||
<ClickAwayHandler
|
||||
onClickOutside={toggleModal}
|
||||
className={`w-full mt-auto sm:m-auto sm:w-11/12 sm:max-w-2xl ${
|
||||
className || ""
|
||||
}`}
|
||||
>
|
||||
<div className="slide-up mt-auto sm:m-auto relative border-neutral-content rounded-t-2xl sm:rounded-2xl border-t sm:border shadow-2xl p-5 bg-base-100 overflow-y-auto sm:overflow-y-visible">
|
||||
<div
|
||||
onClick={toggleModal as MouseEventHandler<HTMLDivElement>}
|
||||
className="absolute top-4 right-3 btn btn-sm outline-none btn-circle btn-ghost z-10"
|
||||
>
|
||||
<i className="bi-x text-neutral text-2xl"></i>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</ClickAwayHandler>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
import React from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
};
|
||||
|
||||
export default function BulkDeleteLinksModal({ onClose }: Props) {
|
||||
const { selectedLinks, setSelectedLinks, deleteLinksById } = useLinkStore();
|
||||
|
||||
const deleteLink = async () => {
|
||||
const load = toast.loading(
|
||||
`Deleting ${selectedLinks.length} Link${
|
||||
selectedLinks.length > 1 ? "s" : ""
|
||||
}...`
|
||||
);
|
||||
|
||||
const response = await deleteLinksById(
|
||||
selectedLinks.map((link) => link.id as number)
|
||||
);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(
|
||||
`Deleted ${selectedLinks.length} Link${
|
||||
selectedLinks.length > 1 ? "s" : ""
|
||||
}`
|
||||
);
|
||||
|
||||
setSelectedLinks([]);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin text-red-500">
|
||||
Delete {selectedLinks.length} Link{selectedLinks.length > 1 ? "s" : ""}
|
||||
</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{selectedLinks.length > 1 ? (
|
||||
<p>Are you sure you want to delete {selectedLinks.length} links?</p>
|
||||
) : (
|
||||
<p>Are you sure you want to delete this link?</p>
|
||||
)}
|
||||
|
||||
<div role="alert" className="alert alert-warning">
|
||||
<i className="bi-exclamation-triangle text-xl" />
|
||||
<span>
|
||||
<b>Warning:</b> This action is irreversible!
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Hold the <kbd className="kbd kbd-sm">Shift</kbd> key while clicking
|
||||
'Delete' to bypass this confirmation in the future.
|
||||
</p>
|
||||
|
||||
<button
|
||||
className={`ml-auto btn w-fit text-white flex items-center gap-2 duration-100 bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer`}
|
||||
onClick={deleteLink}
|
||||
>
|
||||
<i className="bi-trash text-xl" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,102 @@
|
||||
import React, { useState } from "react";
|
||||
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
|
||||
import TagSelection from "@/components/InputSelect/TagSelection";
|
||||
import useLinkStore from "@/store/links";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
};
|
||||
|
||||
export default function BulkEditLinksModal({ onClose }: Props) {
|
||||
const { updateLinks, selectedLinks, setSelectedLinks } = useLinkStore();
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
const [removePreviousTags, setRemovePreviousTags] = useState(false);
|
||||
const [updatedValues, setUpdatedValues] = useState<
|
||||
Pick<LinkIncludingShortenedCollectionAndTags, "tags" | "collectionId">
|
||||
>({ tags: [] });
|
||||
|
||||
const setCollection = (e: any) => {
|
||||
const collectionId = e?.value || null;
|
||||
console.log(updatedValues);
|
||||
setUpdatedValues((prevValues) => ({ ...prevValues, collectionId }));
|
||||
};
|
||||
|
||||
const setTags = (e: any) => {
|
||||
const tags = e.map((tag: any) => ({ name: tag.label }));
|
||||
setUpdatedValues((prevValues) => ({ ...prevValues, tags }));
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Updating...");
|
||||
|
||||
const response = await updateLinks(
|
||||
selectedLinks,
|
||||
removePreviousTags,
|
||||
updatedValues
|
||||
);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Updated!`);
|
||||
setSelectedLinks([]);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
return response;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">
|
||||
Edit {selectedLinks.length} Link{selectedLinks.length > 1 ? "s" : ""}
|
||||
</p>
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
<div className="mt-5">
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<p className="mb-2">Move to Collection</p>
|
||||
<CollectionSelection
|
||||
showDefaultValue={false}
|
||||
onChange={setCollection}
|
||||
creatable={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2">Add Tags</p>
|
||||
<TagSelection onChange={setTags} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="sm:ml-auto w-1/2 p-3">
|
||||
<label className="flex items-center gap-2 ">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="checkbox checkbox-primary"
|
||||
checked={removePreviousTags}
|
||||
onChange={(e) => setRemovePreviousTags(e.target.checked)}
|
||||
/>
|
||||
Remove previous tags
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end items-center mt-5">
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white"
|
||||
onClick={submit}
|
||||
>
|
||||
Save Changes
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import toast from "react-hot-toast";
|
||||
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
||||
import { useRouter } from "next/router";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeCollection: CollectionIncludingMembersAndLinkCount;
|
||||
};
|
||||
|
||||
export default function DeleteCollectionModal({
|
||||
onClose,
|
||||
activeCollection,
|
||||
}: Props) {
|
||||
const [collection, setCollection] =
|
||||
useState<CollectionIncludingMembersAndLinkCount>(activeCollection);
|
||||
|
||||
useEffect(() => {
|
||||
setCollection(activeCollection);
|
||||
}, []);
|
||||
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
const { removeCollection } = useCollectionStore();
|
||||
const router = useRouter();
|
||||
const [inputField, setInputField] = useState("");
|
||||
|
||||
const permissions = usePermissions(collection.id as number);
|
||||
|
||||
const submit = async () => {
|
||||
if (permissions === true) if (collection.name !== inputField) return null;
|
||||
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
if (!collection) return null;
|
||||
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Deleting...");
|
||||
|
||||
let response;
|
||||
|
||||
response = await removeCollection(collection.id as any);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Deleted.`);
|
||||
onClose();
|
||||
router.push("/collections");
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin text-red-500">
|
||||
{permissions === true ? "Delete" : "Leave"} Collection
|
||||
</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{permissions === true ? (
|
||||
<>
|
||||
<div className="flex flex-col gap-3">
|
||||
<p>
|
||||
To confirm, type "
|
||||
<span className="font-bold">{collection.name}</span>
|
||||
" in the box below:
|
||||
</p>
|
||||
|
||||
<TextInput
|
||||
value={inputField}
|
||||
onChange={(e) => setInputField(e.target.value)}
|
||||
placeholder={`Type "${collection.name}" Here.`}
|
||||
className="w-3/4 mx-auto"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div role="alert" className="alert alert-warning">
|
||||
<i className="bi-exclamation-triangle text-xl"></i>
|
||||
<span>
|
||||
<b>Warning:</b> Deleting this collection will permanently erase
|
||||
all its contents, and it will become inaccessible to everyone,
|
||||
including members with previous access.
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p>Click the button below to leave the current collection.</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
disabled={permissions === true && inputField !== collection.name}
|
||||
className={`ml-auto btn w-fit text-white flex items-center gap-2 duration-100 ${
|
||||
permissions === true
|
||||
? inputField === collection.name
|
||||
? "bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer"
|
||||
: "cursor-not-allowed bg-red-300 dark:bg-red-900"
|
||||
: "bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer"
|
||||
}`}
|
||||
onClick={submit}
|
||||
>
|
||||
<i className="bi-trash text-xl"></i>
|
||||
{permissions === true ? "Delete" : "Leave"} Collection
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeLink: LinkIncludingShortenedCollectionAndTags;
|
||||
};
|
||||
|
||||
export default function DeleteLinkModal({ onClose, activeLink }: Props) {
|
||||
const [link, setLink] =
|
||||
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
|
||||
|
||||
const { removeLink } = useLinkStore();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
setLink(activeLink);
|
||||
}, []);
|
||||
|
||||
const deleteLink = async () => {
|
||||
const load = toast.loading("Deleting...");
|
||||
|
||||
const response = await removeLink(link.id as number);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
response.ok && toast.success(`Link Deleted.`);
|
||||
|
||||
if (router.pathname.startsWith("/links/[id]")) {
|
||||
router.push("/dashboard");
|
||||
}
|
||||
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin text-red-500">Delete Link</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<p>Are you sure you want to delete this Link?</p>
|
||||
|
||||
<div role="alert" className="alert alert-warning">
|
||||
<i className="bi-exclamation-triangle text-xl" />
|
||||
<span>
|
||||
<b>Warning:</b> This action is irreversible!
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Hold the <kbd className="kbd kbd-sm">Shift</kbd> key while clicking
|
||||
'Delete' to bypass this confirmation in the future.
|
||||
</p>
|
||||
|
||||
<button
|
||||
className={`ml-auto btn w-fit text-white flex items-center gap-2 duration-100 bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer`}
|
||||
onClick={deleteLink}
|
||||
>
|
||||
<i className="bi-trash text-xl" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
import React, { useState } from "react";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import toast from "react-hot-toast";
|
||||
import { HexColorPicker } from "react-colorful";
|
||||
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeCollection: CollectionIncludingMembersAndLinkCount;
|
||||
};
|
||||
|
||||
export default function EditCollectionModal({
|
||||
onClose,
|
||||
activeCollection,
|
||||
}: Props) {
|
||||
const [collection, setCollection] =
|
||||
useState<CollectionIncludingMembersAndLinkCount>(activeCollection);
|
||||
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
const { updateCollection } = useCollectionStore();
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
if (!collection) return null;
|
||||
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Updating...");
|
||||
|
||||
let response;
|
||||
|
||||
response = await updateCollection(collection as any);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Updated!`);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">Edit Collection Info</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Name</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
<TextInput
|
||||
className="bg-base-200"
|
||||
value={collection.name}
|
||||
placeholder="e.g. Example Collection"
|
||||
onChange={(e) =>
|
||||
setCollection({ ...collection, name: e.target.value })
|
||||
}
|
||||
/>
|
||||
<div>
|
||||
<p className="w-full mb-2">Color</p>
|
||||
<div className="color-picker flex justify-between">
|
||||
<div className="flex flex-col gap-2 items-center w-32">
|
||||
<i
|
||||
className="bi-folder-fill text-5xl drop-shadow"
|
||||
style={{ color: collection.color }}
|
||||
></i>
|
||||
<div
|
||||
className="btn btn-ghost btn-xs"
|
||||
onClick={() =>
|
||||
setCollection({ ...collection, color: "#0ea5e9" })
|
||||
}
|
||||
>
|
||||
Reset
|
||||
</div>
|
||||
</div>
|
||||
<HexColorPicker
|
||||
color={collection.color}
|
||||
onChange={(e) => setCollection({ ...collection, color: e })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Description</p>
|
||||
<textarea
|
||||
className="w-full h-[13rem] resize-none border rounded-md duration-100 bg-base-200 p-2 outline-none border-neutral-content focus:border-primary"
|
||||
placeholder="The purpose of this Collection..."
|
||||
value={collection.description}
|
||||
onChange={(e) =>
|
||||
setCollection({
|
||||
...collection,
|
||||
description: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white w-fit ml-auto"
|
||||
onClick={submit}
|
||||
>
|
||||
Save Changes
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,451 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import toast from "react-hot-toast";
|
||||
import { CollectionIncludingMembersAndLinkCount, Member } from "@/types/global";
|
||||
import getPublicUserData from "@/lib/client/getPublicUserData";
|
||||
import useAccountStore from "@/store/account";
|
||||
import usePermissions from "@/hooks/usePermissions";
|
||||
import ProfilePhoto from "../ProfilePhoto";
|
||||
import addMemberToCollection from "@/lib/client/addMemberToCollection";
|
||||
import Modal from "../Modal";
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeCollection: CollectionIncludingMembersAndLinkCount;
|
||||
};
|
||||
|
||||
export default function EditCollectionSharingModal({
|
||||
onClose,
|
||||
activeCollection,
|
||||
}: Props) {
|
||||
const [collection, setCollection] =
|
||||
useState<CollectionIncludingMembersAndLinkCount>(activeCollection);
|
||||
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
const { updateCollection } = useCollectionStore();
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
if (!collection) return null;
|
||||
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Updating...");
|
||||
|
||||
let response;
|
||||
|
||||
response = await updateCollection(collection as any);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Updated!`);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
}
|
||||
};
|
||||
|
||||
const { account } = useAccountStore();
|
||||
const permissions = usePermissions(collection.id as number);
|
||||
|
||||
const currentURL = new URL(document.URL);
|
||||
|
||||
const publicCollectionURL = `${currentURL.origin}/public/collections/${collection.id}`;
|
||||
|
||||
const [memberUsername, setMemberUsername] = useState("");
|
||||
|
||||
const [collectionOwner, setCollectionOwner] = useState({
|
||||
id: null as unknown as number,
|
||||
name: "",
|
||||
username: "",
|
||||
image: "",
|
||||
archiveAsScreenshot: undefined as unknown as boolean,
|
||||
archiveAsPDF: undefined as unknown as boolean,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchOwner = async () => {
|
||||
const owner = await getPublicUserData(collection.ownerId as number);
|
||||
setCollectionOwner(owner);
|
||||
};
|
||||
|
||||
fetchOwner();
|
||||
|
||||
setCollection(activeCollection);
|
||||
}, []);
|
||||
|
||||
const setMemberState = (newMember: Member) => {
|
||||
if (!collection) return null;
|
||||
|
||||
setCollection({
|
||||
...collection,
|
||||
members: [...collection.members, newMember],
|
||||
});
|
||||
|
||||
setMemberUsername("");
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">
|
||||
{permissions === true ? "Share and Collaborate" : "Team"}
|
||||
</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{permissions === true && (
|
||||
<div>
|
||||
<p>Make Public</p>
|
||||
|
||||
<label className="label cursor-pointer justify-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={collection.isPublic}
|
||||
onChange={() =>
|
||||
setCollection({
|
||||
...collection,
|
||||
isPublic: !collection.isPublic,
|
||||
})
|
||||
}
|
||||
className="checkbox checkbox-primary"
|
||||
/>
|
||||
<span className="label-text">Make this a public collection</span>
|
||||
</label>
|
||||
|
||||
<p className="text-neutral text-sm">
|
||||
This will let <b>Anyone</b> to view this collection and it's
|
||||
users.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{collection.isPublic ? (
|
||||
<div className={permissions === true ? "pl-5" : ""}>
|
||||
<p className="mb-2">Sharable Link (Click to copy)</p>
|
||||
<div
|
||||
onClick={() => {
|
||||
try {
|
||||
navigator.clipboard
|
||||
.writeText(publicCollectionURL)
|
||||
.then(() => toast.success("Copied!"));
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}}
|
||||
className="w-full hide-scrollbar overflow-x-auto whitespace-nowrap rounded-md p-2 bg-base-200 border-neutral-content border-solid border outline-none hover:border-primary dark:hover:border-primary duration-100 cursor-text"
|
||||
>
|
||||
{publicCollectionURL}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{permissions === true && <div className="divider my-3"></div>}
|
||||
|
||||
{permissions === true && (
|
||||
<>
|
||||
<p>Members</p>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<TextInput
|
||||
value={memberUsername || ""}
|
||||
className="bg-base-200"
|
||||
placeholder="Username (without the '@')"
|
||||
onChange={(e) => setMemberUsername(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === "Enter" &&
|
||||
addMemberToCollection(
|
||||
account.username as string,
|
||||
memberUsername || "",
|
||||
collection,
|
||||
setMemberState
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<div
|
||||
onClick={() =>
|
||||
addMemberToCollection(
|
||||
account.username as string,
|
||||
memberUsername || "",
|
||||
collection,
|
||||
setMemberState
|
||||
)
|
||||
}
|
||||
className="btn btn-accent dark:border-violet-400 text-white btn-square btn-sm h-10 w-10"
|
||||
>
|
||||
<i className="bi-person-add text-xl"></i>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{collection?.members[0]?.user && (
|
||||
<>
|
||||
<div className="flex flex-col divide-y divide-neutral-content border border-neutral-content rounded-xl bg-base-200">
|
||||
<div
|
||||
className="relative p-3 bg-base-200 rounded-xl flex gap-2 justify-between"
|
||||
title={`@${collectionOwner.username} is the owner of this collection`}
|
||||
>
|
||||
<div className={"flex items-center justify-between w-full"}>
|
||||
<div className={"flex items-center"}>
|
||||
<div className={"shrink-0"}>
|
||||
<ProfilePhoto
|
||||
src={
|
||||
collectionOwner.image
|
||||
? collectionOwner.image
|
||||
: undefined
|
||||
}
|
||||
name={collectionOwner.name}
|
||||
/>
|
||||
</div>
|
||||
<div className={"grow ml-2"}>
|
||||
<p className="text-sm font-semibold">
|
||||
{collectionOwner.name}
|
||||
</p>
|
||||
<p className="text-xs text-neutral">
|
||||
@{collectionOwner.username}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold">Owner</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="divider my-0 last:hidden h-[3px]"></div>
|
||||
|
||||
{collection.members
|
||||
.sort((a, b) => (a.userId as number) - (b.userId as number))
|
||||
.map((e, i) => {
|
||||
const roleLabel =
|
||||
e.canCreate && e.canUpdate && e.canDelete
|
||||
? "Admin"
|
||||
: e.canCreate && !e.canUpdate && !e.canDelete
|
||||
? "Contributor"
|
||||
: !e.canCreate && !e.canUpdate && !e.canDelete
|
||||
? "Viewer"
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<React.Fragment key={i}>
|
||||
<div className="relative p-3 bg-base-200 rounded-xl flex gap-2 justify-between border-none">
|
||||
<div
|
||||
className={"flex items-center justify-between w-full"}
|
||||
>
|
||||
<div className={"flex items-center"}>
|
||||
<div className={"shrink-0"}>
|
||||
<ProfilePhoto
|
||||
src={e.user.image ? e.user.image : undefined}
|
||||
name={e.user.name}
|
||||
/>
|
||||
</div>
|
||||
<div className={"grow ml-2"}>
|
||||
<p className="text-sm font-semibold">
|
||||
{e.user.name}
|
||||
</p>
|
||||
<p className="text-xs text-neutral">
|
||||
@{e.user.username}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={"flex items-center gap-2"}>
|
||||
{permissions === true ? (
|
||||
<div className="dropdown dropdown-bottom dropdown-end">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-sm btn-primary font-normal"
|
||||
>
|
||||
{roleLabel}
|
||||
<i className="bi-chevron-down"></i>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl w-64 mt-1">
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`role-radio-${e.userId}`}
|
||||
className="radio checked:bg-primary"
|
||||
checked={
|
||||
!e.canCreate &&
|
||||
!e.canUpdate &&
|
||||
!e.canDelete
|
||||
}
|
||||
onChange={() => {
|
||||
const updatedMember = {
|
||||
...e,
|
||||
canCreate: false,
|
||||
canUpdate: false,
|
||||
canDelete: false,
|
||||
};
|
||||
const updatedMembers =
|
||||
collection.members.map((member) =>
|
||||
member.userId === e.userId
|
||||
? updatedMember
|
||||
: member
|
||||
);
|
||||
setCollection({
|
||||
...collection,
|
||||
members: updatedMembers,
|
||||
});
|
||||
(
|
||||
document?.activeElement as HTMLElement
|
||||
)?.blur();
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<p className="font-bold">Viewer</p>
|
||||
<p>Read-only access</p>
|
||||
</div>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`role-radio-${e.userId}`}
|
||||
className="radio checked:bg-primary"
|
||||
checked={
|
||||
e.canCreate &&
|
||||
!e.canUpdate &&
|
||||
!e.canDelete
|
||||
}
|
||||
onChange={() => {
|
||||
const updatedMember = {
|
||||
...e,
|
||||
canCreate: true,
|
||||
canUpdate: false,
|
||||
canDelete: false,
|
||||
};
|
||||
const updatedMembers =
|
||||
collection.members.map((member) =>
|
||||
member.userId === e.userId
|
||||
? updatedMember
|
||||
: member
|
||||
);
|
||||
setCollection({
|
||||
...collection,
|
||||
members: updatedMembers,
|
||||
});
|
||||
(
|
||||
document?.activeElement as HTMLElement
|
||||
)?.blur();
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<p className="font-bold">Contributor</p>
|
||||
<p>Can view and create Links</p>
|
||||
</div>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name={`role-radio-${e.userId}`}
|
||||
className="radio checked:bg-primary"
|
||||
checked={
|
||||
e.canCreate &&
|
||||
e.canUpdate &&
|
||||
e.canDelete
|
||||
}
|
||||
onChange={() => {
|
||||
const updatedMember = {
|
||||
...e,
|
||||
canCreate: true,
|
||||
canUpdate: true,
|
||||
canDelete: true,
|
||||
};
|
||||
const updatedMembers =
|
||||
collection.members.map((member) =>
|
||||
member.userId === e.userId
|
||||
? updatedMember
|
||||
: member
|
||||
);
|
||||
setCollection({
|
||||
...collection,
|
||||
members: updatedMembers,
|
||||
});
|
||||
(
|
||||
document?.activeElement as HTMLElement
|
||||
)?.blur();
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<p className="font-bold">Admin</p>
|
||||
<p>Full access to all Links</p>
|
||||
</div>
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-neutral">
|
||||
{roleLabel}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{permissions === true && (
|
||||
<i
|
||||
className={
|
||||
"bi-x text-xl btn btn-sm btn-square btn-ghost text-neutral hover:text-red-500 dark:hover:text-red-500 duration-100 cursor-pointer"
|
||||
}
|
||||
title="Remove Member"
|
||||
onClick={() => {
|
||||
const updatedMembers =
|
||||
collection.members.filter((member) => {
|
||||
return (
|
||||
member.user.username !== e.user.username
|
||||
);
|
||||
});
|
||||
setCollection({
|
||||
...collection,
|
||||
members: updatedMembers,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divider my-0 last:hidden h-[3px]"></div>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{permissions === true && (
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white w-fit ml-auto mt-3"
|
||||
onClick={submit}
|
||||
>
|
||||
Save Changes
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
166
Securite/Linkwarden/components/ModalContent/EditLinkModal.tsx
Normal file
@ -0,0 +1,166 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
|
||||
import TagSelection from "@/components/InputSelect/TagSelection";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import useLinkStore from "@/store/links";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Link from "next/link";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeLink: LinkIncludingShortenedCollectionAndTags;
|
||||
};
|
||||
|
||||
export default function EditLinkModal({ onClose, activeLink }: Props) {
|
||||
const [link, setLink] =
|
||||
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
|
||||
|
||||
let shortendURL;
|
||||
|
||||
try {
|
||||
shortendURL = new URL(link.url || "").host.toLowerCase();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
const { updateLink } = useLinkStore();
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
|
||||
const setCollection = (e: any) => {
|
||||
if (e?.__isNew__) e.value = null;
|
||||
|
||||
setLink({
|
||||
...link,
|
||||
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
|
||||
});
|
||||
};
|
||||
|
||||
const setTags = (e: any) => {
|
||||
const tagNames = e.map((e: any) => {
|
||||
return { name: e.label };
|
||||
});
|
||||
|
||||
setLink({ ...link, tags: tagNames });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setLink(activeLink);
|
||||
}, []);
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
|
||||
let response;
|
||||
|
||||
const load = toast.loading("Updating...");
|
||||
|
||||
response = await updateLink(link);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Updated!`);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
|
||||
return response;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">Edit Link</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
{link.url ? (
|
||||
<Link
|
||||
href={link.url}
|
||||
className="truncate text-neutral flex gap-2 mb-5 w-fit max-w-full"
|
||||
title={link.url}
|
||||
target="_blank"
|
||||
>
|
||||
<i className="bi-link-45deg text-xl" />
|
||||
<p>{shortendURL}</p>
|
||||
</Link>
|
||||
) : undefined}
|
||||
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Name</p>
|
||||
<TextInput
|
||||
value={link.name}
|
||||
onChange={(e) => setLink({ ...link, name: e.target.value })}
|
||||
placeholder="e.g. Example Link"
|
||||
className="bg-base-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-5">
|
||||
{/* <hr className="mb-3 border border-neutral-content" /> */}
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<p className="mb-2">Collection</p>
|
||||
{link.collection.name ? (
|
||||
<CollectionSelection
|
||||
onChange={setCollection}
|
||||
// defaultValue={{
|
||||
// label: link.collection.name,
|
||||
// value: link.collection.id,
|
||||
// }}
|
||||
defaultValue={
|
||||
link.collection.id
|
||||
? {
|
||||
value: link.collection.id,
|
||||
label: link.collection.name,
|
||||
}
|
||||
: {
|
||||
value: null as unknown as number,
|
||||
label: "Unorganized",
|
||||
}
|
||||
}
|
||||
creatable={false}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2">Tags</p>
|
||||
<TagSelection
|
||||
onChange={setTags}
|
||||
defaultValue={link.tags.map((e) => {
|
||||
return { label: e.name, value: e.id };
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-2">
|
||||
<p className="mb-2">Description</p>
|
||||
<textarea
|
||||
value={unescapeString(link.description) as string}
|
||||
onChange={(e) =>
|
||||
setLink({ ...link, description: e.target.value })
|
||||
}
|
||||
placeholder="Will be auto generated if nothing is provided."
|
||||
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-sky-300 dark:focus:border-sky-600 border-solid border outline-none duration-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end items-center mt-5">
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white"
|
||||
onClick={submit}
|
||||
>
|
||||
Save Changes
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,136 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import toast from "react-hot-toast";
|
||||
import { HexColorPicker } from "react-colorful";
|
||||
import { Collection } from "@prisma/client";
|
||||
import Modal from "../Modal";
|
||||
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
||||
import useAccountStore from "@/store/account";
|
||||
import { useSession } from "next-auth/react";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
parent?: CollectionIncludingMembersAndLinkCount;
|
||||
};
|
||||
|
||||
export default function NewCollectionModal({ onClose, parent }: Props) {
|
||||
const initial = {
|
||||
parentId: parent?.id,
|
||||
name: "",
|
||||
description: "",
|
||||
color: "#0ea5e9",
|
||||
} as Partial<Collection>;
|
||||
|
||||
const [collection, setCollection] = useState<Partial<Collection>>(initial);
|
||||
const { setAccount } = useAccountStore();
|
||||
const { data } = useSession();
|
||||
|
||||
useEffect(() => {
|
||||
setCollection(initial);
|
||||
}, []);
|
||||
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
const { addCollection } = useCollectionStore();
|
||||
|
||||
const submit = async () => {
|
||||
if (submitLoader) return;
|
||||
if (!collection) return null;
|
||||
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Creating...");
|
||||
|
||||
let response = await addCollection(collection as any);
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success("Created!");
|
||||
if (response.data) {
|
||||
// If the collection was created successfully, we need to get the new collection order
|
||||
setAccount(data?.user.id as number);
|
||||
onClose();
|
||||
}
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
{parent?.id ? (
|
||||
<>
|
||||
<p className="text-xl font-thin">New Sub-Collection</p>
|
||||
<p className="capitalize text-sm">For {parent.name}</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-xl font-thin">Create a New Collection</p>
|
||||
)}
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Name</p>
|
||||
<div className="flex flex-col gap-3">
|
||||
<TextInput
|
||||
className="bg-base-200"
|
||||
value={collection.name}
|
||||
placeholder="e.g. Example Collection"
|
||||
onChange={(e) =>
|
||||
setCollection({ ...collection, name: e.target.value })
|
||||
}
|
||||
/>
|
||||
<div>
|
||||
<p className="w-full mb-2">Color</p>
|
||||
<div className="color-picker flex justify-between">
|
||||
<div className="flex flex-col gap-2 items-center w-32">
|
||||
<i
|
||||
className={"bi-folder-fill text-5xl"}
|
||||
style={{ color: collection.color }}
|
||||
></i>
|
||||
<div
|
||||
className="btn btn-ghost btn-xs"
|
||||
onClick={() =>
|
||||
setCollection({ ...collection, color: "#0ea5e9" })
|
||||
}
|
||||
>
|
||||
Reset
|
||||
</div>
|
||||
</div>
|
||||
<HexColorPicker
|
||||
color={collection.color}
|
||||
onChange={(e) => setCollection({ ...collection, color: e })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Description</p>
|
||||
<textarea
|
||||
className="w-full h-[13rem] resize-none border rounded-md duration-100 bg-base-200 p-2 outline-none border-neutral-content focus:border-primary"
|
||||
placeholder="The purpose of this Collection..."
|
||||
value={collection.description}
|
||||
onChange={(e) =>
|
||||
setCollection({
|
||||
...collection,
|
||||
description: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white w-fit ml-auto"
|
||||
onClick={submit}
|
||||
>
|
||||
Create Collection
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
213
Securite/Linkwarden/components/ModalContent/NewLinkModal.tsx
Normal file
@ -0,0 +1,213 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Toaster } from "react-hot-toast";
|
||||
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
|
||||
import TagSelection from "@/components/InputSelect/TagSelection";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import useLinkStore from "@/store/links";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
};
|
||||
|
||||
export default function NewLinkModal({ onClose }: Props) {
|
||||
const { data } = useSession();
|
||||
|
||||
const initial = {
|
||||
name: "",
|
||||
url: "",
|
||||
description: "",
|
||||
type: "url",
|
||||
tags: [],
|
||||
preview: "",
|
||||
image: "",
|
||||
pdf: "",
|
||||
readable: "",
|
||||
textContent: "",
|
||||
collection: {
|
||||
name: "",
|
||||
ownerId: data?.user.id as number,
|
||||
},
|
||||
} as LinkIncludingShortenedCollectionAndTags;
|
||||
|
||||
const [link, setLink] =
|
||||
useState<LinkIncludingShortenedCollectionAndTags>(initial);
|
||||
|
||||
const { addLink } = useLinkStore();
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
|
||||
const [optionsExpanded, setOptionsExpanded] = useState(false);
|
||||
|
||||
const router = useRouter();
|
||||
const { collections } = useCollectionStore();
|
||||
|
||||
const setCollection = (e: any) => {
|
||||
if (e?.__isNew__) e.value = null;
|
||||
|
||||
setLink({
|
||||
...link,
|
||||
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
|
||||
});
|
||||
};
|
||||
|
||||
const setTags = (e: any) => {
|
||||
const tagNames = e.map((e: any) => {
|
||||
return { name: e.label };
|
||||
});
|
||||
|
||||
setLink({ ...link, tags: tagNames });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (router.query.id) {
|
||||
const currentCollection = collections.find(
|
||||
(e) => e.id == Number(router.query.id)
|
||||
);
|
||||
|
||||
if (
|
||||
currentCollection &&
|
||||
currentCollection.ownerId &&
|
||||
router.asPath.startsWith("/collections/")
|
||||
)
|
||||
setLink({
|
||||
...initial,
|
||||
collection: {
|
||||
id: currentCollection.id,
|
||||
name: currentCollection.name,
|
||||
ownerId: currentCollection.ownerId,
|
||||
},
|
||||
});
|
||||
} else
|
||||
setLink({
|
||||
...initial,
|
||||
collection: {
|
||||
name: "Unorganized",
|
||||
ownerId: data?.user.id as number,
|
||||
},
|
||||
});
|
||||
}, []);
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
|
||||
let response;
|
||||
|
||||
const load = toast.loading("Creating...");
|
||||
|
||||
response = await addLink(link);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Created!`);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
setSubmitLoader(false);
|
||||
|
||||
return response;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">Create a New Link</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="grid grid-flow-row-dense sm:grid-cols-5 gap-3">
|
||||
<div className="sm:col-span-3 col-span-5">
|
||||
<p className="mb-2">Link</p>
|
||||
<TextInput
|
||||
value={link.url || ""}
|
||||
onChange={(e) => setLink({ ...link, url: e.target.value })}
|
||||
placeholder="e.g. http://example.com/"
|
||||
className="bg-base-200"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2 col-span-5">
|
||||
<p className="mb-2">Collection</p>
|
||||
{link.collection.name ? (
|
||||
<CollectionSelection
|
||||
onChange={setCollection}
|
||||
defaultValue={{
|
||||
label: link.collection.name,
|
||||
value: link.collection.id,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={"mt-2"}>
|
||||
{optionsExpanded ? (
|
||||
<div className="mt-5">
|
||||
{/* <hr className="mb-3 border border-neutral-content" /> */}
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<p className="mb-2">Name</p>
|
||||
<TextInput
|
||||
value={link.name}
|
||||
onChange={(e) => setLink({ ...link, name: e.target.value })}
|
||||
placeholder="e.g. Example Link"
|
||||
className="bg-base-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2">Tags</p>
|
||||
<TagSelection
|
||||
onChange={setTags}
|
||||
defaultValue={link.tags.map((e) => {
|
||||
return { label: e.name, value: e.id };
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-2">
|
||||
<p className="mb-2">Description</p>
|
||||
<textarea
|
||||
value={unescapeString(link.description) as string}
|
||||
onChange={(e) =>
|
||||
setLink({ ...link, description: e.target.value })
|
||||
}
|
||||
placeholder="Will be auto generated if nothing is provided."
|
||||
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : undefined}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center mt-5">
|
||||
<div
|
||||
onClick={() => setOptionsExpanded(!optionsExpanded)}
|
||||
className={`rounded-md cursor-pointer btn btn-sm btn-ghost duration-100 flex items-center px-2 w-fit text-sm`}
|
||||
>
|
||||
<p className="font-normal">
|
||||
{optionsExpanded ? "Hide" : "More"} Options
|
||||
</p>
|
||||
<i
|
||||
className={`${
|
||||
optionsExpanded ? "bi-chevron-up" : "bi-chevron-down"
|
||||
}`}
|
||||
></i>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white"
|
||||
onClick={submit}
|
||||
>
|
||||
Create Link
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
227
Securite/Linkwarden/components/ModalContent/NewTokenModal.tsx
Normal file
@ -0,0 +1,227 @@
|
||||
import React, { useState } from "react";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import { TokenExpiry } from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
import useTokenStore from "@/store/tokens";
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
};
|
||||
|
||||
export default function NewTokenModal({ onClose }: Props) {
|
||||
const [newToken, setNewToken] = useState("");
|
||||
|
||||
const { addToken } = useTokenStore();
|
||||
|
||||
const initial = {
|
||||
name: "",
|
||||
expires: 0 as TokenExpiry,
|
||||
};
|
||||
|
||||
const [token, setToken] = useState(initial as any);
|
||||
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Creating...");
|
||||
|
||||
const { ok, data } = await addToken(token);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (ok) {
|
||||
toast.success(`Created!`);
|
||||
setNewToken((data as any).secretKey);
|
||||
} else toast.error(data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
{newToken ? (
|
||||
<div className="flex flex-col justify-center space-y-4">
|
||||
<p className="text-xl font-thin">Access Token Created</p>
|
||||
<p>
|
||||
Your new token has been created. Please copy it and store it
|
||||
somewhere safe. You will not be able to see it again.
|
||||
</p>
|
||||
<TextInput
|
||||
spellCheck={false}
|
||||
value={newToken}
|
||||
onChange={() => {}}
|
||||
className="w-full"
|
||||
/>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(newToken);
|
||||
toast.success("Copied to clipboard!");
|
||||
}}
|
||||
className="btn btn-primary w-fit mx-auto"
|
||||
>
|
||||
Copy to Clipboard
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xl font-thin">Create an Access Token</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex sm:flex-row flex-col gap-2 items-center">
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Name</p>
|
||||
|
||||
<TextInput
|
||||
value={token.name}
|
||||
onChange={(e) => setToken({ ...token, name: e.target.value })}
|
||||
placeholder="e.g. For the iOS shortcut"
|
||||
className="bg-base-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:w-fit">
|
||||
<p className="mb-2">Expires in</p>
|
||||
|
||||
<div className="dropdown dropdown-bottom dropdown-end w-full">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-outline w-full sm:w-36 flex items-center btn-sm h-10"
|
||||
>
|
||||
{token.expires === TokenExpiry.sevenDays && "7 Days"}
|
||||
{token.expires === TokenExpiry.oneMonth && "30 Days"}
|
||||
{token.expires === TokenExpiry.twoMonths && "60 Days"}
|
||||
{token.expires === TokenExpiry.threeMonths && "90 Days"}
|
||||
{token.expires === TokenExpiry.never && "No Expiration"}
|
||||
</div>
|
||||
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl w-full sm:w-52 mt-1">
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
checked={token.expires === TokenExpiry.sevenDays}
|
||||
onChange={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setToken({
|
||||
...token,
|
||||
expires: TokenExpiry.sevenDays,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">7 Days</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
checked={token.expires === TokenExpiry.oneMonth}
|
||||
onChange={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setToken({ ...token, expires: TokenExpiry.oneMonth });
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">30 Days</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
checked={token.expires === TokenExpiry.twoMonths}
|
||||
onChange={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setToken({
|
||||
...token,
|
||||
expires: TokenExpiry.twoMonths,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">60 Days</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
checked={token.expires === TokenExpiry.threeMonths}
|
||||
onChange={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setToken({
|
||||
...token,
|
||||
expires: TokenExpiry.threeMonths,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">90 Days</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
checked={token.expires === TokenExpiry.never}
|
||||
onChange={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setToken({ ...token, expires: TokenExpiry.never });
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">No Expiration</span>
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end items-center mt-5">
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white"
|
||||
onClick={submit}
|
||||
>
|
||||
Create Access Token
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,233 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import {
|
||||
ArchivedFormat,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Link from "next/link";
|
||||
import Modal from "../Modal";
|
||||
import { useRouter } from "next/router";
|
||||
import { useSession } from "next-auth/react";
|
||||
import {
|
||||
pdfAvailable,
|
||||
readabilityAvailable,
|
||||
screenshotAvailable,
|
||||
} from "@/lib/shared/getArchiveValidity";
|
||||
import PreservedFormatRow from "@/components/PreserverdFormatRow";
|
||||
import useAccountStore from "@/store/account";
|
||||
import getPublicUserData from "@/lib/client/getPublicUserData";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeLink: LinkIncludingShortenedCollectionAndTags;
|
||||
};
|
||||
|
||||
export default function PreservedFormatsModal({ onClose, activeLink }: Props) {
|
||||
const session = useSession();
|
||||
const { getLink } = useLinkStore();
|
||||
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const [link, setLink] =
|
||||
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
let isPublic = router.pathname.startsWith("/public") ? true : undefined;
|
||||
|
||||
const [collectionOwner, setCollectionOwner] = useState({
|
||||
id: null as unknown as number,
|
||||
name: "",
|
||||
username: "",
|
||||
image: "",
|
||||
archiveAsScreenshot: undefined as unknown as boolean,
|
||||
archiveAsPDF: undefined as unknown as boolean,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchOwner = async () => {
|
||||
if (link.collection.ownerId !== account.id) {
|
||||
const owner = await getPublicUserData(
|
||||
link.collection.ownerId as number
|
||||
);
|
||||
setCollectionOwner(owner);
|
||||
} else if (link.collection.ownerId === account.id) {
|
||||
setCollectionOwner({
|
||||
id: account.id as number,
|
||||
name: account.name,
|
||||
username: account.username as string,
|
||||
image: account.image as string,
|
||||
archiveAsScreenshot: account.archiveAsScreenshot as boolean,
|
||||
archiveAsPDF: account.archiveAsPDF as boolean,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
fetchOwner();
|
||||
}, [link.collection.ownerId]);
|
||||
|
||||
const isReady = () => {
|
||||
return (
|
||||
link &&
|
||||
(collectionOwner.archiveAsScreenshot === true
|
||||
? link.pdf && link.pdf !== "pending"
|
||||
: true) &&
|
||||
(collectionOwner.archiveAsPDF === true
|
||||
? link.pdf && link.pdf !== "pending"
|
||||
: true) &&
|
||||
link.readable &&
|
||||
link.readable !== "pending"
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const data = await getLink(link.id as number, isPublic);
|
||||
setLink(
|
||||
(data as any).response as LinkIncludingShortenedCollectionAndTags
|
||||
);
|
||||
})();
|
||||
|
||||
let interval: any;
|
||||
|
||||
if (!isReady()) {
|
||||
interval = setInterval(async () => {
|
||||
const data = await getLink(link.id as number, isPublic);
|
||||
setLink(
|
||||
(data as any).response as LinkIncludingShortenedCollectionAndTags
|
||||
);
|
||||
}, 5000);
|
||||
} else {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
};
|
||||
}, [link?.image, link?.pdf, link?.readable]);
|
||||
|
||||
const updateArchive = async () => {
|
||||
const load = toast.loading("Sending request...");
|
||||
|
||||
const response = await fetch(`/api/v1/links/${link?.id}/archive`, {
|
||||
method: "PUT",
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
const newLink = await getLink(link?.id as number);
|
||||
setLink(
|
||||
(newLink as any).response as LinkIncludingShortenedCollectionAndTags
|
||||
);
|
||||
toast.success(`Link is being archived...`);
|
||||
} else toast.error(data.response);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">Preserved Formats</p>
|
||||
|
||||
<div className="divider mb-2 mt-1"></div>
|
||||
|
||||
{isReady() &&
|
||||
(screenshotAvailable(link) ||
|
||||
pdfAvailable(link) ||
|
||||
readabilityAvailable(link)) ? (
|
||||
<p className="mb-3">
|
||||
The following formats are available for this link:
|
||||
</p>
|
||||
) : (
|
||||
""
|
||||
)}
|
||||
|
||||
<div className={`flex flex-col gap-3`}>
|
||||
{isReady() ? (
|
||||
<>
|
||||
{screenshotAvailable(link) ? (
|
||||
<PreservedFormatRow
|
||||
name={"Screenshot"}
|
||||
icon={"bi-file-earmark-image"}
|
||||
format={
|
||||
link?.image?.endsWith("png")
|
||||
? ArchivedFormat.png
|
||||
: ArchivedFormat.jpeg
|
||||
}
|
||||
activeLink={link}
|
||||
downloadable={true}
|
||||
/>
|
||||
) : undefined}
|
||||
|
||||
{pdfAvailable(link) ? (
|
||||
<PreservedFormatRow
|
||||
name={"PDF"}
|
||||
icon={"bi-file-earmark-pdf"}
|
||||
format={ArchivedFormat.pdf}
|
||||
activeLink={link}
|
||||
downloadable={true}
|
||||
/>
|
||||
) : undefined}
|
||||
|
||||
{readabilityAvailable(link) ? (
|
||||
<PreservedFormatRow
|
||||
name={"Readable"}
|
||||
icon={"bi-file-earmark-text"}
|
||||
format={ArchivedFormat.readability}
|
||||
activeLink={link}
|
||||
/>
|
||||
) : undefined}
|
||||
</>
|
||||
) : (
|
||||
<div
|
||||
className={`w-full h-full flex flex-col justify-center p-10 skeleton bg-base-200`}
|
||||
>
|
||||
<i className="bi-stack drop-shadow text-primary text-8xl mx-auto mb-5"></i>
|
||||
<p className="text-center text-2xl">
|
||||
Link preservation is in the queue
|
||||
</p>
|
||||
<p className="text-center text-lg">
|
||||
Please check back later to see the result
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={`flex flex-col sm:flex-row gap-3 items-center justify-center ${
|
||||
isReady() ? "sm:mt " : ""
|
||||
}`}
|
||||
>
|
||||
<Link
|
||||
href={`https://web.archive.org/web/${link?.url?.replace(
|
||||
/(^\w+:|^)\/\//,
|
||||
""
|
||||
)}`}
|
||||
target="_blank"
|
||||
className={`text-neutral duration-100 hover:opacity-60 flex gap-2 w-1/2 justify-center items-center text-sm`}
|
||||
>
|
||||
<p className="whitespace-nowrap">
|
||||
View latest snapshot on archive.org
|
||||
</p>
|
||||
<i className="bi-box-arrow-up-right" />
|
||||
</Link>
|
||||
{link?.collection.ownerId === session.data?.user.id ? (
|
||||
<div className={`btn btn-outline`} onClick={() => updateArchive()}>
|
||||
<div>
|
||||
<p>Refresh Preserved Formats</p>
|
||||
<p className="text-xs">
|
||||
This deletes the current preservations
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : undefined}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
import { useRouter } from "next/router";
|
||||
import { AccessToken } from "@prisma/client";
|
||||
import useTokenStore from "@/store/tokens";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
activeToken: AccessToken;
|
||||
};
|
||||
|
||||
export default function DeleteTokenModal({ onClose, activeToken }: Props) {
|
||||
const [token, setToken] = useState<AccessToken>(activeToken);
|
||||
|
||||
const { revokeToken } = useTokenStore();
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
setToken(activeToken);
|
||||
}, []);
|
||||
|
||||
const deleteLink = async () => {
|
||||
console.log(token);
|
||||
const load = toast.loading("Deleting...");
|
||||
|
||||
const response = await revokeToken(token.id as number);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
response.ok && toast.success(`Token Revoked.`);
|
||||
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin text-red-500">Revoke Token</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<p>
|
||||
Are you sure you want to revoke this Access Token? Any apps or
|
||||
services using this token will no longer be able to access Linkwarden
|
||||
using it.
|
||||
</p>
|
||||
|
||||
<button
|
||||
className={`ml-auto btn w-fit text-white flex items-center gap-2 duration-100 bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer`}
|
||||
onClick={deleteLink}
|
||||
>
|
||||
<i className="bi-trash text-xl" />
|
||||
Revoke
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
246
Securite/Linkwarden/components/ModalContent/UploadFileModal.tsx
Normal file
@ -0,0 +1,246 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
|
||||
import TagSelection from "@/components/InputSelect/TagSelection";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import useLinkStore from "@/store/links";
|
||||
import {
|
||||
ArchivedFormat,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import toast from "react-hot-toast";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
};
|
||||
|
||||
export default function UploadFileModal({ onClose }: Props) {
|
||||
const { data } = useSession();
|
||||
|
||||
const initial = {
|
||||
name: "",
|
||||
url: "",
|
||||
description: "",
|
||||
type: "url",
|
||||
tags: [],
|
||||
preview: "",
|
||||
image: "",
|
||||
pdf: "",
|
||||
readable: "",
|
||||
textContent: "",
|
||||
collection: {
|
||||
name: "",
|
||||
ownerId: data?.user.id as number,
|
||||
},
|
||||
} as LinkIncludingShortenedCollectionAndTags;
|
||||
|
||||
const [link, setLink] =
|
||||
useState<LinkIncludingShortenedCollectionAndTags>(initial);
|
||||
|
||||
const [file, setFile] = useState<File>();
|
||||
|
||||
const { addLink } = useLinkStore();
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
|
||||
const [optionsExpanded, setOptionsExpanded] = useState(false);
|
||||
|
||||
const router = useRouter();
|
||||
const { collections } = useCollectionStore();
|
||||
|
||||
const setCollection = (e: any) => {
|
||||
if (e?.__isNew__) e.value = null;
|
||||
|
||||
setLink({
|
||||
...link,
|
||||
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
|
||||
});
|
||||
};
|
||||
|
||||
const setTags = (e: any) => {
|
||||
const tagNames = e.map((e: any) => {
|
||||
return { name: e.label };
|
||||
});
|
||||
|
||||
setLink({ ...link, tags: tagNames });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setOptionsExpanded(false);
|
||||
if (router.query.id) {
|
||||
const currentCollection = collections.find(
|
||||
(e) => e.id == Number(router.query.id)
|
||||
);
|
||||
|
||||
if (
|
||||
currentCollection &&
|
||||
currentCollection.ownerId &&
|
||||
router.asPath.startsWith("/collections/")
|
||||
)
|
||||
setLink({
|
||||
...initial,
|
||||
collection: {
|
||||
id: currentCollection.id,
|
||||
name: currentCollection.name,
|
||||
ownerId: currentCollection.ownerId,
|
||||
},
|
||||
});
|
||||
} else
|
||||
setLink({
|
||||
...initial,
|
||||
collection: {
|
||||
name: "Unorganized",
|
||||
ownerId: data?.user.id as number,
|
||||
},
|
||||
});
|
||||
}, []);
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader && file) {
|
||||
let fileType: ArchivedFormat | null = null;
|
||||
let linkType: "url" | "image" | "pdf" | null = null;
|
||||
|
||||
if (file?.type === "image/jpg" || file.type === "image/jpeg") {
|
||||
fileType = ArchivedFormat.jpeg;
|
||||
linkType = "image";
|
||||
} else if (file.type === "image/png") {
|
||||
fileType = ArchivedFormat.png;
|
||||
linkType = "image";
|
||||
} else if (file.type === "application/pdf") {
|
||||
fileType = ArchivedFormat.pdf;
|
||||
linkType = "pdf";
|
||||
}
|
||||
|
||||
if (fileType !== null && linkType !== null) {
|
||||
setSubmitLoader(true);
|
||||
|
||||
let response;
|
||||
|
||||
const load = toast.loading("Creating...");
|
||||
|
||||
response = await addLink({
|
||||
...link,
|
||||
type: linkType,
|
||||
name: link.name ? link.name : file.name.replace(/\.[^/.]+$/, ""),
|
||||
});
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
const formBody = new FormData();
|
||||
file && formBody.append("file", file);
|
||||
|
||||
await fetch(
|
||||
`/api/v1/archives/${
|
||||
(response.data as LinkIncludingShortenedCollectionAndTags).id
|
||||
}?format=${fileType}`,
|
||||
{
|
||||
body: formBody,
|
||||
method: "POST",
|
||||
}
|
||||
);
|
||||
toast.success(`Created!`);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<div className="flex gap-2 items-start">
|
||||
<p className="text-xl font-thin">Upload File</p>
|
||||
</div>
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
<div className="grid grid-flow-row-dense sm:grid-cols-5 gap-3">
|
||||
<div className="sm:col-span-3 col-span-5">
|
||||
<p className="mb-2">File</p>
|
||||
<label className="btn h-10 btn-sm w-full border border-neutral-content hover:border-neutral-content flex justify-between">
|
||||
<input
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg"
|
||||
className="cursor-pointer custom-file-input"
|
||||
onChange={(e) => e.target.files && setFile(e.target.files[0])}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs font-semibold mt-2">
|
||||
PDF, PNG, JPG (Up to {process.env.NEXT_PUBLIC_MAX_FILE_SIZE || 30}
|
||||
MB)
|
||||
</p>
|
||||
</div>
|
||||
<div className="sm:col-span-2 col-span-5">
|
||||
<p className="mb-2">Collection</p>
|
||||
{link.collection.name ? (
|
||||
<CollectionSelection
|
||||
onChange={setCollection}
|
||||
defaultValue={{
|
||||
label: link.collection.name,
|
||||
value: link.collection.id,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{optionsExpanded ? (
|
||||
<div className="mt-5">
|
||||
{/* <hr className="mb-3 border border-neutral-content" /> */}
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<p className="mb-2">Name</p>
|
||||
<TextInput
|
||||
value={link.name}
|
||||
onChange={(e) => setLink({ ...link, name: e.target.value })}
|
||||
placeholder="e.g. Example Link"
|
||||
className="bg-base-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2">Tags</p>
|
||||
<TagSelection
|
||||
onChange={setTags}
|
||||
defaultValue={link.tags.map((e) => {
|
||||
return { label: e.name, value: e.id };
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-2">
|
||||
<p className="mb-2">Description</p>
|
||||
<textarea
|
||||
value={unescapeString(link.description) as string}
|
||||
onChange={(e) =>
|
||||
setLink({ ...link, description: e.target.value })
|
||||
}
|
||||
placeholder="Will be auto generated if nothing is provided."
|
||||
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-sky-300 dark:focus:border-sky-600 border-solid border outline-none duration-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : undefined}
|
||||
<div className="flex justify-between items-center mt-5">
|
||||
<div
|
||||
onClick={() => setOptionsExpanded(!optionsExpanded)}
|
||||
className={`rounded-md cursor-pointer btn btn-sm btn-ghost duration-100 flex items-center px-2 w-fit text-sm`}
|
||||
>
|
||||
<p>{optionsExpanded ? "Hide" : "More"} Options</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white"
|
||||
onClick={submit}
|
||||
>
|
||||
Create Link
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
196
Securite/Linkwarden/components/Navbar.tsx
Normal file
@ -0,0 +1,196 @@
|
||||
import { signOut } from "next-auth/react";
|
||||
import { useEffect, useState } from "react";
|
||||
import ClickAwayHandler from "@/components/ClickAwayHandler";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import { useRouter } from "next/router";
|
||||
import SearchBar from "@/components/SearchBar";
|
||||
import useAccountStore from "@/store/account";
|
||||
import ProfilePhoto from "@/components/ProfilePhoto";
|
||||
import useWindowDimensions from "@/hooks/useWindowDimensions";
|
||||
import ToggleDarkMode from "./ToggleDarkMode";
|
||||
import useLocalSettingsStore from "@/store/localSettings";
|
||||
import NewLinkModal from "./ModalContent/NewLinkModal";
|
||||
import NewCollectionModal from "./ModalContent/NewCollectionModal";
|
||||
import Link from "next/link";
|
||||
import UploadFileModal from "./ModalContent/UploadFileModal";
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
import MobileNavigation from "./MobileNavigation";
|
||||
|
||||
export default function Navbar() {
|
||||
const { settings, updateSettings } = useLocalSettingsStore();
|
||||
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const [sidebar, setSidebar] = useState(false);
|
||||
|
||||
const { width } = useWindowDimensions();
|
||||
|
||||
const handleToggle = () => {
|
||||
if (settings.theme === "dark") {
|
||||
updateSettings({ theme: "light" });
|
||||
} else {
|
||||
updateSettings({ theme: "dark" });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setSidebar(false);
|
||||
document.body.style.overflow = "auto";
|
||||
}, [width, router]);
|
||||
|
||||
const toggleSidebar = () => {
|
||||
setSidebar(false);
|
||||
document.body.style.overflow = "auto";
|
||||
};
|
||||
|
||||
const [newLinkModal, setNewLinkModal] = useState(false);
|
||||
const [newCollectionModal, setNewCollectionModal] = useState(false);
|
||||
const [uploadFileModal, setUploadFileModal] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="flex justify-between gap-2 items-center pl-3 pr-4 py-2 border-solid border-b-neutral-content border-b">
|
||||
<div
|
||||
onClick={() => {
|
||||
setSidebar(true);
|
||||
document.body.style.overflow = "hidden";
|
||||
}}
|
||||
className="text-neutral btn btn-square btn-sm btn-ghost lg:hidden sm:inline-flex"
|
||||
>
|
||||
<i className="bi-list text-2xl leading-none"></i>
|
||||
</div>
|
||||
<SearchBar />
|
||||
<div className="flex items-center gap-2">
|
||||
<ToggleDarkMode className="hidden sm:inline-grid" />
|
||||
|
||||
<div className="dropdown dropdown-end sm:inline-block hidden">
|
||||
<div className="tooltip tooltip-bottom" data-tip="Create New...">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="flex min-w-[3.4rem] items-center btn btn-accent dark:border-violet-400 text-white btn-sm max-h-[2rem] px-2 relative"
|
||||
>
|
||||
<span>
|
||||
<i className="bi-plus text-4xl absolute -top-[0.3rem] left-0 pointer-events-none"></i>
|
||||
</span>
|
||||
<span>
|
||||
<i className="bi-caret-down-fill text-xs absolute top-2 right-[0.3rem] pointer-events-none"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box w-40 mt-1">
|
||||
<li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setNewLinkModal(true);
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
New Link
|
||||
</div>
|
||||
</li>
|
||||
{/* <li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setUploadFileModal(true);
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
Upload File
|
||||
</div>
|
||||
</li> */}
|
||||
<li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
setNewCollectionModal(true);
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
New Collection
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="dropdown dropdown-end">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-circle btn-ghost"
|
||||
>
|
||||
<ProfilePhoto
|
||||
src={account.image ? account.image : undefined}
|
||||
priority={true}
|
||||
/>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box w-40 mt-1">
|
||||
<li>
|
||||
<Link
|
||||
href="/settings/account"
|
||||
onClick={() => (document?.activeElement as HTMLElement)?.blur()}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
Settings
|
||||
</Link>
|
||||
</li>
|
||||
<li className="block sm:hidden">
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
handleToggle();
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
Switch to {settings.theme === "light" ? "Dark" : "Light"}
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div
|
||||
onClick={() => {
|
||||
(document?.activeElement as HTMLElement)?.blur();
|
||||
signOut();
|
||||
}}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
Logout
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MobileNavigation />
|
||||
|
||||
{sidebar ? (
|
||||
<div className="fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-40">
|
||||
<ClickAwayHandler className="h-full" onClickOutside={toggleSidebar}>
|
||||
<div className="slide-right h-full shadow-lg">
|
||||
<Sidebar />
|
||||
</div>
|
||||
</ClickAwayHandler>
|
||||
</div>
|
||||
) : null}
|
||||
{newLinkModal ? (
|
||||
<NewLinkModal onClose={() => setNewLinkModal(false)} />
|
||||
) : undefined}
|
||||
{newCollectionModal ? (
|
||||
<NewCollectionModal onClose={() => setNewCollectionModal(false)} />
|
||||
) : undefined}
|
||||
{uploadFileModal ? (
|
||||
<UploadFileModal onClose={() => setUploadFileModal(false)} />
|
||||
) : undefined}
|
||||
</div>
|
||||
);
|
||||
}
|
47
Securite/Linkwarden/components/NoLinksFound.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
import React, { useState } from "react";
|
||||
import NewLinkModal from "./ModalContent/NewLinkModal";
|
||||
|
||||
type Props = {
|
||||
text?: string;
|
||||
};
|
||||
|
||||
export default function NoLinksFound({ text }: Props) {
|
||||
const [newLinkModal, setNewLinkModal] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex flex-col justify-center p-3">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="w-1/4 min-w-[7rem] max-w-[15rem] h-auto mx-auto mb-5 text-primary drop-shadow"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 16 16"
|
||||
>
|
||||
<path d="M9.752 6.193c.599.6 1.73.437 2.528-.362.798-.799.96-1.932.362-2.531-.599-.6-1.73-.438-2.528.361-.798.8-.96 1.933-.362 2.532" />
|
||||
<path d="M15.811 3.312c-.363 1.534-1.334 3.626-3.64 6.218l-.24 2.408a2.56 2.56 0 0 1-.732 1.526L8.817 15.85a.51.51 0 0 1-.867-.434l.27-1.899c.04-.28-.013-.593-.131-.956a9.42 9.42 0 0 0-.249-.657l-.082-.202c-.815-.197-1.578-.662-2.191-1.277-.614-.615-1.079-1.379-1.275-2.195l-.203-.083a9.556 9.556 0 0 0-.655-.248c-.363-.119-.675-.172-.955-.132l-1.896.27A.51.51 0 0 1 .15 7.17l2.382-2.386c.41-.41.947-.67 1.524-.734h.006l2.4-.238C9.005 1.55 11.087.582 12.623.208c.89-.217 1.59-.232 2.08-.188.244.023.435.06.57.093.067.017.12.033.16.045.184.06.279.13.351.295l.029.073a3.475 3.475 0 0 1 .157.721c.055.485.051 1.178-.159 2.065Zm-4.828 7.475.04-.04-.107 1.081a1.536 1.536 0 0 1-.44.913l-1.298 1.3.054-.38c.072-.506-.034-.993-.172-1.418a8.548 8.548 0 0 0-.164-.45c.738-.065 1.462-.38 2.087-1.006ZM5.205 5c-.625.626-.94 1.351-1.004 2.09a8.497 8.497 0 0 0-.45-.164c-.424-.138-.91-.244-1.416-.172l-.38.054 1.3-1.3c.245-.246.566-.401.91-.44l1.08-.107-.04.039Zm9.406-3.961c-.38-.034-.967-.027-1.746.163-1.558.38-3.917 1.496-6.937 4.521-.62.62-.799 1.34-.687 2.051.107.676.483 1.362 1.048 1.928.564.565 1.25.941 1.924 1.049.71.112 1.429-.067 2.048-.688 3.079-3.083 4.192-5.444 4.556-6.987.183-.771.18-1.345.138-1.713a2.835 2.835 0 0 0-.045-.283 3.078 3.078 0 0 0-.3-.041Z" />
|
||||
<path d="M7.009 12.139a7.632 7.632 0 0 1-1.804-1.352A7.568 7.568 0 0 1 3.794 8.86c-1.102.992-1.965 5.054-1.839 5.18.125.126 3.936-.896 5.054-1.902Z" />
|
||||
</svg>
|
||||
<p className="text-center text-xl sm:text-2xl">
|
||||
{text || "You haven't created any Links Here"}
|
||||
</p>
|
||||
<p className="text-center text-sm sm:text-base">
|
||||
Start your journey by creating a new Link!
|
||||
</p>
|
||||
<div className="text-center w-full mt-4">
|
||||
<div
|
||||
onClick={() => {
|
||||
setNewLinkModal(true);
|
||||
}}
|
||||
className="inline-flex gap-1 relative w-[11rem] items-center btn btn-accent dark:border-violet-400 text-white group"
|
||||
>
|
||||
<i className="bi-plus-lg text-3xl left-2 group-hover:ml-[4rem] absolute duration-100"></i>
|
||||
<span className="group-hover:opacity-0 text-right w-full duration-100">
|
||||
Create New Link
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{newLinkModal ? (
|
||||
<NewLinkModal onClose={() => setNewLinkModal(false)} />
|
||||
) : undefined}
|
||||
</div>
|
||||
);
|
||||
}
|
23
Securite/Linkwarden/components/PageHeader.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
import React from "react";
|
||||
|
||||
export default function PageHeader({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
icon: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-3">
|
||||
<i
|
||||
className={`${icon} text-primary text-3xl sm:text-4xl drop-shadow`}
|
||||
></i>
|
||||
<div>
|
||||
<p className="text-3xl capitalize font-thin">{title}</p>
|
||||
<p className="text-xs sm:text-sm">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
116
Securite/Linkwarden/components/PreserverdFormatRow.tsx
Normal file
@ -0,0 +1,116 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import useLinkStore from "@/store/links";
|
||||
import {
|
||||
ArchivedFormat,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useSession } from "next-auth/react";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
icon: string;
|
||||
format: ArchivedFormat;
|
||||
activeLink: LinkIncludingShortenedCollectionAndTags;
|
||||
downloadable?: boolean;
|
||||
};
|
||||
|
||||
export default function PreservedFormatRow({
|
||||
name,
|
||||
icon,
|
||||
format,
|
||||
activeLink,
|
||||
downloadable,
|
||||
}: Props) {
|
||||
const session = useSession();
|
||||
const { getLink } = useLinkStore();
|
||||
|
||||
const [link, setLink] =
|
||||
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
let isPublic = router.pathname.startsWith("/public") ? true : undefined;
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const data = await getLink(link.id as number, isPublic);
|
||||
setLink(
|
||||
(data as any).response as LinkIncludingShortenedCollectionAndTags
|
||||
);
|
||||
})();
|
||||
|
||||
let interval: any;
|
||||
if (link?.image === "pending" || link?.pdf === "pending") {
|
||||
interval = setInterval(async () => {
|
||||
const data = await getLink(link.id as number, isPublic);
|
||||
setLink(
|
||||
(data as any).response as LinkIncludingShortenedCollectionAndTags
|
||||
);
|
||||
}, 5000);
|
||||
} else {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
};
|
||||
}, [link?.image, link?.pdf, link?.readable]);
|
||||
|
||||
const handleDownload = () => {
|
||||
const path = `/api/v1/archives/${link?.id}?format=${format}`;
|
||||
fetch(path)
|
||||
.then((response) => {
|
||||
if (response.ok) {
|
||||
// Create a temporary link and click it to trigger the download
|
||||
const link = document.createElement("a");
|
||||
link.href = path;
|
||||
link.download = format === ArchivedFormat.pdf ? "PDF" : "Screenshot";
|
||||
link.click();
|
||||
} else {
|
||||
console.error("Failed to download file");
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error:", error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex justify-between items-center pr-1 border border-neutral-content rounded-md">
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="bg-primary text-primary-content p-2 rounded-l-md">
|
||||
<i className={`${icon} text-2xl`} />
|
||||
</div>
|
||||
<p>{name}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1">
|
||||
{downloadable || false ? (
|
||||
<div
|
||||
onClick={() => handleDownload()}
|
||||
className="btn btn-sm btn-square"
|
||||
>
|
||||
<i className="bi-cloud-arrow-down text-xl text-neutral" />
|
||||
</div>
|
||||
) : undefined}
|
||||
|
||||
<Link
|
||||
href={`${
|
||||
isPublic ? "/public" : ""
|
||||
}/preserved/${link?.id}?format=${format}`}
|
||||
target="_blank"
|
||||
className="btn btn-sm btn-square"
|
||||
>
|
||||
<i className="bi-box-arrow-up-right text-xl text-neutral" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
64
Securite/Linkwarden/components/ProfilePhoto.tsx
Normal file
@ -0,0 +1,64 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Image from "next/image";
|
||||
|
||||
type Props = {
|
||||
src?: string;
|
||||
className?: string;
|
||||
priority?: boolean;
|
||||
name?: string;
|
||||
large?: boolean;
|
||||
};
|
||||
|
||||
export default function ProfilePhoto({
|
||||
src,
|
||||
className,
|
||||
priority,
|
||||
name,
|
||||
large,
|
||||
}: Props) {
|
||||
const [image, setImage] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (src && !src?.includes("base64"))
|
||||
setImage(`/api/v1/${src.replace("uploads/", "").replace(".jpg", "")}`);
|
||||
else if (!src) setImage("");
|
||||
else {
|
||||
setImage(src);
|
||||
}
|
||||
}, [src]);
|
||||
|
||||
return !image ? (
|
||||
<div
|
||||
className={`avatar drop-shadow-md placeholder ${className || ""} ${
|
||||
large ? "w-28 h-28" : "w-8 h-8"
|
||||
}`}
|
||||
>
|
||||
<div className="bg-base-100 text-neutral rounded-full w-full h-full ring-2 ring-neutral-content select-none">
|
||||
{name ? (
|
||||
<span className="text-2xl capitalize">{name.slice(0, 1)}</span>
|
||||
) : (
|
||||
<i className={`bi-person ${large ? "text-5xl" : "text-xl"}`}></i>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={`avatar skeleton rounded-full drop-shadow-md ${
|
||||
className || ""
|
||||
} ${large ? "w-28 h-28" : "w-8 h-8"}`}
|
||||
>
|
||||
<div className="rounded-full w-full h-full ring-2 ring-neutral-content">
|
||||
<Image
|
||||
alt=""
|
||||
src={image}
|
||||
height={112}
|
||||
width={112}
|
||||
priority={priority}
|
||||
draggable={false}
|
||||
onError={() => setImage("")}
|
||||
className="aspect-square rounded-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
30
Securite/Linkwarden/components/RadioButton.tsx
Normal file
@ -0,0 +1,30 @@
|
||||
import { ChangeEventHandler } from "react";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
state: boolean;
|
||||
onClick: ChangeEventHandler<HTMLInputElement>;
|
||||
};
|
||||
|
||||
export default function RadioButton({ label, state, onClick }: Props) {
|
||||
return (
|
||||
<label className="cursor-pointer flex items-center gap-2">
|
||||
<input
|
||||
type="radio"
|
||||
value={label}
|
||||
className="peer sr-only"
|
||||
checked={state}
|
||||
onChange={onClick}
|
||||
/>
|
||||
{/*<FontAwesomeIcon*/}
|
||||
{/* icon={faCircleCheck}*/}
|
||||
{/* className="w-5 h-5 text-primary peer-checked:block hidden"*/}
|
||||
{/*/>*/}
|
||||
{/*<FontAwesomeIcon*/}
|
||||
{/* icon={faCircle}*/}
|
||||
{/* className="w-5 h-5 text-primary peer-checked:hidden block"*/}
|
||||
{/*/>*/}
|
||||
<span className="rounded select-none">{label}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
267
Securite/Linkwarden/components/ReadableView.tsx
Normal file
@ -0,0 +1,267 @@
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import { readabilityAvailable } from "@/lib/shared/getArchiveValidity";
|
||||
import isValidUrl from "@/lib/shared/isValidUrl";
|
||||
import useLinkStore from "@/store/links";
|
||||
import {
|
||||
ArchivedFormat,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
} from "@/types/global";
|
||||
import ColorThief, { RGBColor } from "colorthief";
|
||||
import DOMPurify from "dompurify";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
type LinkContent = {
|
||||
title: string;
|
||||
content: string;
|
||||
textContent: string;
|
||||
length: number;
|
||||
excerpt: string;
|
||||
byline: string;
|
||||
dir: string;
|
||||
siteName: string;
|
||||
lang: string;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
link: LinkIncludingShortenedCollectionAndTags;
|
||||
};
|
||||
|
||||
export default function ReadableView({ link }: Props) {
|
||||
const [linkContent, setLinkContent] = useState<LinkContent>();
|
||||
const [imageError, setImageError] = useState<boolean>(false);
|
||||
const [colorPalette, setColorPalette] = useState<RGBColor[]>();
|
||||
|
||||
const [date, setDate] = useState<Date | string>();
|
||||
|
||||
const colorThief = new ColorThief();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const { links, getLink } = useLinkStore();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchLinkContent = async () => {
|
||||
if (router.query.id && readabilityAvailable(link)) {
|
||||
const response = await fetch(
|
||||
`/api/v1/archives/${link?.id}?format=${ArchivedFormat.readability}`
|
||||
);
|
||||
|
||||
const data = await response?.json();
|
||||
|
||||
setLinkContent(data);
|
||||
}
|
||||
};
|
||||
|
||||
fetchLinkContent();
|
||||
|
||||
setDate(link.importDate || link.createdAt);
|
||||
}, [link]);
|
||||
|
||||
useEffect(() => {
|
||||
if (link) getLink(link?.id as number);
|
||||
|
||||
let interval: any;
|
||||
if (
|
||||
link &&
|
||||
(link?.image === "pending" ||
|
||||
link?.pdf === "pending" ||
|
||||
link?.readable === "pending" ||
|
||||
!link?.image ||
|
||||
!link?.pdf ||
|
||||
!link?.readable)
|
||||
) {
|
||||
interval = setInterval(() => getLink(link.id as number), 5000);
|
||||
} else {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
};
|
||||
}, [link?.image, link?.pdf, link?.readable]);
|
||||
|
||||
const rgbToHex = (r: number, g: number, b: number): string =>
|
||||
"#" +
|
||||
[r, g, b]
|
||||
.map((x) => {
|
||||
const hex = x.toString(16);
|
||||
return hex.length === 1 ? "0" + hex : hex;
|
||||
})
|
||||
.join("");
|
||||
|
||||
useEffect(() => {
|
||||
const banner = document.getElementById("link-banner");
|
||||
const bannerInner = document.getElementById("link-banner-inner");
|
||||
|
||||
if (colorPalette && banner && bannerInner) {
|
||||
if (colorPalette[0] && colorPalette[1]) {
|
||||
banner.style.background = `linear-gradient(to bottom, ${rgbToHex(
|
||||
colorPalette[0][0],
|
||||
colorPalette[0][1],
|
||||
colorPalette[0][2]
|
||||
)}20, ${rgbToHex(
|
||||
colorPalette[1][0],
|
||||
colorPalette[1][1],
|
||||
colorPalette[1][2]
|
||||
)}20)`;
|
||||
}
|
||||
|
||||
if (colorPalette[2] && colorPalette[3]) {
|
||||
bannerInner.style.background = `linear-gradient(to bottom, ${rgbToHex(
|
||||
colorPalette[2][0],
|
||||
colorPalette[2][1],
|
||||
colorPalette[2][2]
|
||||
)}30, ${rgbToHex(
|
||||
colorPalette[3][0],
|
||||
colorPalette[3][1],
|
||||
colorPalette[3][2]
|
||||
)})30`;
|
||||
}
|
||||
}
|
||||
}, [colorPalette]);
|
||||
|
||||
return (
|
||||
<div className={`flex flex-col max-w-screen-md h-full mx-auto py-5`}>
|
||||
<div
|
||||
id="link-banner"
|
||||
className="link-banner bg-opacity-10 border-neutral-content p-3 border mb-3"
|
||||
>
|
||||
<div id="link-banner-inner" className="link-banner-inner"></div>
|
||||
|
||||
<div className={`flex flex-col gap-3 items-start`}>
|
||||
<div className="flex gap-3 items-start">
|
||||
{!imageError && link?.url && (
|
||||
<Image
|
||||
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${link.url}&size=32`}
|
||||
width={42}
|
||||
height={42}
|
||||
alt=""
|
||||
id={"favicon-" + link.id}
|
||||
className="bg-white shadow rounded-md p-1 select-none mt-1"
|
||||
draggable="false"
|
||||
onLoad={(e) => {
|
||||
try {
|
||||
const color = colorThief.getPalette(
|
||||
e.target as HTMLImageElement,
|
||||
4
|
||||
);
|
||||
|
||||
setColorPalette(color);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}}
|
||||
onError={(e) => {
|
||||
setImageError(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col">
|
||||
<p className="text-xl">
|
||||
{unescapeString(
|
||||
link?.name || link?.description || link?.url || ""
|
||||
)}
|
||||
</p>
|
||||
{link?.url ? (
|
||||
<Link
|
||||
href={link?.url || ""}
|
||||
title={link?.url}
|
||||
target="_blank"
|
||||
className="hover:opacity-60 duration-100 break-all text-sm flex items-center gap-1 text-neutral w-fit"
|
||||
>
|
||||
<i className="bi-link-45deg"></i>
|
||||
|
||||
{isValidUrl(link?.url || "")
|
||||
? new URL(link?.url as string).host
|
||||
: undefined}
|
||||
</Link>
|
||||
) : undefined}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 items-center flex-wrap">
|
||||
<Link
|
||||
href={`/collections/${link?.collection.id}`}
|
||||
className="flex items-center gap-1 cursor-pointer hover:opacity-60 duration-100 mr-2 z-10"
|
||||
>
|
||||
<i
|
||||
className="bi-folder-fill drop-shadow text-2xl"
|
||||
style={{ color: link?.collection.color }}
|
||||
></i>
|
||||
<p
|
||||
title={link?.collection.name}
|
||||
className="text-lg truncate max-w-[12rem]"
|
||||
>
|
||||
{link?.collection.name}
|
||||
</p>
|
||||
</Link>
|
||||
{link?.tags.map((e, i) => (
|
||||
<Link key={i} href={`/tags/${e.id}`} className="z-10">
|
||||
<p
|
||||
title={e.name}
|
||||
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
|
||||
>
|
||||
#{e.name}
|
||||
</p>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="min-w-fit text-sm text-neutral">
|
||||
{date
|
||||
? new Date(date).toLocaleString("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
})
|
||||
: undefined}
|
||||
</p>
|
||||
|
||||
{link?.name ? <p>{unescapeString(link?.description)}</p> : undefined}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-5 h-full">
|
||||
{link?.readable?.startsWith("archives") ? (
|
||||
<div
|
||||
className="line-break px-1 reader-view"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: DOMPurify.sanitize(linkContent?.content || "") || "",
|
||||
}}
|
||||
></div>
|
||||
) : (
|
||||
<div
|
||||
className={`w-full h-full flex flex-col justify-center p-10 ${
|
||||
link?.readable === "pending" || !link?.readable ? "skeleton" : ""
|
||||
}`}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="16"
|
||||
height="16"
|
||||
fill="currentColor"
|
||||
className="w-1/4 min-w-[7rem] max-w-[15rem] h-auto mx-auto mb-5"
|
||||
viewBox="0 0 16 16"
|
||||
>
|
||||
<path d="m14.12 10.163 1.715.858c.22.11.22.424 0 .534L8.267 15.34a.598.598 0 0 1-.534 0L.165 11.555a.299.299 0 0 1 0-.534l1.716-.858 5.317 2.659c.505.252 1.1.252 1.604 0l5.317-2.66zM7.733.063a.598.598 0 0 1 .534 0l7.568 3.784a.3.3 0 0 1 0 .535L8.267 8.165a.598.598 0 0 1-.534 0L.165 4.382a.299.299 0 0 1 0-.535L7.733.063z" />
|
||||
<path d="m14.12 6.576 1.715.858c.22.11.22.424 0 .534l-7.568 3.784a.598.598 0 0 1-.534 0L.165 7.968a.299.299 0 0 1 0-.534l1.716-.858 5.317 2.659c.505.252 1.1.252 1.604 0l5.317-2.659z" />
|
||||
</svg>
|
||||
<p className="text-center text-2xl">
|
||||
The Link preservation is currently in the queue
|
||||
</p>
|
||||
<p className="text-center text-lg mt-2">
|
||||
Please check back later to see the result
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
63
Securite/Linkwarden/components/SearchBar.tsx
Normal file
@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
import { toast } from "react-hot-toast";
|
||||
|
||||
type Props = {
|
||||
placeholder?: string;
|
||||
};
|
||||
|
||||
export default function SearchBar({ placeholder }: Props) {
|
||||
const router = useRouter();
|
||||
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
router.query.q
|
||||
? setSearchQuery(decodeURIComponent(router.query.q as string))
|
||||
: setSearchQuery("");
|
||||
}, [router.query.q]);
|
||||
|
||||
return (
|
||||
<div className="flex items-center relative group">
|
||||
<label
|
||||
htmlFor="search-box"
|
||||
className="inline-flex items-center w-fit absolute left-1 pointer-events-none rounded-md p-1 text-primary"
|
||||
>
|
||||
<i className="bi-search"></i>
|
||||
</label>
|
||||
|
||||
<input
|
||||
id="search-box"
|
||||
type="text"
|
||||
placeholder={placeholder || "Search for Links"}
|
||||
value={searchQuery}
|
||||
onChange={(e) => {
|
||||
e.target.value.includes("%") &&
|
||||
toast.error("The search query should not contain '%'.");
|
||||
setSearchQuery(e.target.value.replace("%", ""));
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (router.pathname.startsWith("/public")) {
|
||||
if (!searchQuery) {
|
||||
return router.push("/public/collections/" + router.query.id);
|
||||
}
|
||||
|
||||
return router.push(
|
||||
"/public/collections/" +
|
||||
router.query.id +
|
||||
"?q=" +
|
||||
encodeURIComponent(searchQuery || "")
|
||||
);
|
||||
} else {
|
||||
return router.push(
|
||||
"/search?q=" + encodeURIComponent(searchQuery)
|
||||
);
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="border border-neutral-content bg-base-200 focus:border-primary py-1 rounded-md pl-9 pr-2 w-full max-w-[15rem] md:focus:w-80 md:w-[15rem] md:max-w-full duration-200 outline-none"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
143
Securite/Linkwarden/components/SettingsSidebar.tsx
Normal file
@ -0,0 +1,143 @@
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
export default function SettingsSidebar({ className }: { className?: string }) {
|
||||
const LINKWARDEN_VERSION = "v2.5.1";
|
||||
|
||||
const { collections } = useCollectionStore();
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const [active, setActive] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setActive(router.asPath);
|
||||
}, [router, collections]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`bg-base-100 h-full w-64 overflow-y-auto border-solid border border-base-100 border-r-neutral-content p-5 z-20 flex flex-col gap-5 justify-between ${
|
||||
className || ""
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Link href="/settings/account">
|
||||
<div
|
||||
className={`${
|
||||
active === `/settings/account`
|
||||
? "bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 py-5 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-person text-primary text-2xl"></i>
|
||||
|
||||
<p className="truncate w-full pr-7">Account</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href="/settings/preference">
|
||||
<div
|
||||
className={`${
|
||||
active === `/settings/preference`
|
||||
? "bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 py-5 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-sliders text-primary text-2xl"></i>
|
||||
|
||||
<p className="truncate w-full pr-7">Preference</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href="/settings/access-tokens">
|
||||
<div
|
||||
className={`${
|
||||
active === `/settings/access-tokens`
|
||||
? "bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 py-5 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-key text-primary text-2xl"></i>
|
||||
<p className="truncate w-full pr-7">Access Tokens</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href="/settings/password">
|
||||
<div
|
||||
className={`${
|
||||
active === `/settings/password`
|
||||
? "bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 py-5 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-lock text-primary text-2xl"></i>
|
||||
<p className="truncate w-full pr-7">Password</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
{process.env.NEXT_PUBLIC_STRIPE ? (
|
||||
<Link href="/settings/billing">
|
||||
<div
|
||||
className={`${
|
||||
active === `/settings/billing`
|
||||
? "bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 py-5 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-credit-card text-primary text-xl"></i>
|
||||
<p className="truncate w-full pr-7">Billing</p>
|
||||
</div>
|
||||
</Link>
|
||||
) : undefined}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<Link
|
||||
href={`https://github.com/linkwarden/linkwarden/releases`}
|
||||
target="_blank"
|
||||
className="text-neutral text-sm ml-2 hover:opacity-50 duration-100"
|
||||
>
|
||||
Linkwarden {LINKWARDEN_VERSION}
|
||||
</Link>
|
||||
<Link href="https://docs.linkwarden.app" target="_blank">
|
||||
<div
|
||||
className={`hover:bg-neutral/20 duration-100 py-2 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-question-circle text-primary text-xl"></i>
|
||||
|
||||
<p className="truncate w-full pr-7">Help</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href="https://github.com/linkwarden/linkwarden" target="_blank">
|
||||
<div
|
||||
className={`hover:bg-neutral/20 duration-100 py-2 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-github text-primary text-xl"></i>
|
||||
<p className="truncate w-full pr-7">GitHub</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href="https://twitter.com/LinkwardenHQ" target="_blank">
|
||||
<div
|
||||
className={`hover:bg-neutral/20 duration-100 py-2 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-twitter-x text-primary text-xl"></i>
|
||||
<p className="truncate w-full pr-7">Twitter</p>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href="https://fosstodon.org/@linkwarden" target="_blank">
|
||||
<div
|
||||
className={`hover:bg-neutral/20 duration-100 py-2 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-mastodon text-primary text-xl"></i>
|
||||
<p className="truncate w-full pr-7">Mastodon</p>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
164
Securite/Linkwarden/components/Sidebar.tsx
Normal file
@ -0,0 +1,164 @@
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import useTagStore from "@/store/tags";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Disclosure, Transition } from "@headlessui/react";
|
||||
import SidebarHighlightLink from "@/components/SidebarHighlightLink";
|
||||
import CollectionListing from "@/components/CollectionListing";
|
||||
|
||||
export default function Sidebar({ className }: { className?: string }) {
|
||||
const [tagDisclosure, setTagDisclosure] = useState<boolean>(() => {
|
||||
const storedValue = localStorage.getItem("tagDisclosure");
|
||||
return storedValue ? storedValue === "true" : true;
|
||||
});
|
||||
|
||||
const [collectionDisclosure, setCollectionDisclosure] = useState<boolean>(
|
||||
() => {
|
||||
const storedValue = localStorage.getItem("collectionDisclosure");
|
||||
return storedValue ? storedValue === "true" : true;
|
||||
}
|
||||
);
|
||||
|
||||
const { collections } = useCollectionStore();
|
||||
const { tags } = useTagStore();
|
||||
const [active, setActive] = useState("");
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem("tagDisclosure", tagDisclosure ? "true" : "false");
|
||||
}, [tagDisclosure]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(
|
||||
"collectionDisclosure",
|
||||
collectionDisclosure ? "true" : "false"
|
||||
);
|
||||
}, [collectionDisclosure]);
|
||||
|
||||
useEffect(() => {
|
||||
setActive(router.asPath);
|
||||
}, [router, collections]);
|
||||
|
||||
return (
|
||||
<div
|
||||
id="sidebar"
|
||||
className={`bg-base-200 h-full w-80 overflow-y-auto border-solid border border-base-200 border-r-neutral-content p-2 z-20 ${
|
||||
className || ""
|
||||
}`}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<SidebarHighlightLink
|
||||
title={"Dashboard"}
|
||||
href={`/dashboard`}
|
||||
icon={"bi-house"}
|
||||
active={active === `/dashboard`}
|
||||
/>
|
||||
<SidebarHighlightLink
|
||||
title={"Pinned"}
|
||||
href={`/links/pinned`}
|
||||
icon={"bi-pin-angle"}
|
||||
active={active === `/links/pinned`}
|
||||
/>
|
||||
<SidebarHighlightLink
|
||||
title={"All Links"}
|
||||
href={`/links`}
|
||||
icon={"bi-link-45deg"}
|
||||
active={active === `/links`}
|
||||
/>
|
||||
<SidebarHighlightLink
|
||||
title={"All Collections"}
|
||||
href={`/collections`}
|
||||
icon={"bi-folder"}
|
||||
active={active === `/collections`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Disclosure defaultOpen={collectionDisclosure}>
|
||||
<Disclosure.Button
|
||||
onClick={() => {
|
||||
setCollectionDisclosure(!collectionDisclosure);
|
||||
}}
|
||||
className="flex items-center justify-between w-full text-left mb-2 pl-2 font-bold text-neutral mt-5"
|
||||
>
|
||||
<p className="text-sm">Collections</p>
|
||||
<i
|
||||
className={`bi-chevron-down ${
|
||||
collectionDisclosure ? "rotate-reverse" : "rotate"
|
||||
}`}
|
||||
></i>
|
||||
</Disclosure.Button>
|
||||
<Transition
|
||||
enter="transition duration-100 ease-out"
|
||||
enterFrom="transform opacity-0 -translate-y-3"
|
||||
enterTo="transform opacity-100 translate-y-0"
|
||||
leave="transition duration-100 ease-out"
|
||||
leaveFrom="transform opacity-100 translate-y-0"
|
||||
leaveTo="transform opacity-0 -translate-y-3"
|
||||
>
|
||||
<Disclosure.Panel>
|
||||
<CollectionListing />
|
||||
</Disclosure.Panel>
|
||||
</Transition>
|
||||
</Disclosure>
|
||||
<Disclosure defaultOpen={tagDisclosure}>
|
||||
<Disclosure.Button
|
||||
onClick={() => {
|
||||
setTagDisclosure(!tagDisclosure);
|
||||
}}
|
||||
className="flex items-center justify-between w-full text-left mb-2 pl-2 font-bold text-neutral mt-5"
|
||||
>
|
||||
<p className="text-sm">Tags</p>
|
||||
<i
|
||||
className={`bi-chevron-down ${
|
||||
tagDisclosure ? "rotate-reverse" : "rotate"
|
||||
}`}
|
||||
></i>
|
||||
</Disclosure.Button>
|
||||
<Transition
|
||||
enter="transition duration-100 ease-out"
|
||||
enterFrom="transform opacity-0 -translate-y-3"
|
||||
enterTo="transform opacity-100 translate-y-0"
|
||||
leave="transition duration-100 ease-out"
|
||||
leaveFrom="transform opacity-100 translate-y-0"
|
||||
leaveTo="transform opacity-0 -translate-y-3"
|
||||
>
|
||||
<Disclosure.Panel className="flex flex-col gap-1">
|
||||
{tags[0] ? (
|
||||
tags
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map((e, i) => {
|
||||
return (
|
||||
<Link key={i} href={`/tags/${e.id}`}>
|
||||
<div
|
||||
className={`${
|
||||
active === `/tags/${e.id}`
|
||||
? "bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
} duration-100 py-1 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
|
||||
>
|
||||
<i className="bi-hash text-2xl text-primary drop-shadow"></i>
|
||||
<p className="truncate w-full pr-7">{e.name}</p>
|
||||
<div className="drop-shadow text-neutral text-xs">
|
||||
{e._count?.links}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div
|
||||
className={`duration-100 py-1 px-2 flex items-center gap-2 w-full rounded-md h-8 capitalize`}
|
||||
>
|
||||
<p className="text-neutral text-xs font-semibold truncate w-full pr-7">
|
||||
You Have No Tags...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Disclosure.Panel>
|
||||
</Transition>
|
||||
</Disclosure>
|
||||
</div>
|
||||
);
|
||||
}
|
36
Securite/Linkwarden/components/SidebarHighlightLink.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function SidebarHighlightLink({
|
||||
title,
|
||||
href,
|
||||
icon,
|
||||
active,
|
||||
}: {
|
||||
title: string;
|
||||
href: string;
|
||||
icon: string;
|
||||
active?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Link href={href}>
|
||||
<div
|
||||
className={`${
|
||||
active || false
|
||||
? "bg-primary/20"
|
||||
: "bg-neutral-content/20 hover:bg-neutral/20"
|
||||
} duration-200 px-3 py-2 cursor-pointer gap-2 w-full rounded-lg capitalize`}
|
||||
>
|
||||
<div
|
||||
className={
|
||||
"w-10 h-10 inline-flex items-center justify-center bg-black/10 dark:bg-white/5 rounded-full"
|
||||
}
|
||||
>
|
||||
<i className={`${icon} text-primary text-2xl drop-shadow`}></i>
|
||||
</div>
|
||||
<div className={"mt-1"}>
|
||||
<p className="truncate w-full font-semibold text-sm">{title}</p>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
129
Securite/Linkwarden/components/SortDropdown.tsx
Normal file
@ -0,0 +1,129 @@
|
||||
import React, { Dispatch, SetStateAction } from "react";
|
||||
import { Sort } from "@/types/global";
|
||||
import { dropdownTriggerer } from "@/lib/client/utils";
|
||||
|
||||
type Props = {
|
||||
sortBy: Sort;
|
||||
setSort: Dispatch<SetStateAction<Sort>>;
|
||||
};
|
||||
|
||||
export default function SortDropdown({ sortBy, setSort }: Props) {
|
||||
return (
|
||||
<div className="dropdown dropdown-bottom dropdown-end">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
onMouseDown={dropdownTriggerer}
|
||||
className="btn btn-sm btn-square btn-ghost border-none"
|
||||
>
|
||||
<i className="bi-chevron-expand text-neutral text-2xl"></i>
|
||||
</div>
|
||||
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl w-52 mt-1">
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
value="Date (Newest First)"
|
||||
checked={sortBy === Sort.DateNewestFirst}
|
||||
onChange={() => {
|
||||
setSort(Sort.DateNewestFirst);
|
||||
}}
|
||||
/>
|
||||
<span className="label-text">Date (Newest First)</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
value="Date (Oldest First)"
|
||||
checked={sortBy === Sort.DateOldestFirst}
|
||||
onChange={() => setSort(Sort.DateOldestFirst)}
|
||||
/>
|
||||
<span className="label-text">Date (Oldest First)</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
value="Name (A-Z)"
|
||||
checked={sortBy === Sort.NameAZ}
|
||||
onChange={() => setSort(Sort.NameAZ)}
|
||||
/>
|
||||
<span className="label-text">Name (A-Z)</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
value="Name (Z-A)"
|
||||
checked={sortBy === Sort.NameZA}
|
||||
onChange={() => setSort(Sort.NameZA)}
|
||||
/>
|
||||
<span className="label-text">Name (Z-A)</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
value="Description (A-Z)"
|
||||
checked={sortBy === Sort.DescriptionAZ}
|
||||
onChange={() => setSort(Sort.DescriptionAZ)}
|
||||
/>
|
||||
<span className="label-text">Description (A-Z)</span>
|
||||
</label>
|
||||
</li>
|
||||
<li>
|
||||
<label
|
||||
className="label cursor-pointer flex justify-start"
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="sort-radio"
|
||||
className="radio checked:bg-primary"
|
||||
value="Description (Z-A)"
|
||||
checked={sortBy === Sort.DescriptionZA}
|
||||
onChange={() => setSort(Sort.DescriptionZA)}
|
||||
/>
|
||||
<span className="label-text">Description (Z-A)</span>
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
29
Securite/Linkwarden/components/SubmitButton.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
type Props = {
|
||||
onClick?: Function;
|
||||
label: string;
|
||||
loading: boolean;
|
||||
className?: string;
|
||||
type?: "button" | "submit" | "reset" | undefined;
|
||||
};
|
||||
|
||||
export default function SubmitButton({
|
||||
onClick,
|
||||
label,
|
||||
loading,
|
||||
className,
|
||||
type,
|
||||
}: Props) {
|
||||
return (
|
||||
<button
|
||||
type={type ? type : undefined}
|
||||
className={`btn btn-accent dark:border-violet-400 text-white tracking-wider w-fit flex items-center gap-2 ${
|
||||
className || ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (!loading && onClick) onClick();
|
||||
}}
|
||||
>
|
||||
<p>{label}</p>
|
||||
</button>
|
||||
);
|
||||
}
|
38
Securite/Linkwarden/components/TextInput.tsx
Normal file
@ -0,0 +1,38 @@
|
||||
import { ChangeEventHandler, KeyboardEventHandler } from "react";
|
||||
|
||||
type Props = {
|
||||
autoFocus?: boolean;
|
||||
value?: string;
|
||||
type?: string;
|
||||
placeholder?: string;
|
||||
onChange: ChangeEventHandler<HTMLInputElement>;
|
||||
onKeyDown?: KeyboardEventHandler<HTMLInputElement> | undefined;
|
||||
className?: string;
|
||||
spellCheck?: boolean;
|
||||
};
|
||||
|
||||
export default function TextInput({
|
||||
autoFocus,
|
||||
value,
|
||||
type,
|
||||
placeholder,
|
||||
onChange,
|
||||
onKeyDown,
|
||||
className,
|
||||
spellCheck,
|
||||
}: Props) {
|
||||
return (
|
||||
<input
|
||||
spellCheck={spellCheck}
|
||||
autoFocus={autoFocus}
|
||||
type={type ? type : "text"}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onKeyDown={onKeyDown}
|
||||
className={`w-full rounded-md p-2 border-neutral-content border-solid border outline-none focus:border-primary duration-100 ${
|
||||
className || ""
|
||||
}`}
|
||||
/>
|
||||
);
|
||||
}
|
40
Securite/Linkwarden/components/ToggleDarkMode.tsx
Normal file
@ -0,0 +1,40 @@
|
||||
import useLocalSettingsStore from "@/store/localSettings";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
type Props = {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function ToggleDarkMode({ className }: Props) {
|
||||
const { settings, updateSettings } = useLocalSettingsStore();
|
||||
|
||||
const [theme, setTheme] = useState(localStorage.getItem("theme"));
|
||||
|
||||
const handleToggle = (e: any) => {
|
||||
setTheme(e.target.checked ? "dark" : "light");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
updateSettings({ theme: theme as string });
|
||||
}, [theme]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="tooltip tooltip-bottom"
|
||||
data-tip={`Switch to ${settings.theme === "light" ? "Dark" : "Light"}`}
|
||||
>
|
||||
<label
|
||||
className={`swap swap-rotate btn-square text-neutral btn btn-ghost btn-sm ${className}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
onChange={handleToggle}
|
||||
className="theme-controller"
|
||||
checked={localStorage.getItem("theme") === "light" ? false : true}
|
||||
/>
|
||||
<i className="bi-sun-fill text-xl swap-on"></i>
|
||||
<i className="bi-moon-fill text-xl swap-off"></i>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
61
Securite/Linkwarden/components/ViewDropdown.tsx
Normal file
@ -0,0 +1,61 @@
|
||||
import React, { Dispatch, SetStateAction, useEffect } from "react";
|
||||
import useLocalSettingsStore from "@/store/localSettings";
|
||||
|
||||
import { ViewMode } from "@/types/global";
|
||||
|
||||
type Props = {
|
||||
viewMode: string;
|
||||
setViewMode: Dispatch<SetStateAction<string>>;
|
||||
};
|
||||
|
||||
export default function ViewDropdown({ viewMode, setViewMode }: Props) {
|
||||
const { updateSettings } = useLocalSettingsStore();
|
||||
|
||||
const onChangeViewMode = (
|
||||
e: React.MouseEvent<HTMLButtonElement>,
|
||||
viewMode: ViewMode
|
||||
) => {
|
||||
setViewMode(viewMode);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
updateSettings({ viewMode: viewMode as ViewMode });
|
||||
}, [viewMode]);
|
||||
|
||||
return (
|
||||
<div className="p-1 flex flex-row gap-1 border border-neutral-content rounded-[0.625rem]">
|
||||
<button
|
||||
onClick={(e) => onChangeViewMode(e, ViewMode.Card)}
|
||||
className={`btn btn-square btn-sm btn-ghost ${
|
||||
viewMode == ViewMode.Card
|
||||
? "bg-primary/20 hover:bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
}`}
|
||||
>
|
||||
<i className="bi-grid w-4 h-4 text-neutral"></i>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={(e) => onChangeViewMode(e, ViewMode.List)}
|
||||
className={`btn btn-square btn-sm btn-ghost ${
|
||||
viewMode == ViewMode.List
|
||||
? "bg-primary/20 hover:bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
}`}
|
||||
>
|
||||
<i className="bi bi-view-stacked w-4 h-4 text-neutral"></i>
|
||||
</button>
|
||||
|
||||
{/* <button
|
||||
onClick={(e) => onChangeViewMode(e, ViewMode.Grid)}
|
||||
className={`btn btn-square btn-sm btn-ghost ${
|
||||
viewMode == ViewMode.Grid
|
||||
? "bg-primary/20 hover:bg-primary/20"
|
||||
: "hover:bg-neutral/20"
|
||||
}`}
|
||||
>
|
||||
<i className="bi-columns-gap w-4 h-4 text-neutral"></i>
|
||||
</button> */}
|
||||
</div>
|
||||
);
|
||||
}
|
66
Securite/Linkwarden/docker-compose-traefik.yml
Normal file
@ -0,0 +1,66 @@
|
||||

|
||||
URL : HHHHH
|
||||
|
||||
# Fichier-Stockage
|
||||
|
||||
GGGGG
|
||||
|
||||
# Téléchargement, Configuration et Lancement
|
||||
|
||||
## Téléchargement de Fichier-Stockage
|
||||
|
||||
Saisir la commande pour télécharger la source
|
||||
```bash
|
||||
git clone https://git.tips-of-mine.fr/Tips-Of-Mine/Docker.git
|
||||
```
|
||||
|
||||
Saisir la commande pour vous rendre dans le dossier
|
||||
```bash
|
||||
cd AAAAA\Fichier-Stockage
|
||||
```
|
||||
|
||||
## Modifier la configuration de Fichier-Stockage
|
||||
|
||||
Saisir la commande pour vous rendre dans le dossier
|
||||
```bash
|
||||
cd AAAAA\Fichier-Stockage
|
||||
```
|
||||
|
||||
Nous éditons le fichier de configuration
|
||||
```bash
|
||||
nano .env
|
||||
```
|
||||
|
||||
Nous modifions les variables dont nous avons besoin.
|
||||
|
||||
## Lancement de Fichier-Stockage
|
||||
|
||||
Pour utiliser Fichier-Stockage tout seul
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Pour utiliser Fichier-Stockage avec Traefik
|
||||
```bash
|
||||
docker compose -f docker-compose-traefik.yml up -d
|
||||
```
|
||||
|
||||
# Utilisation
|
||||
|
||||
## Accueil
|
||||
|
||||
Ouvrir une page web avec l'url :
|
||||
Pour une utilisation tout seul
|
||||
|
||||
http://10.0.4.29:3000
|
||||
|
||||
Pour une utilisation avec Traefik
|
||||
|
||||
https://Fichier-Stockage.10.0.4.29.traefik.me`)"
|
||||
|
||||
|
||||
# More info
|
||||
- more information on the website [Tips-Of-Mine](https://www.tips-of-mine.fr/)
|
||||
|
||||
# Buy me a coffe
|
||||
<a href='https://ko-fi.com/R5R2KNI3N' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi4.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
|
21
Securite/Linkwarden/docker-compose.yml
Normal file
@ -0,0 +1,21 @@
|
||||
version: "3.5"
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
env_file: .env
|
||||
restart: always
|
||||
volumes:
|
||||
- ./pgdata:/var/lib/postgresql/data
|
||||
linkwarden:
|
||||
env_file: .env
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgres:5432/postgres
|
||||
restart: always
|
||||
# build: . # uncomment this line to build from source
|
||||
image: ghcr.io/linkwarden/linkwarden:latest # comment this line to build from source
|
||||
ports:
|
||||
- 3000:3000
|
||||
volumes:
|
||||
- ./data:/data/data
|
||||
depends_on:
|
||||
- postgres
|
34
Securite/Linkwarden/hooks/useCollectivePermissions.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import useAccountStore from "@/store/account";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import { Member } from "@/types/global";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function useCollectivePermissions(collectionIds: number[]) {
|
||||
const { collections } = useCollectionStore();
|
||||
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const [permissions, setPermissions] = useState<Member | true>();
|
||||
useEffect(() => {
|
||||
for (const collectionId of collectionIds) {
|
||||
const collection = collections.find((e) => e.id === collectionId);
|
||||
|
||||
if (collection) {
|
||||
let getPermission: Member | undefined = collection.members.find(
|
||||
(e) => e.userId === account.id
|
||||
);
|
||||
|
||||
if (
|
||||
getPermission?.canCreate === false &&
|
||||
getPermission?.canUpdate === false &&
|
||||
getPermission?.canDelete === false
|
||||
)
|
||||
getPermission = undefined;
|
||||
|
||||
setPermissions(account.id === collection.ownerId || getPermission);
|
||||
}
|
||||
}
|
||||
}, [account, collections, collectionIds]);
|
||||
|
||||
return permissions;
|
||||
}
|
26
Securite/Linkwarden/hooks/useDetectPageBottom.tsx
Normal file
@ -0,0 +1,26 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
const useDetectPageBottom = () => {
|
||||
const [reachedBottom, setReachedBottom] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
const totalHeight = document.documentElement.scrollHeight;
|
||||
const scrolledHeight = window.scrollY + window.innerHeight;
|
||||
|
||||
if (scrolledHeight >= totalHeight) {
|
||||
setReachedBottom(true);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("scroll", handleScroll);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("scroll", handleScroll);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { reachedBottom, setReachedBottom };
|
||||
};
|
||||
|
||||
export default useDetectPageBottom;
|
32
Securite/Linkwarden/hooks/useInitialData.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import { useEffect } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import useTagStore from "@/store/tags";
|
||||
import useAccountStore from "@/store/account";
|
||||
import useLocalSettingsStore from "@/store/localSettings";
|
||||
|
||||
export default function useInitialData() {
|
||||
const { status, data } = useSession();
|
||||
const { setCollections } = useCollectionStore();
|
||||
const { setTags } = useTagStore();
|
||||
// const { setLinks } = useLinkStore();
|
||||
const { account, setAccount } = useAccountStore();
|
||||
const { setSettings } = useLocalSettingsStore();
|
||||
|
||||
useEffect(() => {
|
||||
setSettings();
|
||||
if (status === "authenticated") {
|
||||
// Get account info
|
||||
setAccount(data?.user.id as number);
|
||||
}
|
||||
}, [status, data]);
|
||||
|
||||
// Get the rest of the data
|
||||
useEffect(() => {
|
||||
if (account.id && (!process.env.NEXT_PUBLIC_STRIPE || account.username)) {
|
||||
setCollections();
|
||||
setTags();
|
||||
// setLinks();
|
||||
}
|
||||
}, [account]);
|
||||
}
|
103
Securite/Linkwarden/hooks/useLinks.tsx
Normal file
@ -0,0 +1,103 @@
|
||||
import { LinkRequestQuery } from "@/types/global";
|
||||
import { useEffect, useState } from "react";
|
||||
import useDetectPageBottom from "./useDetectPageBottom";
|
||||
import { useRouter } from "next/router";
|
||||
import useLinkStore from "@/store/links";
|
||||
|
||||
export default function useLinks(
|
||||
{
|
||||
sort,
|
||||
collectionId,
|
||||
tagId,
|
||||
pinnedOnly,
|
||||
searchQueryString,
|
||||
searchByName,
|
||||
searchByUrl,
|
||||
searchByDescription,
|
||||
searchByTags,
|
||||
searchByTextContent,
|
||||
}: LinkRequestQuery = { sort: 0 }
|
||||
) {
|
||||
const { links, setLinks, resetLinks, selectedLinks, setSelectedLinks } =
|
||||
useLinkStore();
|
||||
const router = useRouter();
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const { reachedBottom, setReachedBottom } = useDetectPageBottom();
|
||||
|
||||
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
|
||||
const params = {
|
||||
sort,
|
||||
cursor,
|
||||
collectionId,
|
||||
tagId,
|
||||
pinnedOnly,
|
||||
searchQueryString,
|
||||
searchByName,
|
||||
searchByUrl,
|
||||
searchByDescription,
|
||||
searchByTags,
|
||||
searchByTextContent,
|
||||
};
|
||||
|
||||
const buildQueryString = (params: LinkRequestQuery) => {
|
||||
return Object.keys(params)
|
||||
.filter((key) => params[key as keyof LinkRequestQuery] !== undefined)
|
||||
.map(
|
||||
(key) =>
|
||||
`${encodeURIComponent(key)}=${encodeURIComponent(
|
||||
params[key as keyof LinkRequestQuery] as string
|
||||
)}`
|
||||
)
|
||||
.join("&");
|
||||
};
|
||||
|
||||
let queryString = buildQueryString(params);
|
||||
|
||||
let basePath;
|
||||
|
||||
if (router.pathname === "/dashboard") basePath = "/api/v1/dashboard";
|
||||
else if (router.pathname.startsWith("/public/collections/[id]")) {
|
||||
queryString = queryString + "&collectionId=" + router.query.id;
|
||||
basePath = "/api/v1/public/collections/links";
|
||||
} else basePath = "/api/v1/links";
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
const response = await fetch(`${basePath}?${queryString}`);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
setIsLoading(false);
|
||||
|
||||
if (response.ok) setLinks(data.response, isInitialCall);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Save the selected links before resetting the links
|
||||
// and then restore the selected links after resetting the links
|
||||
const previouslySelected = selectedLinks;
|
||||
resetLinks();
|
||||
|
||||
setSelectedLinks(previouslySelected);
|
||||
getLinks(true);
|
||||
}, [
|
||||
router,
|
||||
sort,
|
||||
searchQueryString,
|
||||
searchByName,
|
||||
searchByUrl,
|
||||
searchByDescription,
|
||||
searchByTextContent,
|
||||
searchByTags,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (reachedBottom) getLinks(false, links?.at(-1)?.id);
|
||||
|
||||
setReachedBottom(false);
|
||||
}, [reachedBottom]);
|
||||
|
||||
return { isLoading };
|
||||
}
|
20
Securite/Linkwarden/hooks/useOnScreen.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import { RefObject, useEffect, useMemo, useState } from "react";
|
||||
|
||||
export default function useOnScreen(ref: RefObject<HTMLElement>) {
|
||||
const [isIntersecting, setIntersecting] = useState(false);
|
||||
|
||||
const observer = useMemo(
|
||||
() =>
|
||||
new IntersectionObserver(([entry]) =>
|
||||
setIntersecting(entry.isIntersecting)
|
||||
),
|
||||
[ref]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
observer.observe(ref.current as HTMLElement);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return isIntersecting;
|
||||
}
|
32
Securite/Linkwarden/hooks/usePermissions.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import useAccountStore from "@/store/account";
|
||||
import useCollectionStore from "@/store/collections";
|
||||
import { Member } from "@/types/global";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function usePermissions(collectionId: number) {
|
||||
const { collections } = useCollectionStore();
|
||||
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const [permissions, setPermissions] = useState<Member | true>();
|
||||
useEffect(() => {
|
||||
const collection = collections.find((e) => e.id === collectionId);
|
||||
|
||||
if (collection) {
|
||||
let getPermission: Member | undefined = collection.members.find(
|
||||
(e) => e.userId === account.id
|
||||
);
|
||||
|
||||
if (
|
||||
getPermission?.canCreate === false &&
|
||||
getPermission?.canUpdate === false &&
|
||||
getPermission?.canDelete === false
|
||||
)
|
||||
getPermission = undefined;
|
||||
|
||||
setPermissions(account.id === collection.ownerId || getPermission);
|
||||
}
|
||||
}, [account, collections, collectionId]);
|
||||
|
||||
return permissions;
|
||||
}
|
56
Securite/Linkwarden/hooks/useSort.tsx
Normal file
@ -0,0 +1,56 @@
|
||||
import {
|
||||
CollectionIncludingMembersAndLinkCount,
|
||||
LinkIncludingShortenedCollectionAndTags,
|
||||
Sort,
|
||||
} from "@/types/global";
|
||||
import { SetStateAction, useEffect } from "react";
|
||||
|
||||
type Props<
|
||||
T extends
|
||||
| CollectionIncludingMembersAndLinkCount
|
||||
| LinkIncludingShortenedCollectionAndTags,
|
||||
> = {
|
||||
sortBy: Sort;
|
||||
|
||||
data: T[];
|
||||
setData: (value: SetStateAction<T[]>) => void;
|
||||
};
|
||||
|
||||
export default function useSort<
|
||||
T extends
|
||||
| CollectionIncludingMembersAndLinkCount
|
||||
| LinkIncludingShortenedCollectionAndTags,
|
||||
>({ sortBy, data, setData }: Props<T>) {
|
||||
useEffect(() => {
|
||||
const dataArray = [...data];
|
||||
|
||||
if (sortBy === Sort.NameAZ)
|
||||
setData(dataArray.sort((a, b) => a.name.localeCompare(b.name)));
|
||||
else if (sortBy === Sort.DescriptionAZ)
|
||||
setData(
|
||||
dataArray.sort((a, b) => a.description.localeCompare(b.description))
|
||||
);
|
||||
else if (sortBy === Sort.NameZA)
|
||||
setData(dataArray.sort((a, b) => b.name.localeCompare(a.name)));
|
||||
else if (sortBy === Sort.DescriptionZA)
|
||||
setData(
|
||||
dataArray.sort((a, b) => b.description.localeCompare(a.description))
|
||||
);
|
||||
else if (sortBy === Sort.DateNewestFirst)
|
||||
setData(
|
||||
dataArray.sort(
|
||||
(a, b) =>
|
||||
new Date(b.createdAt as string).getTime() -
|
||||
new Date(a.createdAt as string).getTime()
|
||||
)
|
||||
);
|
||||
else if (sortBy === Sort.DateOldestFirst)
|
||||
setData(
|
||||
dataArray.sort(
|
||||
(a, b) =>
|
||||
new Date(a.createdAt as string).getTime() -
|
||||
new Date(b.createdAt as string).getTime()
|
||||
)
|
||||
);
|
||||
}, [sortBy, data]);
|
||||
}
|
25
Securite/Linkwarden/hooks/useWindowDimensions.tsx
Normal file
@ -0,0 +1,25 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
|
||||
export default function useWindowDimensions() {
|
||||
const [dimensions, setDimensions] = useState({
|
||||
height: window.innerHeight,
|
||||
width: window.innerWidth,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
function handleResize() {
|
||||
setDimensions({
|
||||
height: window.innerHeight,
|
||||
width: window.innerWidth,
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener("resize", handleResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", handleResize);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return dimensions;
|
||||
}
|
BIN
Securite/Linkwarden/img/banniere-Linkwarden.png
Normal file
After Width: | Height: | Size: 13 KiB |
84
Securite/Linkwarden/layouts/AuthRedirect.tsx
Normal file
@ -0,0 +1,84 @@
|
||||
import { ReactNode } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import Loader from "../components/Loader";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useState } from "react";
|
||||
import useInitialData from "@/hooks/useInitialData";
|
||||
import useAccountStore from "@/store/account";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function AuthRedirect({ children }: Props) {
|
||||
const router = useRouter();
|
||||
const { status, data } = useSession();
|
||||
const [redirect, setRedirect] = useState(true);
|
||||
const { account } = useAccountStore();
|
||||
|
||||
const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true";
|
||||
const stripeEnabled = process.env.NEXT_PUBLIC_STRIPE === "true";
|
||||
|
||||
useInitialData();
|
||||
|
||||
useEffect(() => {
|
||||
if (!router.pathname.startsWith("/public")) {
|
||||
if (
|
||||
status === "authenticated" &&
|
||||
account.id &&
|
||||
!account.subscription?.active &&
|
||||
stripeEnabled
|
||||
) {
|
||||
router.push("/subscribe").then(() => {
|
||||
setRedirect(false);
|
||||
});
|
||||
}
|
||||
// Redirect to "/choose-username" if user is authenticated and is either a subscriber OR subscription is undefiend, and doesn't have a username
|
||||
else if (
|
||||
emailEnabled &&
|
||||
status === "authenticated" &&
|
||||
account.subscription?.active &&
|
||||
stripeEnabled &&
|
||||
account.id &&
|
||||
!account.username
|
||||
) {
|
||||
router.push("/choose-username").then(() => {
|
||||
setRedirect(false);
|
||||
});
|
||||
} else if (
|
||||
status === "authenticated" &&
|
||||
account.id &&
|
||||
(router.pathname === "/login" ||
|
||||
router.pathname === "/register" ||
|
||||
router.pathname === "/confirmation" ||
|
||||
router.pathname === "/subscribe" ||
|
||||
router.pathname === "/choose-username" ||
|
||||
router.pathname === "/forgot" ||
|
||||
router.pathname === "/")
|
||||
) {
|
||||
router.push("/dashboard").then(() => {
|
||||
setRedirect(false);
|
||||
});
|
||||
} else if (
|
||||
status === "unauthenticated" &&
|
||||
!(
|
||||
router.pathname === "/login" ||
|
||||
router.pathname === "/register" ||
|
||||
router.pathname === "/confirmation" ||
|
||||
router.pathname === "/forgot"
|
||||
)
|
||||
) {
|
||||
router.push("/login").then(() => {
|
||||
setRedirect(false);
|
||||
});
|
||||
} else if (status === "loading") setRedirect(true);
|
||||
else setRedirect(false);
|
||||
} else {
|
||||
setRedirect(false);
|
||||
}
|
||||
}, [status, account, router.pathname]);
|
||||
|
||||
if (status !== "loading" && !redirect) return <>{children}</>;
|
||||
else return <></>;
|
||||
// return <>{children}</>;
|
||||
}
|
44
Securite/Linkwarden/layouts/CenteredForm.tsx
Normal file
@ -0,0 +1,44 @@
|
||||
import useLocalSettingsStore from "@/store/localSettings";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import React, { ReactNode, useEffect } from "react";
|
||||
|
||||
interface Props {
|
||||
text?: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function CenteredForm({ text, children }: Props) {
|
||||
const { settings } = useLocalSettingsStore();
|
||||
|
||||
return (
|
||||
<div className="absolute top-0 bottom-0 left-0 right-0 flex justify-center items-center p-5">
|
||||
<div className="m-auto flex flex-col gap-2 w-full">
|
||||
{settings.theme ? (
|
||||
<Image
|
||||
src={`/linkwarden_${
|
||||
settings.theme === "dark" ? "dark" : "light"
|
||||
}.png`}
|
||||
width={640}
|
||||
height={136}
|
||||
alt="Linkwarden"
|
||||
className="h-12 w-fit mx-auto"
|
||||
/>
|
||||
) : undefined}
|
||||
{text ? (
|
||||
<p className="text-lg max-w-[30rem] min-w-80 w-full mx-auto font-semibold px-2 text-center">
|
||||
{text}
|
||||
</p>
|
||||
) : undefined}
|
||||
{children}
|
||||
<p className="text-center text-xs text-neutral mb-5">
|
||||
© {new Date().getFullYear()}{" "}
|
||||
<Link href="https://linkwarden.app" className="font-semibold">
|
||||
Linkwarden
|
||||
</Link>
|
||||
. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
59
Securite/Linkwarden/layouts/MainLayout.tsx
Normal file
@ -0,0 +1,59 @@
|
||||
import Navbar from "@/components/Navbar";
|
||||
import AnnouncementBar from "@/components/AnnouncementBar";
|
||||
import Sidebar from "@/components/Sidebar";
|
||||
import { ReactNode, useEffect, useState } from "react";
|
||||
import getLatestVersion from "@/lib/client/getLatestVersion";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function MainLayout({ children }: Props) {
|
||||
const showAnnouncementBar = localStorage.getItem("showAnnouncementBar");
|
||||
const [showAnnouncement, setShowAnnouncement] = useState(
|
||||
showAnnouncementBar ? showAnnouncementBar === "true" : true
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
getLatestVersion(setShowAnnouncement);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (showAnnouncement) {
|
||||
localStorage.setItem("showAnnouncementBar", "true");
|
||||
setShowAnnouncement(true);
|
||||
} else if (!showAnnouncement) {
|
||||
localStorage.setItem("showAnnouncementBar", "false");
|
||||
setShowAnnouncement(false);
|
||||
}
|
||||
}, [showAnnouncement]);
|
||||
|
||||
const toggleAnnouncementBar = () => {
|
||||
setShowAnnouncement(!showAnnouncement);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{showAnnouncement ? (
|
||||
<AnnouncementBar toggleAnnouncementBar={toggleAnnouncementBar} />
|
||||
) : undefined}
|
||||
|
||||
<div className="flex">
|
||||
<div className="hidden lg:block">
|
||||
<Sidebar
|
||||
className={`fixed ${showAnnouncement ? "top-10" : "top-0"}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`w-full sm:pb-0 pb-20 flex flex-col min-h-${
|
||||
showAnnouncement ? "full" : "screen"
|
||||
} lg:ml-80 ${showAnnouncement ? "mt-10" : ""}`}
|
||||
>
|
||||
<Navbar />
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
73
Securite/Linkwarden/layouts/SettingsLayout.tsx
Normal file
@ -0,0 +1,73 @@
|
||||
import SettingsSidebar from "@/components/SettingsSidebar";
|
||||
import React, { ReactNode, useEffect, useState } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
import ClickAwayHandler from "@/components/ClickAwayHandler";
|
||||
import Link from "next/link";
|
||||
import useWindowDimensions from "@/hooks/useWindowDimensions";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function SettingsLayout({ children }: Props) {
|
||||
const router = useRouter();
|
||||
|
||||
const [sidebar, setSidebar] = useState(false);
|
||||
|
||||
const { width } = useWindowDimensions();
|
||||
|
||||
useEffect(() => {
|
||||
setSidebar(false);
|
||||
}, [width]);
|
||||
|
||||
useEffect(() => {
|
||||
setSidebar(false);
|
||||
}, [router]);
|
||||
|
||||
const toggleSidebar = () => {
|
||||
setSidebar(!sidebar);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex max-w-screen-md mx-auto">
|
||||
<div className="hidden lg:block fixed h-screen">
|
||||
<SettingsSidebar />
|
||||
</div>
|
||||
|
||||
<div className="w-full min-h-screen p-5 lg:ml-64">
|
||||
<div className="gap-2 inline-flex mr-3">
|
||||
<div
|
||||
onClick={toggleSidebar}
|
||||
className="text-neutral btn btn-square btn-sm btn-ghost lg:hidden"
|
||||
>
|
||||
<i className="bi-list text-2xl leading-none"></i>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="/dashboard"
|
||||
className="text-neutral btn btn-square btn-sm btn-ghost"
|
||||
>
|
||||
<i className="bi-chevron-left text-xl"></i>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{children}
|
||||
|
||||
{sidebar ? (
|
||||
<div className="fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-30">
|
||||
<ClickAwayHandler
|
||||
className="h-full"
|
||||
onClickOutside={toggleSidebar}
|
||||
>
|
||||
<div className="slide-right h-full shadow-lg">
|
||||
<SettingsSidebar />
|
||||
</div>
|
||||
</ClickAwayHandler>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
411
Securite/Linkwarden/lib/api/archiveHandler.ts
Normal file
@ -0,0 +1,411 @@
|
||||
import { LaunchOptions, chromium, devices } from "playwright";
|
||||
import { prisma } from "./db";
|
||||
import createFile from "./storage/createFile";
|
||||
import sendToWayback from "./sendToWayback";
|
||||
import { Readability } from "@mozilla/readability";
|
||||
import { JSDOM } from "jsdom";
|
||||
import DOMPurify from "dompurify";
|
||||
import { Collection, Link, User } from "@prisma/client";
|
||||
import validateUrlSize from "./validateUrlSize";
|
||||
import removeFile from "./storage/removeFile";
|
||||
import Jimp from "jimp";
|
||||
import createFolder from "./storage/createFolder";
|
||||
|
||||
type LinksAndCollectionAndOwner = Link & {
|
||||
collection: Collection & {
|
||||
owner: User;
|
||||
};
|
||||
};
|
||||
|
||||
const BROWSER_TIMEOUT = Number(process.env.BROWSER_TIMEOUT) || 5;
|
||||
|
||||
export default async function archiveHandler(link: LinksAndCollectionAndOwner) {
|
||||
// allow user to configure a proxy
|
||||
let browserOptions: LaunchOptions = {};
|
||||
if (process.env.PROXY) {
|
||||
browserOptions.proxy = {
|
||||
server: process.env.PROXY,
|
||||
bypass: process.env.PROXY_BYPASS,
|
||||
username: process.env.PROXY_USERNAME,
|
||||
password: process.env.PROXY_PASSWORD,
|
||||
};
|
||||
}
|
||||
|
||||
const browser = await chromium.launch(browserOptions);
|
||||
const context = await browser.newContext({
|
||||
...devices["Desktop Chrome"],
|
||||
ignoreHTTPSErrors: process.env.IGNORE_HTTPS_ERRORS === "true",
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
|
||||
const timeoutPromise = new Promise((_, reject) => {
|
||||
setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new Error(
|
||||
`Browser has been open for more than ${BROWSER_TIMEOUT} minutes.`
|
||||
)
|
||||
),
|
||||
BROWSER_TIMEOUT * 60000
|
||||
);
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
(async () => {
|
||||
const validatedUrl = link.url
|
||||
? await validateUrlSize(link.url)
|
||||
: undefined;
|
||||
|
||||
if (validatedUrl === null)
|
||||
throw "Something went wrong while retrieving the file size.";
|
||||
|
||||
const contentType = validatedUrl?.get("content-type");
|
||||
let linkType = "url";
|
||||
let imageExtension = "png";
|
||||
|
||||
if (!link.url) linkType = link.type;
|
||||
else if (contentType?.includes("application/pdf")) linkType = "pdf";
|
||||
else if (contentType?.startsWith("image")) {
|
||||
linkType = "image";
|
||||
if (contentType.includes("image/jpeg")) imageExtension = "jpeg";
|
||||
else if (contentType.includes("image/png")) imageExtension = "png";
|
||||
}
|
||||
|
||||
const user = link.collection?.owner;
|
||||
|
||||
// send to archive.org
|
||||
if (user.archiveAsWaybackMachine && link.url) sendToWayback(link.url);
|
||||
|
||||
const targetLink = await prisma.link.update({
|
||||
where: { id: link.id },
|
||||
data: {
|
||||
type: linkType,
|
||||
image:
|
||||
user.archiveAsScreenshot && !link.image?.startsWith("archive")
|
||||
? "pending"
|
||||
: "unavailable",
|
||||
pdf:
|
||||
user.archiveAsPDF && !link.pdf?.startsWith("archive")
|
||||
? "pending"
|
||||
: "unavailable",
|
||||
readable: !link.readable?.startsWith("archive")
|
||||
? "pending"
|
||||
: undefined,
|
||||
preview: !link.readable?.startsWith("archive")
|
||||
? "pending"
|
||||
: undefined,
|
||||
lastPreserved: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
|
||||
if (linkType === "image" && !link.image?.startsWith("archive")) {
|
||||
await imageHandler(link, imageExtension); // archive image (jpeg/png)
|
||||
return;
|
||||
} else if (linkType === "pdf" && !link.pdf?.startsWith("archive")) {
|
||||
await pdfHandler(link); // archive pdf
|
||||
return;
|
||||
} else if (link.url) {
|
||||
// archive url
|
||||
|
||||
await page.goto(link.url, { waitUntil: "domcontentloaded" });
|
||||
|
||||
const content = await page.content();
|
||||
|
||||
// TODO single file
|
||||
// const session = await page.context().newCDPSession(page);
|
||||
// const doc = await session.send("Page.captureSnapshot", {
|
||||
// format: "mhtml",
|
||||
// });
|
||||
// const saveDocLocally = (doc: any) => {
|
||||
// console.log(doc);
|
||||
// return createFile({
|
||||
// data: doc,
|
||||
// filePath: `archives/${targetLink.collectionId}/${link.id}.mhtml`,
|
||||
// });
|
||||
// };
|
||||
// saveDocLocally(doc.data);
|
||||
|
||||
// Readability
|
||||
const window = new JSDOM("").window;
|
||||
const purify = DOMPurify(window);
|
||||
const cleanedUpContent = purify.sanitize(content);
|
||||
const dom = new JSDOM(cleanedUpContent, { url: link.url || "" });
|
||||
const article = new Readability(dom.window.document).parse();
|
||||
const articleText = article?.textContent
|
||||
.replace(/ +(?= )/g, "") // strip out multiple spaces
|
||||
.replace(/(\r\n|\n|\r)/gm, " "); // strip out line breaks
|
||||
if (
|
||||
articleText &&
|
||||
articleText !== "" &&
|
||||
!link.readable?.startsWith("archive")
|
||||
) {
|
||||
await createFile({
|
||||
data: JSON.stringify(article),
|
||||
filePath: `archives/${targetLink.collectionId}/${link.id}_readability.json`,
|
||||
});
|
||||
|
||||
await prisma.link.update({
|
||||
where: { id: link.id },
|
||||
data: {
|
||||
readable: `archives/${targetLink.collectionId}/${link.id}_readability.json`,
|
||||
textContent: articleText,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Preview
|
||||
|
||||
const ogImageUrl = await page.evaluate(() => {
|
||||
const metaTag = document.querySelector('meta[property="og:image"]');
|
||||
return metaTag ? (metaTag as any).content : null;
|
||||
});
|
||||
|
||||
createFolder({
|
||||
filePath: `archives/preview/${link.collectionId}`,
|
||||
});
|
||||
|
||||
if (ogImageUrl) {
|
||||
console.log("Found og:image URL:", ogImageUrl);
|
||||
|
||||
// Download the image
|
||||
const imageResponse = await page.goto(ogImageUrl);
|
||||
|
||||
// Check if imageResponse is not null
|
||||
if (imageResponse && !link.preview?.startsWith("archive")) {
|
||||
const buffer = await imageResponse.body();
|
||||
|
||||
// Check if buffer is not null
|
||||
if (buffer) {
|
||||
// Load the image using Jimp
|
||||
Jimp.read(buffer, async (err, image) => {
|
||||
if (image && !err) {
|
||||
image?.resize(1280, Jimp.AUTO).quality(20);
|
||||
const processedBuffer = await image?.getBufferAsync(
|
||||
Jimp.MIME_JPEG
|
||||
);
|
||||
|
||||
createFile({
|
||||
data: processedBuffer,
|
||||
filePath: `archives/preview/${link.collectionId}/${link.id}.jpeg`,
|
||||
}).then(() => {
|
||||
return prisma.link.update({
|
||||
where: { id: link.id },
|
||||
data: {
|
||||
preview: `archives/preview/${link.collectionId}/${link.id}.jpeg`,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}).catch((err) => {
|
||||
console.error("Error processing the image:", err);
|
||||
});
|
||||
} else {
|
||||
console.log("No image data found.");
|
||||
}
|
||||
}
|
||||
|
||||
await page.goBack();
|
||||
} else if (!link.preview?.startsWith("archive")) {
|
||||
console.log("No og:image found");
|
||||
await page
|
||||
.screenshot({ type: "jpeg", quality: 20 })
|
||||
.then((screenshot) => {
|
||||
return createFile({
|
||||
data: screenshot,
|
||||
filePath: `archives/preview/${link.collectionId}/${link.id}.jpeg`,
|
||||
});
|
||||
})
|
||||
.then(() => {
|
||||
return prisma.link.update({
|
||||
where: { id: link.id },
|
||||
data: {
|
||||
preview: `archives/preview/${link.collectionId}/${link.id}.jpeg`,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Screenshot/PDF
|
||||
await page.evaluate(
|
||||
autoScroll,
|
||||
Number(process.env.AUTOSCROLL_TIMEOUT) || 30
|
||||
);
|
||||
|
||||
// Check if the user hasn't deleted the link by the time we're done scrolling
|
||||
const linkExists = await prisma.link.findUnique({
|
||||
where: { id: link.id },
|
||||
});
|
||||
if (linkExists) {
|
||||
const processingPromises = [];
|
||||
|
||||
if (
|
||||
user.archiveAsScreenshot &&
|
||||
!link.image?.startsWith("archive")
|
||||
) {
|
||||
processingPromises.push(
|
||||
page.screenshot({ fullPage: true }).then((screenshot) => {
|
||||
return createFile({
|
||||
data: screenshot,
|
||||
filePath: `archives/${linkExists.collectionId}/${link.id}.png`,
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// apply administrator's defined pdf margins or default to 15px
|
||||
const margins = {
|
||||
top: process.env.PDF_MARGIN_TOP || "15px",
|
||||
bottom: process.env.PDF_MARGIN_BOTTOM || "15px",
|
||||
};
|
||||
|
||||
if (user.archiveAsPDF && !link.pdf?.startsWith("archive")) {
|
||||
processingPromises.push(
|
||||
page
|
||||
.pdf({
|
||||
width: "1366px",
|
||||
height: "1931px",
|
||||
printBackground: true,
|
||||
margin: margins,
|
||||
})
|
||||
.then((pdf) => {
|
||||
return createFile({
|
||||
data: pdf,
|
||||
filePath: `archives/${linkExists.collectionId}/${link.id}.pdf`,
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
await Promise.allSettled(processingPromises);
|
||||
await prisma.link.update({
|
||||
where: { id: link.id },
|
||||
data: {
|
||||
image: user.archiveAsScreenshot
|
||||
? `archives/${linkExists.collectionId}/${link.id}.png`
|
||||
: undefined,
|
||||
pdf: user.archiveAsPDF
|
||||
? `archives/${linkExists.collectionId}/${link.id}.pdf`
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
})(),
|
||||
timeoutPromise,
|
||||
]);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
console.log("Failed Link details:", link);
|
||||
throw err;
|
||||
} finally {
|
||||
const finalLink = await prisma.link.findUnique({
|
||||
where: { id: link.id },
|
||||
});
|
||||
|
||||
if (finalLink)
|
||||
await prisma.link.update({
|
||||
where: { id: link.id },
|
||||
data: {
|
||||
lastPreserved: new Date().toISOString(),
|
||||
readable: !finalLink.readable?.startsWith("archives")
|
||||
? "unavailable"
|
||||
: undefined,
|
||||
image: !finalLink.image?.startsWith("archives")
|
||||
? "unavailable"
|
||||
: undefined,
|
||||
pdf: !finalLink.pdf?.startsWith("archives")
|
||||
? "unavailable"
|
||||
: undefined,
|
||||
preview: !finalLink.preview?.startsWith("archives")
|
||||
? "unavailable"
|
||||
: undefined,
|
||||
},
|
||||
});
|
||||
else {
|
||||
removeFile({ filePath: `archives/${link.collectionId}/${link.id}.png` });
|
||||
removeFile({ filePath: `archives/${link.collectionId}/${link.id}.pdf` });
|
||||
removeFile({
|
||||
filePath: `archives/${link.collectionId}/${link.id}_readability.json`,
|
||||
});
|
||||
removeFile({
|
||||
filePath: `archives/preview/${link.collectionId}/${link.id}.jpeg`,
|
||||
});
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
const autoScroll = async (AUTOSCROLL_TIMEOUT: number) => {
|
||||
const timeoutPromise = new Promise<void>((_, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new Error(`Webpage was too long to be archived.`));
|
||||
}, AUTOSCROLL_TIMEOUT * 1000);
|
||||
});
|
||||
|
||||
const scrollingPromise = new Promise<void>((resolve) => {
|
||||
let totalHeight = 0;
|
||||
let distance = 100;
|
||||
let scrollDown = setInterval(() => {
|
||||
let scrollHeight = document.body.scrollHeight;
|
||||
window.scrollBy(0, distance);
|
||||
totalHeight += distance;
|
||||
if (totalHeight >= scrollHeight) {
|
||||
clearInterval(scrollDown);
|
||||
window.scroll(0, 0);
|
||||
resolve();
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
await Promise.race([scrollingPromise, timeoutPromise]);
|
||||
};
|
||||
|
||||
const imageHandler = async ({ url, id }: Link, extension: string) => {
|
||||
const image = await fetch(url as string).then((res) => res.blob());
|
||||
|
||||
const buffer = Buffer.from(await image.arrayBuffer());
|
||||
|
||||
const linkExists = await prisma.link.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (linkExists) {
|
||||
await createFile({
|
||||
data: buffer,
|
||||
filePath: `archives/${linkExists.collectionId}/${id}.${extension}`,
|
||||
});
|
||||
|
||||
await prisma.link.update({
|
||||
where: { id },
|
||||
data: {
|
||||
image: `archives/${linkExists.collectionId}/${id}.${extension}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const pdfHandler = async ({ url, id }: Link) => {
|
||||
const pdf = await fetch(url as string).then((res) => res.blob());
|
||||
|
||||
const buffer = Buffer.from(await pdf.arrayBuffer());
|
||||
|
||||
const linkExists = await prisma.link.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (linkExists) {
|
||||
await createFile({
|
||||
data: buffer,
|
||||
filePath: `archives/${linkExists.collectionId}/${id}.pdf`,
|
||||
});
|
||||
|
||||
await prisma.link.update({
|
||||
where: { id },
|
||||
data: {
|
||||
pdf: `archives/${linkExists.collectionId}/${id}.pdf`,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
53
Securite/Linkwarden/lib/api/checkSubscriptionByEmail.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import Stripe from "stripe";
|
||||
|
||||
const MONTHLY_PRICE_ID = process.env.MONTHLY_PRICE_ID;
|
||||
const YEARLY_PRICE_ID = process.env.YEARLY_PRICE_ID;
|
||||
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
|
||||
|
||||
export default async function checkSubscriptionByEmail(email: string) {
|
||||
let active: boolean | undefined,
|
||||
stripeSubscriptionId: string | undefined,
|
||||
currentPeriodStart: number | undefined,
|
||||
currentPeriodEnd: number | undefined;
|
||||
|
||||
if (!STRIPE_SECRET_KEY)
|
||||
return {
|
||||
active,
|
||||
stripeSubscriptionId,
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
};
|
||||
|
||||
const stripe = new Stripe(STRIPE_SECRET_KEY, {
|
||||
apiVersion: "2022-11-15",
|
||||
});
|
||||
|
||||
console.log("Request made to Stripe by:", email);
|
||||
const listByEmail = await stripe.customers.list({
|
||||
email: email.toLowerCase(),
|
||||
expand: ["data.subscriptions"],
|
||||
});
|
||||
|
||||
listByEmail.data.some((customer) => {
|
||||
customer.subscriptions?.data.some((subscription) => {
|
||||
subscription.current_period_end;
|
||||
|
||||
active =
|
||||
subscription.items.data.some(
|
||||
(e) =>
|
||||
(e.price.id === MONTHLY_PRICE_ID && e.price.active === true) ||
|
||||
(e.price.id === YEARLY_PRICE_ID && e.price.active === true)
|
||||
) || false;
|
||||
stripeSubscriptionId = subscription.id;
|
||||
currentPeriodStart = subscription.current_period_start * 1000;
|
||||
currentPeriodEnd = subscription.current_period_end * 1000;
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
active: active || false,
|
||||
stripeSubscriptionId,
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
};
|
||||
}
|
@ -0,0 +1,129 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
import getPermission from "@/lib/api/getPermission";
|
||||
import { Collection, UsersAndCollections } from "@prisma/client";
|
||||
import removeFolder from "@/lib/api/storage/removeFolder";
|
||||
|
||||
export default async function deleteCollection(
|
||||
userId: number,
|
||||
collectionId: number
|
||||
) {
|
||||
if (!collectionId)
|
||||
return { response: "Please choose a valid collection.", status: 401 };
|
||||
|
||||
const collectionIsAccessible = await getPermission({
|
||||
userId,
|
||||
collectionId,
|
||||
});
|
||||
|
||||
const memberHasAccess = collectionIsAccessible?.members.some(
|
||||
(e: UsersAndCollections) => e.userId === userId
|
||||
);
|
||||
|
||||
if (collectionIsAccessible?.ownerId !== userId && memberHasAccess) {
|
||||
// Remove relation/Leave collection
|
||||
const deletedUsersAndCollectionsRelation =
|
||||
await prisma.usersAndCollections.delete({
|
||||
where: {
|
||||
userId_collectionId: {
|
||||
userId: userId,
|
||||
collectionId: collectionId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await removeFromOrders(userId, collectionId);
|
||||
|
||||
return { response: deletedUsersAndCollectionsRelation, status: 200 };
|
||||
} else if (collectionIsAccessible?.ownerId !== userId) {
|
||||
return { response: "Collection is not accessible.", status: 401 };
|
||||
}
|
||||
|
||||
const deletedCollection = await prisma.$transaction(async () => {
|
||||
await deleteSubCollections(collectionId);
|
||||
|
||||
await prisma.usersAndCollections.deleteMany({
|
||||
where: {
|
||||
collection: {
|
||||
id: collectionId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.link.deleteMany({
|
||||
where: {
|
||||
collection: {
|
||||
id: collectionId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await removeFolder({ filePath: `archives/${collectionId}` });
|
||||
|
||||
await removeFromOrders(userId, collectionId);
|
||||
|
||||
return await prisma.collection.delete({
|
||||
where: {
|
||||
id: collectionId,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return { response: deletedCollection, status: 200 };
|
||||
}
|
||||
|
||||
async function deleteSubCollections(collectionId: number) {
|
||||
const subCollections = await prisma.collection.findMany({
|
||||
where: { parentId: collectionId },
|
||||
});
|
||||
|
||||
for (const subCollection of subCollections) {
|
||||
await deleteSubCollections(subCollection.id);
|
||||
|
||||
await prisma.usersAndCollections.deleteMany({
|
||||
where: {
|
||||
collection: {
|
||||
id: subCollection.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.link.deleteMany({
|
||||
where: {
|
||||
collection: {
|
||||
id: subCollection.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.collection.delete({
|
||||
where: { id: subCollection.id },
|
||||
});
|
||||
|
||||
await removeFolder({ filePath: `archives/${subCollection.id}` });
|
||||
}
|
||||
}
|
||||
|
||||
async function removeFromOrders(userId: number, collectionId: number) {
|
||||
const userCollectionOrder = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
select: {
|
||||
collectionOrder: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (userCollectionOrder)
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
collectionOrder: {
|
||||
set: userCollectionOrder.collectionOrder.filter(
|
||||
(e: number) => e !== collectionId
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
|
||||
export default async function getCollectionById(
|
||||
userId: number,
|
||||
collectionId: number
|
||||
) {
|
||||
const collections = await prisma.collection.findFirst({
|
||||
where: {
|
||||
id: collectionId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{ members: { some: { user: { id: userId } } } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: { links: true },
|
||||
},
|
||||
members: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
username: true,
|
||||
name: true,
|
||||
image: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { response: collections, status: 200 };
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
|
||||
import getPermission from "@/lib/api/getPermission";
|
||||
|
||||
export default async function updateCollection(
|
||||
userId: number,
|
||||
collectionId: number,
|
||||
data: CollectionIncludingMembersAndLinkCount
|
||||
) {
|
||||
if (!collectionId)
|
||||
return { response: "Please choose a valid collection.", status: 401 };
|
||||
|
||||
const collectionIsAccessible = await getPermission({
|
||||
userId,
|
||||
collectionId,
|
||||
});
|
||||
|
||||
if (!(collectionIsAccessible?.ownerId === userId))
|
||||
return { response: "Collection is not accessible.", status: 401 };
|
||||
|
||||
console.log(data);
|
||||
|
||||
if (data.parentId) {
|
||||
if (data.parentId !== ("root" as any)) {
|
||||
const findParentCollection = await prisma.collection.findUnique({
|
||||
where: {
|
||||
id: data.parentId,
|
||||
},
|
||||
select: {
|
||||
ownerId: true,
|
||||
parentId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
findParentCollection?.ownerId !== userId ||
|
||||
typeof data.parentId !== "number" ||
|
||||
findParentCollection?.parentId === data.parentId
|
||||
)
|
||||
return {
|
||||
response: "You are not authorized to create a sub-collection here.",
|
||||
status: 403,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const updatedCollection = await prisma.$transaction(async () => {
|
||||
await prisma.usersAndCollections.deleteMany({
|
||||
where: {
|
||||
collection: {
|
||||
id: collectionId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return await prisma.collection.update({
|
||||
where: {
|
||||
id: collectionId,
|
||||
},
|
||||
data: {
|
||||
name: data.name.trim(),
|
||||
description: data.description,
|
||||
color: data.color,
|
||||
isPublic: data.isPublic,
|
||||
parent:
|
||||
data.parentId && data.parentId !== ("root" as any)
|
||||
? {
|
||||
connect: {
|
||||
id: data.parentId,
|
||||
},
|
||||
}
|
||||
: data.parentId === ("root" as any)
|
||||
? {
|
||||
disconnect: true,
|
||||
}
|
||||
: undefined,
|
||||
members: {
|
||||
create: data.members.map((e) => ({
|
||||
user: { connect: { id: e.user.id || e.userId } },
|
||||
canCreate: e.canCreate,
|
||||
canUpdate: e.canUpdate,
|
||||
canDelete: e.canDelete,
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: { links: true },
|
||||
},
|
||||
members: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
image: true,
|
||||
username: true,
|
||||
name: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return { response: updatedCollection, status: 200 };
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
|
||||
export default async function getCollection(userId: number) {
|
||||
const collections = await prisma.collection.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{ members: { some: { user: { id: userId } } } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: { links: true },
|
||||
},
|
||||
parent: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
members: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
username: true,
|
||||
name: true,
|
||||
image: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { response: collections, status: 200 };
|
||||
}
|