Compare commits
No commits in common. "main" and "v1.3.0" have entirely different histories.
991 changed files with 78263 additions and 160428 deletions
177
.coderabbit.yaml
177
.coderabbit.yaml
|
|
@ -1,177 +0,0 @@
|
|||
language: en-US
|
||||
tone_instructions: ''
|
||||
early_access: false
|
||||
enable_free_tier: true
|
||||
reviews:
|
||||
profile: chill
|
||||
request_changes_workflow: false
|
||||
high_level_summary: true
|
||||
high_level_summary_placeholder: '@coderabbitai summary'
|
||||
high_level_summary_in_walkthrough: false
|
||||
auto_title_placeholder: '@coderabbitai'
|
||||
auto_title_instructions: ''
|
||||
review_status: false
|
||||
commit_status: true
|
||||
fail_commit_status: false
|
||||
collapse_walkthrough: false
|
||||
changed_files_summary: true
|
||||
sequence_diagrams: true
|
||||
estimate_code_review_effort: true
|
||||
assess_linked_issues: true
|
||||
related_issues: true
|
||||
related_prs: true
|
||||
suggested_labels: true
|
||||
auto_apply_labels: false
|
||||
suggested_reviewers: true
|
||||
auto_assign_reviewers: false
|
||||
poem: true
|
||||
labeling_instructions: []
|
||||
path_filters: []
|
||||
path_instructions: []
|
||||
abort_on_close: true
|
||||
disable_cache: false
|
||||
auto_review:
|
||||
enabled: false
|
||||
auto_incremental_review: true
|
||||
ignore_title_keywords: []
|
||||
labels: []
|
||||
drafts: false
|
||||
base_branches: []
|
||||
finishing_touches:
|
||||
docstrings:
|
||||
enabled: true
|
||||
unit_tests:
|
||||
enabled: true
|
||||
pre_merge_checks:
|
||||
docstrings:
|
||||
mode: warning
|
||||
threshold: 80
|
||||
title:
|
||||
mode: warning
|
||||
requirements: ''
|
||||
description:
|
||||
mode: warning
|
||||
issue_assessment:
|
||||
mode: warning
|
||||
tools:
|
||||
ast-grep:
|
||||
rule_dirs: []
|
||||
util_dirs: []
|
||||
essential_rules: true
|
||||
packages: []
|
||||
shellcheck:
|
||||
enabled: true
|
||||
ruff:
|
||||
enabled: true
|
||||
markdownlint:
|
||||
enabled: true
|
||||
github-checks:
|
||||
enabled: true
|
||||
timeout_ms: 90000
|
||||
languagetool:
|
||||
enabled: true
|
||||
enabled_rules: []
|
||||
disabled_rules: []
|
||||
enabled_categories: []
|
||||
disabled_categories: []
|
||||
enabled_only: false
|
||||
level: default
|
||||
biome:
|
||||
enabled: true
|
||||
hadolint:
|
||||
enabled: true
|
||||
swiftlint:
|
||||
enabled: true
|
||||
phpstan:
|
||||
enabled: true
|
||||
level: default
|
||||
phpmd:
|
||||
enabled: true
|
||||
phpcs:
|
||||
enabled: true
|
||||
golangci-lint:
|
||||
enabled: true
|
||||
yamllint:
|
||||
enabled: true
|
||||
gitleaks:
|
||||
enabled: true
|
||||
checkov:
|
||||
enabled: true
|
||||
detekt:
|
||||
enabled: true
|
||||
eslint:
|
||||
enabled: true
|
||||
flake8:
|
||||
enabled: true
|
||||
rubocop:
|
||||
enabled: true
|
||||
buf:
|
||||
enabled: true
|
||||
regal:
|
||||
enabled: true
|
||||
actionlint:
|
||||
enabled: true
|
||||
pmd:
|
||||
enabled: true
|
||||
cppcheck:
|
||||
enabled: true
|
||||
semgrep:
|
||||
enabled: true
|
||||
circleci:
|
||||
enabled: true
|
||||
clippy:
|
||||
enabled: true
|
||||
sqlfluff:
|
||||
enabled: true
|
||||
prismaLint:
|
||||
enabled: true
|
||||
pylint:
|
||||
enabled: true
|
||||
oxc:
|
||||
enabled: true
|
||||
shopifyThemeCheck:
|
||||
enabled: true
|
||||
luacheck:
|
||||
enabled: true
|
||||
brakeman:
|
||||
enabled: true
|
||||
dotenvLint:
|
||||
enabled: true
|
||||
htmlhint:
|
||||
enabled: true
|
||||
checkmake:
|
||||
enabled: true
|
||||
chat:
|
||||
auto_reply: true
|
||||
integrations:
|
||||
jira:
|
||||
usage: auto
|
||||
linear:
|
||||
usage: auto
|
||||
knowledge_base:
|
||||
opt_out: false
|
||||
web_search:
|
||||
enabled: true
|
||||
code_guidelines:
|
||||
enabled: true
|
||||
filePatterns: []
|
||||
learnings:
|
||||
scope: auto
|
||||
issues:
|
||||
scope: auto
|
||||
jira:
|
||||
usage: auto
|
||||
project_keys: []
|
||||
linear:
|
||||
usage: auto
|
||||
team_keys: []
|
||||
pull_requests:
|
||||
scope: auto
|
||||
code_generation:
|
||||
docstrings:
|
||||
language: en-US
|
||||
path_instructions: []
|
||||
unit_tests:
|
||||
path_instructions: []
|
||||
autopilot:
|
||||
enabled: false
|
||||
|
|
@ -2,22 +2,12 @@
|
|||
# any half-built stuff in the build context as a pre-caution (also saves copying
|
||||
# 180k files in node_modules that isn't used!).
|
||||
**/node_modules
|
||||
node_modules/*
|
||||
node_modules
|
||||
docker-data/*
|
||||
dist
|
||||
.nx
|
||||
/apps/frontend/.next
|
||||
/apps/backend/dist
|
||||
/apps/workers/dist
|
||||
/apps/cron/dist
|
||||
/apps/commands/dist
|
||||
.devcontainer
|
||||
**/.git
|
||||
**/dist
|
||||
**/*.md
|
||||
**/LICENSE
|
||||
**/npm-debug.log
|
||||
**/*.vscode
|
||||
.git
|
||||
.github
|
||||
reports
|
||||
69
.env.example
69
.env.example
|
|
@ -4,22 +4,22 @@
|
|||
DATABASE_URL="postgresql://postiz-user:postiz-password@localhost:5432/postiz-db-local"
|
||||
REDIS_URL="redis://localhost:6379"
|
||||
JWT_SECRET="random string for your JWT secret, make it long"
|
||||
|
||||
# === This needs to be exactly the URL you're accessing Postiz on
|
||||
FRONTEND_URL="http://localhost:4200"
|
||||
NEXT_PUBLIC_BACKEND_URL="http://localhost:3000"
|
||||
BACKEND_INTERNAL_URL="http://localhost:3000"
|
||||
|
||||
## These are dummy values, you must create your own from Cloudflare.
|
||||
## Remember to set your public internet IP address in the allow-list for the API token.
|
||||
##
|
||||
## Cloudflare is currently required to save things like social media avatars for accounts.
|
||||
CLOUDFLARE_ACCOUNT_ID="your-account-id"
|
||||
CLOUDFLARE_ACCESS_KEY="your-access-key"
|
||||
CLOUDFLARE_SECRET_ACCESS_KEY="your-secret-access-key"
|
||||
CLOUDFLARE_BUCKETNAME="your-bucket-name"
|
||||
CLOUDFLARE_BUCKET_URL="https://your-bucket-url.r2.cloudflarestorage.com/"
|
||||
CLOUDFLARE_ACCOUNT_ID="QhcMSXQyPuMCRpSQcSYdEuTYgHeCXHbu"
|
||||
CLOUDFLARE_ACCESS_KEY="dcfCMSuFEeCNfvByUureMZEfxWJmDqZe"
|
||||
CLOUDFLARE_SECRET_ACCESS_KEY="zTTMXBmtyLPwHEdpACGHgDgzRTNpTJewiNriLnUS"
|
||||
CLOUDFLARE_BUCKETNAME="postiz"
|
||||
CLOUDFLARE_BUCKET_URL="https://QhcMSXQyPuMCRpSQcSYdEuTYgHeCXHbu.r2.cloudflarestorage.com/"
|
||||
CLOUDFLARE_REGION="auto"
|
||||
|
||||
|
||||
# === Common optional Settings
|
||||
|
||||
## This is a dummy key, you must create your own from Resend.
|
||||
|
|
@ -28,21 +28,19 @@ CLOUDFLARE_REGION="auto"
|
|||
#RESEND_API_KEY="RzeTwHijvxvPUerScFcenUZUALuQJzSaGSMJ"
|
||||
#EMAIL_FROM_ADDRESS=""
|
||||
#EMAIL_FROM_NAME=""
|
||||
#DISABLE_REGISTRATION=false
|
||||
|
||||
# Where will social media icons be saved - local or cloudflare.
|
||||
STORAGE_PROVIDER="local"
|
||||
|
||||
# Your upload directory path if you host your files locally, otherwise Cloudflare will be used.
|
||||
#UPLOAD_DIRECTORY=""
|
||||
#UPLOAD_DIRECTORY="/opt/postiz/uploads/"
|
||||
|
||||
# Your upload directory path if you host your files locally, otherwise Cloudflare will be used.
|
||||
#NEXT_PUBLIC_UPLOAD_STATIC_DIRECTORY=""
|
||||
#NEXT_PUBLIC_UPLOAD_STATIC_DIRECTORY="/opt/postiz/uploads/"
|
||||
|
||||
|
||||
# Social Media API Settings
|
||||
X_URL=""
|
||||
X_API_KEY=""
|
||||
X_API_SECRET=""
|
||||
X_CLIENT=""
|
||||
X_SECRET=""
|
||||
LINKEDIN_CLIENT_ID=""
|
||||
LINKEDIN_CLIENT_SECRET=""
|
||||
REDDIT_CLIENT_ID=""
|
||||
|
|
@ -51,10 +49,6 @@ GITHUB_CLIENT_ID=""
|
|||
GITHUB_CLIENT_SECRET=""
|
||||
BEEHIIVE_API_KEY=""
|
||||
BEEHIIVE_PUBLICATION_ID=""
|
||||
LISTMONK_DOMAIN=""
|
||||
LISTMONK_USER=""
|
||||
LISTMONK_API_KEY=""
|
||||
LISTMONK_LIST_ID=""
|
||||
THREADS_APP_ID=""
|
||||
THREADS_APP_SECRET=""
|
||||
FACEBOOK_APP_ID=""
|
||||
|
|
@ -67,25 +61,11 @@ PINTEREST_CLIENT_ID=""
|
|||
PINTEREST_CLIENT_SECRET=""
|
||||
DRIBBBLE_CLIENT_ID=""
|
||||
DRIBBBLE_CLIENT_SECRET=""
|
||||
DISCORD_CLIENT_ID=""
|
||||
DISCORD_CLIENT_SECRET=""
|
||||
DISCORD_BOT_TOKEN_ID=""
|
||||
SLACK_ID=""
|
||||
SLACK_SECRET=""
|
||||
SLACK_SIGNING_SECRET=""
|
||||
MASTODON_URL="https://mastodon.social"
|
||||
MASTODON_CLIENT_ID=""
|
||||
MASTODON_CLIENT_SECRET=""
|
||||
|
||||
# Chrome Extension Settings (for cookie-based platform integrations like Skool)
|
||||
EXTENSION_ID=""
|
||||
|
||||
# Misc Settings
|
||||
OPENAI_API_KEY=""
|
||||
NEXT_PUBLIC_DISCORD_SUPPORT=""
|
||||
NEXT_PUBLIC_POLOTNO=""
|
||||
# NOT_SECURED=false
|
||||
API_LIMIT=30 # The limit of the public API hour limit
|
||||
|
||||
# Payment settings
|
||||
FEE_AMOUNT=0.05
|
||||
|
|
@ -97,28 +77,3 @@ STRIPE_SIGNING_KEY_CONNECT=""
|
|||
# Developer Settings
|
||||
NX_ADD_PLUGINS=false
|
||||
IS_GENERAL="true" # required for now
|
||||
NEXT_PUBLIC_POSTIZ_OAUTH_DISPLAY_NAME="Authentik"
|
||||
NEXT_PUBLIC_POSTIZ_OAUTH_LOGO_URL="https://raw.githubusercontent.com/walkxcode/dashboard-icons/master/png/authentik.png"
|
||||
POSTIZ_GENERIC_OAUTH="false"
|
||||
POSTIZ_OAUTH_URL="https://auth.example.com"
|
||||
POSTIZ_OAUTH_AUTH_URL="https://auth.example.com/application/o/authorize"
|
||||
POSTIZ_OAUTH_TOKEN_URL="https://auth.example.com/application/o/token"
|
||||
POSTIZ_OAUTH_USERINFO_URL="https://authentik.example.com/application/o/userinfo"
|
||||
POSTIZ_OAUTH_CLIENT_ID=""
|
||||
POSTIZ_OAUTH_CLIENT_SECRET=""
|
||||
# POSTIZ_OAUTH_SCOPE="openid profile email" # default values
|
||||
|
||||
# Short Link Service Settings
|
||||
# DUB_TOKEN="" # Your self-hosted Dub API token
|
||||
# DUB_API_ENDPOINT="https://api.dub.co" # Your self-hosted Dub API endpoint
|
||||
# DUB_SHORT_LINK_DOMAIN="dub.sh" # Your self-hosted Dub domain
|
||||
|
||||
# SHORT_IO_SECRET_KEY="" # Your Short.io API secret key
|
||||
|
||||
# KUTT_API_KEY="" # Your Kutt.it API key
|
||||
# KUTT_API_ENDPOINT="https://kutt.it/api/v2" # Your self-hosted Kutt API endpoint
|
||||
# KUTT_SHORT_LINK_DOMAIN="kutt.it" # Your self-hosted Kutt domain
|
||||
|
||||
# LINK_DRIP_API_KEY="" # Your LinkDrip API key
|
||||
# LINK_DRIP_API_ENDPOINT="https://api.linkdrip.com/v1/" # Your self-hosted LinkDrip API endpoint
|
||||
# LINK_DRIP_SHORT_LINK_DOMAIN="dripl.ink" # Your self-hosted LinkDrip domain
|
||||
27
.eslintrc.json
Normal file
27
.eslintrc.json
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"root": true,
|
||||
"ignorePatterns": ["**/*"],
|
||||
"plugins": ["@nx"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
|
||||
"rules": {
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["*.ts", "*.tsx"],
|
||||
"extends": ["plugin:@nx/typescript"],
|
||||
"rules": {
|
||||
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"react/display-name": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["*.js", "*.jsx"],
|
||||
"extends": ["plugin:@nx/javascript"],
|
||||
"rules": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
11
.github/Dependabot.yml
vendored
11
.github/Dependabot.yml
vendored
|
|
@ -1,11 +0,0 @@
|
|||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "daily"
|
||||
3
.github/FUNDING.yaml
vendored
3
.github/FUNDING.yaml
vendored
|
|
@ -1,3 +0,0 @@
|
|||
#patreon: Postiz
|
||||
open_collective: postiz
|
||||
# github: gitroomhq
|
||||
14
.github/ISSUE_TEMPLATE/config.yml
vendored
14
.github/ISSUE_TEMPLATE/config.yml
vendored
|
|
@ -1,14 +0,0 @@
|
|||
# Disable the default option to open a blank issue
|
||||
blank_issues_enabled: true
|
||||
|
||||
# Define your custom links
|
||||
contact_links:
|
||||
# The first link definition
|
||||
- name: 🙏 Installation Issue
|
||||
url: https://discord.postiz.com
|
||||
about: If you have an installation / configuration issue.
|
||||
|
||||
# You can add more links if needed
|
||||
- name: Security Issue
|
||||
url: https://github.com/gitroomhq/postiz-app/security/advisories/new
|
||||
about: Please submit security Issues our GitHub Security Advisories.
|
||||
15
.github/PULL_REQUEST_TEMPLATE.md
vendored
15
.github/PULL_REQUEST_TEMPLATE.md
vendored
|
|
@ -1,22 +1,11 @@
|
|||
<!-- Remember to first apply via [the contribution form](https://contribute.postiz.com/p/postiz) before submitting a PR. -->
|
||||
|
||||
# What kind of change does this PR introduce?
|
||||
|
||||
eg: Bug fix, feature, docs update, ...
|
||||
|
||||
# Why was this change needed?
|
||||
|
||||
Please link to related issues when possible, and explain WHY you changed things, not WHAT you changed.
|
||||
Please link to related issues when possible.
|
||||
|
||||
# Other information:
|
||||
|
||||
eg: Did you discuss this change with anybody before working on it (not required, but can be a good idea for bigger changes). Any plans for the future, etc?
|
||||
|
||||
# Checklist:
|
||||
|
||||
Put a "X" in the boxes below to indicate you have followed the checklist;
|
||||
|
||||
- [ ] I have read the [CONTRIBUTING](https://github.com/gitroomhq/postiz-app/blob/main/CONTRIBUTING.md) guide.
|
||||
- [ ] I confirm I have not used AI to submit this PR or generate code for it.
|
||||
- [ ] I checked that there were no similar issues or PRs already open for this.
|
||||
- [ ] This PR fixes just ONE issue
|
||||
eg: Did you discuss this change with anybody before working on it (not required, but can be a good idea for bigger changes). Any plans for the future, etc?
|
||||
|
|
|
|||
116
.github/copilot-instructions.md
vendored
116
.github/copilot-instructions.md
vendored
|
|
@ -1,116 +0,0 @@
|
|||
|
||||
# Copilot Coding Agent Instructions for Postiz
|
||||
|
||||
## Project Architecture
|
||||
- Monorepo managed by NX, with apps in `apps/` and shared code in `libraries/`.
|
||||
- Main services: `frontend` (Next.js), `backend` (NestJS), `cron`, `commands`, `extension`, `sdk`, and `workers`.
|
||||
- Data layer uses Prisma ORM (`libraries/nestjs-libraries/src/database/prisma/schema.prisma`) with PostgreSQL as the default database.
|
||||
- Redis (BullMQ) is used for queues and caching.
|
||||
- Email notifications via Resend.
|
||||
- Social login integrations (Instagram, Facebook) and Make.com/N8N integrations.
|
||||
|
||||
## Developer Workflows
|
||||
- Use Node.js 20.17.0 and pnpm 8+.
|
||||
- Install dependencies: `pnpm install`
|
||||
- Build all apps: `pnpm run build`
|
||||
- Run all apps in dev mode: `pnpm run dev`
|
||||
- Test: `pnpm test` (Jest, coverage enabled)
|
||||
- Individual app scripts are in each app's `package.json` (e.g., `pnpm --filter ./apps/backend run dev`).
|
||||
- Prisma DB commands: `pnpm run prisma-generate`, `pnpm run prisma-db-push`, `pnpm run prisma-reset`.
|
||||
- Docker: `docker compose -f ./docker-compose.dev.yaml up -d`
|
||||
|
||||
## Conventions & Patterns
|
||||
- Use conventional commits (`feat:`, `fix:`, `chore:`).
|
||||
- PRs should include clear descriptions, related issue links, and UI screenshots/GIFs if relevant.
|
||||
- Comments are required for complex logic.
|
||||
- Shared code lives in `libraries/` (e.g., helpers, React shared libraries, NestJS modules).
|
||||
- Environment variables are managed via `.env` and referenced in Docker and scripts.
|
||||
- Make sure to keep the `.env.example` file updated with new environment variables.
|
||||
|
||||
## Integration Points
|
||||
- External APIs: Social media (Instagram, Facebook), Make.com, N8N, Resend, Stripe, etc.
|
||||
- SDK (`apps/sdk`) provides programmatic access to Postiz features.
|
||||
- Extension (`apps/extension`) is built with Vite, React, TypeScript, and Tailwind CSS.
|
||||
|
||||
## Key Files & Directories
|
||||
- `apps/` — Main services and applications
|
||||
- `libraries/` — Shared code and modules
|
||||
- `docker-compose.dev.yaml` — Local development Docker setup
|
||||
- `.env` — Environment configuration
|
||||
- `jest.config.ts` — Test configuration
|
||||
- `pnpm-workspace.yaml` — Workspace package management
|
||||
- `README.md` — General project overview
|
||||
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma` — Database schema
|
||||
|
||||
## Documentation
|
||||
- Main docs: https://docs.postiz.com/
|
||||
- Developer guide: https://docs.postiz.com/developer-guide
|
||||
- Public API: https://docs.postiz.com/public-api
|
||||
|
||||
---
|
||||
|
||||
# Logs
|
||||
|
||||
- Where logs are used, ensure Sentry is imported using `import * as Sentry from "@sentry/nextjs"`
|
||||
- Enable logging in Sentry using `Sentry.init({ enableLogs: true })`
|
||||
- Reference the logger using `const { logger } = Sentry`
|
||||
- Sentry offers a `consoleLoggingIntegration` that can be used to log specific console error types automatically without instrumenting the individual logger calls
|
||||
|
||||
## Configuration
|
||||
|
||||
The Sentry initialization needs to be updated to enable the logs feature.
|
||||
|
||||
### Baseline
|
||||
|
||||
```javascript
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
|
||||
Sentry.init({
|
||||
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
|
||||
|
||||
enableLogs: true,
|
||||
});
|
||||
```
|
||||
|
||||
### Logger Integration
|
||||
|
||||
```javascript
|
||||
Sentry.init({
|
||||
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
|
||||
integrations: [
|
||||
// send console.log, console.error, and console.warn calls as logs to Sentry
|
||||
Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Logger Examples
|
||||
|
||||
`logger.fmt` is a template literal function that should be used to bring variables into the structured logs.
|
||||
|
||||
```javascript
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
|
||||
const { logger } = Sentry;
|
||||
|
||||
logger.trace("Starting database connection", { database: "users" });
|
||||
logger.debug(logger.fmt`Cache miss for user: ${userId}`);
|
||||
logger.info("Updated profile", { profileId: 345 });
|
||||
logger.warn("Rate limit reached for endpoint", {
|
||||
endpoint: "/api/results/",
|
||||
isEnterprise: false,
|
||||
});
|
||||
logger.error("Failed to process payment", {
|
||||
orderId: "order_123",
|
||||
amount: 99.99,
|
||||
});
|
||||
logger.fatal("Database connection pool exhausted", {
|
||||
database: "users",
|
||||
activeConnections: 100,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
For questions or unclear conventions, check the main README or ask for clarification in your PR description.
|
||||
|
||||
BIN
.github/sponsors/hostinger.png
vendored
BIN
.github/sponsors/hostinger.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 69 KiB |
94
.github/workflows/build-containers.yml
vendored
94
.github/workflows/build-containers.yml
vendored
|
|
@ -8,35 +8,14 @@ on:
|
|||
- '*'
|
||||
|
||||
jobs:
|
||||
build-containers-common:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
containerver: ${{ steps.getcontainerver.outputs.containerver }}
|
||||
steps:
|
||||
- name: Get Container Version
|
||||
id: getcontainerver
|
||||
run: |
|
||||
echo "containerver=${{ github.ref_name }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build-containers:
|
||||
needs: build-containers-common
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- runnertags: ubuntu-latest
|
||||
arch: amd64
|
||||
- runnertags: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
runs-on: ${{ matrix.runnertags }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to ghcr
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
|
|
@ -44,60 +23,27 @@ jobs:
|
|||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Build and Push Image
|
||||
env:
|
||||
CONTAINERVER: ${{ needs.build-containers-common.outputs.containerver }}
|
||||
NEXT_PUBLIC_VERSION: ${{ github.ref_name }}
|
||||
- name: docker build
|
||||
run: ./var/docker/docker-build.sh
|
||||
|
||||
- name: Get date
|
||||
run: |
|
||||
docker buildx build --platform linux/${{ matrix.arch }} \
|
||||
-f Dockerfile.dev \
|
||||
-t ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-${{ matrix.arch }} \
|
||||
--build-arg NEXT_PUBLIC_VERSION=${{ env.NEXT_PUBLIC_VERSION }} \
|
||||
--pull \
|
||||
--no-cache \
|
||||
--provenance=false --sbom=false \
|
||||
--output "type=registry,name=ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-${{ matrix.arch }}" .
|
||||
echo "DATE=$(date +'%s')" >> "$GITHUB_ENV"
|
||||
|
||||
build-container-manifest:
|
||||
needs: [build-containers, build-containers-common]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Login to ghcr
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Create Docker Manifest
|
||||
env:
|
||||
CONTAINERVER: ${{ needs.build-containers-common.outputs.containerver }}
|
||||
- name: Print post-build debug info
|
||||
run: |
|
||||
# Verify the architecture images
|
||||
echo "Verifying AMD64 image:"
|
||||
docker buildx imagetools inspect ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-amd64
|
||||
|
||||
echo "Verifying ARM64 image:"
|
||||
docker buildx imagetools inspect ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-arm64
|
||||
|
||||
# Try to remove any existing manifests first
|
||||
docker manifest rm ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }} || true
|
||||
docker manifest rm ghcr.io/gitroomhq/postiz-app:latest || true
|
||||
|
||||
# Create and push the version-specific manifest
|
||||
docker manifest create ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }} \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-amd64 \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-arm64
|
||||
docker images
|
||||
|
||||
docker manifest push ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}
|
||||
|
||||
# Create and push the latest manifest
|
||||
docker manifest create ghcr.io/gitroomhq/postiz-app:latest \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-amd64 \
|
||||
--amend ghcr.io/gitroomhq/postiz-app:${{ env.CONTAINERVER }}-arm64
|
||||
|
||||
docker manifest push ghcr.io/gitroomhq/postiz-app:latest
|
||||
|
||||
- name: Verify Manifest
|
||||
- name: docker tag
|
||||
run: |
|
||||
docker manifest inspect ghcr.io/gitroomhq/postiz-app:latest
|
||||
docker tag localhost/postiz ghcr.io/gitroomhq/postiz-app:${{ env.DATE }}
|
||||
docker push ghcr.io/gitroomhq/postiz-app:${{ env.DATE }}
|
||||
|
||||
docker tag ghcr.io/gitroomhq/postiz-app:${{ env.DATE }} ghcr.io/gitroomhq/postiz-app:latest
|
||||
docker push ghcr.io/gitroomhq/postiz-app:latest
|
||||
|
||||
docker tag localhost/postiz-devcontainer ghcr.io/gitroomhq/postiz-devcontainer:${{ env.DATE }}
|
||||
docker push ghcr.io/gitroomhq/postiz-devcontainer:${{ env.DATE }}
|
||||
|
||||
docker tag ghcr.io/gitroomhq/postiz-devcontainer:${{ env.DATE }} ghcr.io/gitroomhq/postiz-devcontainer:latest
|
||||
docker push ghcr.io/gitroomhq/postiz-devcontainer:latest
|
||||
|
|
|
|||
34
.github/workflows/build-extension.yaml
vendored
34
.github/workflows/build-extension.yaml
vendored
|
|
@ -1,34 +0,0 @@
|
|||
name: Build Extension
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
submit:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Zip extensions
|
||||
run: FRONTEND_URL=https://platform.postiz.com pnpm run build:extension
|
||||
|
||||
- name: Upload to Nextcloud
|
||||
env:
|
||||
NEXTCLOUD_URL: ${{ secrets.NEXTCLOUD_URL }}
|
||||
NEXTCLOUD_USERNAME: ${{ secrets.NEXTCLOUD_USERNAME }}
|
||||
NEXTCLOUD_PASSWORD: ${{ secrets.NEXTCLOUD_PASSWORD }}
|
||||
run: |
|
||||
curl -T apps/extension/extension.zip \
|
||||
-u "$NEXTCLOUD_USERNAME:$NEXTCLOUD_PASSWORD" \
|
||||
"$NEXTCLOUD_URL/extension.zip"
|
||||
52
.github/workflows/build.yaml
vendored
Normal file
52
.github/workflows/build.yaml
vendored
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
---
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- package.json
|
||||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- package.json
|
||||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: ['20.17.0']
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
**/package-lock.json
|
||||
|
||||
# https://nextjs.org/docs/pages/building-your-application/deploying/ci-build-caching#github-actions
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.npm
|
||||
${{ github.workspace }}/.next/cache
|
||||
|
||||
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-
|
||||
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
54
.github/workflows/build.yml
vendored
54
.github/workflows/build.yml
vendored
|
|
@ -1,54 +0,0 @@
|
|||
---
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
merge_group:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: ['22.12.0']
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v2
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
- name: Get pnpm store directory
|
||||
shell: bash
|
||||
run: |
|
||||
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
|
||||
|
||||
# - name: Setup pnpm cache
|
||||
# uses: actions/cache@v4
|
||||
# with:
|
||||
# path: |
|
||||
# ${{ env.STORE_PATH }}
|
||||
# ${{ github.workspace }}/.next/cache
|
||||
# key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
|
||||
# restore-keys: |
|
||||
# ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build
|
||||
run: pnpm run build
|
||||
8
.github/workflows/codeql.yml
vendored
8
.github/workflows/codeql.yml
vendored
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
name: "Code Quality Analysis"
|
||||
name: "Code Quality Analysis"
|
||||
|
||||
on:
|
||||
push:
|
||||
|
|
@ -9,8 +9,12 @@ on:
|
|||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
merge_group:
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- apps/**
|
||||
- '!apps/docs/**'
|
||||
- libraries/**
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ jobs:
|
|||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: |
|
||||
**/pnpm-lock.yaml
|
||||
**/package-lock.json
|
||||
|
||||
- name: Install ESLint
|
||||
run: |
|
||||
28
.github/workflows/issue-label-triggers.yml
vendored
28
.github/workflows/issue-label-triggers.yml
vendored
|
|
@ -1,28 +0,0 @@
|
|||
---
|
||||
name: Issue Label Triggers
|
||||
on:
|
||||
issues:
|
||||
types:
|
||||
- labeled
|
||||
|
||||
jobs:
|
||||
closed-public-website:
|
||||
if: github.event.label.name == 'trigger-public-website'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
- name: Add comment
|
||||
run: gh issue comment "$NUMBER" --body "$BODY" && gh issue close "$NUMBER"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
NUMBER: ${{ github.event.issue.number }}
|
||||
BODY: >
|
||||
This issue concerns the public website, which is not open source and is not part of this repository.
|
||||
|
||||
|
||||
If you have a question or concern about the content of the public website, please contact Nevo David.
|
||||
|
||||
|
||||
If you are looking to contribute to the open source Postiz project code, this is the correct repository, and we welcome your contributions in a new GitHub issue.
|
||||
32
.github/workflows/publish-extension.yml
vendored
32
.github/workflows/publish-extension.yml
vendored
|
|
@ -1,32 +0,0 @@
|
|||
name: Publish Extension
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
submit:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Zip extensions
|
||||
run: FRONTEND_URL=https://platform.postiz.com pnpm run build:extension
|
||||
|
||||
- name: Publish to Chrome Web Store
|
||||
uses: mnao305/chrome-extension-upload@v5.0.0
|
||||
with:
|
||||
extension-id: ${{ secrets.CHROME_EXTENSION_ID }}
|
||||
client-id: ${{ secrets.CHROME_CLIENT_ID }}
|
||||
client-secret: ${{ secrets.CHROME_CLIENT_SECRET }}
|
||||
refresh-token: ${{ secrets.CHROME_REFRESH_TOKEN }}
|
||||
file-path: apps/extension/extension.zip
|
||||
33
.github/workflows/stale.yml
vendored
33
.github/workflows/stale.yml
vendored
|
|
@ -1,33 +0,0 @@
|
|||
name: Close inactive issues
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "*/30 * * * *"
|
||||
|
||||
jobs:
|
||||
close-issues:
|
||||
if: github.repository == 'gitroomhq/postiz-app'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 90
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "This issue is stale because it has been open for 90 days with no activity."
|
||||
close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
|
||||
exempt-issue-labels: "no-stale-bot"
|
||||
|
||||
days-before-pr-stale: 90
|
||||
days-before-pr-close: 7
|
||||
stale-pr-label: "stale"
|
||||
stale-pr-message: "This PR is stale because it has been open for 90 days with no activity."
|
||||
close-pr-message: "This PR was closed because it has been inactive for 7 days since being marked as stale."
|
||||
exempt-pr-label: "no-stale-bot"
|
||||
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
operations-per-run: 180
|
||||
16
.gitignore
vendored
16
.gitignore
vendored
|
|
@ -16,10 +16,9 @@ node_modules
|
|||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
.vscode/*
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
|
|
@ -48,16 +47,3 @@ Thumbs.db
|
|||
# Vim files
|
||||
**/*.swp
|
||||
**/*.swo
|
||||
|
||||
# Temporary files
|
||||
*.orig
|
||||
*.~*~
|
||||
*.tsbuildinfo
|
||||
|
||||
# ignore Secrets folder
|
||||
.secrets/
|
||||
libraries/plugins/src/plugins.ts
|
||||
i18n.cache
|
||||
|
||||
# Generated by apps/frontend/scripts/fetch-gtm.mjs on install
|
||||
apps/frontend/public/g.js
|
||||
|
|
|
|||
3
.gitmodules
vendored
3
.gitmodules
vendored
|
|
@ -1,3 +0,0 @@
|
|||
[submodule "libraries/plugins/src/list/public-api"]
|
||||
path = libraries/plugins/src/list/public-api
|
||||
url = git@github.com:gitroomhq/public-api.git
|
||||
5
.npmrc
5
.npmrc
|
|
@ -1,5 +0,0 @@
|
|||
ignore-workspace-root-check=true
|
||||
node-linker=hoisted
|
||||
restrict-manifest-changes=true
|
||||
sync-injected-deps-after-scripts[]=build
|
||||
inject-workspace-packages=true
|
||||
8
.vscode/extensions.json
vendored
Normal file
8
.vscode/extensions.json
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"recommendations": [
|
||||
"nrwl.angular-console",
|
||||
"esbenp.prettier-vscode",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"firsttris.vscode-jest-runner"
|
||||
]
|
||||
}
|
||||
61
CLAUDE.md
61
CLAUDE.md
|
|
@ -1,61 +0,0 @@
|
|||
This project is Postiz, a tool to schedule social media and chat posts to 28+ channels.
|
||||
You can add posts to the calendar, they will be added into a workflow and posted at the right time.
|
||||
You can find things like:
|
||||
- Schedule posts
|
||||
- Calendar view
|
||||
- Analytics
|
||||
- Team management
|
||||
- Media library
|
||||
|
||||
This project is a monorepo with a root only package.json of dependencies.
|
||||
Made with PNPM.
|
||||
We have 3 important folders
|
||||
|
||||
- apps/backend - this is where the API code is (NESTJS)
|
||||
- apps/orchestrator - this is temporal, it's for background jobs (NESTJS) it contains all the workflows and activities
|
||||
- apps/frontend - this is the code of the frontend (Vite ReactJS)
|
||||
- /libraries contains a lot of services shared between backend and orchestrator and frontend components.
|
||||
|
||||
We are using only pnpm, don't use any other dependency manager.
|
||||
Never install frontend components from npmjs, focus on writing native components.
|
||||
|
||||
The project uses tailwind 3, before writing any component look at:
|
||||
- /apps/frontend/src/app/colors.scss
|
||||
- /apps/frontend/src/app/global.scss
|
||||
- /apps/frontend/tailwind.config.js
|
||||
|
||||
All the --color-custom* are deprecated, don't use them.
|
||||
|
||||
And check other components in the system before to get the right design.
|
||||
|
||||
When working on the backend we need to pass the 3 layers:
|
||||
Controller >> Service >> Repository (no shortcuts)
|
||||
In some cases we will have
|
||||
Controller >> Mananger >> Service >> Repository.
|
||||
|
||||
Most of the server logic should be inside of libs/server.
|
||||
The backend repository is mostly used to write controller, and import files from libs.server.
|
||||
|
||||
For the frontend follow this:
|
||||
- Many of the UI components lives in /apps/frontend/src/components/ui
|
||||
- Routing is in /apps/frontend/src/app
|
||||
- Components are in /apps/frontend/src/components
|
||||
- always use SWR to fetch stuff, and use "useFetch" hook from /libraries/helpers/src/utils/custom.fetch.tsx
|
||||
|
||||
When using SWR, each one have to be in a seperate hook and must comply with react-hooks/rules-of-hooks, never put eslint-disable-next-line on it.
|
||||
|
||||
It means that this is valid:
|
||||
const useCommunity = () => {
|
||||
return useSWR....
|
||||
}
|
||||
|
||||
This is not valid:
|
||||
const useCommunity = () => {
|
||||
return {
|
||||
communities: () => useSWR<CommunitiesListResponse>("communities", getCommunities),
|
||||
providers: () => useSWR<ProvidersListResponse>("providers", getProviders),
|
||||
};
|
||||
}
|
||||
|
||||
- Linting of the project can run only from the root.
|
||||
- Use only pnpm.
|
||||
|
|
@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.
|
|||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
|
@ -106,7 +106,7 @@ Violating these terms may lead to a permanent ban.
|
|||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
|
|
|
|||
|
|
@ -1,63 +0,0 @@
|
|||
# Contributing
|
||||
|
||||
Contributions are welcome - code, docs, whatever it might be! If this is your first contribution to an Open Source project or you're a core maintainer of multiple projects, your time and interest in contributing to this project is most welcome.
|
||||
|
||||
## Read the developers guide
|
||||
|
||||
The main documentation site has a [developer guide](https://docs.postiz.com/developer-guide) . That guide provides you a good understanding of the project structure, and how to setup your development environment. Read this document after you have read that guide. This document is intended to provide you a good understanding of how to submit your first contribution.
|
||||
|
||||
## Apply via the contribution form
|
||||
|
||||
To submit your contribution, please fill out the [contribution form](https://contribute.postiz.com/p/postiz). This helps us evaluate whether your contribution is a good fit for the project. We will review your submission and get back to you as soon as possible.
|
||||
|
||||
## Write code with others
|
||||
|
||||
This is an open source project, with an open and welcoming community that is always keen to welcome new contributors. We recommend the two best ways to interact with the community are:
|
||||
|
||||
- **GitHub issues**: To discuss more slowly, or longer-written messages.
|
||||
- **[Discord chat](https://discord.postiz.com)**: To chat with people [Discord chat](https://discord.postiz.com/) and a quicker feedback.
|
||||
|
||||
As a general rule;
|
||||
|
||||
- **If a change is less than 3 lines**: You're probably safe just to submit the change without a discussion. This includes typos, dependency changes, and quick fixes, etc.
|
||||
- **If a change is more than 3 lines**: It's probably best to discuss the change in an issue or on discord first. This is simply because you might not be aware of the roadmap for the project, or understand the impact this change might have. We're just trying to save you time here, and importantly, avoid you being disappointed if your change isn't accepted.
|
||||
|
||||
## Types of Contributions
|
||||
|
||||
Contributions can include:
|
||||
|
||||
- **Code improvements:** Fixing bugs or adding new features.
|
||||
- **Documentation updates:** Enhancing clarity or adding missing information.
|
||||
- **Feature requests:** Suggesting new capabilities or integrations.
|
||||
- **Bug reports:** Identifying and reporting issues.
|
||||
|
||||
## AI
|
||||
|
||||
To ensure the quality and maintainability of the codebase, **we do not accept Pull Requests generated primarily by AI tools** (e.g., ChatGPT, GitHub Copilot, Claude Code, etc.).
|
||||
All contributions must be the original work of the author. We reserve the right to close any PR that appears to be AI-generated without further review.
|
||||
|
||||
## How to contribute
|
||||
|
||||
This project follows a Fork/Feature Branch/Pull Request model. If you're not familiar with this, here's how it works:
|
||||
|
||||
1. **Fork the project:** Create a personal copy of the repository on your GitHub account.
|
||||
2. **Clone your fork:** Bring a copy of your fork to your local machine.
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/postiz.git
|
||||
```
|
||||
3. **Create a new branch**: Start a new branch for your changes
|
||||
```bash
|
||||
git checkout -b feature/your-feature-name
|
||||
```
|
||||
4. **Make your changes**: Implement the changes you wish to contribute.
|
||||
5. **Push your changes**: Upload your changes to your fork.
|
||||
```bash
|
||||
git push -u origin feature/your-feature-name
|
||||
```
|
||||
6. **Create a pull request**: Propose your changes **to the main branch**.
|
||||
|
||||
# Need Help?
|
||||
|
||||
Again, do check the [developer guide](https://docs.postiz.com/developer-guide). Much of what you probably need to know is in there.
|
||||
|
||||
If you encounter any issues, please visit our [support page](https://docs.postiz.com/support) or check the community forums. Your contributions help make Postiz better!
|
||||
|
|
@ -1,28 +1,72 @@
|
|||
FROM node:22.20-bookworm-slim
|
||||
ARG NEXT_PUBLIC_VERSION
|
||||
ENV NEXT_PUBLIC_VERSION=$NEXT_PUBLIC_VERSION
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
g++ \
|
||||
make \
|
||||
python3-pip \
|
||||
bash \
|
||||
nginx \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# This Dockerfile is used for producing 3 container images.
|
||||
#
|
||||
# base - which is thrown away, that contains node and the basic infrastructure.
|
||||
# devcontainer - which is used for development, and contains the source code and the node_modules.
|
||||
# dist - which is used for production, and contains the built source code and the node_modules.
|
||||
|
||||
RUN addgroup --system www \
|
||||
&& adduser --system --ingroup www --home /www --shell /usr/sbin/nologin www \
|
||||
&& mkdir -p /www \
|
||||
&& chown -R www:www /www /var/lib/nginx
|
||||
ARG NODE_VERSION="20.17"
|
||||
|
||||
# Base image
|
||||
FROM docker.io/node:${NODE_VERSION}-alpine3.19 AS base
|
||||
|
||||
RUN npm --no-update-notifier --no-fund --global install pnpm@10.6.1 pm2
|
||||
## Just reduce unccessary noise in the logs.
|
||||
ENV NPM_CONFIG_UPDATE_NOTIFIER=false
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
RUN apk add --no-cache \
|
||||
bash=5.2.21-r0 \
|
||||
supervisor=4.2.5-r4
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . /app
|
||||
COPY var/docker/nginx.conf /etc/nginx/nginx.conf
|
||||
EXPOSE 4200
|
||||
EXPOSE 3000
|
||||
|
||||
RUN pnpm install
|
||||
RUN NODE_OPTIONS="--max-old-space-size=4096" pnpm run build
|
||||
COPY var/docker/entrypoint.sh /app/entrypoint.sh
|
||||
COPY var/docker/supervisord.conf /etc/supervisord.conf
|
||||
COPY var/docker/supervisord /app/supervisord_available_configs/
|
||||
COPY .env.example /config/postiz.env
|
||||
|
||||
CMD ["sh", "-c", "nginx && pnpm run pm2"]
|
||||
VOLUME /config
|
||||
|
||||
LABEL org.opencontainers.image.source=https://github.com/gitroomhq/postiz-app
|
||||
|
||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||
|
||||
# Builder image
|
||||
FROM base AS devcontainer
|
||||
|
||||
RUN apk add --no-cache \
|
||||
pkgconfig \
|
||||
gcc \
|
||||
pixman-dev \
|
||||
cairo-dev \
|
||||
pango-dev \
|
||||
make \
|
||||
build-base
|
||||
|
||||
COPY nx.json tsconfig.base.json package.json package-lock.json /app/
|
||||
COPY apps /app/apps/
|
||||
COPY libraries /app/libraries/
|
||||
|
||||
RUN npm ci --no-fund && npx nx run-many --target=build --projects=frontend,backend,workers,cron
|
||||
|
||||
VOLUME /config
|
||||
|
||||
LABEL org.opencontainers.image.title="Postiz App (DevContainer)"
|
||||
|
||||
# Output image
|
||||
FROM base AS dist
|
||||
|
||||
COPY --from=devcontainer /app/node_modules/ /app/node_modules/
|
||||
COPY --from=devcontainer /app/dist/ /app/dist/
|
||||
|
||||
# Required for prisma
|
||||
COPY --from=devcontainer /app/libraries/ /app/libraries/
|
||||
|
||||
COPY package.json nx.json /app/
|
||||
|
||||
VOLUME /config
|
||||
|
||||
## Labels at the bottom, because CI will eventually add dates, commit hashes, etc.
|
||||
LABEL org.opencontainers.image.title="Postiz App (Production)"
|
||||
|
|
|
|||
|
|
@ -1,96 +0,0 @@
|
|||
// Declarative Pipeline for building Node.js application and running SonarQube analysis triggered by a push event.
|
||||
pipeline {
|
||||
// Defines the execution environment. Using 'agent any' to ensure an agent is available.
|
||||
agent any
|
||||
|
||||
// Global environment block removed to prevent Groovy scoping issues with manual path calculation.
|
||||
|
||||
stages {
|
||||
// Stage 1: Checkout the code (Relies on the initial SCM checkout done by Jenkins)
|
||||
stage('Source Checkout') {
|
||||
steps {
|
||||
echo "Workspace already populated by the initial SCM checkout. Proceeding."
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 2: Setup Node.js v20 and install pnpm
|
||||
stage('Setup Environment and Tools') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Ensuring required utilities and Node.js are installed..."
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl unzip nodejs
|
||||
|
||||
# 1. Install Node.js v20
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
echo "Node.js version: \$(node -v)"
|
||||
|
||||
# 2. Install pnpm globally (version 8)
|
||||
npm install -g pnpm@8
|
||||
echo "pnpm version: \$(pnpm -v)"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 3: Install dependencies and build the application
|
||||
stage('Install and Build') {
|
||||
steps {
|
||||
sh 'pnpm install'
|
||||
sh 'pnpm run build'
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 4: Run SonarQube analysis: Install scanner, get version, and execute.
|
||||
stage('SonarQube Analysis') {
|
||||
steps {
|
||||
script {
|
||||
// 1. Get the short 8-character commit SHA for project versioning
|
||||
def commitShaShort = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim()
|
||||
echo "Commit SHA (short) is: ${commitShaShort}"
|
||||
|
||||
// --- 2. MANUALLY INSTALL THE SONAR SCANNER CLI LOCALLY IN THIS STAGE ---
|
||||
sh """
|
||||
echo "Manually downloading and installing Sonar Scanner CLI..."
|
||||
|
||||
# Download the stable scanner CLI package
|
||||
curl -sS -o sonar-scanner.zip \
|
||||
"https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.7.0.2747.zip"
|
||||
|
||||
# Added -o flag to force overwrite and prevent interactive prompt failure
|
||||
unzip -o -q sonar-scanner.zip -d .
|
||||
"""
|
||||
|
||||
// 3. Find the extracted directory name and capture the full absolute bin path in Groovy
|
||||
// This is defined locally and used directly, avoiding environment variable issues.
|
||||
def scannerBinPath = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
SCANNER_DIR=$(find . -maxdepth 1 -type d -name "sonar-scanner*" | head -n 1)
|
||||
# Get the full absolute path to the executable file
|
||||
echo \$(pwd)/\${SCANNER_DIR}/bin/sonar-scanner
|
||||
'''
|
||||
).trim()
|
||||
|
||||
echo "Scanner executable path captured: ${scannerBinPath}"
|
||||
|
||||
// 4. Use withSonarQubeEnv to set up the secure variables (HOST and TOKEN)
|
||||
withSonarQubeEnv(installationName: 'SonarQube-Server') {
|
||||
// 5. Execute the scanner using the Groovy variable directly.
|
||||
sh """
|
||||
echo "Starting SonarQube Analysis for project version: ${commitShaShort}"
|
||||
|
||||
# Execute the full, absolute path captured in the Groovy variable.
|
||||
'${scannerBinPath}' \\
|
||||
-Dsonar.projectVersion=${commitShaShort} \\
|
||||
-Dsonar.sources=.
|
||||
|
||||
# SONAR_HOST_URL and SONAR_TOKEN are automatically passed as environment variables
|
||||
# by the withSonarQubeEnv block.
|
||||
"""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
// Declarative Pipeline for building Node.js application and running SonarQube analysis for a Pull Request.
|
||||
pipeline {
|
||||
// Defines the execution environment. Using 'agent any' to ensure an agent is available.
|
||||
agent any
|
||||
|
||||
// Environment variables that hold PR details, provided by Jenkins Multibranch setup.
|
||||
environment {
|
||||
// FIX: Environment variables must be quoted or wrapped in a function call.
|
||||
// We quote the 'env.CHANGE_ID' reference to fix the compilation error.
|
||||
PR_KEY = "${env.CHANGE_ID}"
|
||||
PR_BRANCH = "${env.CHANGE_BRANCH}"
|
||||
PR_BASE = "${env.CHANGE_TARGET}"
|
||||
}
|
||||
|
||||
stages {
|
||||
// Stage 1: Checkout the code (Relies on the initial SCM checkout done by Jenkins)
|
||||
stage('Source Checkout') {
|
||||
steps {
|
||||
echo "Workspace already populated by the initial SCM checkout. Proceeding."
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 2: Setup Node.js v20, install pnpm, and install required tools (curl, unzip)
|
||||
stage('Setup Environment and Tools') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Ensuring required utilities and Node.js are installed..."
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl unzip nodejs
|
||||
|
||||
# 1. Install Node.js v20 (closest matching the specified version '20.17.0')
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
echo "Node.js version: \$(node -v)"
|
||||
|
||||
# 2. Install pnpm globally (version 8)
|
||||
npm install -g pnpm@8
|
||||
echo "pnpm version: \$(pnpm -v)"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 3: Install dependencies and build the application
|
||||
stage('Install and Build') {
|
||||
steps {
|
||||
sh 'pnpm install'
|
||||
sh 'pnpm run build'
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 4: Run SonarQube PR analysis: Install scanner locally, get version, and execute.
|
||||
stage('SonarQube Pull Request Analysis') {
|
||||
steps {
|
||||
script {
|
||||
// 1. Get the short 8-character commit SHA for project versioning
|
||||
def commitShaShort = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim()
|
||||
echo "Commit SHA (short) is: ${commitShaShort}"
|
||||
|
||||
// --- 2. MANUALLY INSTALL THE SONAR SCANNER CLI LOCALLY ---
|
||||
sh """
|
||||
echo "Manually downloading and installing Sonar Scanner CLI..."
|
||||
curl -sS -o sonar-scanner.zip \
|
||||
"https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.7.0.2747.zip"
|
||||
unzip -o -q sonar-scanner.zip -d .
|
||||
"""
|
||||
|
||||
// 3. Find the extracted directory name and capture the full absolute executable path.
|
||||
def scannerBinPath = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
SCANNER_DIR=$(find . -maxdepth 1 -type d -name "sonar-scanner*" | head -n 1)
|
||||
# Get the full absolute path to the executable file
|
||||
echo \$(pwd)/\${SCANNER_DIR}/bin/sonar-scanner
|
||||
'''
|
||||
).trim()
|
||||
|
||||
echo "Scanner executable path captured: ${scannerBinPath}"
|
||||
|
||||
// 4. Use withSonarQubeEnv to set up the secure variables (HOST and TOKEN)
|
||||
withSonarQubeEnv(installationName: 'SonarQube-Server') {
|
||||
// 5. Execute the scanner using the Groovy variable directly with PR parameters.
|
||||
sh """
|
||||
echo "Starting SonarQube Pull Request Analysis for PR #${PR_KEY}"
|
||||
|
||||
'${scannerBinPath}' \\
|
||||
-Dsonar.projectVersion=${commitShaShort} \\
|
||||
-Dsonar.sources=. \\
|
||||
-Dsonar.pullrequest.key=${PR_KEY} \\
|
||||
-Dsonar.pullrequest.branch=${PR_BRANCH} \\
|
||||
-Dsonar.pullrequest.base=${PR_BASE}
|
||||
|
||||
# SONAR_HOST_URL and SONAR_TOKEN are automatically passed as environment variables
|
||||
# by the withSonarQubeEnv block.
|
||||
"""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
862
LICENSE
862
LICENSE
|
|
@ -1,661 +1,201 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Postiz - Social media schedule tool
|
||||
Copyright (C) 2025 Nevo David
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2024 Gitroom, LLC
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
|
|||
113
README.md
113
README.md
|
|
@ -1,27 +1,42 @@
|
|||
|
||||
<p align="center">
|
||||
<a href="https://postiz.com/" target="_blank">
|
||||
<a href="https://x.com/intent/follow?screen_name=nevodavid" target="_blank">
|
||||
<img alt="Follow me" src="https://github.com/user-attachments/assets/1562c93f-95c6-4307-8a85-e62003e26348" />
|
||||
</a>
|
||||
<br />
|
||||
|
||||
<a href="https://devfest.ai" target="_blank">
|
||||
<img alt="DevFest" src="https://github.com/user-attachments/assets/cab9a4e5-e88e-4a28-be7d-28ed749e537a" width="850" />
|
||||
</a>
|
||||
|
||||
<br /><br />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://postiz.com" target="_blank">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/765e9d72-3ee7-4a56-9d59-a2c9befe2311">
|
||||
<img alt="Postiz Logo" src="https://github.com/user-attachments/assets/f0d30d70-dddb-4142-8876-e9aa6ed1cb99" width="280"/>
|
||||
<img alt="Novu Logo" src="https://github.com/user-attachments/assets/f0d30d70-dddb-4142-8876-e9aa6ed1cb99" width="280"/>
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://opensource.org/license/agpl-v3">
|
||||
<img src="https://img.shields.io/badge/License-AGPL%203.0-blue.svg" alt="License">
|
||||
<a href="https://opensource.org/licenses/Apache-2.0">
|
||||
<img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h3 align="center"><strong><a href="https://github.com/gitroomhq/postiz-agent">NEW: check out Postiz agent CLI! perfect for OpenClaw and other agents</a></strong></h3>
|
||||
<div align="center">
|
||||
<strong>
|
||||
<h2>Your ultimate AI social media scheduling tool</h2><br />
|
||||
<a href="https://postiz.com">Postiz</a>: An alternative to: Buffer.com, Hypefury, Twitter Hunter, etc...<br /><br />
|
||||
<a href="https://postiz.com">Postiz</a>: An alternative to: Buffer.com, Hypefury, Twitter Hunter, Etc...<br /><br />
|
||||
</strong>
|
||||
Postiz offers everything you need to manage your social media posts,<br />build an audience, capture leads, and grow your business.
|
||||
</div>
|
||||
|
||||
|
||||
<div class="flex" align="center">
|
||||
<br />
|
||||
<img alt="Instagram" src="https://postiz.com/svgs/socials/Instagram.svg" width="32">
|
||||
|
|
@ -34,10 +49,6 @@
|
|||
<img alt="Pinterest" src="https://postiz.com/svgs/socials/Pinterest.svg" width="32">
|
||||
<img alt="Threads" src="https://postiz.com/svgs/socials/Threads.svg" width="32">
|
||||
<img alt="X" src="https://postiz.com/svgs/socials/X.svg" width="32">
|
||||
<img alt="Slack" src="https://postiz.com/svgs/socials/Slack.svg" width="32">
|
||||
<img alt="Discord" src="https://postiz.com/svgs/socials/Discord.svg" width="32">
|
||||
<img alt="Mastodon" src="https://postiz.com/svgs/socials/Mastodon.svg" width="32">
|
||||
<img alt="Bluesky" src="https://postiz.com/svgs/socials/Bluesky.svg" width="32">
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
|
|
@ -45,51 +56,28 @@
|
|||
<a href="https://docs.postiz.com" rel="dofollow"><strong>Explore the docs »</strong></a>
|
||||
<br />
|
||||
|
||||
<br />
|
||||
<a href="https://youtube.com/@postizofficial" rel="dofollow"><strong>Watch the YouTube Tutorials»</strong></a>
|
||||
<br />
|
||||
</p>
|
||||
<br/>
|
||||
<a href="https://platform.postiz.com">Register</a>
|
||||
·
|
||||
<a href="https://discord.postiz.com">Join Our Discord</a>
|
||||
·
|
||||
<a href="https://twitter.com/nevodavid">X</a>
|
||||
·
|
||||
<a href="https://gitroom.com">Gitroom</a>
|
||||
</p>
|
||||
|
||||
<br />
|
||||
|
||||
<p align="center">
|
||||
<a href="https://platform.postiz.com">Register</a>
|
||||
·
|
||||
<a href="https://discord.postiz.com">Join Our Discord (devs only)</a>
|
||||
·
|
||||
<a href="https://docs.postiz.com/public-api">Public API</a><br />
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/@postiz/node">NodeJS SDK</a>
|
||||
·
|
||||
<a href="https://www.npmjs.com/package/n8n-nodes-postiz">N8N custom node</a>
|
||||
·
|
||||
<a href="https://apps.make.com/postiz">Make.com integration</a>
|
||||
</p>
|
||||
|
||||
<br /><br />
|
||||
|
||||
## 🔌 See the leading Postiz features
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.youtube.com/watch?v=BdsCVvEYgHU" target="_blank">
|
||||
<img alt="Postiz" src="https://github.com/user-attachments/assets/8b9b7939-da1a-4be5-95be-42c6fce772de" />
|
||||
</a>
|
||||
<video src="https://github.com/user-attachments/assets/05436a01-19c8-4827-b57f-05a5e7637a67" width="100%" />
|
||||
</p>
|
||||
|
||||
## ✨ Features
|
||||
|
||||
|  |  |
|
||||
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
|--------------------------------|--------------------------------|
|
||||
|  |  |
|
||||
|
||||
### Our Sponsors
|
||||
|
||||
| Sponsor | Logo | Description |
|
||||
|---------|:-----------------------------------------------------------------------:|-----------------|
|
||||
| [Hostinger](https://www.hostinger.com/vps/docker/postiz?ref=postiz) | <img src=".github/sponsors/hostinger.png" alt="Hostinger" width="500"/> | Hostinger is on a mission to make online success possible for anyone – from developers to aspiring bloggers and business owners |
|
||||
| [Virlo](https://dev.virlo.ai/?ref=postiz) | <img src="https://github.com/user-attachments/assets/25182598-5344-45fc-b9cd-e4cfa16aabfd" alt="Virlo" width="500"/> | Virlo is the #1 social media trend spotting and all-in-one GTM tool for teams leveraging short-form video |
|
||||
|
||||
|
||||
|
||||
# Intro
|
||||
|
||||
- Schedule all your social media posts (many AI features)
|
||||
|
|
@ -97,49 +85,30 @@
|
|||
- Collaborate with other team members to exchange or buy posts.
|
||||
- Invite your team members to collaborate, comment, and schedule posts.
|
||||
- At the moment there is no difference between the hosted version to the self-hosted version
|
||||
- Perfect for automation (API) with platforms like N8N, Make.com, Zapier, etc.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Pnpm workspaces (Monorepo)
|
||||
- NX (Monorepo)
|
||||
- NextJS (React)
|
||||
- NestJS
|
||||
- Prisma (Default to PostgreSQL)
|
||||
- Temporal
|
||||
- Redis (BullMQ)
|
||||
- Resend (email notifications)
|
||||
|
||||
## Quick Start
|
||||
|
||||
To have the project up and running, please follow the [Quick Start Guide](https://docs.postiz.com/quickstart)
|
||||
|
||||
## Sponsor Postiz
|
||||
##
|
||||
|
||||
We now give a few options to Sponsor Postiz:
|
||||
- Just a donation: You like what we are building, and want to buy us some coffees so we can build faster.
|
||||
- Main Repository: Get your logo with a backlink from the main Postiz repository. Postiz has almost 3m downloads and 20k views per month.
|
||||
- Main Repository + Website: Get your logo on the central repository and the main website. Here are some metrics: - Website has 20k hits per month + 65 DR (strong backlink) - Repository has 20k hits per month + Almost 3m docker downloads.
|
||||
|
||||
Link: https://opencollective.com/postiz
|
||||
# License
|
||||
|
||||
## Postiz Compliance
|
||||
|
||||
- Postiz is an open-source, self-hosted social media scheduling tool that supports platforms like X (formerly Twitter), Bluesky, Mastodon, Discord, and others.
|
||||
- Postiz hosted service uses official, platform-approved OAuth flows.
|
||||
- Postiz does not automate or scrape content from social media platforms.
|
||||
- Postiz does not collect, store, or proxy API keys or access tokens from users.
|
||||
- Postiz never ask users to paste API keys into our hosted product.
|
||||
- Postiz Users always authenticate directly with the social platform (e.g., X, Discord, etc.), ensuring platform compliance and data privacy.
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://www.star-history.com/#gitroomhq/postiz-app&type=date&legend=top-left)
|
||||
|
||||
## License
|
||||
|
||||
This repository's source code is available under the [AGPL-3.0 license](LICENSE).
|
||||
This repository's source code is available under the [Apache 2.0 License](LICENSE).
|
||||
|
||||
<br /><br /><br />
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.g2.com/products/postiz/take_survey" target="blank"><img alt="g2" src="https://github.com/user-attachments/assets/892cb74c-0b49-4589-b2f5-fbdbf7a98f66" /></a>
|
||||
</p>
|
||||
|
||||
|
||||
|
|
|
|||
69
SECURITY.md
69
SECURITY.md
|
|
@ -1,69 +0,0 @@
|
|||
# Security Policy
|
||||
|
||||
## Introduction
|
||||
|
||||
The Postiz app is committed to ensuring the security and integrity of our users' data. This security policy outlines our procedures for handling security vulnerabilities and our disclosure policy.
|
||||
|
||||
## Scope
|
||||
|
||||
We, at Postiz (gitroomhq), cover the following scopes for vulnerability disclosures:
|
||||
|
||||
- The core repository for `postiz-app` (github.com/gitroomhq/postiz-app)
|
||||
- All `gitroomhq` repositories that are official components, tooling, or integrations of Postiz
|
||||
- Official Postiz container images published under `gitroomhq` on GHCR
|
||||
- Official Postiz CLI tools and NPM packages (NPM org: @postiz)
|
||||
- Postiz-Cloud related infrastructure & services. (API, Frontend, Configurations etc.)
|
||||
- Plugins for Postiz maintained within the `gitroomhq` organization
|
||||
|
||||
Vulnerabilities in third-party dependencies or user-hosted infrastructure are outside of this scope.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
This project currently only supports the latest release. We recommend that users always use the latest version of the Postiz app to ensure they have the latest security patches.
|
||||
*CVE IDs will only be assigned to vulnerabilities affecting currently supported versions.*
|
||||
|
||||
## Reporting Security Vulnerabilities
|
||||
|
||||
If you discover a security vulnerability in the Postiz app, please report it through the [GitHub Security Advisory system](https://github.com/gitroomhq/postiz-app/security/advisories/new).
|
||||
|
||||
When reporting a security vulnerability, please provide as much detail as possible, including:
|
||||
|
||||
- A clear description of the vulnerability
|
||||
- Proof of concept (PoC), where possible
|
||||
- Steps to reproduce the vulnerability
|
||||
- Any relevant code or configuration files
|
||||
|
||||
If the report has immediate urgency, please contact one (or more) of the maintainers via email:
|
||||
|
||||
- @egelhaus ([E-Mail](mailto:egelhaus@ennogelhaus.de))
|
||||
|
||||
### AI Reports
|
||||
|
||||
Reports that appear to be LLM-generated without meaningful human analysis — typically lacking a working proof of concept, reproducible steps, or accurate impact assessment — will be closed without detailed response.
|
||||
|
||||
Reports that include AI-assisted analysis are welcome provided they have been validated by the reporter and include a proof of concept, reproduction steps, and impact assessment.
|
||||
|
||||
## Disclosure Guidelines
|
||||
|
||||
We follow a private disclosure policy. If you discover a security vulnerability, please report it to us privately via GitHub Security Advisories, and if immediate urgency, via email as listed above. We will respond promptly to reports of vulnerabilities and work to resolve them as quickly as possible.
|
||||
|
||||
We will not publicly disclose security vulnerabilities until a patch or fix is available to prevent malicious actors from exploiting the vulnerability before a fix is released.
|
||||
|
||||
## Security Vulnerability Response Process
|
||||
|
||||
We take security vulnerabilities seriously and will respond promptly to reports of vulnerabilities. Our response process includes:
|
||||
|
||||
- Investigating the report and verifying the vulnerability.
|
||||
- Developing a patch or fix for the vulnerability.
|
||||
- Releasing the patch or fix as soon as possible.
|
||||
- Notifying users of the vulnerability and the patch or fix.
|
||||
|
||||
## Response Timelines
|
||||
|
||||
We aim to follow these timelines:
|
||||
|
||||
- **Initial Acknowledgment:** Within 72 hours of initial report.
|
||||
- **Completed Triage / Verification:** Within 7 days of initial acknowledgment.
|
||||
- **Critical Issue Remediation:** Within 90 days of completed triage.
|
||||
- **Non-Critical Issue Remediation:** Within 180 days of completed triage.
|
||||
- **CVE Publication:** Within 24 hours of remediation release.
|
||||
18
apps/backend/.eslintrc.json
Normal file
18
apps/backend/.eslintrc.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"extends": ["../../.eslintrc.json"],
|
||||
"ignorePatterns": ["!**/*"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.ts", "*.tsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.js", "*.jsx"],
|
||||
"rules": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
8
apps/backend/.gitignore
vendored
8
apps/backend/.gitignore
vendored
|
|
@ -1,8 +0,0 @@
|
|||
dist/
|
||||
node_modules/
|
||||
[._]*.s[a-v][a-z]
|
||||
[._]*.sw[a-p]
|
||||
[._]s[a-rt-v][a-z]
|
||||
[._]ss[a-gi-z]
|
||||
[._]sw[a-p]
|
||||
|
||||
11
apps/backend/jest.config.ts
Normal file
11
apps/backend/jest.config.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/* eslint-disable */
|
||||
export default {
|
||||
displayName: 'backend',
|
||||
preset: '../../jest.preset.js',
|
||||
testEnvironment: 'node',
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../coverage/apps/backend',
|
||||
};
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"monorepo": false,
|
||||
"sourceRoot": "src",
|
||||
"entryFile": "../../dist/backend/apps/backend/src/main",
|
||||
"language": "ts",
|
||||
"generateOptions": {
|
||||
"spec": false
|
||||
},
|
||||
"compilerOptions": {
|
||||
"manualRestart": true,
|
||||
"tsConfigPath": "./tsconfig.build.json",
|
||||
"webpack": false,
|
||||
"deleteOutDir": true,
|
||||
"assets": [],
|
||||
"watchAssets": false,
|
||||
"plugins": []
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"name": "postiz-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"scripts": {
|
||||
"dev": "dotenv -e ../../.env -- nest start --watch --entryFile=./apps/backend/src/main",
|
||||
"build": "cross-env NODE_ENV=production nest build",
|
||||
"start": "dotenv -e ../../.env -- node --experimental-require-module ./dist/apps/backend/src/main.js",
|
||||
"pm2": "pm2 start pnpm --name backend -- start"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC"
|
||||
}
|
||||
65
apps/backend/project.json
Normal file
65
apps/backend/project.json
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
{
|
||||
"name": "backend",
|
||||
"$schema": "../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "apps/backend/src",
|
||||
"projectType": "application",
|
||||
"targets": {
|
||||
"build": {
|
||||
"executor": "@nx/webpack:webpack",
|
||||
"outputs": ["{options.outputPath}"],
|
||||
"defaultConfiguration": "production",
|
||||
"options": {
|
||||
"target": "node",
|
||||
"compiler": "tsc",
|
||||
"outputPath": "dist/apps/backend",
|
||||
"main": "apps/backend/src/main.ts",
|
||||
"tsConfig": "apps/backend/tsconfig.app.json",
|
||||
"assets": ["apps/backend/src/assets"],
|
||||
"webpackConfig": "apps/backend/webpack.config.js",
|
||||
"transformers": [
|
||||
{
|
||||
"name": "@nestjs/swagger/plugin",
|
||||
"options": {
|
||||
"dtoFileNameSuffix": [".dto.ts"],
|
||||
"controllerFileNameSuffix": [".controller.ts"],
|
||||
"introspectComments": true,
|
||||
"classValidatorShim": true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"configurations": {
|
||||
"development": {},
|
||||
"production": {}
|
||||
}
|
||||
},
|
||||
"serve": {
|
||||
"executor": "@nx/js:node",
|
||||
"defaultConfiguration": "development",
|
||||
"options": {
|
||||
"buildTarget": "backend:build",
|
||||
"inspect": false
|
||||
},
|
||||
"configurations": {
|
||||
"development": {
|
||||
"buildTarget": "backend:build:development"
|
||||
},
|
||||
"production": {
|
||||
"buildTarget": "backend:build:production"
|
||||
}
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": ["{options.outputFile}"]
|
||||
},
|
||||
"test": {
|
||||
"executor": "@nx/jest:jest",
|
||||
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
|
||||
"options": {
|
||||
"jestConfig": "apps/backend/jest.config.ts"
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": []
|
||||
}
|
||||
|
|
@ -11,39 +11,22 @@ import { PermissionsService } from '@gitroom/backend/services/auth/permissions/p
|
|||
import { IntegrationsController } from '@gitroom/backend/api/routes/integrations.controller';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { SettingsController } from '@gitroom/backend/api/routes/settings.controller';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { PostsController } from '@gitroom/backend/api/routes/posts.controller';
|
||||
import { MediaController } from '@gitroom/backend/api/routes/media.controller';
|
||||
import { UploadModule } from '@gitroom/nestjs-libraries/upload/upload.module';
|
||||
import { ServeStaticModule } from '@nestjs/serve-static';
|
||||
import { CommentsController } from '@gitroom/backend/api/routes/comments.controller';
|
||||
import { BillingController } from '@gitroom/backend/api/routes/billing.controller';
|
||||
import { NotificationsController } from '@gitroom/backend/api/routes/notifications.controller';
|
||||
import { MarketplaceController } from '@gitroom/backend/api/routes/marketplace.controller';
|
||||
import { MessagesController } from '@gitroom/backend/api/routes/messages.controller';
|
||||
import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';
|
||||
import { ExtractContentService } from '@gitroom/nestjs-libraries/openai/extract.content.service';
|
||||
import { CodesService } from '@gitroom/nestjs-libraries/services/codes.service';
|
||||
import { CopilotController } from '@gitroom/backend/api/routes/copilot.controller';
|
||||
import { AgenciesController } from '@gitroom/backend/api/routes/agencies.controller';
|
||||
import { PublicController } from '@gitroom/backend/api/routes/public.controller';
|
||||
import { RootController } from '@gitroom/backend/api/routes/root.controller';
|
||||
import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';
|
||||
import { ShortLinkService } from '@gitroom/nestjs-libraries/short-linking/short.link.service';
|
||||
import { Nowpayments } from '@gitroom/nestjs-libraries/crypto/nowpayments';
|
||||
import { WebhookController } from '@gitroom/backend/api/routes/webhooks.controller';
|
||||
import { SignatureController } from '@gitroom/backend/api/routes/signature.controller';
|
||||
import { AutopostController } from '@gitroom/backend/api/routes/autopost.controller';
|
||||
import { SetsController } from '@gitroom/backend/api/routes/sets.controller';
|
||||
import { ThirdPartyController } from '@gitroom/backend/api/routes/third-party.controller';
|
||||
import { MonitorController } from '@gitroom/backend/api/routes/monitor.controller';
|
||||
import { NoAuthIntegrationsController } from '@gitroom/backend/api/routes/no.auth.integrations.controller';
|
||||
import { EnterpriseController } from '@gitroom/backend/api/routes/enterprise.controller';
|
||||
import { OAuthAppController } from '@gitroom/backend/api/routes/oauth-app.controller';
|
||||
import { ApprovedAppsController } from '@gitroom/backend/api/routes/approved-apps.controller';
|
||||
import { OAuthController, OAuthAuthorizedController } from '@gitroom/backend/api/routes/oauth.controller';
|
||||
import { AnnouncementsController } from '@gitroom/backend/api/routes/announcements.controller';
|
||||
import { AdminController } from '@gitroom/backend/api/routes/admin.controller';
|
||||
import { AuthProviderManager } from '@gitroom/backend/services/auth/providers/providers.manager';
|
||||
import { GithubProvider } from '@gitroom/backend/services/auth/providers/github.provider';
|
||||
import { GoogleProvider } from '@gitroom/backend/services/auth/providers/google.provider';
|
||||
import { FarcasterProvider } from '@gitroom/backend/services/auth/providers/farcaster.provider';
|
||||
import { WalletProvider } from '@gitroom/backend/services/auth/providers/wallet.provider';
|
||||
import { OauthProvider } from '@gitroom/backend/services/auth/providers/oauth.provider';
|
||||
|
||||
const authenticatedController = [
|
||||
UsersController,
|
||||
|
|
@ -52,31 +35,34 @@ const authenticatedController = [
|
|||
SettingsController,
|
||||
PostsController,
|
||||
MediaController,
|
||||
CommentsController,
|
||||
BillingController,
|
||||
NotificationsController,
|
||||
MarketplaceController,
|
||||
MessagesController,
|
||||
CopilotController,
|
||||
WebhookController,
|
||||
SignatureController,
|
||||
AutopostController,
|
||||
SetsController,
|
||||
ThirdPartyController,
|
||||
OAuthAppController,
|
||||
ApprovedAppsController,
|
||||
OAuthAuthorizedController,
|
||||
AnnouncementsController,
|
||||
AdminController,
|
||||
AgenciesController,
|
||||
];
|
||||
@Module({
|
||||
imports: [UploadModule],
|
||||
imports: [
|
||||
UploadModule,
|
||||
...(!!process.env.UPLOAD_DIRECTORY &&
|
||||
!!process.env.NEXT_PUBLIC_UPLOAD_STATIC_DIRECTORY
|
||||
? [
|
||||
ServeStaticModule.forRoot({
|
||||
rootPath: process.env.UPLOAD_DIRECTORY,
|
||||
serveRoot: '/' + process.env.NEXT_PUBLIC_UPLOAD_STATIC_DIRECTORY,
|
||||
serveStaticOptions: {
|
||||
index: false,
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
controllers: [
|
||||
RootController,
|
||||
StripeController,
|
||||
AuthController,
|
||||
PublicController,
|
||||
MonitorController,
|
||||
EnterpriseController,
|
||||
NoAuthIntegrationsController,
|
||||
OAuthController,
|
||||
...authenticatedController,
|
||||
],
|
||||
providers: [
|
||||
|
|
@ -89,15 +75,6 @@ const authenticatedController = [
|
|||
PermissionsService,
|
||||
CodesService,
|
||||
IntegrationManager,
|
||||
TrackService,
|
||||
ShortLinkService,
|
||||
Nowpayments,
|
||||
AuthProviderManager,
|
||||
GithubProvider,
|
||||
GoogleProvider,
|
||||
FarcasterProvider,
|
||||
WalletProvider,
|
||||
OauthProvider,
|
||||
],
|
||||
get exports() {
|
||||
return [...this.imports, ...this.providers];
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { ErrorsService } from '@gitroom/nestjs-libraries/database/prisma/errors/errors.service';
|
||||
|
||||
@ApiTags('Admin')
|
||||
@Controller('/admin')
|
||||
export class AdminController {
|
||||
constructor(private _errorsService: ErrorsService) {}
|
||||
|
||||
private assertSuperAdmin(user: User) {
|
||||
if (!user?.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/errors')
|
||||
async listErrors(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('platform') platform?: string,
|
||||
@Query('email') email?: string,
|
||||
@Query('unknownFirst') unknownFirst?: string
|
||||
) {
|
||||
this.assertSuperAdmin(user);
|
||||
return this._errorsService.listErrors({
|
||||
page: page ? parseInt(page, 10) : 0,
|
||||
limit: limit ? parseInt(limit, 10) : 20,
|
||||
platform: platform || undefined,
|
||||
email: email || undefined,
|
||||
unknownFirst: unknownFirst === 'true' || unknownFirst === '1',
|
||||
});
|
||||
}
|
||||
|
||||
@Get('/errors/platforms')
|
||||
async listPlatforms(@GetUserFromRequest() user: User) {
|
||||
this.assertSuperAdmin(user);
|
||||
return this._errorsService.listPlatforms();
|
||||
}
|
||||
}
|
||||
37
apps/backend/src/api/routes/agencies.controller.ts
Normal file
37
apps/backend/src/api/routes/agencies.controller.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AgenciesService } from '@gitroom/nestjs-libraries/database/prisma/agencies/agencies.service';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { CreateAgencyDto } from '@gitroom/nestjs-libraries/dtos/agencies/create.agency.dto';
|
||||
|
||||
@ApiTags('Agencies')
|
||||
@Controller('/agencies')
|
||||
export class AgenciesController {
|
||||
constructor(private _agenciesService: AgenciesService) {}
|
||||
@Get('/')
|
||||
async getAgencyByUser(@GetUserFromRequest() user: User) {
|
||||
return (await this._agenciesService.getAgencyByUser(user)) || {};
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createAgency(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: CreateAgencyDto
|
||||
) {
|
||||
return this._agenciesService.createAgency(user, body);
|
||||
}
|
||||
|
||||
@Post('/action/:action/:id')
|
||||
async updateAgency(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('action') action: string,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
return 400;
|
||||
}
|
||||
|
||||
return this._agenciesService.approveOrDecline(user.email, action, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +1,60 @@
|
|||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Inject,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { StarsService } from '@gitroom/nestjs-libraries/database/prisma/stars/stars.service';
|
||||
import dayjs from 'dayjs';
|
||||
import { StarsListDto } from '@gitroom/nestjs-libraries/dtos/analytics/stars.list.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
import { timer } from '@gitroom/helpers/utils/timer';
|
||||
|
||||
@ApiTags('Analytics')
|
||||
@Controller('/analytics')
|
||||
export class AnalyticsController {
|
||||
constructor(
|
||||
private _starsService: StarsService,
|
||||
private _integrationService: IntegrationService,
|
||||
private _postsService: PostsService
|
||||
private _integrationManager: IntegrationManager
|
||||
) {}
|
||||
@Get('/')
|
||||
async getStars(@GetOrgFromRequest() org: Organization) {
|
||||
return this._starsService.getStars(org.id);
|
||||
}
|
||||
|
||||
@Get('/trending')
|
||||
async getTrending() {
|
||||
const todayTrending = dayjs(dayjs().format('YYYY-MM-DDT12:00:00'));
|
||||
const last = todayTrending.isAfter(dayjs())
|
||||
? todayTrending.subtract(1, 'day')
|
||||
: todayTrending;
|
||||
const nextTrending = last.add(1, 'day');
|
||||
|
||||
return {
|
||||
last: last.format('YYYY-MM-DD HH:mm:ss'),
|
||||
predictions: nextTrending.format('YYYY-MM-DD HH:mm:ss'),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/stars')
|
||||
async getStarsFilter(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() starsFilter: StarsListDto
|
||||
) {
|
||||
return {
|
||||
stars: await this._starsService.getStarsFilter(org.id, starsFilter),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/:integration')
|
||||
async getIntegration(
|
||||
|
|
@ -21,13 +64,4 @@ export class AnalyticsController {
|
|||
) {
|
||||
return this._integrationService.checkAnalytics(org, integration, date);
|
||||
}
|
||||
|
||||
@Get('/post/:postId')
|
||||
async getPostAnalytics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('postId') postId: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
return this._postsService.checkPostAnalytics(org.id, postId, +date);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AnnouncementsService } from '@gitroom/nestjs-libraries/database/prisma/announcements/announcements.service';
|
||||
import { AnnouncementDto } from '@gitroom/nestjs-libraries/dtos/announcements/announcements.dto';
|
||||
|
||||
@ApiTags('Announcements')
|
||||
@Controller('/announcements')
|
||||
export class AnnouncementsController {
|
||||
constructor(private _announcementsService: AnnouncementsService) {}
|
||||
|
||||
@Get('/')
|
||||
async getAnnouncements() {
|
||||
return this._announcementsService.getAnnouncements();
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createAnnouncement(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: AnnouncementDto
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
return this._announcementsService.createAnnouncement(body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteAnnouncement(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
return this._announcementsService.deleteAnnouncement(id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
import { Controller, Delete, Get, Param } from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
|
||||
@ApiTags('Approved Apps')
|
||||
@Controller('/user/approved-apps')
|
||||
export class ApprovedAppsController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Get('/')
|
||||
async list(@GetUserFromRequest() user: User) {
|
||||
return this._oauthService.getApprovedApps(user.id);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async revoke(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._oauthService.revokeApp(user.id, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,13 +1,4 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, Req, Res } from '@nestjs/common';
|
||||
import { Response, Request } from 'express';
|
||||
|
||||
import { CreateOrgUserDto } from '@gitroom/nestjs-libraries/dtos/auth/create.org.user.dto';
|
||||
|
|
@ -15,37 +6,18 @@ import { LoginUserDto } from '@gitroom/nestjs-libraries/dtos/auth/login.user.dto
|
|||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { ForgotReturnPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot-return.password.dto';
|
||||
import { ForgotPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot.password.dto';
|
||||
import { ResendActivationDto } from '@gitroom/nestjs-libraries/dtos/auth/resend-activation.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { EmailService } from '@gitroom/nestjs-libraries/services/email.service';
|
||||
import { RealIP } from 'nestjs-real-ip';
|
||||
import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';
|
||||
import { Provider } from '@prisma/client';
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@Controller('/auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private _authService: AuthService,
|
||||
private _emailService: EmailService
|
||||
) {}
|
||||
|
||||
@Get('/can-register')
|
||||
async canRegister() {
|
||||
return {
|
||||
register: await this._authService.canRegister(Provider.LOCAL as string),
|
||||
};
|
||||
}
|
||||
|
||||
constructor(private _authService: AuthService) {}
|
||||
@Post('/register')
|
||||
async register(
|
||||
@Req() req: Request,
|
||||
@Body() body: CreateOrgUserDto,
|
||||
@Res({ passthrough: false }) response: Response,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
try {
|
||||
const getOrgFromCookie = this._authService.getOrgFromCookie(
|
||||
|
|
@ -55,15 +27,10 @@ export class AuthController {
|
|||
const { jwt, addedOrg } = await this._authService.routeAuth(
|
||||
body.provider,
|
||||
body,
|
||||
ip,
|
||||
userAgent,
|
||||
getOrgFromCookie
|
||||
);
|
||||
|
||||
const activationRequired =
|
||||
body.provider === 'LOCAL' && this._emailService.hasProvider();
|
||||
|
||||
if (activationRequired) {
|
||||
if (body.provider === 'LOCAL') {
|
||||
response.header('activate', 'true');
|
||||
response.status(200).json({ activate: true });
|
||||
return;
|
||||
|
|
@ -71,44 +38,27 @@ export class AuthController {
|
|||
|
||||
response.cookie('auth', jwt, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', jwt);
|
||||
}
|
||||
|
||||
if (typeof addedOrg !== 'boolean' && addedOrg?.organizationId) {
|
||||
response.cookie('showorg', addedOrg.organizationId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('showorg', addedOrg.organizationId);
|
||||
}
|
||||
}
|
||||
|
||||
Sentry.metrics.count('new_user', 1);
|
||||
response.header('onboarding', 'true');
|
||||
response.status(200).json({
|
||||
register: true,
|
||||
});
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
response.status(400).send(e.message);
|
||||
}
|
||||
}
|
||||
|
|
@ -117,9 +67,7 @@ export class AuthController {
|
|||
async login(
|
||||
@Req() req: Request,
|
||||
@Body() body: LoginUserDto,
|
||||
@Res({ passthrough: false }) response: Response,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
try {
|
||||
const getOrgFromCookie = this._authService.getOrgFromCookie(
|
||||
|
|
@ -129,50 +77,32 @@ export class AuthController {
|
|||
const { jwt, addedOrg } = await this._authService.routeAuth(
|
||||
body.provider,
|
||||
body,
|
||||
ip,
|
||||
userAgent,
|
||||
getOrgFromCookie
|
||||
);
|
||||
|
||||
response.cookie('auth', jwt, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', jwt);
|
||||
}
|
||||
|
||||
if (typeof addedOrg !== 'boolean' && addedOrg?.organizationId) {
|
||||
response.cookie('showorg', addedOrg.organizationId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('showorg', addedOrg.organizationId);
|
||||
}
|
||||
}
|
||||
|
||||
response.header('reload', 'true');
|
||||
response.status(200).json({
|
||||
login: true,
|
||||
});
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
response.status(400).send(e.message);
|
||||
}
|
||||
}
|
||||
|
|
@ -199,107 +129,52 @@ export class AuthController {
|
|||
};
|
||||
}
|
||||
|
||||
@Get('/oauth-mobile-callback')
|
||||
mobileCallback(
|
||||
@Query('code') code: string,
|
||||
@Query('state') state: string,
|
||||
@Res({ passthrough: false }) response: Response
|
||||
) {
|
||||
const scheme = process.env.MOBILE_APP_SCHEME || 'postiz://auth/callback';
|
||||
const params = new URLSearchParams();
|
||||
if (code) params.set('code', code);
|
||||
if (state) params.set('state', state);
|
||||
return response.redirect(302, `${scheme}?${params.toString()}`);
|
||||
}
|
||||
|
||||
@Get('/oauth/:provider')
|
||||
async oauthLink(@Param('provider') provider: string, @Query() query: any) {
|
||||
return this._authService.oauthLink(provider, query);
|
||||
async oauthLink(@Param('provider') provider: string) {
|
||||
return this._authService.oauthLink(provider);
|
||||
}
|
||||
|
||||
@Post('/activate')
|
||||
async activate(
|
||||
@Body('code') code: string,
|
||||
@Body('datafast_visitor_id') datafast_visitor_id: string,
|
||||
@Res({ passthrough: false }) response: Response
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
const activate = await this._authService.activate(
|
||||
code,
|
||||
datafast_visitor_id
|
||||
);
|
||||
const activate = await this._authService.activate(code);
|
||||
if (!activate) {
|
||||
return response.status(200).json({ can: false });
|
||||
return response.status(200).send({ can: false });
|
||||
}
|
||||
|
||||
response.cookie('auth', activate, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', activate);
|
||||
}
|
||||
|
||||
response.header('onboarding', 'true');
|
||||
|
||||
return response.status(200).json({ can: true });
|
||||
}
|
||||
|
||||
@Post('/resend-activation')
|
||||
async resendActivation(@Body() body: ResendActivationDto) {
|
||||
try {
|
||||
await this._authService.resendActivationEmail(body.email);
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
} catch (e: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: e.message,
|
||||
};
|
||||
}
|
||||
return response.status(200).send({ can: true });
|
||||
}
|
||||
|
||||
@Post('/oauth/:provider/exists')
|
||||
async oauthExists(
|
||||
@Body('code') code: string,
|
||||
@Body('redirect_uri') redirect_uri: string,
|
||||
@Param('provider') provider: string,
|
||||
@Res({ passthrough: false }) response: Response
|
||||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
const { jwt, token } = await this._authService.checkExists(
|
||||
provider,
|
||||
code,
|
||||
redirect_uri
|
||||
);
|
||||
|
||||
const { jwt, token } = await this._authService.checkExists(provider, code);
|
||||
if (token) {
|
||||
return response.json({ token });
|
||||
}
|
||||
|
||||
response.cookie('auth', jwt, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('auth', jwt);
|
||||
}
|
||||
|
||||
response.header('reload', 'true');
|
||||
|
||||
response.status(200).json({
|
||||
|
|
|
|||
|
|
@ -1,69 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { AutopostService } from '@gitroom/nestjs-libraries/database/prisma/autopost/autopost.service';
|
||||
import { AutopostDto } from '@gitroom/nestjs-libraries/dtos/autopost/autopost.dto';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
|
||||
|
||||
@ApiTags('Autopost')
|
||||
@Controller('/autopost')
|
||||
export class AutopostController {
|
||||
constructor(private _autopostsService: AutopostService) {}
|
||||
|
||||
@Get('/')
|
||||
async getAutoposts(@GetOrgFromRequest() org: Organization) {
|
||||
return this._autopostsService.getAutoposts(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.WEBHOOKS])
|
||||
async createAutopost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AutopostDto
|
||||
) {
|
||||
return this._autopostsService.createAutopost(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
async updateAutopost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AutopostDto,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._autopostsService.createAutopost(org.id, body, id);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteAutopost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._autopostsService.deleteAutopost(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/:id/active')
|
||||
async changeActive(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('active') active: boolean
|
||||
) {
|
||||
return this._autopostsService.changeActive(org.id, id, active);
|
||||
}
|
||||
|
||||
@Post('/send')
|
||||
async sendWebhook(@Query() query: OnlyURL) {
|
||||
return this._autopostsService.loadXML(query.url);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { Body, Controller, Get, HttpException, Param, Post, Req } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
|
|
@ -6,19 +6,13 @@ import { Organization, User } from '@prisma/client';
|
|||
import { BillingSubscribeDto } from '@gitroom/nestjs-libraries/dtos/billing/billing.subscribe.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { Request } from 'express';
|
||||
import { Nowpayments } from '@gitroom/nestjs-libraries/crypto/nowpayments';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
|
||||
@ApiTags('Billing')
|
||||
@Controller('/billing')
|
||||
export class BillingController {
|
||||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _stripeService: StripeService,
|
||||
private _notificationService: NotificationService,
|
||||
private _nowpayments: Nowpayments
|
||||
private _stripeService: StripeService
|
||||
) {}
|
||||
|
||||
@Get('/check/:id')
|
||||
|
|
@ -27,73 +21,19 @@ export class BillingController {
|
|||
@Param('id') body: string
|
||||
) {
|
||||
return {
|
||||
status: await this._stripeService.checkSubscription(org.id, body),
|
||||
exists: !!(await this._subscriptionService.checkSubscription(
|
||||
org.id,
|
||||
body
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/check-discount')
|
||||
async checkDiscount(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
offerCoupon: !(await this._stripeService.checkDiscount(org.paymentId))
|
||||
? false
|
||||
: AuthService.signJWT({ discount: true }),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/apply-discount')
|
||||
async applyDiscount(@GetOrgFromRequest() org: Organization) {
|
||||
await this._stripeService.applyDiscount(org.paymentId);
|
||||
}
|
||||
|
||||
@Post('/finish-trial')
|
||||
async finishTrial(@GetOrgFromRequest() org: Organization) {
|
||||
try {
|
||||
await this._stripeService.finishTrial(org.paymentId);
|
||||
} catch (err) {}
|
||||
return {
|
||||
finish: true,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/is-trial-finished')
|
||||
async isTrialFinished(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
finished: !org.isTrailing,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/embedded')
|
||||
embedded(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: BillingSubscribeDto,
|
||||
@Req() req: Request
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track;
|
||||
return this._stripeService.embedded(
|
||||
uniqueId,
|
||||
org.id,
|
||||
user.id,
|
||||
body,
|
||||
org.allowTrial
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/subscribe')
|
||||
subscribe(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: BillingSubscribeDto,
|
||||
@Req() req: Request
|
||||
@Body() body: BillingSubscribeDto
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track;
|
||||
return this._stripeService.subscribe(
|
||||
uniqueId,
|
||||
org.id,
|
||||
user.id,
|
||||
body,
|
||||
org.allowTrial
|
||||
);
|
||||
return this._stripeService.subscribe(org.id, body);
|
||||
}
|
||||
|
||||
@Get('/portal')
|
||||
|
|
@ -113,18 +53,7 @@ export class BillingController {
|
|||
}
|
||||
|
||||
@Post('/cancel')
|
||||
async cancel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: { feedback: string }
|
||||
) {
|
||||
await this._notificationService.sendEmail(
|
||||
process.env.EMAIL_FROM_ADDRESS,
|
||||
'Subscription Cancelled',
|
||||
`Organization ${org.name} has cancelled their subscription because: ${body.feedback}`,
|
||||
user.email
|
||||
);
|
||||
|
||||
cancel(@GetOrgFromRequest() org: Organization) {
|
||||
return this._stripeService.setToCancel(org.id);
|
||||
}
|
||||
|
||||
|
|
@ -144,43 +73,6 @@ export class BillingController {
|
|||
return this._stripeService.lifetimeDeal(org.id, body.code);
|
||||
}
|
||||
|
||||
@Get('/charges')
|
||||
async getCharges(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._stripeService.getCharges(org.id);
|
||||
}
|
||||
|
||||
@Post('/refund-charges')
|
||||
async refundCharges(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: { chargeIds: string[] }
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._stripeService.refundCharges(org.id, body.chargeIds);
|
||||
}
|
||||
|
||||
@Post('/cancel-subscription')
|
||||
async cancelSubscription(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Unauthorized', 400);
|
||||
}
|
||||
|
||||
return this._stripeService.cancelSubscription(org.id);
|
||||
}
|
||||
|
||||
@Post('/add-subscription')
|
||||
async addSubscription(
|
||||
@Body() body: { subscription: string },
|
||||
|
|
@ -191,15 +83,6 @@ export class BillingController {
|
|||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
await this._subscriptionService.addSubscription(
|
||||
org.id,
|
||||
user.id,
|
||||
body.subscription
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/crypto')
|
||||
async crypto(@GetOrgFromRequest() org: Organization) {
|
||||
return this._nowpayments.createPaymentPage(org.id);
|
||||
await this._subscriptionService.addSubscription(org.id, user.id, body.subscription);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
82
apps/backend/src/api/routes/comments.controller.ts
Normal file
82
apps/backend/src/api/routes/comments.controller.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import {Body, Controller, Delete, Get, Param, Post, Put} from '@nestjs/common';
|
||||
import { CommentsService } from '@gitroom/nestjs-libraries/database/prisma/comments/comments.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { AddCommentDto } from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
|
||||
import {ApiTags} from "@nestjs/swagger";
|
||||
|
||||
@ApiTags('Comments')
|
||||
@Controller('/comments')
|
||||
export class CommentsController {
|
||||
constructor(private _commentsService: CommentsService) {}
|
||||
|
||||
@Post('/')
|
||||
addComment(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() addCommentDto: AddCommentDto
|
||||
) {
|
||||
return this._commentsService.addAComment(
|
||||
org.id,
|
||||
user.id,
|
||||
addCommentDto.content,
|
||||
addCommentDto.date
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/:id')
|
||||
addCommentTocComment(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() addCommentDto: AddCommentDto,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._commentsService.addACommentToComment(
|
||||
org.id,
|
||||
user.id,
|
||||
id,
|
||||
addCommentDto.content,
|
||||
addCommentDto.date
|
||||
);
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
editComment(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() addCommentDto: AddCommentDto,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._commentsService.updateAComment(
|
||||
org.id,
|
||||
user.id,
|
||||
id,
|
||||
addCommentDto.content
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
deleteComment(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._commentsService.deleteAComment(
|
||||
org.id,
|
||||
user.id,
|
||||
id,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/:date')
|
||||
loadAllCommentsAndSubCommentsForADate(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('date') date: string
|
||||
) {
|
||||
return this._commentsService.loadAllCommentsAndSubCommentsForADate(
|
||||
org.id,
|
||||
date
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,154 +1,37 @@
|
|||
import {
|
||||
Logger,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Req,
|
||||
Res,
|
||||
Query,
|
||||
Param,
|
||||
} from '@nestjs/common';
|
||||
import { Controller, Get, Post, Req, Res } from '@nestjs/common';
|
||||
import {
|
||||
CopilotRuntime,
|
||||
OpenAIAdapter,
|
||||
copilotRuntimeNodeHttpEndpoint,
|
||||
copilotRuntimeNextJSAppRouterEndpoint,
|
||||
copilotRuntimeNestEndpoint,
|
||||
} from '@copilotkit/runtime';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { MastraAgent } from '@ag-ui/mastra';
|
||||
import { MastraService } from '@gitroom/nestjs-libraries/chat/mastra.service';
|
||||
import { Request, Response } from 'express';
|
||||
import { RequestContext } from '@mastra/core/di';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
export type ChannelsContext = {
|
||||
integrations: string;
|
||||
organization: string;
|
||||
ui: string;
|
||||
};
|
||||
|
||||
@Controller('/copilot')
|
||||
export class CopilotController {
|
||||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _mastraService: MastraService
|
||||
) {}
|
||||
constructor(private _subscriptionService: SubscriptionService) {}
|
||||
@Post('/chat')
|
||||
chatAgent(@Req() req: Request, @Res() res: Response) {
|
||||
if (
|
||||
process.env.OPENAI_API_KEY === undefined ||
|
||||
process.env.OPENAI_API_KEY === ''
|
||||
) {
|
||||
Logger.warn('OpenAI API key not set, chat functionality will not work');
|
||||
return;
|
||||
}
|
||||
|
||||
const copilotRuntimeHandler = copilotRuntimeNodeHttpEndpoint({
|
||||
chat(@Req() req: Request, @Res() res: Response) {
|
||||
const copilotRuntimeHandler = copilotRuntimeNestEndpoint({
|
||||
endpoint: '/copilot/chat',
|
||||
runtime: new CopilotRuntime(),
|
||||
serviceAdapter: new OpenAIAdapter({
|
||||
model: 'gpt-4.1',
|
||||
model:
|
||||
// @ts-ignore
|
||||
req?.body?.variables?.data?.metadata?.requestType ===
|
||||
'TextareaCompletion'
|
||||
? 'gpt-4o-mini'
|
||||
: 'gpt-4o-2024-08-06',
|
||||
}),
|
||||
});
|
||||
|
||||
// @ts-ignore
|
||||
return copilotRuntimeHandler(req, res);
|
||||
}
|
||||
|
||||
@Post('/agent')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.AI])
|
||||
async agent(
|
||||
@Req() req: Request,
|
||||
@Res() res: Response,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
if (
|
||||
process.env.OPENAI_API_KEY === undefined ||
|
||||
process.env.OPENAI_API_KEY === ''
|
||||
) {
|
||||
Logger.warn('OpenAI API key not set, chat functionality will not work');
|
||||
return;
|
||||
}
|
||||
const mastra = await this._mastraService.mastra();
|
||||
const requestContext = new RequestContext<ChannelsContext>();
|
||||
requestContext.set(
|
||||
'integrations',
|
||||
req?.body?.variables?.properties?.integrations || []
|
||||
);
|
||||
|
||||
requestContext.set('organization', JSON.stringify(organization));
|
||||
requestContext.set('ui', 'true');
|
||||
|
||||
const agents = MastraAgent.getLocalAgents({
|
||||
resourceId: organization.id,
|
||||
mastra,
|
||||
requestContext: requestContext as any,
|
||||
});
|
||||
|
||||
const runtime = new CopilotRuntime({
|
||||
agents,
|
||||
});
|
||||
|
||||
const copilotRuntimeHandler = copilotRuntimeNextJSAppRouterEndpoint({
|
||||
endpoint: '/copilot/agent',
|
||||
runtime,
|
||||
// properties: req.body.variables.properties,
|
||||
serviceAdapter: new OpenAIAdapter({
|
||||
model: 'gpt-4.1',
|
||||
}),
|
||||
});
|
||||
|
||||
return copilotRuntimeHandler.handleRequest(req, res);
|
||||
}
|
||||
|
||||
@Get('/credits')
|
||||
calculateCredits(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Query('type') type: 'ai_images' | 'ai_videos'
|
||||
) {
|
||||
return this._subscriptionService.checkCredits(
|
||||
organization,
|
||||
type || 'ai_images'
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/:thread/list')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.AI])
|
||||
async getMessagesList(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('thread') threadId: string
|
||||
): Promise<any> {
|
||||
const mastra = await this._mastraService.mastra();
|
||||
const memory = await mastra.getAgent('postiz').getMemory();
|
||||
try {
|
||||
return await memory.recall({
|
||||
resourceId: organization.id,
|
||||
threadId,
|
||||
});
|
||||
} catch (err) {
|
||||
return { messages: [] };
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.AI])
|
||||
async getList(@GetOrgFromRequest() organization: Organization) {
|
||||
const mastra = await this._mastraService.mastra();
|
||||
const memory = await mastra.getAgent('postiz').getMemory();
|
||||
const list = await memory.listThreads({
|
||||
filter: { resourceId: organization.id },
|
||||
perPage: 100000,
|
||||
page: 0,
|
||||
orderBy: { field: 'createdAt', direction: 'DESC' },
|
||||
});
|
||||
|
||||
return {
|
||||
threads: list.threads.map((p) => ({
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
})),
|
||||
};
|
||||
calculateCredits(@GetOrgFromRequest() organization: Organization) {
|
||||
return this._subscriptionService.checkCredits(organization);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,128 +0,0 @@
|
|||
import { Body, Controller, Param, Post, Res } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
|
||||
@ApiTags('Enterprise')
|
||||
@Controller('/enterprise')
|
||||
export class EnterpriseController {
|
||||
constructor(
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _organizationService: OrganizationService,
|
||||
private _integrationService: IntegrationService,
|
||||
private _postsService: PostsService
|
||||
) {}
|
||||
|
||||
@Post('/create-user')
|
||||
async createUser(@Body('params') params: string) {
|
||||
try {
|
||||
const { id, name, saasName, email } = AuthService.verifyJWT(params) as {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
saasName: string;
|
||||
};
|
||||
|
||||
try {
|
||||
return await this._organizationService.createMaxUser(
|
||||
id,
|
||||
name,
|
||||
saasName,
|
||||
email
|
||||
);
|
||||
} catch (err) {
|
||||
return { create: false };
|
||||
}
|
||||
} catch (err) {
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/url')
|
||||
async redirectParams(@Body('params') params: string) {
|
||||
try {
|
||||
const load = AuthService.verifyJWT(params) as {
|
||||
redirectUrl: string;
|
||||
apiKey: string;
|
||||
refreshId?: string;
|
||||
provider: string;
|
||||
webhookUrl: string;
|
||||
};
|
||||
|
||||
if (!load || !load.redirectUrl || !load.apiKey || !load.provider) {
|
||||
return;
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgByApiKey(load.apiKey);
|
||||
|
||||
if (!org) {
|
||||
throw new Error('Organization not found');
|
||||
}
|
||||
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(load.provider)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
const integrationProvider = this._integrationManager.getSocialIntegration(
|
||||
load.provider
|
||||
);
|
||||
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl();
|
||||
|
||||
if (load.refreshId) {
|
||||
await ioRedis.set(`refresh:${state}`, load.refreshId, 'EX', 3600);
|
||||
}
|
||||
|
||||
await ioRedis.set(`webhookUrl:${state}`, load.webhookUrl, 'EX', 3600);
|
||||
await ioRedis.set(`redirect:${state}`, load.redirectUrl, 'EX', 3600);
|
||||
await ioRedis.set(`organization:${state}`, org.id, 'EX', 3600);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 3600);
|
||||
|
||||
return url;
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
@Post('/delete-channel')
|
||||
async deleteChannel(@Body('params') params: string) {
|
||||
try {
|
||||
const load = AuthService.verifyJWT(params) as {
|
||||
apiKey: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
if (!load || !load.apiKey || !load.id) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgByApiKey(load.apiKey);
|
||||
|
||||
if (!org) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const isTherePosts = await this._integrationService.getPostsForChannel(
|
||||
org.id,
|
||||
load.id
|
||||
);
|
||||
if (isTherePosts.length) {
|
||||
for (const post of isTherePosts) {
|
||||
this._postsService.deletePost(org.id, post.group).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
await this._integrationService.deleteChannel(org.id, load.id);
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,33 +5,28 @@ import {
|
|||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { ConnectIntegrationDto } from '@gitroom/nestjs-libraries/dtos/integrations/connect.integration.dto';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { ApiKeyDto } from '@gitroom/nestjs-libraries/dtos/integrations/api.key.dto';
|
||||
import { IntegrationFunctionDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.function.dto';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { NotEnoughScopesFilter } from '@gitroom/nestjs-libraries/integrations/integration.missing.scopes';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { IntegrationTimeDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.time.dto';
|
||||
import { PlugDto } from '@gitroom/nestjs-libraries/dtos/plugs/plug.dto';
|
||||
import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
|
||||
import { timer } from '@gitroom/helpers/utils/timer';
|
||||
import { TelegramProvider } from '@gitroom/nestjs-libraries/integrations/social/telegram.provider';
|
||||
import { MoltbookProvider } from '@gitroom/nestjs-libraries/integrations/social/moltbook.provider';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { uniqBy } from 'lodash';
|
||||
import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
|
||||
|
||||
@ApiTags('Integrations')
|
||||
@Controller('/integrations')
|
||||
|
|
@ -39,142 +34,33 @@ export class IntegrationsController {
|
|||
constructor(
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _integrationService: IntegrationService,
|
||||
private _postService: PostsService,
|
||||
private _refreshIntegrationService: RefreshIntegrationService
|
||||
private _postService: PostsService
|
||||
) {}
|
||||
|
||||
@Post('/provider/:id/connect')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async saveProviderPage(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: any
|
||||
) {
|
||||
return this._integrationService.saveProviderPage(org.id, id, body);
|
||||
}
|
||||
|
||||
@Get('/:identifier/internal-plugs')
|
||||
getInternalPlugs(@Param('identifier') identifier: string) {
|
||||
return this._integrationManager.getInternalPlugs(identifier);
|
||||
}
|
||||
|
||||
@Get('/customers')
|
||||
getCustomers(@GetOrgFromRequest() org: Organization) {
|
||||
return this._integrationService.customers(org.id);
|
||||
}
|
||||
|
||||
@Put('/:id/group')
|
||||
async updateIntegrationGroup(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { group: string }
|
||||
) {
|
||||
return this._integrationService.updateIntegrationGroup(
|
||||
org.id,
|
||||
id,
|
||||
body.group
|
||||
);
|
||||
}
|
||||
|
||||
@Put('/:id/customer-name')
|
||||
async updateOnCustomerName(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { name: string }
|
||||
) {
|
||||
return this._integrationService.updateOnCustomerName(org.id, id, body.name);
|
||||
@Get('/')
|
||||
getIntegration() {
|
||||
return this._integrationManager.getAllIntegrations();
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
async getIntegrationList(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
integrations: await Promise.all(
|
||||
(
|
||||
await this._integrationService.getIntegrationsList(org.id)
|
||||
).map(async (p) => {
|
||||
const findIntegration = this._integrationManager.getSocialIntegration(
|
||||
p.providerIdentifier
|
||||
);
|
||||
return {
|
||||
name: p.name,
|
||||
id: p.id,
|
||||
internalId: p.internalId,
|
||||
disabled: p.disabled,
|
||||
editor: findIntegration.editor,
|
||||
stripLinks: !!findIntegration?.stripLinks?.(),
|
||||
picture: p.picture || '/no-picture.jpg',
|
||||
identifier: p.providerIdentifier,
|
||||
inBetweenSteps: p.inBetweenSteps,
|
||||
refreshNeeded: p.refreshNeeded,
|
||||
isCustomFields: !!findIntegration.customFields,
|
||||
...(findIntegration.customFields
|
||||
? { customFields: await findIntegration.customFields() }
|
||||
: {}),
|
||||
display: p.profile,
|
||||
type: p.type,
|
||||
time: JSON.parse(p.postingTimes),
|
||||
changeProfilePicture: !!findIntegration?.changeProfilePicture,
|
||||
changeNickName: !!findIntegration?.changeNickname,
|
||||
customer: p.customer,
|
||||
additionalSettings: p.additionalSettings || '[]',
|
||||
};
|
||||
})
|
||||
),
|
||||
integrations: (
|
||||
await this._integrationService.getIntegrationsList(org.id)
|
||||
).map((p) => ({
|
||||
name: p.name,
|
||||
id: p.id,
|
||||
internalId: p.internalId,
|
||||
disabled: p.disabled,
|
||||
picture: p.picture,
|
||||
identifier: p.providerIdentifier,
|
||||
inBetweenSteps: p.inBetweenSteps,
|
||||
refreshNeeded: p.refreshNeeded,
|
||||
type: p.type,
|
||||
time: JSON.parse(p.postingTimes)
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/:id/settings')
|
||||
async updateProviderSettings(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('additionalSettings') body: string
|
||||
) {
|
||||
if (typeof body !== 'string') {
|
||||
throw new Error('Invalid body');
|
||||
}
|
||||
|
||||
await this._integrationService.updateProviderSettings(org.id, id, body);
|
||||
}
|
||||
@Post('/:id/nickname')
|
||||
async setNickname(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { name: string; picture: string }
|
||||
) {
|
||||
const integration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
if (!integration) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
const manager = this._integrationManager.getSocialIntegration(
|
||||
integration.providerIdentifier
|
||||
);
|
||||
if (!manager.changeProfilePicture && !manager.changeNickname) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
const { url } = manager.changeProfilePicture
|
||||
? await manager.changeProfilePicture(
|
||||
integration.internalId,
|
||||
integration.token,
|
||||
body.picture
|
||||
)
|
||||
: { url: '' };
|
||||
|
||||
const { name } = manager.changeNickname
|
||||
? await manager.changeNickname(
|
||||
integration.internalId,
|
||||
integration.token,
|
||||
body.name
|
||||
)
|
||||
: { name: '' };
|
||||
|
||||
return this._integrationService.updateNameAndUrl(id, name, url);
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
getSingleIntegration(
|
||||
@Param('id') id: string,
|
||||
|
|
@ -194,11 +80,7 @@ export class IntegrationsController {
|
|||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async getIntegrationUrl(
|
||||
@Param('integration') integration: string,
|
||||
@Query('refresh') refresh: string,
|
||||
@Query('externalUrl') externalUrl: string,
|
||||
@Query('redirectUrl') redirectUrl: string,
|
||||
@Query('onboarding') onboarding: string,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
@Query('refresh') refresh: string
|
||||
) {
|
||||
if (
|
||||
!this._integrationManager
|
||||
|
|
@ -210,47 +92,11 @@ export class IntegrationsController {
|
|||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl(refresh);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 300);
|
||||
|
||||
if (integrationProvider.externalUrl && !externalUrl) {
|
||||
throw new Error('Missing external url');
|
||||
}
|
||||
|
||||
try {
|
||||
const getExternalUrl = integrationProvider.externalUrl
|
||||
? {
|
||||
...(await integrationProvider.externalUrl(externalUrl)),
|
||||
instanceUrl: externalUrl,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl(getExternalUrl);
|
||||
|
||||
if (refresh) {
|
||||
await ioRedis.set(`refresh:${state}`, refresh, 'EX', 3600);
|
||||
}
|
||||
|
||||
if (onboarding === 'true') {
|
||||
await ioRedis.set(`onboarding:${state}`, 'true', 'EX', 3600);
|
||||
}
|
||||
|
||||
if (redirectUrl) {
|
||||
await ioRedis.set(`redirect:${state}`, redirectUrl, 'EX', 3600);
|
||||
}
|
||||
|
||||
await ioRedis.set(`organization:${state}`, org.id, 'EX', 3600);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 3600);
|
||||
await ioRedis.set(
|
||||
`external:${state}`,
|
||||
JSON.stringify(getExternalUrl),
|
||||
'EX',
|
||||
3600
|
||||
);
|
||||
|
||||
return { url };
|
||||
} catch (err) {
|
||||
return { err: true };
|
||||
}
|
||||
return { url };
|
||||
}
|
||||
|
||||
@Post('/:id/time')
|
||||
|
|
@ -261,9 +107,8 @@ export class IntegrationsController {
|
|||
) {
|
||||
return this._integrationService.setTimes(org.id, id, body);
|
||||
}
|
||||
|
||||
@Post('/mentions')
|
||||
async mentions(
|
||||
@Post('/function')
|
||||
async functionIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: IntegrationFunctionDto
|
||||
) {
|
||||
|
|
@ -275,107 +120,137 @@ export class IntegrationsController {
|
|||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
let newList: any[] | { none: true } = [];
|
||||
try {
|
||||
newList = (await this.functionIntegration(org, body)) || [];
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
if (!Array.isArray(newList) && newList?.none) {
|
||||
return newList;
|
||||
}
|
||||
|
||||
const list = await this._integrationService.getMentions(
|
||||
getIntegration.providerIdentifier,
|
||||
body?.data?.query
|
||||
);
|
||||
|
||||
if (Array.isArray(newList) && newList.length) {
|
||||
await this._integrationService.insertMentions(
|
||||
getIntegration.providerIdentifier,
|
||||
newList
|
||||
.map((p: any) => ({
|
||||
name: p.label || '',
|
||||
username: p.id || '',
|
||||
image: p.image || '',
|
||||
doNotCache: p.doNotCache || false,
|
||||
}))
|
||||
.filter((f: any) => f.name && !f.doNotCache)
|
||||
if (getIntegration.type === 'social') {
|
||||
const integrationProvider = this._integrationManager.getSocialIntegration(
|
||||
getIntegration.providerIdentifier
|
||||
);
|
||||
if (!integrationProvider) {
|
||||
throw new Error('Invalid provider');
|
||||
}
|
||||
|
||||
if (integrationProvider[body.name]) {
|
||||
return integrationProvider[body.name](getIntegration.token, body.data);
|
||||
}
|
||||
throw new Error('Function not found');
|
||||
}
|
||||
|
||||
return uniqBy(
|
||||
[
|
||||
...list.map((p) => ({
|
||||
id: p.username,
|
||||
image: p.image,
|
||||
label: p.name,
|
||||
})),
|
||||
...(newList as any[]),
|
||||
],
|
||||
(p) => p.id
|
||||
).filter((f) => f.label && f.id);
|
||||
if (getIntegration.type === 'article') {
|
||||
const integrationProvider =
|
||||
this._integrationManager.getArticlesIntegration(
|
||||
getIntegration.providerIdentifier
|
||||
);
|
||||
if (!integrationProvider) {
|
||||
throw new Error('Invalid provider');
|
||||
}
|
||||
|
||||
if (integrationProvider[body.name]) {
|
||||
return integrationProvider[body.name](getIntegration.token, body.data);
|
||||
}
|
||||
throw new Error('Function not found');
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/function')
|
||||
async functionIntegration(
|
||||
@Post('/article/:integration/connect')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async connectArticle(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: IntegrationFunctionDto
|
||||
): Promise<any> {
|
||||
const getIntegration = await this._integrationService.getIntegrationById(
|
||||
@Param('integration') integration: string,
|
||||
@Body() api: ApiKeyDto
|
||||
) {
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedArticlesIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
if (!api) {
|
||||
throw new Error('Missing api');
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getArticlesIntegration(integration);
|
||||
const { id, name, token, picture, username } =
|
||||
await integrationProvider.authenticate(api.api);
|
||||
|
||||
if (!id) {
|
||||
throw new Error('Invalid api key');
|
||||
}
|
||||
|
||||
return this._integrationService.createOrUpdateIntegration(
|
||||
org.id,
|
||||
body.id
|
||||
name,
|
||||
picture,
|
||||
'article',
|
||||
String(id),
|
||||
integration,
|
||||
token,
|
||||
'',
|
||||
undefined,
|
||||
username,
|
||||
false
|
||||
);
|
||||
if (!getIntegration) {
|
||||
throw new Error('Invalid integration');
|
||||
}
|
||||
|
||||
@Post('/social/:integration/connect')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
@UseFilters(new NotEnoughScopesFilter())
|
||||
async connectSocialMedia(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('integration') integration: string,
|
||||
@Body() body: ConnectIntegrationDto
|
||||
) {
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
const integrationProvider = this._integrationManager.getSocialIntegration(
|
||||
getIntegration.providerIdentifier
|
||||
const getCodeVerifier = await ioRedis.get(`login:${body.state}`);
|
||||
if (!getCodeVerifier) {
|
||||
throw new Error('Invalid state');
|
||||
}
|
||||
|
||||
await ioRedis.del(`login:${body.state}`);
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
const {
|
||||
accessToken,
|
||||
expiresIn,
|
||||
refreshToken,
|
||||
id,
|
||||
name,
|
||||
picture,
|
||||
username,
|
||||
} = await integrationProvider.authenticate({
|
||||
code: body.code,
|
||||
codeVerifier: getCodeVerifier,
|
||||
refresh: body.refresh,
|
||||
});
|
||||
|
||||
if (!id) {
|
||||
throw new Error('Invalid api key');
|
||||
}
|
||||
|
||||
return this._integrationService.createOrUpdateIntegration(
|
||||
org.id,
|
||||
name,
|
||||
picture,
|
||||
'social',
|
||||
String(id),
|
||||
integration,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresIn,
|
||||
username,
|
||||
integrationProvider.isBetweenSteps,
|
||||
body.refresh,
|
||||
+body.timezone
|
||||
);
|
||||
if (!integrationProvider) {
|
||||
throw new Error('Invalid provider');
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
if (integrationProvider[body.name]) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
const load = await integrationProvider[body.name](
|
||||
getIntegration.token,
|
||||
body.data,
|
||||
getIntegration.internalId,
|
||||
getIntegration
|
||||
);
|
||||
|
||||
return load;
|
||||
} catch (err) {
|
||||
if (err instanceof RefreshToken) {
|
||||
const data = await this._refreshIntegrationService.refresh(
|
||||
getIntegration
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { accessToken } = data;
|
||||
|
||||
if (accessToken) {
|
||||
if (integrationProvider.refreshWait) {
|
||||
await timer(10000);
|
||||
}
|
||||
return this.functionIntegration(org, body);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
throw new Error('Function not found');
|
||||
}
|
||||
|
||||
@Post('/disable')
|
||||
|
|
@ -386,6 +261,33 @@ export class IntegrationsController {
|
|||
return this._integrationService.disableChannel(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/instagram/:id')
|
||||
async saveInstagram(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { pageId: string; id: string },
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
return this._integrationService.saveInstagram(org.id, id, body);
|
||||
}
|
||||
|
||||
@Post('/facebook/:id')
|
||||
async saveFacebook(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { page: string },
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
return this._integrationService.saveFacebook(org.id, id, body.page);
|
||||
}
|
||||
|
||||
@Post('/linkedin-page/:id')
|
||||
async saveLinkedin(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { page: string },
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
return this._integrationService.saveLinkedin(org.id, id, body.page);
|
||||
}
|
||||
|
||||
@Post('/enable')
|
||||
enableChannel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
|
|
@ -410,72 +312,10 @@ export class IntegrationsController {
|
|||
);
|
||||
if (isTherePosts.length) {
|
||||
for (const post of isTherePosts) {
|
||||
this._postService.deletePost(org.id, post.group).catch((err) => {});
|
||||
await this._postService.deletePost(org.id, post.group);
|
||||
}
|
||||
}
|
||||
|
||||
return this._integrationService.deleteChannel(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/plug/list')
|
||||
async getPlugList() {
|
||||
return { plugs: this._integrationManager.getAllPlugs() };
|
||||
}
|
||||
|
||||
@Get('/:id/plugs')
|
||||
async getPlugsByIntegrationId(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
return this._integrationService.getPlugsByIntegrationId(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/:id/plugs')
|
||||
async postPlugsByIntegrationId(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: PlugDto
|
||||
) {
|
||||
return this._integrationService.createOrUpdatePlug(org.id, id, body);
|
||||
}
|
||||
|
||||
@Put('/plugs/:id/activate')
|
||||
async changePlugActivation(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body('status') status: boolean
|
||||
) {
|
||||
return this._integrationService.changePlugActivation(org.id, id, status);
|
||||
}
|
||||
|
||||
@Get('/telegram/updates')
|
||||
async getUpdates(@Query() query: { word: string; id?: number }) {
|
||||
return new TelegramProvider().getBotId(query);
|
||||
}
|
||||
|
||||
@Post('/moltbook/register')
|
||||
async moltbookRegister(@Body() body: { name: string; description: string }) {
|
||||
try {
|
||||
const provider = new MoltbookProvider();
|
||||
const result = await provider.registerAgent(body.name, body.description);
|
||||
return {
|
||||
apiKey: result.api_key,
|
||||
claimUrl: result.claim_url,
|
||||
verificationCode: result.verification_code,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return { error: err.message || 'Registration failed' };
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/moltbook/status')
|
||||
async moltbookStatus(@Query('apiKey') apiKey: string) {
|
||||
try {
|
||||
const provider = new MoltbookProvider();
|
||||
const result = await provider.checkAgentStatus(apiKey);
|
||||
return { claimed: result?.status === 'claimed' };
|
||||
} catch (err) {
|
||||
return { claimed: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
231
apps/backend/src/api/routes/marketplace.controller.ts
Normal file
231
apps/backend/src/api/routes/marketplace.controller.ts
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { ItemUserService } from '@gitroom/nestjs-libraries/database/prisma/marketplace/item.user.service';
|
||||
import { AddRemoveItemDto } from '@gitroom/nestjs-libraries/dtos/marketplace/add.remove.item.dto';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { ChangeActiveDto } from '@gitroom/nestjs-libraries/dtos/marketplace/change.active.dto';
|
||||
import { ItemsDto } from '@gitroom/nestjs-libraries/dtos/marketplace/items.dto';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { AudienceDto } from '@gitroom/nestjs-libraries/dtos/marketplace/audience.dto';
|
||||
import { NewConversationDto } from '@gitroom/nestjs-libraries/dtos/marketplace/new.conversation.dto';
|
||||
import { MessagesService } from '@gitroom/nestjs-libraries/database/prisma/marketplace/messages.service';
|
||||
import { CreateOfferDto } from '@gitroom/nestjs-libraries/dtos/marketplace/create.offer.dto';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
|
||||
@ApiTags('Marketplace')
|
||||
@Controller('/marketplace')
|
||||
export class MarketplaceController {
|
||||
constructor(
|
||||
private _itemUserService: ItemUserService,
|
||||
private _stripeService: StripeService,
|
||||
private _userService: UsersService,
|
||||
private _messagesService: MessagesService,
|
||||
private _postsService: PostsService
|
||||
) {}
|
||||
|
||||
@Post('/')
|
||||
getInfluencers(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: ItemsDto
|
||||
) {
|
||||
return this._userService.getMarketplacePeople(
|
||||
organization.id,
|
||||
user.id,
|
||||
body
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/conversation')
|
||||
createConversation(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Body() body: NewConversationDto
|
||||
) {
|
||||
return this._messagesService.createConversation(
|
||||
user.id,
|
||||
organization.id,
|
||||
body
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/bank')
|
||||
connectBankAccount(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Query('country') country: string
|
||||
) {
|
||||
return this._stripeService.createAccountProcess(user.id, user.email, country);
|
||||
}
|
||||
|
||||
@Post('/item')
|
||||
async addItems(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: AddRemoveItemDto
|
||||
) {
|
||||
return this._itemUserService.addOrRemoveItem(body.state, user.id, body.key);
|
||||
}
|
||||
|
||||
@Post('/active')
|
||||
async changeActive(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: ChangeActiveDto
|
||||
) {
|
||||
await this._userService.changeMarketplaceActive(user.id, body.active);
|
||||
}
|
||||
|
||||
@Post('/audience')
|
||||
async changeAudience(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: AudienceDto
|
||||
) {
|
||||
await this._userService.changeAudienceSize(user.id, body.audience);
|
||||
}
|
||||
|
||||
@Get('/item')
|
||||
async getItems(@GetUserFromRequest() user: User) {
|
||||
return this._itemUserService.getItems(user.id);
|
||||
}
|
||||
|
||||
@Get('/orders')
|
||||
async getOrders(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Query('type') type: 'seller' | 'buyer'
|
||||
) {
|
||||
return this._messagesService.getOrders(user.id, organization.id, type);
|
||||
}
|
||||
|
||||
@Get('/account')
|
||||
async getAccount(@GetUserFromRequest() user: User) {
|
||||
const { account, marketplace, connectedAccount, name, picture, audience } =
|
||||
await this._userService.getUserByEmail(user.email);
|
||||
return {
|
||||
account,
|
||||
marketplace,
|
||||
connectedAccount,
|
||||
fullname: name,
|
||||
audience,
|
||||
picture,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/offer')
|
||||
async createOffer(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: CreateOfferDto
|
||||
) {
|
||||
return this._messagesService.createOffer(user.id, body);
|
||||
}
|
||||
|
||||
@Get('/posts/:id')
|
||||
async post(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
const getPost = await this._messagesService.getPost(user.id, organization.id, id);
|
||||
if (!getPost) {
|
||||
return ;
|
||||
}
|
||||
|
||||
return {...await this._postsService.getPost(getPost.organizationId, id), providerId: getPost.integration.providerIdentifier};
|
||||
}
|
||||
|
||||
@Post('/posts/:id/revision')
|
||||
async revision(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('message') message: string
|
||||
) {
|
||||
return this._messagesService.requestRevision(
|
||||
user.id,
|
||||
organization.id,
|
||||
id,
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/posts/:id/approve')
|
||||
async approve(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('message') message: string
|
||||
) {
|
||||
return this._messagesService.requestApproved(
|
||||
user.id,
|
||||
organization.id,
|
||||
id,
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/posts/:id/cancel')
|
||||
async cancel(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._messagesService.requestCancel(organization.id, id);
|
||||
}
|
||||
|
||||
@Post('/offer/:id/complete')
|
||||
async completeOrder(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
const order = await this._messagesService.completeOrderAndPay(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!order) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this._stripeService.payout(
|
||||
id,
|
||||
order.charge,
|
||||
order.account,
|
||||
order.price
|
||||
);
|
||||
} catch (e) {
|
||||
await this._messagesService.payoutProblem(
|
||||
id,
|
||||
order.sellerId,
|
||||
order.price
|
||||
);
|
||||
}
|
||||
await this._messagesService.completeOrder(id);
|
||||
}
|
||||
|
||||
@Post('/orders/:id/payment')
|
||||
async payOrder(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
const orderDetails = await this._messagesService.getOrderDetails(
|
||||
user.id,
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
const payment = await this._stripeService.payAccountStepOne(
|
||||
user.id,
|
||||
organization,
|
||||
orderDetails.seller,
|
||||
orderDetails.order.id,
|
||||
orderDetails.order.ordersItems.map((p) => ({
|
||||
quantity: p.quantity,
|
||||
integrationType: p.integration.providerIdentifier,
|
||||
price: p.price,
|
||||
})),
|
||||
orderDetails.order.messageGroupId
|
||||
);
|
||||
return payment;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,5 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
UsePipes,
|
||||
Body, Controller, Get, Param, Post, Query, Req, Res, UploadedFile, UseInterceptors, UsePipes
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
|
|
@ -21,110 +10,27 @@ import handleR2Upload from '@gitroom/nestjs-libraries/upload/r2.uploader';
|
|||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { CustomFileValidationPipe } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
|
||||
import { SaveMediaInformationDto } from '@gitroom/nestjs-libraries/dtos/media/save.media.information.dto';
|
||||
import { VideoDto } from '@gitroom/nestjs-libraries/dtos/videos/video.dto';
|
||||
import { VideoFunctionDto } from '@gitroom/nestjs-libraries/dtos/videos/video.function.dto';
|
||||
|
||||
@ApiTags('Media')
|
||||
@Controller('/media')
|
||||
export class MediaController {
|
||||
private storage = UploadFactory.createStorage();
|
||||
constructor(
|
||||
private _mediaService: MediaService,
|
||||
private _subscriptionService: SubscriptionService
|
||||
) {}
|
||||
|
||||
@Delete('/:id')
|
||||
deleteMedia(@GetOrgFromRequest() org: Organization, @Param('id') id: string) {
|
||||
return this._mediaService.deleteMedia(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/generate-video')
|
||||
generateVideo(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: VideoDto
|
||||
) {
|
||||
console.log('hello');
|
||||
return this._mediaService.generateVideo(org, body);
|
||||
}
|
||||
|
||||
@Post('/generate-image')
|
||||
async generateImage(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Body('prompt') prompt: string,
|
||||
isPicturePrompt = false
|
||||
) {
|
||||
const total = await this._subscriptionService.checkCredits(org);
|
||||
if (process.env.STRIPE_PUBLISHABLE_KEY && total.credits <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
output:
|
||||
(isPicturePrompt ? '' : 'data:image/png;base64,') +
|
||||
(await this._mediaService.generateImage(prompt, org, isPicturePrompt)),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/generate-image-with-prompt')
|
||||
async generateImageFromText(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Body('prompt') prompt: string
|
||||
) {
|
||||
const image = await this.generateImage(org, req, prompt, true);
|
||||
if (!image) {
|
||||
const total = await this._subscriptionService.checkCredits(org);
|
||||
if (total.credits <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const file = await this.storage.uploadSimple(image.output);
|
||||
|
||||
return this._mediaService.saveFile(org.id, file.split('/').pop(), file);
|
||||
}
|
||||
|
||||
@Post('/upload-server')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@UsePipes(new CustomFileValidationPipe())
|
||||
async uploadServer(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@UploadedFile() file: Express.Multer.File
|
||||
) {
|
||||
const originalName = file?.originalname || '';
|
||||
const uploadedFile = await this.storage.uploadFile(file);
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
uploadedFile.originalname,
|
||||
uploadedFile.path,
|
||||
originalName
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/save-media')
|
||||
async saveMedia(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Body('name') name: string,
|
||||
@Body('originalName') originalName: string
|
||||
) {
|
||||
if (!name) {
|
||||
return false;
|
||||
}
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
name,
|
||||
process.env.CLOUDFLARE_BUCKET_URL + '/' + name,
|
||||
originalName || undefined
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/information')
|
||||
saveMediaInformation(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SaveMediaInformationDto
|
||||
) {
|
||||
return this._mediaService.saveMediaInformation(org.id, body);
|
||||
return {output: 'data:image/png;base64,' + await this._mediaService.generateImage(prompt, org)};
|
||||
}
|
||||
|
||||
@Post('/upload-simple')
|
||||
|
|
@ -132,31 +38,26 @@ export class MediaController {
|
|||
@UsePipes(new CustomFileValidationPipe())
|
||||
async uploadSimple(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@UploadedFile('file') file: Express.Multer.File,
|
||||
@Body('preventSave') preventSave: string = 'false'
|
||||
@UploadedFile('file')
|
||||
file: Express.Multer.File
|
||||
) {
|
||||
const originalName = file.originalname;
|
||||
const getFile = await this.storage.uploadFile(file);
|
||||
|
||||
if (preventSave === 'true') {
|
||||
const { path } = getFile;
|
||||
return { path };
|
||||
}
|
||||
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
getFile.originalname,
|
||||
getFile.path,
|
||||
originalName
|
||||
);
|
||||
const filePath =
|
||||
file.path.indexOf('http') === 0
|
||||
? file.path
|
||||
: file.path.replace(process.env.UPLOAD_DIRECTORY, '');
|
||||
return this._mediaService.saveFile(org.id, file.originalname, filePath);
|
||||
}
|
||||
|
||||
@Post('/:endpoint')
|
||||
// @UseInterceptors(FileInterceptor('file'))
|
||||
// @UsePipes(new CustomFileValidationPipe())
|
||||
async uploadFile(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Req() req: Request,
|
||||
@Res() res: Response,
|
||||
@Param('endpoint') endpoint: string
|
||||
// @UploadedFile('file')
|
||||
// file: Express.Multer.File
|
||||
) {
|
||||
const upload = await handleR2Upload(endpoint, req, res);
|
||||
if (endpoint !== 'complete-multipart-upload') {
|
||||
|
|
@ -165,45 +66,23 @@ export class MediaController {
|
|||
|
||||
// @ts-ignore
|
||||
const name = upload.Location.split('/').pop();
|
||||
const originalName = req.body?.file?.name;
|
||||
|
||||
const saveFile = await this._mediaService.saveFile(
|
||||
org.id,
|
||||
name,
|
||||
// @ts-ignore
|
||||
upload.Location,
|
||||
originalName || undefined
|
||||
);
|
||||
// @ts-ignore
|
||||
await this._mediaService.saveFile(org.id, name, upload.Location);
|
||||
|
||||
res.status(200).json({ ...upload, saved: saveFile });
|
||||
res.status(200).json(upload);
|
||||
// const filePath =
|
||||
// file.path.indexOf('http') === 0
|
||||
// ? file.path
|
||||
// : file.path.replace(process.env.UPLOAD_DIRECTORY, '');
|
||||
// return this._mediaService.saveFile(org.id, file.originalname, filePath);
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
getMedia(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query('page') page: number,
|
||||
@Query('search') search?: string
|
||||
@Query('page') page: number
|
||||
) {
|
||||
return this._mediaService.getMedia(org.id, page, search);
|
||||
}
|
||||
|
||||
@Get('/video-options')
|
||||
getVideos() {
|
||||
return this._mediaService.getVideoOptions();
|
||||
}
|
||||
|
||||
@Post('/video/function')
|
||||
videoFunction(
|
||||
@Body() body: VideoFunctionDto
|
||||
) {
|
||||
return this._mediaService.videoFunction(body.identifier, body.functionName, body.params);
|
||||
}
|
||||
|
||||
@Get('/generate-video/:type/allowed')
|
||||
generateVideoAllowed(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('type') type: string
|
||||
) {
|
||||
return this._mediaService.generateVideoAllowed(org, type);
|
||||
return this._mediaService.getMedia(org.id, page);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
40
apps/backend/src/api/routes/messages.controller.ts
Normal file
40
apps/backend/src/api/routes/messages.controller.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { MessagesService } from '@gitroom/nestjs-libraries/database/prisma/marketplace/messages.service';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { AddMessageDto } from '@gitroom/nestjs-libraries/dtos/messages/add.message';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
|
||||
@ApiTags('Messages')
|
||||
@Controller('/messages')
|
||||
export class MessagesController {
|
||||
constructor(private _messagesService: MessagesService) {}
|
||||
|
||||
@Get('/')
|
||||
getMessagesGroup(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
return this._messagesService.getMessagesGroup(user.id, organization.id);
|
||||
}
|
||||
|
||||
@Get('/:groupId/:page')
|
||||
getMessages(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('groupId') groupId: string,
|
||||
@Param('page') page: string
|
||||
) {
|
||||
return this._messagesService.getMessages(user.id, organization.id, groupId, +page);
|
||||
}
|
||||
@Post('/:groupId')
|
||||
createMessage(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('groupId') groupId: string,
|
||||
@Body() message: AddMessageDto
|
||||
) {
|
||||
return this._messagesService.createMessage(user.id, organization.id, groupId, message);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import { Controller, Get, Param } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Monitor')
|
||||
@Controller('/monitor')
|
||||
export class MonitorController {
|
||||
@Get('/queue/:name')
|
||||
async getMessagesGroup(@Param('name') name: string) {
|
||||
return {
|
||||
status: 'success',
|
||||
message: `Queue ${name} is healthy.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,395 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import { ConnectIntegrationDto } from '@gitroom/nestjs-libraries/dtos/integrations/connect.integration.dto';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { NotEnoughScopesFilter } from '@gitroom/nestjs-libraries/integrations/integration.missing.scopes';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { AuthTokenDetails } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
|
||||
import { NotEnoughScopes } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
|
||||
@ApiTags('Integrations')
|
||||
@Controller('/integrations')
|
||||
export class NoAuthIntegrationsController {
|
||||
constructor(
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _integrationService: IntegrationService,
|
||||
private _refreshIntegrationService: RefreshIntegrationService,
|
||||
private _organizationService: OrganizationService
|
||||
) {}
|
||||
|
||||
@Get('/')
|
||||
getIntegrations() {
|
||||
return this._integrationManager.getAllIntegrations();
|
||||
}
|
||||
|
||||
@Post('/social-connect/:integration')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
@UseFilters(new NotEnoughScopesFilter())
|
||||
async connectSocialMedia(
|
||||
@Param('integration') integration: string,
|
||||
@Body() body: ConnectIntegrationDto
|
||||
) {
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new Error('Integration not allowed');
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
|
||||
const getCodeVerifier = integrationProvider.customFields
|
||||
? 'none'
|
||||
: await ioRedis.get(`login:${body.state}`);
|
||||
if (!getCodeVerifier) {
|
||||
throw new Error('Invalid state');
|
||||
}
|
||||
|
||||
const organization = await ioRedis.get(`organization:${body.state}`);
|
||||
if (!organization) {
|
||||
throw new Error('Organization not found');
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgById(organization);
|
||||
|
||||
if (!integrationProvider.customFields) {
|
||||
await ioRedis.del(`login:${body.state}`);
|
||||
}
|
||||
|
||||
const details = integrationProvider.externalUrl
|
||||
? await ioRedis.get(`external:${body.state}`)
|
||||
: undefined;
|
||||
|
||||
if (details) {
|
||||
await ioRedis.del(`external:${body.state}`);
|
||||
}
|
||||
|
||||
const refresh = await ioRedis.get(`refresh:${body.state}`);
|
||||
if (refresh) {
|
||||
await ioRedis.del(`refresh:${body.state}`);
|
||||
}
|
||||
|
||||
const onboarding = await ioRedis.get(`onboarding:${body.state}`);
|
||||
if (onboarding) {
|
||||
await ioRedis.del(`onboarding:${body.state}`);
|
||||
}
|
||||
|
||||
const {
|
||||
error,
|
||||
accessToken,
|
||||
expiresIn,
|
||||
refreshToken,
|
||||
id,
|
||||
name,
|
||||
picture,
|
||||
username,
|
||||
additionalSettings,
|
||||
// eslint-disable-next-line no-async-promise-executor
|
||||
} = await new Promise<AuthTokenDetails>(async (res) => {
|
||||
try {
|
||||
const auth = await integrationProvider.authenticate(
|
||||
{
|
||||
code: body.code,
|
||||
codeVerifier: getCodeVerifier,
|
||||
refresh: body.refresh,
|
||||
},
|
||||
details ? JSON.parse(details) : undefined
|
||||
);
|
||||
|
||||
if (typeof auth === 'string') {
|
||||
return res({
|
||||
error: auth,
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (refresh && integrationProvider.reConnect) {
|
||||
console.log('reconnect');
|
||||
try {
|
||||
const newAuth = await integrationProvider.reConnect(
|
||||
auth.id,
|
||||
refresh,
|
||||
auth.accessToken
|
||||
);
|
||||
return res({ ...newAuth, refreshToken: body.refresh });
|
||||
} catch (err: any) {
|
||||
return res({
|
||||
error: err.message,
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return res(auth);
|
||||
} catch (err) {
|
||||
if (err instanceof NotEnoughScopes) {
|
||||
return res({
|
||||
error: err.message,
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
|
||||
return res({
|
||||
error: 'Authentication failed',
|
||||
accessToken: '',
|
||||
id: '',
|
||||
name: '',
|
||||
picture: '',
|
||||
username: '',
|
||||
additionalSettings: [],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new NotEnoughScopes(error);
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
throw new NotEnoughScopes('Invalid API key');
|
||||
}
|
||||
|
||||
if (refresh && String(id) !== String(refresh)) {
|
||||
throw new NotEnoughScopes(
|
||||
'Please refresh the channel that needs to be refreshed'
|
||||
);
|
||||
}
|
||||
|
||||
let validName = name;
|
||||
if (!validName) {
|
||||
if (username) {
|
||||
validName = username.split('.')[0] ?? username;
|
||||
} else {
|
||||
validName = `Channel_${String(id).slice(0, 8)}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.env.STRIPE_PUBLISHABLE_KEY &&
|
||||
org.isTrailing &&
|
||||
(await this._integrationService.checkPreviousConnections(
|
||||
org.id,
|
||||
String(id)
|
||||
))
|
||||
) {
|
||||
throw new HttpException('', 412);
|
||||
}
|
||||
|
||||
const createUpdate =
|
||||
await this._integrationService.createOrUpdateIntegration(
|
||||
additionalSettings,
|
||||
!!integrationProvider.oneTimeToken,
|
||||
org.id,
|
||||
validName.trim(),
|
||||
picture,
|
||||
'social',
|
||||
String(id),
|
||||
integration,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresIn,
|
||||
username,
|
||||
refresh ? false : integrationProvider.isBetweenSteps,
|
||||
body.refresh,
|
||||
+body.timezone,
|
||||
details
|
||||
? AuthService.fixedEncryption(details)
|
||||
: integrationProvider.customFields
|
||||
? AuthService.fixedEncryption(
|
||||
Buffer.from(body.code, 'base64').toString()
|
||||
)
|
||||
: integrationProvider.isChromeExtension
|
||||
? AuthService.signJWT(
|
||||
JSON.parse(Buffer.from(body.code, 'base64').toString())
|
||||
)
|
||||
: undefined
|
||||
);
|
||||
|
||||
this._refreshIntegrationService
|
||||
.startRefreshWorkflow(org.id, createUpdate.id, integrationProvider)
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
});
|
||||
|
||||
// Fetch pages if this is a two-step provider and not a refresh
|
||||
let pages: any[] = [];
|
||||
if (integrationProvider.isBetweenSteps && !refresh) {
|
||||
try {
|
||||
// Check which method the provider uses (pages or companies)
|
||||
const fetchMethod =
|
||||
'pages' in integrationProvider
|
||||
? 'pages'
|
||||
: 'companies' in integrationProvider
|
||||
? 'companies'
|
||||
: null;
|
||||
|
||||
if (fetchMethod) {
|
||||
// @ts-ignore - dynamic method call
|
||||
pages = await integrationProvider[fetchMethod](accessToken);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Failed to fetch pages:', err);
|
||||
}
|
||||
}
|
||||
|
||||
const webhookUrl = await ioRedis.get(`webhookUrl:${body.state}`);
|
||||
if (webhookUrl) {
|
||||
try {
|
||||
await fetch(webhookUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
params: AuthService.signJWT({
|
||||
apiKey: org.apiKey,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
} catch (err) {}
|
||||
|
||||
await ioRedis.del(`webhookUrl:${body.state}`);
|
||||
}
|
||||
|
||||
const returnURL = await ioRedis.get(`redirect:${body.state}`);
|
||||
if (returnURL) {
|
||||
await ioRedis.del(`redirect:${body.state}`);
|
||||
}
|
||||
|
||||
const extensionToken = integrationProvider.isChromeExtension
|
||||
? AuthService.signJWT({
|
||||
integrationId: createUpdate.id,
|
||||
organizationId: org.id,
|
||||
internalId: String(id),
|
||||
provider: integration,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
...createUpdate,
|
||||
onboarding: onboarding === 'true',
|
||||
pages,
|
||||
...(returnURL ? { returnURL } : {}),
|
||||
...(extensionToken ? { extensionToken } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/public/provider/:id/connect')
|
||||
async saveProviderPage(@Param('id') id: string, @Body() body: any) {
|
||||
if (!body.state) {
|
||||
throw new Error('Invalid state');
|
||||
}
|
||||
|
||||
const organization = await ioRedis.get(`organization:${body.state}`);
|
||||
if (!organization) {
|
||||
throw new Error('Organization not found');
|
||||
}
|
||||
|
||||
const org = await this._organizationService.getOrgById(organization);
|
||||
|
||||
return this._integrationService.saveProviderPage(org.id, id, body);
|
||||
}
|
||||
|
||||
@Post('/extension-refresh')
|
||||
async extensionRefreshCookies(
|
||||
@Body() body: { jwt: string; cookies: string }
|
||||
) {
|
||||
let payload: any;
|
||||
try {
|
||||
payload = AuthService.verifyJWT(body.jwt);
|
||||
} catch {
|
||||
throw new HttpException('Invalid token', 401);
|
||||
}
|
||||
|
||||
const { integrationId, organizationId, internalId, provider } = payload;
|
||||
if (!integrationId || !organizationId || !internalId || !provider) {
|
||||
throw new HttpException('Invalid token payload', 400);
|
||||
}
|
||||
|
||||
const integration = await this._integrationService.getIntegrationById(
|
||||
organizationId,
|
||||
integrationId
|
||||
);
|
||||
if (!integration || integration.internalId !== internalId) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(provider);
|
||||
if (!integrationProvider?.isChromeExtension) {
|
||||
throw new HttpException('Not a Chrome extension integration', 400);
|
||||
}
|
||||
|
||||
const authResult = await integrationProvider.authenticate({
|
||||
code: body.cookies,
|
||||
codeVerifier: '',
|
||||
});
|
||||
|
||||
if (typeof authResult === 'string') {
|
||||
throw new HttpException(authResult, 400);
|
||||
}
|
||||
|
||||
if (String(authResult.id) !== String(integration.internalId)) {
|
||||
await this._integrationService.refreshNeeded(
|
||||
organizationId,
|
||||
integrationId
|
||||
);
|
||||
return { success: false, reason: 'account_mismatch' };
|
||||
}
|
||||
|
||||
await this._integrationService.createOrUpdateIntegration(
|
||||
undefined,
|
||||
false,
|
||||
organizationId,
|
||||
integration.name,
|
||||
undefined,
|
||||
'social',
|
||||
integration.internalId,
|
||||
integration.providerIdentifier,
|
||||
authResult.accessToken,
|
||||
'',
|
||||
authResult.expiresIn,
|
||||
undefined,
|
||||
false,
|
||||
undefined,
|
||||
undefined,
|
||||
AuthService.signJWT(
|
||||
JSON.parse(Buffer.from(body.cookies, 'base64').toString())
|
||||
)
|
||||
);
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.req
|
|||
import { Organization, User } from '@prisma/client';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import {ApiTags} from "@nestjs/swagger";
|
||||
|
||||
@ApiTags('Notifications')
|
||||
@Controller('/notifications')
|
||||
|
|
|
|||
|
|
@ -1,54 +0,0 @@
|
|||
import { Body, Controller, Delete, Get, Post, Put } from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { CreateOAuthAppDto } from '@gitroom/nestjs-libraries/dtos/oauth/create-oauth-app.dto';
|
||||
import { UpdateOAuthAppDto } from '@gitroom/nestjs-libraries/dtos/oauth/update-oauth-app.dto';
|
||||
|
||||
@ApiTags('OAuth App')
|
||||
@Controller('/user/oauth-app')
|
||||
export class OAuthAppController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Get('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getApp(@GetOrgFromRequest() org: Organization) {
|
||||
return this._oauthService.getApp(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async createApp(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateOAuthAppDto
|
||||
) {
|
||||
return this._oauthService.createApp(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async updateApp(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UpdateOAuthAppDto
|
||||
) {
|
||||
return this._oauthService.updateApp(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async deleteApp(@GetOrgFromRequest() org: Organization) {
|
||||
return this._oauthService.deleteApp(org.id);
|
||||
}
|
||||
|
||||
@Post('/rotate-secret')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async rotateSecret(@GetOrgFromRequest() org: Organization) {
|
||||
return this._oauthService.rotateSecret(org.id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { User, Organization } from '@prisma/client';
|
||||
import { AuthorizeOAuthQueryDto, ApproveOAuthDto } from '@gitroom/nestjs-libraries/dtos/oauth/authorize-oauth.dto';
|
||||
import { TokenExchangeDto } from '@gitroom/nestjs-libraries/dtos/oauth/token-exchange.dto';
|
||||
|
||||
@ApiTags('OAuth')
|
||||
@Controller('/oauth')
|
||||
export class OAuthController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Get('/authorize')
|
||||
async authorize(@Query() query: AuthorizeOAuthQueryDto) {
|
||||
const app = await this._oauthService.validateAuthorizationRequest(
|
||||
query.client_id
|
||||
);
|
||||
|
||||
return {
|
||||
app: {
|
||||
name: app.name,
|
||||
description: app.description,
|
||||
picture: app.picture,
|
||||
clientId: app.clientId,
|
||||
redirectUrl: app.redirectUrl,
|
||||
},
|
||||
state: query.state,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/token')
|
||||
async token(@Body() body: TokenExchangeDto) {
|
||||
if (body.grant_type !== 'authorization_code') {
|
||||
throw new HttpException(
|
||||
{ error: 'unsupported_grant_type' },
|
||||
HttpStatus.BAD_REQUEST
|
||||
);
|
||||
}
|
||||
|
||||
return this._oauthService.exchangeCodeForToken(
|
||||
body.code,
|
||||
body.client_id,
|
||||
body.client_secret
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiTags('OAuth')
|
||||
@Controller('/oauth')
|
||||
export class OAuthAuthorizedController {
|
||||
constructor(private _oauthService: OAuthService) {}
|
||||
|
||||
@Post('/authorize')
|
||||
async approveOrDeny(
|
||||
@Body() body: ApproveOAuthDto,
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
const app = await this._oauthService.validateAuthorizationRequest(
|
||||
body.client_id
|
||||
);
|
||||
|
||||
if (body.action === 'deny') {
|
||||
const redirectUrl = new URL(app.redirectUrl);
|
||||
redirectUrl.searchParams.set('error', 'access_denied');
|
||||
if (body.state) {
|
||||
redirectUrl.searchParams.set('state', body.state);
|
||||
}
|
||||
return { redirect: redirectUrl.toString() };
|
||||
}
|
||||
|
||||
const code = await this._oauthService.createAuthorizationCode(
|
||||
app.id,
|
||||
user.id,
|
||||
org.id
|
||||
);
|
||||
|
||||
const redirectUrl = new URL(app.redirectUrl);
|
||||
redirectUrl.searchParams.set('code', code);
|
||||
if (body.state) {
|
||||
redirectUrl.searchParams.set('state', body.state);
|
||||
}
|
||||
return { redirect: redirectUrl.toString() };
|
||||
}
|
||||
}
|
||||
|
|
@ -3,109 +3,42 @@ import {
|
|||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { CreatePostDto } from '@gitroom/nestjs-libraries/dtos/posts/create.post.dto';
|
||||
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
|
||||
import { GetPostsListDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.list.dto';
|
||||
import { StarsService } from '@gitroom/nestjs-libraries/database/prisma/stars/stars.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GeneratorDto } from '@gitroom/nestjs-libraries/dtos/generator/generator.dto';
|
||||
import { CreateGeneratedPostsDto } from '@gitroom/nestjs-libraries/dtos/generator/create.generated.posts.dto';
|
||||
import { AgentGraphService } from '@gitroom/nestjs-libraries/agent/agent.graph.service';
|
||||
import { Response } from 'express';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { ShortLinkService } from '@gitroom/nestjs-libraries/short-linking/short.link.service';
|
||||
import { CreateTagDto } from '@gitroom/nestjs-libraries/dtos/posts/create.tag.dto';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { MessagesService } from '@gitroom/nestjs-libraries/database/prisma/marketplace/messages.service';
|
||||
import { GeneratorDto } from '@gitroom/nestjs-libraries/dtos/generator/generator.dto';
|
||||
import { CreateGeneratedPostsDto } from '@gitroom/nestjs-libraries/dtos/generator/create.generated.posts.dto';
|
||||
|
||||
@ApiTags('Posts')
|
||||
@Controller('/posts')
|
||||
export class PostsController {
|
||||
constructor(
|
||||
private _postsService: PostsService,
|
||||
private _agentGraphService: AgentGraphService,
|
||||
private _shortLinkService: ShortLinkService
|
||||
private _starsService: StarsService,
|
||||
private _messagesService: MessagesService
|
||||
) {}
|
||||
|
||||
@Get('/:id/statistics')
|
||||
async getStatistics(
|
||||
@Get('/marketplace/:id?')
|
||||
async getMarketplacePosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.getStatistics(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/:id/missing')
|
||||
async getMissingContent(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.getMissingContent(org.id, id);
|
||||
}
|
||||
|
||||
@Put('/:id/release-id')
|
||||
async updateReleaseId(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('releaseId') releaseId: string
|
||||
) {
|
||||
return this._postsService.updateReleaseId(org.id, id, releaseId);
|
||||
}
|
||||
|
||||
@Post('/should-shortlink')
|
||||
async shouldShortlink(@Body() body: { messages: string[] }) {
|
||||
return { ask: this._shortLinkService.askShortLinkedin(body.messages) };
|
||||
}
|
||||
|
||||
@Post('/:id/comments')
|
||||
async createComment(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { comment: string }
|
||||
) {
|
||||
return this._postsService.createComment(org.id, user.id, id, body.comment);
|
||||
}
|
||||
|
||||
@Get('/tags')
|
||||
async getTags(@GetOrgFromRequest() org: Organization) {
|
||||
return { tags: await this._postsService.getTags(org.id) };
|
||||
}
|
||||
|
||||
@Post('/tags')
|
||||
async createTag(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateTagDto
|
||||
) {
|
||||
return this._postsService.createTag(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/tags/:id')
|
||||
async editTag(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: CreateTagDto,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.editTag(id, org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/tags/:id')
|
||||
async deleteTag(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._postsService.deleteTag(id, org.id);
|
||||
return this._messagesService.getMarketplaceAvailableOffers(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
|
|
@ -113,28 +46,24 @@ export class PostsController {
|
|||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetPostsDto
|
||||
) {
|
||||
return this._postsService.getPostsMinified(org.id, query);
|
||||
const [posts] = await Promise.all([
|
||||
this._postsService.getPosts(org.id, query),
|
||||
// this._commentsService.getAllCommentsByWeekYear(
|
||||
// org.id,
|
||||
// query.year,
|
||||
// query.week
|
||||
// ),
|
||||
]);
|
||||
|
||||
return {
|
||||
posts,
|
||||
// comments,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/find-slot')
|
||||
async findSlot(@GetOrgFromRequest() org: Organization) {
|
||||
return { date: await this._postsService.findFreeDateTime(org.id) };
|
||||
}
|
||||
|
||||
@Get('/find-slot/:id')
|
||||
async findSlotIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id?: string
|
||||
) {
|
||||
return { date: await this._postsService.findFreeDateTime(org.id, id) };
|
||||
}
|
||||
|
||||
@Get('/list')
|
||||
async getPostsList(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetPostsListDto
|
||||
) {
|
||||
return this._postsService.getPostsList(org.id, query);
|
||||
@Get('/predict-trending')
|
||||
predictTrending() {
|
||||
return this._starsService.predictTrending();
|
||||
}
|
||||
|
||||
@Get('/old')
|
||||
|
|
@ -145,23 +74,6 @@ export class PostsController {
|
|||
return this._postsService.getOldPosts(org.id, date);
|
||||
}
|
||||
|
||||
@Get('/group/:group/debug-export')
|
||||
async getPostGroupDebugExport(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@GetUserFromRequest() user: User,
|
||||
@Param('group') group: string
|
||||
) {
|
||||
if (!user.isSuperAdmin) {
|
||||
throw new HttpException('Forbidden', 403);
|
||||
}
|
||||
return this._postsService.getPostGroupDebugExport(org.id, group);
|
||||
}
|
||||
|
||||
@Get('/group/:group')
|
||||
getPostsByGroup(@GetOrgFromRequest() org: Organization, @Param('group') group: string) {
|
||||
return this._postsService.getPostsByGroup(org.id, group);
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
getPost(@GetOrgFromRequest() org: Organization, @Param('id') id: string) {
|
||||
return this._postsService.getPost(org.id, id);
|
||||
|
|
@ -169,13 +81,12 @@ export class PostsController {
|
|||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
async createPost(
|
||||
createPost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() rawBody: any
|
||||
@Body() body: CreatePostDto
|
||||
) {
|
||||
console.log(JSON.stringify(rawBody, null, 2));
|
||||
const body = await this._postsService.mapTypeToPost(rawBody, org.id);
|
||||
return this._postsService.createPost(org.id, body, 'WEB');
|
||||
console.log(JSON.stringify(body, null, 2));
|
||||
return this._postsService.createPost(org.id, body);
|
||||
}
|
||||
|
||||
@Post('/generator/draft')
|
||||
|
|
@ -189,17 +100,11 @@ export class PostsController {
|
|||
|
||||
@Post('/generator')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
async generatePosts(
|
||||
generatePosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: GeneratorDto,
|
||||
@Res({ passthrough: false }) res: Response
|
||||
@Body() body: GeneratorDto
|
||||
) {
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
for await (const event of this._agentGraphService.start(org.id, body)) {
|
||||
res.write(JSON.stringify(event) + '\n');
|
||||
}
|
||||
|
||||
res.end();
|
||||
return this._postsService.generatePosts(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:group')
|
||||
|
|
@ -214,17 +119,8 @@ export class PostsController {
|
|||
changeDate(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('date') date: string,
|
||||
@Body('action') action: 'schedule' | 'update' = 'schedule'
|
||||
@Body('date') date: string
|
||||
) {
|
||||
return this._postsService.changeDate(org.id, id, date, action);
|
||||
}
|
||||
|
||||
@Post('/separate-posts')
|
||||
async separatePosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: { content: string; len: number }
|
||||
) {
|
||||
return this._postsService.separatePosts(body.content, body.len);
|
||||
return this._postsService.changeDate(org.id, id, date);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,246 +1,30 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
StreamableFile,
|
||||
} from '@nestjs/common';
|
||||
import { Controller, Get, Param } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';
|
||||
import { RealIP } from 'nestjs-real-ip';
|
||||
import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';
|
||||
import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';
|
||||
import { Request, Response } from 'express';
|
||||
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { AgentGraphInsertService } from '@gitroom/nestjs-libraries/agent/agent.graph.insert.service';
|
||||
import { Nowpayments } from '@gitroom/nestjs-libraries/crypto/nowpayments';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { Readable, pipeline } from 'stream';
|
||||
import { promisify } from 'util';
|
||||
import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
|
||||
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
|
||||
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
|
||||
|
||||
const pump = promisify(pipeline);
|
||||
import { AgenciesService } from '@gitroom/nestjs-libraries/database/prisma/agencies/agencies.service';
|
||||
|
||||
@ApiTags('Public')
|
||||
@Controller('/public')
|
||||
export class PublicController {
|
||||
constructor(
|
||||
private _trackService: TrackService,
|
||||
private _agentGraphInsertService: AgentGraphInsertService,
|
||||
private _postsService: PostsService,
|
||||
private _nowpayments: Nowpayments,
|
||||
private _subscriptionService: SubscriptionService
|
||||
) {}
|
||||
@Post('/agent')
|
||||
async createAgent(@Body() body: { text: string; apiKey: string }) {
|
||||
if (
|
||||
!body.apiKey ||
|
||||
!process.env.AGENT_API_KEY ||
|
||||
body.apiKey !== process.env.AGENT_API_KEY
|
||||
) {
|
||||
return;
|
||||
}
|
||||
return this._agentGraphInsertService.newPost(body.text);
|
||||
constructor(private _agenciesService: AgenciesService) {}
|
||||
@Get('/agencies-list')
|
||||
async getAgencyByUser() {
|
||||
return this._agenciesService.getAllAgencies();
|
||||
}
|
||||
|
||||
@Get(`/posts/:id`)
|
||||
async getPreview(@Param('id') id: string) {
|
||||
return (await this._postsService.getPostsRecursively(id, true)).map(
|
||||
({ childrenPost, ...p }) => ({
|
||||
...p,
|
||||
...(p.integration
|
||||
? {
|
||||
integration: {
|
||||
id: p.integration.id,
|
||||
name: p.integration.name,
|
||||
picture: p.integration.picture,
|
||||
providerIdentifier: p.integration.providerIdentifier,
|
||||
profile: p.integration.profile,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
);
|
||||
@Get('/agencies-list-slug')
|
||||
async getAgencySlug() {
|
||||
return this._agenciesService.getAllAgenciesSlug();
|
||||
}
|
||||
|
||||
@Get(`/posts/:id/comments`)
|
||||
async getComments(@Param('id') postId: string) {
|
||||
return { comments: await this._postsService.getComments(postId) };
|
||||
}
|
||||
|
||||
@Post('/t')
|
||||
async trackEvent(
|
||||
@Res() res: Response,
|
||||
@Req() req: Request,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string,
|
||||
@Body()
|
||||
body: { fbclid?: string; tt: TrackEnum; additional: Record<string, any> }
|
||||
@Get('/agencies-information/:agency')
|
||||
async getAgencyInformation(
|
||||
@Param('agency') agency: string,
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track || makeId(10);
|
||||
const fbclid = req?.cookies?.fbclid || body.fbclid;
|
||||
await this._trackService.track(
|
||||
uniqueId,
|
||||
ip,
|
||||
userAgent,
|
||||
body.tt,
|
||||
body.additional,
|
||||
fbclid
|
||||
);
|
||||
if (!req.cookies.track) {
|
||||
res.cookie('track', uniqueId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
}
|
||||
: {}),
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
if (body.fbclid && !req.cookies.fbclid) {
|
||||
res.cookie('fbclid', body.fbclid, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
}
|
||||
: {}),
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
track: uniqueId,
|
||||
});
|
||||
return this._agenciesService.getAgencyInformation(agency);
|
||||
}
|
||||
|
||||
@Post('/modify-subscription')
|
||||
async modifySubscription(@Body('params') params: string) {
|
||||
try {
|
||||
const load = AuthService.verifyJWT(params) as {
|
||||
orgId: string;
|
||||
billing: 'FREE' | 'STANDARD' | 'TEAM' | 'PRO' | 'ULTIMATE';
|
||||
};
|
||||
|
||||
if (!load || !load.orgId || !load.billing || !pricing[load.billing]) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
const totalChannels = pricing[load.billing].channel || 0;
|
||||
|
||||
await this._subscriptionService.modifySubscriptionByOrg(
|
||||
load.orgId,
|
||||
totalChannels,
|
||||
load.billing
|
||||
);
|
||||
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/crypto/:path')
|
||||
async cryptoPost(@Body() body: any, @Param('path') path: string) {
|
||||
console.log('cryptoPost', body, path);
|
||||
return this._nowpayments.processPayment(path, body);
|
||||
}
|
||||
|
||||
@Get('/stream')
|
||||
async streamFile(
|
||||
@Query() query: OnlyURL,
|
||||
@Res() res: Response,
|
||||
@Req() req: Request
|
||||
) {
|
||||
const { url } = query;
|
||||
if (!url.endsWith('mp4')) {
|
||||
return res.status(400).send('Invalid video URL');
|
||||
}
|
||||
|
||||
const ac = new AbortController();
|
||||
const onClose = () => ac.abort();
|
||||
req.on('aborted', onClose);
|
||||
res.on('close', onClose);
|
||||
|
||||
// Manually follow redirects so every hop is re-validated against
|
||||
// the SSRF blocklist (see GHSA-34w8-5j2v-h6ww). `fetch` defaults to
|
||||
// `redirect: 'follow'`, which bypasses the DTO-level URL check.
|
||||
const MAX_REDIRECTS = 5;
|
||||
let currentUrl = url;
|
||||
let r: globalThis.Response | undefined;
|
||||
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
||||
if (!(await isSafePublicHttpsUrl(currentUrl))) {
|
||||
return res.status(400).send('Blocked URL');
|
||||
}
|
||||
|
||||
r = await fetch(currentUrl, {
|
||||
signal: ac.signal,
|
||||
redirect: 'manual',
|
||||
// @ts-ignore — undici option, not in lib.dom fetch types
|
||||
dispatcher: ssrfSafeDispatcher,
|
||||
});
|
||||
|
||||
if (r.status >= 300 && r.status < 400) {
|
||||
const location = r.headers.get('location');
|
||||
if (!location) {
|
||||
return res.status(502).send('Redirect without Location');
|
||||
}
|
||||
try {
|
||||
currentUrl = new URL(location, currentUrl).toString();
|
||||
} catch {
|
||||
return res.status(400).send('Invalid redirect target');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (!r) {
|
||||
return res.status(502).send('No upstream response');
|
||||
}
|
||||
|
||||
if (r.status >= 300 && r.status < 400) {
|
||||
return res.status(508).send('Too many redirects');
|
||||
}
|
||||
|
||||
if (!r.ok && r.status !== 206) {
|
||||
res.status(r.status);
|
||||
throw new Error(`Upstream error: ${r.statusText}`);
|
||||
}
|
||||
|
||||
const type = r.headers.get('content-type') ?? 'application/octet-stream';
|
||||
res.setHeader('Content-Type', type);
|
||||
|
||||
const contentRange = r.headers.get('content-range');
|
||||
if (contentRange) res.setHeader('Content-Range', contentRange);
|
||||
|
||||
const len = r.headers.get('content-length');
|
||||
if (len) res.setHeader('Content-Length', len);
|
||||
|
||||
const acceptRanges = r.headers.get('accept-ranges') ?? 'bytes';
|
||||
res.setHeader('Accept-Ranges', acceptRanges);
|
||||
|
||||
if (r.status === 206) res.status(206); // Partial Content for range responses
|
||||
|
||||
try {
|
||||
await pump(Readable.fromWeb(r.body as any), res);
|
||||
} catch (err) {}
|
||||
@Get('/agencies-list-count')
|
||||
async getAgenciesCount() {
|
||||
return this._agenciesService.getCount();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
import { Controller, Get } from '@nestjs/common';
|
||||
@Controller('/')
|
||||
export class RootController {
|
||||
@Get('/')
|
||||
getRoot(): string {
|
||||
return 'App is running!';
|
||||
}
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
} from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { SetsService } from '@gitroom/nestjs-libraries/database/prisma/sets/sets.service';
|
||||
import {
|
||||
UpdateSetsDto,
|
||||
SetsDto,
|
||||
} from '@gitroom/nestjs-libraries/dtos/sets/sets.dto';
|
||||
|
||||
@ApiTags('Sets')
|
||||
@Controller('/sets')
|
||||
export class SetsController {
|
||||
constructor(private _setsService: SetsService) {}
|
||||
|
||||
@Get('/')
|
||||
async getSets(@GetOrgFromRequest() org: Organization) {
|
||||
return this._setsService.getSets(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createASet(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SetsDto
|
||||
) {
|
||||
return this._setsService.createSet(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/')
|
||||
async updateSet(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UpdateSetsDto
|
||||
) {
|
||||
return this._setsService.createSet(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteSet(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._setsService.deleteSet(org.id, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,67 +1,130 @@
|
|||
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { StarsService } from '@gitroom/nestjs-libraries/database/prisma/stars/stars.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { AddTeamMemberDto } from '@gitroom/nestjs-libraries/dtos/settings/add.team.member.dto';
|
||||
import { ShortlinkPreferenceDto } from '@gitroom/nestjs-libraries/dtos/settings/shortlink-preference.dto';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import {AddTeamMemberDto} from "@gitroom/nestjs-libraries/dtos/settings/add.team.member.dto";
|
||||
import {ApiTags} from "@nestjs/swagger";
|
||||
|
||||
@ApiTags('Settings')
|
||||
@Controller('/settings')
|
||||
export class SettingsController {
|
||||
constructor(
|
||||
private _starsService: StarsService,
|
||||
private _organizationService: OrganizationService
|
||||
) {}
|
||||
|
||||
@Get('/github')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getConnectedGithubAccounts(@GetOrgFromRequest() org: Organization) {
|
||||
return {
|
||||
github: (
|
||||
await this._starsService.getGitHubRepositoriesByOrgId(org.id)
|
||||
).map((repo) => ({
|
||||
id: repo.id,
|
||||
login: repo.login,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/github')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async addGitHub(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body('code') code: string
|
||||
) {
|
||||
if (!code) {
|
||||
throw new Error('No code provided');
|
||||
}
|
||||
await this._starsService.addGitHub(org.id, code);
|
||||
}
|
||||
|
||||
@Get('/github/url')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
authUrl() {
|
||||
return {
|
||||
url: `https://github.com/login/oauth/authorize?client_id=${
|
||||
process.env.GITHUB_CLIENT_ID
|
||||
}&scope=${encodeURIComponent(
|
||||
'user:email'
|
||||
)}&redirect_uri=${encodeURIComponent(
|
||||
`${process.env.FRONTEND_URL}/settings`
|
||||
)}`,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/organizations/:id')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getOrganizations(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return {
|
||||
organizations: await this._starsService.getOrganizations(org.id, id),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/organizations/:id/:github')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getRepositories(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Param('github') github: string
|
||||
) {
|
||||
return {
|
||||
repositories: await this._starsService.getRepositoriesOfOrganization(
|
||||
org.id,
|
||||
id,
|
||||
github
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/organizations/:id')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async updateGitHubLogin(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('login') login: string
|
||||
) {
|
||||
return this._starsService.updateGitHubLogin(org.id, id, login);
|
||||
}
|
||||
|
||||
@Delete('/repository/:id')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async deleteRepository(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._starsService.deleteRepository(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/team')
|
||||
@CheckPolicies(
|
||||
[AuthorizationActions.Create, Sections.TEAM_MEMBERS],
|
||||
[AuthorizationActions.Create, Sections.ADMIN]
|
||||
)
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.TEAM_MEMBERS], [AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getTeam(@GetOrgFromRequest() org: Organization) {
|
||||
return this._organizationService.getTeam(org.id);
|
||||
}
|
||||
|
||||
@Post('/team')
|
||||
@CheckPolicies(
|
||||
[AuthorizationActions.Create, Sections.TEAM_MEMBERS],
|
||||
[AuthorizationActions.Create, Sections.ADMIN]
|
||||
)
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.TEAM_MEMBERS], [AuthorizationActions.Create, Sections.ADMIN])
|
||||
async inviteTeamMember(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AddTeamMemberDto
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: AddTeamMemberDto,
|
||||
) {
|
||||
return this._organizationService.inviteTeamMember(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/team/:id')
|
||||
@CheckPolicies(
|
||||
[AuthorizationActions.Create, Sections.TEAM_MEMBERS],
|
||||
[AuthorizationActions.Create, Sections.ADMIN]
|
||||
)
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.TEAM_MEMBERS], [AuthorizationActions.Create, Sections.ADMIN])
|
||||
deleteTeamMember(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._organizationService.deleteTeamMember(org, id);
|
||||
}
|
||||
|
||||
@Get('/shortlink')
|
||||
async getShortlinkPreference(@GetOrgFromRequest() org: Organization) {
|
||||
return this._organizationService.getShortlinkPreference(org.id);
|
||||
}
|
||||
|
||||
@Post('/shortlink')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async updateShortlinkPreference(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: ShortlinkPreferenceDto
|
||||
) {
|
||||
return this._organizationService.updateShortlinkPreference(
|
||||
org.id,
|
||||
body.shortlink
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { SignatureService } from '@gitroom/nestjs-libraries/database/prisma/signatures/signature.service';
|
||||
import { SignatureDto } from '@gitroom/nestjs-libraries/dtos/signature/signature.dto';
|
||||
|
||||
@ApiTags('Signatures')
|
||||
@Controller('/signatures')
|
||||
export class SignatureController {
|
||||
constructor(private _signatureService: SignatureService) {}
|
||||
|
||||
@Get('/')
|
||||
async getSignatures(@GetOrgFromRequest() org: Organization) {
|
||||
return this._signatureService.getSignaturesByOrgId(org.id);
|
||||
}
|
||||
|
||||
@Get('/default')
|
||||
async getDefaultSignature(@GetOrgFromRequest() org: Organization) {
|
||||
return (await this._signatureService.getDefaultSignature(org.id)) || {};
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
async createSignature(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SignatureDto
|
||||
) {
|
||||
return this._signatureService.createOrUpdateSignature(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteSignature(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._signatureService.deleteSignature(org.id, id);
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
async updateSignature(
|
||||
@Param('id') id: string,
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: SignatureDto
|
||||
) {
|
||||
return this._signatureService.createOrUpdateSignature(org.id, body, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,54 +1,83 @@
|
|||
import {
|
||||
Controller,
|
||||
HttpException,
|
||||
Get,
|
||||
Header,
|
||||
Param,
|
||||
Post,
|
||||
RawBodyRequest,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { CodesService } from '@gitroom/nestjs-libraries/services/codes.service';
|
||||
|
||||
@ApiTags('Stripe')
|
||||
@Controller('/stripe')
|
||||
export class StripeController {
|
||||
constructor(
|
||||
private readonly _stripeService: StripeService,
|
||||
private readonly _codesService: CodesService
|
||||
) {}
|
||||
@Post('/connect')
|
||||
stripeConnect(@Req() req: RawBodyRequest<Request>) {
|
||||
const event = this._stripeService.validateRequest(
|
||||
req.rawBody,
|
||||
req.headers['stripe-signature'],
|
||||
process.env.STRIPE_SIGNING_KEY_CONNECT
|
||||
);
|
||||
|
||||
// Maybe it comes from another stripe webhook
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
if (event?.data?.object?.metadata?.service !== 'gitroom') {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed':
|
||||
return this._stripeService.updateOrder(event);
|
||||
case 'account.updated':
|
||||
return this._stripeService.updateAccount(event);
|
||||
default:
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
stripe(@Req() req: RawBodyRequest<Request>) {
|
||||
const event = this._stripeService.validateRequest(
|
||||
req.rawBody,
|
||||
// @ts-ignore
|
||||
req.headers['stripe-signature'],
|
||||
process.env.STRIPE_SIGNING_KEY
|
||||
);
|
||||
|
||||
// Maybe it comes from another stripe webhook
|
||||
if (
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
event?.data?.object?.metadata?.service !== 'gitroom' &&
|
||||
event.type !== 'invoice.payment_succeeded'
|
||||
) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
if (event?.data?.object?.metadata?.service !== 'gitroom') {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
try {
|
||||
switch (event.type) {
|
||||
case 'invoice.payment_succeeded':
|
||||
return this._stripeService.paymentSucceeded(event);
|
||||
case 'customer.subscription.created':
|
||||
return this._stripeService.createSubscription(event);
|
||||
case 'customer.subscription.updated':
|
||||
return this._stripeService.updateSubscription(event);
|
||||
case 'customer.subscription.deleted':
|
||||
return this._stripeService.deleteSubscription(event);
|
||||
default:
|
||||
return { ok: true };
|
||||
}
|
||||
} catch (e) {
|
||||
throw new HttpException(e, 500);
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed':
|
||||
return this._stripeService.updateOrder(event);
|
||||
case 'account.updated':
|
||||
return this._stripeService.updateAccount(event);
|
||||
case 'customer.subscription.created':
|
||||
return this._stripeService.createSubscription(event);
|
||||
case 'customer.subscription.updated':
|
||||
return this._stripeService.updateSubscription(event);
|
||||
case 'customer.subscription.deleted':
|
||||
return this._stripeService.deleteSubscription(event);
|
||||
default:
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/lifetime-deal-codes/:provider')
|
||||
@Header('Content-disposition', 'attachment; filename=codes.csv')
|
||||
@Header('Content-type', 'text/csv')
|
||||
async getStripeCodes(@Param('provider') providerToken: string) {
|
||||
return this._codesService.generateCodes(providerToken);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,207 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Delete,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { ThirdPartyManager } from '@gitroom/nestjs-libraries/3rdparties/thirdparty.manager';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { AuthService } from '@gitroom/helpers/auth/auth.service';
|
||||
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
|
||||
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
|
||||
import { ImportMediaDto } from '@gitroom/nestjs-libraries/dtos/third-party/import-media.dto';
|
||||
|
||||
@ApiTags('Third Party')
|
||||
@Controller('/third-party')
|
||||
export class ThirdPartyController {
|
||||
private storage = UploadFactory.createStorage();
|
||||
|
||||
constructor(
|
||||
private _thirdPartyManager: ThirdPartyManager,
|
||||
private _mediaService: MediaService,
|
||||
) {}
|
||||
|
||||
@Get('/list')
|
||||
async getThirdPartyList() {
|
||||
return this._thirdPartyManager.getAllThirdParties();
|
||||
}
|
||||
|
||||
@Get('/')
|
||||
async getSavedThirdParty(@GetOrgFromRequest() organization: Organization) {
|
||||
return Promise.all(
|
||||
(
|
||||
await this._thirdPartyManager.getAllThirdPartiesByOrganization(
|
||||
organization.id
|
||||
)
|
||||
).map((thirdParty) => {
|
||||
const { description, fields, position, title, identifier } =
|
||||
this._thirdPartyManager.getThirdPartyByName(thirdParty.identifier);
|
||||
return {
|
||||
...thirdParty,
|
||||
title,
|
||||
position,
|
||||
fields,
|
||||
description,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
deleteById(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._thirdPartyManager.deleteIntegration(organization.id, id);
|
||||
}
|
||||
|
||||
@Post('/:id/submit')
|
||||
async generate(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() data: any
|
||||
) {
|
||||
const thirdParty = await this._thirdPartyManager.getIntegrationById(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const thirdPartyInstance = this._thirdPartyManager.getThirdPartyByName(
|
||||
thirdParty.identifier
|
||||
);
|
||||
|
||||
if (!thirdPartyInstance) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
const loadedData = await thirdPartyInstance?.instance?.sendData(
|
||||
AuthService.fixedDecryption(thirdParty.apiKey),
|
||||
data
|
||||
);
|
||||
|
||||
const file = await this.storage.uploadSimple(loadedData);
|
||||
return this._mediaService.saveFile(organization.id, file.split('/').pop(), file);
|
||||
}
|
||||
|
||||
@Post('/function/:id/:functionName')
|
||||
async callFunction(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Param('functionName') functionName: string,
|
||||
@Body() data: any
|
||||
) {
|
||||
const thirdParty = await this._thirdPartyManager.getIntegrationById(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const thirdPartyInstance = this._thirdPartyManager.getThirdPartyByName(
|
||||
thirdParty.identifier
|
||||
);
|
||||
|
||||
if (!thirdPartyInstance) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
return thirdPartyInstance?.instance?.[functionName](
|
||||
AuthService.fixedDecryption(thirdParty.apiKey),
|
||||
data
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/:id/import')
|
||||
async importMedia(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: ImportMediaDto
|
||||
) {
|
||||
const thirdParty = await this._thirdPartyManager.getIntegrationById(
|
||||
organization.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Integration not found', 404);
|
||||
}
|
||||
|
||||
const thirdPartyInstance = this._thirdPartyManager.getThirdPartyByName(
|
||||
thirdParty.identifier
|
||||
);
|
||||
|
||||
if (!thirdPartyInstance) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
const downloadUrls = await thirdPartyInstance?.instance?.['importMedia']?.(
|
||||
AuthService.fixedDecryption(thirdParty.apiKey),
|
||||
body.items
|
||||
);
|
||||
|
||||
if (!downloadUrls || !Array.isArray(downloadUrls)) {
|
||||
throw new HttpException('Import not supported', 400);
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const item of downloadUrls) {
|
||||
const file = await this.storage.uploadSimple(item.url);
|
||||
const saved = await this._mediaService.saveFile(
|
||||
organization.id,
|
||||
item.name || file.split('/').pop(),
|
||||
file
|
||||
);
|
||||
results.push(saved);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
@Post('/:identifier')
|
||||
async addApiKey(
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Param('identifier') identifier: string,
|
||||
@Body('api') api: string
|
||||
) {
|
||||
const thirdParty = this._thirdPartyManager.getThirdPartyByName(identifier);
|
||||
if (!thirdParty) {
|
||||
throw new HttpException('Invalid identifier', 400);
|
||||
}
|
||||
|
||||
const connect = await thirdParty.instance.checkConnection(api);
|
||||
if (!connect) {
|
||||
throw new HttpException('Invalid API key', 400);
|
||||
}
|
||||
|
||||
try {
|
||||
const save = await this._thirdPartyManager.saveIntegration(
|
||||
organization.id,
|
||||
identifier,
|
||||
api,
|
||||
{
|
||||
name: connect.name,
|
||||
username: connect.username,
|
||||
id: connect.id,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
id: save.id,
|
||||
};
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
throw new HttpException('Integration Already Exists', 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -9,7 +9,6 @@ import {
|
|||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.request';
|
||||
import { sign } from 'jsonwebtoken';
|
||||
import { Organization, User } from '@prisma/client';
|
||||
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
|
|
@ -18,19 +17,16 @@ import { Response, Request } from 'express';
|
|||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { removeSubdomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { UserDetailDto } from '@gitroom/nestjs-libraries/dtos/users/user.details.dto';
|
||||
import { EmailNotificationsDto } from '@gitroom/nestjs-libraries/dtos/users/email-notifications.dto';
|
||||
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
import { RealIP } from 'nestjs-real-ip';
|
||||
import { UserAgent } from '@gitroom/nestjs-libraries/user/user.agent';
|
||||
import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';
|
||||
import { TrackService } from '@gitroom/nestjs-libraries/track/track.service';
|
||||
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
@ApiTags('User')
|
||||
@Controller('/user')
|
||||
|
|
@ -40,61 +36,36 @@ export class UsersController {
|
|||
private _stripeService: StripeService,
|
||||
private _authService: AuthService,
|
||||
private _orgService: OrganizationService,
|
||||
private _userService: UsersService,
|
||||
private _trackService: TrackService
|
||||
private _userService: UsersService
|
||||
) {}
|
||||
@Get('/agent-media-sso')
|
||||
async getAgentMediaSsoUrl(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization
|
||||
) {
|
||||
if (!process.env.AGENT_MEDIA_SSO_KEY) {
|
||||
throw new HttpException('Agent Media SSO is not configured', 400);
|
||||
}
|
||||
|
||||
const token = sign(
|
||||
{ id: organization.id, displayName: organization.name },
|
||||
process.env.AGENT_MEDIA_SSO_KEY
|
||||
);
|
||||
|
||||
return { url: `https://agent-media.ai/sso/${token}` };
|
||||
}
|
||||
|
||||
@Get('/self')
|
||||
async getSelf(
|
||||
@GetUserFromRequest() user: User,
|
||||
@GetOrgFromRequest() organization: Organization,
|
||||
@Req() req: Request
|
||||
@Req() req: Request,
|
||||
) {
|
||||
if (!organization) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
const impersonate = req.cookies.impersonate || req.headers.impersonate;
|
||||
// @ts-ignore
|
||||
return {
|
||||
...user,
|
||||
orgId: organization.id,
|
||||
// @ts-ignore
|
||||
totalChannels: !process.env.STRIPE_PUBLISHABLE_KEY ? 10000 : organization?.subscription?.totalChannels || pricing.FREE.channel,
|
||||
totalChannels: organization?.subscription?.totalChannels || pricing.FREE.channel,
|
||||
// @ts-ignore
|
||||
tier: organization?.subscription?.subscriptionTier || (!process.env.STRIPE_PUBLISHABLE_KEY ? 'ULTIMATE' : 'FREE'),
|
||||
tier: organization?.subscription?.subscriptionTier || 'FREE',
|
||||
// @ts-ignore
|
||||
role: organization?.users[0]?.role,
|
||||
// @ts-ignore
|
||||
isLifetime: !!organization?.subscription?.isLifetime,
|
||||
admin: !!user.isSuperAdmin,
|
||||
impersonate: !!impersonate,
|
||||
isTrailing: !process.env.STRIPE_PUBLISHABLE_KEY ? false : organization?.isTrailing,
|
||||
allowTrial: organization?.allowTrial,
|
||||
streakSince: organization?.streakSince || null,
|
||||
// @ts-ignore
|
||||
publicApi: organization?.users[0]?.role === 'SUPERADMIN' || organization?.users[0]?.role === 'ADMIN' ? organization?.apiKey : '',
|
||||
impersonate: !!req.cookies.impersonate,
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/personal')
|
||||
async getPersonalInformation(@GetUserFromRequest() user: User) {
|
||||
async getPersonal(@GetUserFromRequest() user: User) {
|
||||
return this._userService.getPersonal(user.id);
|
||||
}
|
||||
|
||||
|
|
@ -121,20 +92,13 @@ export class UsersController {
|
|||
}
|
||||
|
||||
response.cookie('impersonate', id, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
domain:
|
||||
'.' + new URL(removeSubdomain(process.env.FRONTEND_URL!)).hostname,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('impersonate', id);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('/personal')
|
||||
|
|
@ -145,25 +109,6 @@ export class UsersController {
|
|||
return this._userService.changePersonal(user.id, body);
|
||||
}
|
||||
|
||||
@Get('/email-notifications')
|
||||
async getEmailNotifications(@GetUserFromRequest() user: User) {
|
||||
return this._userService.getEmailNotifications(user.id);
|
||||
}
|
||||
|
||||
@Post('/email-notifications')
|
||||
async updateEmailNotifications(
|
||||
@GetUserFromRequest() user: User,
|
||||
@Body() body: EmailNotificationsDto
|
||||
) {
|
||||
return this._userService.updateEmailNotifications(user.id, body);
|
||||
}
|
||||
|
||||
@Post('/api-key/rotate')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async rotateApiKey(@GetOrgFromRequest() organization: Organization) {
|
||||
return this._orgService.updateApiKey(organization.id);
|
||||
}
|
||||
|
||||
@Get('/subscription')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
|
||||
async getSubscription(@GetOrgFromRequest() organization: Organization) {
|
||||
|
|
@ -218,106 +163,49 @@ export class UsersController {
|
|||
@Res({ passthrough: true }) response: Response
|
||||
) {
|
||||
response.cookie('showorg', id, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
domain:
|
||||
'.' + new URL(removeSubdomain(process.env.FRONTEND_URL!)).hostname,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
|
||||
if (process.env.NOT_SECURED) {
|
||||
response.header('showorg', id);
|
||||
}
|
||||
|
||||
response.status(200).send();
|
||||
}
|
||||
|
||||
@Post('/logout')
|
||||
logout(@Res({ passthrough: true }) response: Response) {
|
||||
response.header('logout', 'true');
|
||||
response.cookie('auth', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
domain:
|
||||
'.' + new URL(removeSubdomain(process.env.FRONTEND_URL!)).hostname,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
maxAge: -1,
|
||||
expires: new Date(0),
|
||||
sameSite: 'none',
|
||||
});
|
||||
|
||||
response.cookie('showorg', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
domain:
|
||||
'.' + new URL(removeSubdomain(process.env.FRONTEND_URL!)).hostname,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
maxAge: -1,
|
||||
expires: new Date(0),
|
||||
sameSite: 'none',
|
||||
});
|
||||
|
||||
response.cookie('impersonate', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
domain:
|
||||
'.' + new URL(removeSubdomain(process.env.FRONTEND_URL!)).hostname,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
maxAge: -1,
|
||||
expires: new Date(0),
|
||||
sameSite: 'none',
|
||||
});
|
||||
|
||||
response.status(200).send();
|
||||
}
|
||||
|
||||
@Post('/t')
|
||||
async trackEvent(
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
@Req() req: Request,
|
||||
@GetUserFromRequest() user: User,
|
||||
@RealIP() ip: string,
|
||||
@UserAgent() userAgent: string,
|
||||
@Body()
|
||||
body: { tt: TrackEnum; fbclid: string; additional: Record<string, any> }
|
||||
) {
|
||||
const uniqueId = req?.cookies?.track || makeId(10);
|
||||
const fbclid = req?.cookies?.fbclid || body.fbclid;
|
||||
await this._trackService.track(
|
||||
uniqueId,
|
||||
ip,
|
||||
userAgent,
|
||||
body.tt,
|
||||
body.additional,
|
||||
fbclid,
|
||||
user
|
||||
);
|
||||
if (!req.cookies.track) {
|
||||
res.cookie('track', uniqueId, {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
track: uniqueId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,70 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { WebhooksService } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import {
|
||||
OnlyURL, UpdateDto, WebhooksDto
|
||||
} from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
|
||||
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
|
||||
@ApiTags('Webhooks')
|
||||
@Controller('/webhooks')
|
||||
export class WebhookController {
|
||||
constructor(private _webhooksService: WebhooksService) {}
|
||||
|
||||
@Get('/')
|
||||
async getStatistics(@GetOrgFromRequest() org: Organization) {
|
||||
return this._webhooksService.getWebhooks(org.id);
|
||||
}
|
||||
|
||||
@Post('/')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.WEBHOOKS])
|
||||
async createAWebhook(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: WebhooksDto
|
||||
) {
|
||||
return this._webhooksService.createWebhook(org.id, body);
|
||||
}
|
||||
|
||||
@Put('/')
|
||||
async updateWebhook(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UpdateDto
|
||||
) {
|
||||
return this._webhooksService.createWebhook(org.id, body);
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
async deleteWebhook(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
return this._webhooksService.deleteWebhook(org.id, id);
|
||||
}
|
||||
|
||||
@Post('/send')
|
||||
async sendWebhook(@Body() body: any, @Query() query: OnlyURL) {
|
||||
try {
|
||||
await fetch(query.url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
/** sent **/
|
||||
}
|
||||
|
||||
return { send: true };
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +1,21 @@
|
|||
import { Global, Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '@gitroom/nestjs-libraries/database/prisma/database.module';
|
||||
import { ApiModule } from '@gitroom/backend/api/api.module';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { PoliciesGuard } from '@gitroom/backend/services/auth/permissions/permissions.guard';
|
||||
import { PublicApiModule } from '@gitroom/backend/public-api/public.api.module';
|
||||
import { ThrottlerBehindProxyGuard } from '@gitroom/nestjs-libraries/throttler/throttler.provider';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { AgentModule } from '@gitroom/nestjs-libraries/agent/agent.module';
|
||||
import { ThirdPartyModule } from '@gitroom/nestjs-libraries/3rdparties/thirdparty.module';
|
||||
import { VideoModule } from '@gitroom/nestjs-libraries/videos/video.module';
|
||||
import { SentryModule } from '@sentry/nestjs/setup';
|
||||
import { FILTER } from '@gitroom/nestjs-libraries/sentry/sentry.exception';
|
||||
import { ChatModule } from '@gitroom/nestjs-libraries/chat/chat.module';
|
||||
import { getTemporalModule } from '@gitroom/nestjs-libraries/temporal/temporal.module';
|
||||
import { TemporalRegisterMissingSearchAttributesModule } from '@gitroom/nestjs-libraries/temporal/temporal.register';
|
||||
import { InfiniteWorkflowRegisterModule } from '@gitroom/nestjs-libraries/temporal/infinite.workflow.register';
|
||||
import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import {Global, Module} from '@nestjs/common';
|
||||
|
||||
import {DatabaseModule} from "@gitroom/nestjs-libraries/database/prisma/database.module";
|
||||
import {ApiModule} from "@gitroom/backend/api/api.module";
|
||||
import {APP_GUARD} from "@nestjs/core";
|
||||
import {PoliciesGuard} from "@gitroom/backend/services/auth/permissions/permissions.guard";
|
||||
import { BullMqModule } from '@gitroom/nestjs-libraries/bull-mq-transport-new/bull.mq.module';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
SentryModule.forRoot(),
|
||||
DatabaseModule,
|
||||
ApiModule,
|
||||
PublicApiModule,
|
||||
AgentModule,
|
||||
ThirdPartyModule,
|
||||
VideoModule,
|
||||
ChatModule,
|
||||
getTemporalModule(false),
|
||||
TemporalRegisterMissingSearchAttributesModule,
|
||||
InfiniteWorkflowRegisterModule,
|
||||
ThrottlerModule.forRoot({
|
||||
throttlers: [
|
||||
{
|
||||
ttl: 3600000,
|
||||
limit: process.env.API_LIMIT ? Number(process.env.API_LIMIT) : 90,
|
||||
},
|
||||
],
|
||||
storage: new ThrottlerStorageRedisService(ioRedis),
|
||||
}),
|
||||
],
|
||||
imports: [BullMqModule, DatabaseModule, ApiModule],
|
||||
controllers: [],
|
||||
providers: [
|
||||
FILTER,
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerBehindProxyGuard,
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: PoliciesGuard,
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
DatabaseModule,
|
||||
ApiModule,
|
||||
PublicApiModule,
|
||||
AgentModule,
|
||||
ThrottlerModule,
|
||||
ChatModule,
|
||||
],
|
||||
providers: [{
|
||||
provide: APP_GUARD,
|
||||
useClass: PoliciesGuard
|
||||
}],
|
||||
get exports() {
|
||||
return [...this.imports];
|
||||
}
|
||||
})
|
||||
export class AppModule {}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,4 @@
|
|||
import { initializeSentry } from '@gitroom/nestjs-libraries/sentry/initialize.sentry';
|
||||
initializeSentry('backend', true);
|
||||
import compression from 'compression';
|
||||
|
||||
import { loadSwagger } from '@gitroom/helpers/swagger/load.swagger';
|
||||
import { json } from 'express';
|
||||
import { Runtime } from '@temporalio/worker';
|
||||
Runtime.install({ shutdownSignals: [] });
|
||||
|
||||
process.env.TZ = 'UTC';
|
||||
|
||||
|
|
@ -13,54 +6,29 @@ import cookieParser from 'cookie-parser';
|
|||
import { Logger, ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
import { SubscriptionExceptionFilter } from '@gitroom/backend/services/auth/permissions/subscription.exception';
|
||||
import { HttpExceptionFilter } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
import { ConfigurationChecker } from '@gitroom/helpers/configuration/configuration.checker';
|
||||
import { startMcp } from '@gitroom/nestjs-libraries/chat/start.mcp';
|
||||
|
||||
async function start() {
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
rawBody: true,
|
||||
cors: {
|
||||
...(!process.env.NOT_SECURED ? { credentials: true } : {}),
|
||||
allowedHeaders: [
|
||||
'Content-Type',
|
||||
'Authorization',
|
||||
'auth',
|
||||
'showorg',
|
||||
'impersonate',
|
||||
'x-copilotkit-runtime-client-gql-version',
|
||||
],
|
||||
exposedHeaders: [
|
||||
'reload',
|
||||
'onboarding',
|
||||
'activate',
|
||||
'x-copilotkit-runtime-client-gql-version',
|
||||
...(process.env.NOT_SECURED ? ['auth', 'showorg', 'impersonate'] : []),
|
||||
],
|
||||
credentials: true,
|
||||
exposedHeaders: ['reload', 'onboarding', 'activate'],
|
||||
origin: [
|
||||
process.env.FRONTEND_URL,
|
||||
'http://localhost:6274',
|
||||
...(process.env.MAIN_URL ? [process.env.MAIN_URL] : []),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await startMcp(app);
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
transform: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(['/copilot/{*splat}', '/posts'], (req: any, res: any, next: any) => {
|
||||
json({ limit: '50mb' })(req, res, next);
|
||||
});
|
||||
|
||||
app.use(cookieParser());
|
||||
app.use(compression());
|
||||
app.useGlobalFilters(new SubscriptionExceptionFilter());
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
|
||||
|
|
@ -70,9 +38,6 @@ async function start() {
|
|||
|
||||
try {
|
||||
await app.listen(port);
|
||||
console.log('Backend started successfully on port ' + port);
|
||||
|
||||
checkConfiguration(); // Do this last, so that users will see obvious issues at the end of the startup log without having to scroll up.
|
||||
|
||||
Logger.log(`🚀 Backend is running on: http://localhost:${port}`);
|
||||
} catch (e) {
|
||||
|
|
@ -80,20 +45,4 @@ async function start() {
|
|||
}
|
||||
}
|
||||
|
||||
function checkConfiguration() {
|
||||
const checker = new ConfigurationChecker();
|
||||
checker.readEnvFromProcess();
|
||||
checker.check();
|
||||
|
||||
if (checker.hasIssues()) {
|
||||
for (const issue of checker.getIssues()) {
|
||||
Logger.warn(issue, 'Configuration issue');
|
||||
}
|
||||
|
||||
Logger.warn('Configuration issues found: ' + checker.getIssuesCount());
|
||||
} else {
|
||||
Logger.log('Configuration check completed without any issues');
|
||||
}
|
||||
}
|
||||
|
||||
start();
|
||||
bootstrap();
|
||||
|
|
|
|||
|
|
@ -1,37 +0,0 @@
|
|||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
|
||||
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
|
||||
import { PoliciesGuard } from '@gitroom/backend/services/auth/permissions/permissions.guard';
|
||||
import { PermissionsService } from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { UploadModule } from '@gitroom/nestjs-libraries/upload/upload.module';
|
||||
import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';
|
||||
import { ExtractContentService } from '@gitroom/nestjs-libraries/openai/extract.content.service';
|
||||
import { CodesService } from '@gitroom/nestjs-libraries/services/codes.service';
|
||||
import { PublicIntegrationsController } from '@gitroom/backend/public-api/routes/v1/public.integrations.controller';
|
||||
import { PublicAuthMiddleware } from '@gitroom/backend/services/auth/public.auth.middleware';
|
||||
|
||||
const authenticatedController = [PublicIntegrationsController];
|
||||
@Module({
|
||||
imports: [UploadModule],
|
||||
controllers: [...authenticatedController],
|
||||
providers: [
|
||||
AuthService,
|
||||
StripeService,
|
||||
OpenaiService,
|
||||
ExtractContentService,
|
||||
PoliciesGuard,
|
||||
PermissionsService,
|
||||
CodesService,
|
||||
IntegrationManager,
|
||||
],
|
||||
get exports() {
|
||||
return [...this.imports, ...this.providers];
|
||||
},
|
||||
})
|
||||
export class PublicApiModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer.apply(PublicAuthMiddleware).forRoutes(...authenticatedController);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,515 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
UsePipes,
|
||||
} from '@nestjs/common';
|
||||
import { CustomFileValidationPipe } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
|
||||
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
|
||||
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
|
||||
import { ChangePostStatusDto } from '@gitroom/nestjs-libraries/dtos/posts/change.post.status.dto';
|
||||
import {
|
||||
AuthorizationActions,
|
||||
Sections,
|
||||
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import { VideoDto } from '@gitroom/nestjs-libraries/dtos/videos/video.dto';
|
||||
import { VideoFunctionDto } from '@gitroom/nestjs-libraries/dtos/videos/video.function.dto';
|
||||
import { UploadDto } from '@gitroom/nestjs-libraries/dtos/media/upload.dto';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { GetNotificationsDto } from '@gitroom/nestjs-libraries/dtos/notifications/get.notifications.dto';
|
||||
import { Readable } from 'stream';
|
||||
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const { fromBuffer } = require('file-type');
|
||||
|
||||
const PUBLIC_API_ALLOWED_MIME = new Set<string>([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'image/avif',
|
||||
'image/bmp',
|
||||
'image/tiff',
|
||||
'video/mp4',
|
||||
]);
|
||||
import * as Sentry from '@sentry/nestjs';
|
||||
import {
|
||||
socialIntegrationList,
|
||||
IntegrationManager,
|
||||
} from '@gitroom/nestjs-libraries/integrations/integration.manager';
|
||||
import { getValidationSchemas } from '@gitroom/nestjs-libraries/chat/validation.schemas.helper';
|
||||
import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
|
||||
import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
|
||||
import { timer } from '@gitroom/helpers/utils/timer';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
|
||||
@ApiTags('Public API')
|
||||
@Controller('/public/v1')
|
||||
export class PublicIntegrationsController {
|
||||
private storage = UploadFactory.createStorage();
|
||||
|
||||
constructor(
|
||||
private _integrationService: IntegrationService,
|
||||
private _postsService: PostsService,
|
||||
private _mediaService: MediaService,
|
||||
private _notificationService: NotificationService,
|
||||
private _integrationManager: IntegrationManager,
|
||||
private _refreshIntegrationService: RefreshIntegrationService
|
||||
) {}
|
||||
|
||||
@Post('/upload')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@UsePipes(new CustomFileValidationPipe())
|
||||
async uploadSimple(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@UploadedFile('file') file: Express.Multer.File
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
if (!file) {
|
||||
throw new HttpException({ msg: 'No file provided' }, 400);
|
||||
}
|
||||
|
||||
const getFile = await this.storage.uploadFile(file);
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
getFile.originalname,
|
||||
getFile.path
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/upload-from-url')
|
||||
async uploadsFromUrl(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: UploadDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const response = await fetch(body.url, {
|
||||
// @ts-ignore — undici option, not in lib.dom fetch types
|
||||
dispatcher: ssrfSafeDispatcher,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HttpException({ msg: 'Failed to fetch URL' }, 400);
|
||||
}
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
const detected = await fromBuffer(buffer);
|
||||
if (!detected || !PUBLIC_API_ALLOWED_MIME.has(detected.mime)) {
|
||||
throw new HttpException({ msg: 'Unsupported file type.' }, 400);
|
||||
}
|
||||
const mimetype = detected.mime;
|
||||
const ext = detected.ext;
|
||||
|
||||
const getFile = await this.storage.uploadFile({
|
||||
buffer,
|
||||
mimetype,
|
||||
size: buffer.length,
|
||||
path: '',
|
||||
fieldname: '',
|
||||
destination: '',
|
||||
stream: new Readable(),
|
||||
filename: '',
|
||||
originalname: `upload.${ext}`,
|
||||
encoding: '',
|
||||
});
|
||||
|
||||
return this._mediaService.saveFile(
|
||||
org.id,
|
||||
getFile.originalname,
|
||||
getFile.path
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/find-slot/:id')
|
||||
async findSlotIntegration(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id?: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return { date: await this._postsService.findFreeDateTime(org.id, id) };
|
||||
}
|
||||
|
||||
@Get('/posts')
|
||||
async getPosts(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetPostsDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const posts = await this._postsService.getPosts(org.id, query);
|
||||
return {
|
||||
posts,
|
||||
// comments,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('/posts')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
|
||||
async createPost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() rawBody: any
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const body = await this._postsService.mapTypeToPost(
|
||||
rawBody,
|
||||
org.id,
|
||||
rawBody.type === 'draft'
|
||||
);
|
||||
body.type = rawBody.type;
|
||||
|
||||
if (
|
||||
process.env.RESTRICT_UPLOAD_DOMAINS &&
|
||||
body.posts.some((p) =>
|
||||
p.value.some((a) =>
|
||||
a.image.some(
|
||||
(i) => i.path.indexOf(process.env.RESTRICT_UPLOAD_DOMAINS) === -1
|
||||
)
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new HttpException(
|
||||
{
|
||||
msg: `All media must be uploaded through our upload API route and contain the domain: ${process.env.RESTRICT_UPLOAD_DOMAINS}`,
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
const allowedCreationMethods = ['CLI', 'API'] as const;
|
||||
const creationMethod = allowedCreationMethods.includes(
|
||||
rawBody.creationMethod
|
||||
)
|
||||
? (rawBody.creationMethod as 'CLI' | 'API')
|
||||
: 'API';
|
||||
|
||||
console.log(JSON.stringify(body, null, 2));
|
||||
return this._postsService.createPost(org.id, body, creationMethod);
|
||||
}
|
||||
|
||||
@Delete('/posts/:id')
|
||||
async deletePost(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const getPostById = await this._postsService.getPost(org.id, id);
|
||||
return this._postsService.deletePost(org.id, getPostById.group);
|
||||
}
|
||||
|
||||
@Delete('/posts/group/:group')
|
||||
deletePostByGroup(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('group') group: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.deletePost(org.id, group);
|
||||
}
|
||||
|
||||
@Get('/is-connected')
|
||||
async getActiveIntegrations(@GetOrgFromRequest() org: Organization) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return { connected: true };
|
||||
}
|
||||
|
||||
@Get('/integrations')
|
||||
async listIntegration(@GetOrgFromRequest() org: Organization) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return (await this._integrationService.getIntegrationsList(org.id)).map(
|
||||
(org) => ({
|
||||
id: org.id,
|
||||
name: org.name,
|
||||
identifier: org.providerIdentifier,
|
||||
picture: org.picture,
|
||||
disabled: org.disabled,
|
||||
profile: org.profile,
|
||||
customer: org.customer
|
||||
? {
|
||||
id: org.customer.id,
|
||||
name: org.customer.name,
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/social/:integration')
|
||||
@CheckPolicies([AuthorizationActions.Create, Sections.CHANNEL])
|
||||
async getIntegrationUrl(
|
||||
@Param('integration') integration: string,
|
||||
@Query('refresh') refresh: string,
|
||||
@GetOrgFromRequest() org: Organization
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
if (
|
||||
!this._integrationManager
|
||||
.getAllowedSocialsIntegrations()
|
||||
.includes(integration)
|
||||
) {
|
||||
throw new HttpException({ msg: 'Integration not allowed' }, 400);
|
||||
}
|
||||
|
||||
const integrationProvider =
|
||||
this._integrationManager.getSocialIntegration(integration);
|
||||
|
||||
if (integrationProvider.externalUrl) {
|
||||
throw new HttpException(
|
||||
{
|
||||
msg: 'This integration requires an external URL and is not supported via the public API',
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const { codeVerifier, state, url } =
|
||||
await integrationProvider.generateAuthUrl();
|
||||
|
||||
if (refresh) {
|
||||
await ioRedis.set(`refresh:${state}`, refresh, 'EX', 3600);
|
||||
}
|
||||
|
||||
await ioRedis.set(`organization:${state}`, org.id, 'EX', 3600);
|
||||
await ioRedis.set(`login:${state}`, codeVerifier, 'EX', 3600);
|
||||
|
||||
return { url };
|
||||
} catch (err) {
|
||||
throw new HttpException({ msg: 'Failed to generate auth URL' }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('/notifications')
|
||||
async getNotifications(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Query() query: GetNotificationsDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._notificationService.getNotificationsPaginated(
|
||||
org.id,
|
||||
query.page ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
@Post('/generate-video')
|
||||
generateVideo(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Body() body: VideoDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._mediaService.generateVideo(org, body);
|
||||
}
|
||||
|
||||
@Post('/video/function')
|
||||
videoFunction(@Body() body: VideoFunctionDto) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._mediaService.videoFunction(
|
||||
body.identifier,
|
||||
body.functionName,
|
||||
body.params
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('/integrations/:id')
|
||||
async deleteChannel(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const isTherePosts = await this._integrationService.getPostsForChannel(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
if (isTherePosts.length) {
|
||||
for (const post of isTherePosts) {
|
||||
this._postsService.deletePost(org.id, post.group).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
return this._integrationService.deleteChannel(org.id, id);
|
||||
}
|
||||
|
||||
@Get('/integration-settings/:id')
|
||||
async getIntegrationSettings(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const loadIntegration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
|
||||
const verified =
|
||||
JSON.parse(loadIntegration.additionalSettings || '[]')?.find(
|
||||
(p: any) => p?.title === 'Verified'
|
||||
)?.value || false;
|
||||
|
||||
const integration = socialIntegrationList.find(
|
||||
(p) => p.identifier === loadIntegration.providerIdentifier
|
||||
)!;
|
||||
|
||||
if (!integration) {
|
||||
return {
|
||||
output: { rules: '', maxLength: 0, settings: {}, tools: [] as any[] },
|
||||
};
|
||||
}
|
||||
|
||||
const maxLength = integration.maxLength(verified);
|
||||
const schemas = !integration.dto
|
||||
? false
|
||||
: getValidationSchemas()[integration.dto.name];
|
||||
const tools = this._integrationManager.getAllTools();
|
||||
const rules = this._integrationManager.getAllRulesDescription();
|
||||
|
||||
return {
|
||||
output: {
|
||||
rules: rules[integration.identifier],
|
||||
maxLength,
|
||||
settings: !schemas ? 'No additional settings required' : schemas,
|
||||
tools: tools[integration.identifier],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/posts/:id/missing')
|
||||
async getMissingContent(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.getMissingContent(org.id, id);
|
||||
}
|
||||
|
||||
@Put('/posts/:id/status')
|
||||
async changePostStatus(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: ChangePostStatusDto
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.changePostStatus(org.id, id, body.status);
|
||||
}
|
||||
|
||||
@Put('/posts/:id/release-id')
|
||||
async updateReleaseId(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body('releaseId') releaseId: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.updateReleaseId(org.id, id, releaseId);
|
||||
}
|
||||
|
||||
@Get('/analytics/:integration')
|
||||
async getAnalytics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('integration') integration: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._integrationService.checkAnalytics(org, integration, date);
|
||||
}
|
||||
|
||||
@Get('/analytics/post/:postId')
|
||||
async getPostAnalytics(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('postId') postId: string,
|
||||
@Query('date') date: string
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
return this._postsService.checkPostAnalytics(org.id, postId, +date);
|
||||
}
|
||||
|
||||
@Post('/integration-trigger/:id')
|
||||
async triggerIntegrationTool(
|
||||
@GetOrgFromRequest() org: Organization,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { methodName: string; data: Record<string, string> }
|
||||
) {
|
||||
Sentry.metrics.count('public_api-request', 1);
|
||||
const getIntegration = await this._integrationService.getIntegrationById(
|
||||
org.id,
|
||||
id
|
||||
);
|
||||
|
||||
if (!getIntegration) {
|
||||
throw new HttpException({ msg: 'Integration not found' }, 404);
|
||||
}
|
||||
|
||||
const integrationProvider = socialIntegrationList.find(
|
||||
(p) => p.identifier === getIntegration.providerIdentifier
|
||||
)!;
|
||||
|
||||
if (!integrationProvider) {
|
||||
throw new HttpException({ msg: 'Integration provider not found' }, 404);
|
||||
}
|
||||
|
||||
const tools = this._integrationManager.getAllTools();
|
||||
if (
|
||||
// @ts-ignore
|
||||
!tools[integrationProvider.identifier]?.some(
|
||||
(p: any) => p.methodName === body.methodName
|
||||
) ||
|
||||
// @ts-ignore
|
||||
!integrationProvider[body.methodName]
|
||||
) {
|
||||
throw new HttpException({ msg: 'Tool not found' }, 404);
|
||||
}
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
const result = await integrationProvider[body.methodName](
|
||||
getIntegration.token,
|
||||
body.data || {},
|
||||
getIntegration.internalId,
|
||||
getIntegration
|
||||
);
|
||||
|
||||
return { output: result };
|
||||
} catch (err) {
|
||||
if (err instanceof RefreshToken) {
|
||||
const data = await this._refreshIntegrationService.refresh(
|
||||
getIntegration
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
await this._integrationService.disconnectChannel(
|
||||
org.id,
|
||||
getIntegration
|
||||
);
|
||||
throw new HttpException(
|
||||
{ msg: 'Channel disconnected due to expired token' },
|
||||
401
|
||||
);
|
||||
}
|
||||
|
||||
const { accessToken } = data;
|
||||
|
||||
if (accessToken) {
|
||||
getIntegration.token = accessToken;
|
||||
|
||||
if (integrationProvider.refreshWait) {
|
||||
await timer(10000);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw new HttpException({ msg: 'Unexpected error' }, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,21 +6,17 @@ import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/o
|
|||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { getCookieUrlFromDomain } from '@gitroom/helpers/subdomain/subdomain.management';
|
||||
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
import { MastraService } from '@gitroom/nestjs-libraries/chat/mastra.service';
|
||||
|
||||
export const removeAuth = (res: Response) => {
|
||||
res.cookie('auth', '', {
|
||||
domain: getCookieUrlFromDomain(process.env.FRONTEND_URL!),
|
||||
...(!process.env.NOT_SECURED
|
||||
? {
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
}
|
||||
: {}),
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: 'none',
|
||||
expires: new Date(0),
|
||||
maxAge: -1,
|
||||
});
|
||||
|
||||
res.header('logout', 'true');
|
||||
};
|
||||
|
||||
|
|
@ -47,10 +43,9 @@ export class AuthMiddleware implements NestMiddleware {
|
|||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
const impersonate = req.cookies.impersonate || req.headers.impersonate;
|
||||
if (user?.isSuperAdmin && impersonate) {
|
||||
if (user?.isSuperAdmin && req.cookies.impersonate) {
|
||||
const loadImpersonate = await this._organizationService.getUserOrg(
|
||||
impersonate
|
||||
req.cookies.impersonate
|
||||
);
|
||||
|
||||
if (loadImpersonate) {
|
||||
|
|
@ -86,10 +81,6 @@ export class AuthMiddleware implements NestMiddleware {
|
|||
throw new HttpForbiddenException();
|
||||
}
|
||||
|
||||
if (!setOrg.apiKey) {
|
||||
await this._organizationService.updateApiKey(setOrg.id);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
req.user = user;
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ import { LoginUserDto } from '@gitroom/nestjs-libraries/dtos/auth/login.user.dto
|
|||
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { AuthService as AuthChecker } from '@gitroom/helpers/auth/auth.service';
|
||||
import { AuthProviderManager } from '@gitroom/backend/services/auth/providers/providers.manager';
|
||||
import { ProvidersFactory } from '@gitroom/backend/services/auth/providers/providers.factory';
|
||||
import dayjs from 'dayjs';
|
||||
import { NewsletterService } from '@gitroom/nestjs-libraries/services/newsletter.service';
|
||||
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
|
||||
import { ForgotReturnPasswordDto } from '@gitroom/nestjs-libraries/dtos/auth/forgot-return.password.dto';
|
||||
import { EmailService } from '@gitroom/nestjs-libraries/services/email.service';
|
||||
import { NewsletterService } from '@gitroom/nestjs-libraries/newsletter/newsletter.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
|
|
@ -19,48 +19,20 @@ export class AuthService {
|
|||
private _organizationService: OrganizationService,
|
||||
private _notificationService: NotificationService,
|
||||
private _emailService: EmailService,
|
||||
private _providerManager: AuthProviderManager
|
||||
) {}
|
||||
async canRegister(provider: string) {
|
||||
if (
|
||||
process.env.DISABLE_REGISTRATION !== 'true' ||
|
||||
provider === Provider.GENERIC
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (await this._organizationService.getCount()) === 0;
|
||||
}
|
||||
|
||||
async routeAuth(
|
||||
provider: Provider,
|
||||
body: CreateOrgUserDto | LoginUserDto,
|
||||
ip: string,
|
||||
userAgent: string,
|
||||
addToOrg?: boolean | { orgId: string; role: 'USER' | 'ADMIN'; id: string }
|
||||
) {
|
||||
if (provider === Provider.LOCAL) {
|
||||
if (process.env.DISALLOW_PLUS && body.email.includes('+')) {
|
||||
throw new Error('Email with plus sign is not allowed');
|
||||
}
|
||||
if (body instanceof CreateOrgUserDto) {
|
||||
body.email = body.email.toLowerCase();
|
||||
}
|
||||
const user = await this._userService.getUserByEmail(body.email);
|
||||
if (body instanceof CreateOrgUserDto) {
|
||||
if (user) {
|
||||
throw new Error('Email already exists');
|
||||
throw new Error('User already exists');
|
||||
}
|
||||
|
||||
if (!(await this.canRegister(provider))) {
|
||||
throw new Error('Registration is disabled');
|
||||
}
|
||||
|
||||
const create = await this._organizationService.createOrgAndUser(
|
||||
body,
|
||||
ip,
|
||||
userAgent
|
||||
);
|
||||
const create = await this._organizationService.createOrgAndUser(body);
|
||||
|
||||
const addedOrg =
|
||||
addToOrg && typeof addToOrg !== 'boolean'
|
||||
|
|
@ -73,12 +45,7 @@ export class AuthService {
|
|||
: false;
|
||||
|
||||
const obj = { addedOrg, jwt: await this.jwt(create.users[0].user) };
|
||||
await this._emailService.sendEmail(
|
||||
body.email,
|
||||
'Activate your account',
|
||||
`Click <a href="${process.env.FRONTEND_URL}/auth/activate/${obj.jwt}">here</a> to activate your account`,
|
||||
'top'
|
||||
);
|
||||
await this._emailService.sendEmail(body.email, 'Activate your account', `Click <a href="${process.env.FRONTEND_URL}/auth/activate/${obj.jwt}">here</a> to activate your account`);
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
|
@ -95,9 +62,7 @@ export class AuthService {
|
|||
|
||||
const user = await this.loginOrRegisterProvider(
|
||||
provider,
|
||||
body as CreateOrgUserDto,
|
||||
ip,
|
||||
userAgent
|
||||
body as CreateOrgUserDto
|
||||
);
|
||||
|
||||
const addedOrg =
|
||||
|
|
@ -136,11 +101,9 @@ export class AuthService {
|
|||
|
||||
private async loginOrRegisterProvider(
|
||||
provider: Provider,
|
||||
body: CreateOrgUserDto,
|
||||
ip: string,
|
||||
userAgent: string
|
||||
body: CreateOrgUserDto
|
||||
) {
|
||||
const providerInstance = this._providerManager.getProvider(provider);
|
||||
const providerInstance = ProvidersFactory.loadProvider(provider);
|
||||
const providerUser = await providerInstance.getUser(body.providerToken);
|
||||
|
||||
if (!providerUser) {
|
||||
|
|
@ -155,65 +118,19 @@ export class AuthService {
|
|||
return user;
|
||||
}
|
||||
|
||||
if (!(await this.canRegister(provider))) {
|
||||
throw new Error('Registration is disabled');
|
||||
}
|
||||
const create = await this._organizationService.createOrgAndUser({
|
||||
company: body.company,
|
||||
email: providerUser.email,
|
||||
password: '',
|
||||
provider,
|
||||
providerId: providerUser.id,
|
||||
});
|
||||
|
||||
const create = await this._organizationService.createOrgAndUser(
|
||||
{
|
||||
company: body.company,
|
||||
email: providerUser.email,
|
||||
password: '',
|
||||
provider,
|
||||
providerId: providerUser.id,
|
||||
datafast_visitor_id: body.datafast_visitor_id,
|
||||
},
|
||||
ip,
|
||||
userAgent
|
||||
);
|
||||
|
||||
this._track('register', providerUser.email, body.datafast_visitor_id).catch(
|
||||
(err) => {}
|
||||
);
|
||||
|
||||
await NewsletterService.register(providerUser.email);
|
||||
|
||||
try {
|
||||
if (providerInstance?.postRegistration) {
|
||||
await providerInstance.postRegistration(body.providerToken, create.id);
|
||||
}
|
||||
} catch (err) {
|
||||
// Don't fail registration if postRegistration fails
|
||||
}
|
||||
NewsletterService.register(providerUser.email);
|
||||
|
||||
return create.users[0].user;
|
||||
}
|
||||
|
||||
private async _track(
|
||||
name: string,
|
||||
email: string,
|
||||
datafast_visitor_id: string
|
||||
) {
|
||||
if (email && datafast_visitor_id && process.env.DATAFAST_API_KEY) {
|
||||
try {
|
||||
await fetch('https://datafa.st/api/v1/goals', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${process.env.DATAFAST_API_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
datafast_visitor_id: datafast_visitor_id,
|
||||
name: name,
|
||||
metadata: {
|
||||
email,
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
|
||||
async forgot(email: string) {
|
||||
const user = await this._userService.getUserByEmail(email);
|
||||
if (!user || user.providerName !== Provider.LOCAL) {
|
||||
|
|
@ -244,12 +161,8 @@ export class AuthService {
|
|||
return this._userService.updatePassword(user.id, body.password);
|
||||
}
|
||||
|
||||
async activate(code: string, tracking: string) {
|
||||
const user = AuthChecker.verifyJWT(code) as {
|
||||
id: string;
|
||||
activated: boolean;
|
||||
email: string;
|
||||
};
|
||||
async activate(code: string) {
|
||||
const user = AuthChecker.verifyJWT(code) as { id: string, activated: boolean, email: string };
|
||||
if (user.id && !user.activated) {
|
||||
const getUserAgain = await this._userService.getUserByEmail(user.email);
|
||||
if (getUserAgain.activated) {
|
||||
|
|
@ -257,7 +170,6 @@ export class AuthService {
|
|||
}
|
||||
await this._userService.activateUser(user.id);
|
||||
user.activated = true;
|
||||
this._track('register', user.email, tracking).catch((err) => {});
|
||||
await NewsletterService.register(user.email);
|
||||
return this.jwt(user as any);
|
||||
}
|
||||
|
|
@ -265,37 +177,18 @@ export class AuthService {
|
|||
return false;
|
||||
}
|
||||
|
||||
async resendActivationEmail(email: string) {
|
||||
const user = await this._userService.getUserByEmail(email);
|
||||
|
||||
if (!user) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
|
||||
if (user.activated) {
|
||||
throw new Error('Account is already activated');
|
||||
}
|
||||
|
||||
const jwt = await this.jwt(user);
|
||||
|
||||
await this._emailService.sendEmail(
|
||||
user.email,
|
||||
'Activate your account',
|
||||
`Click <a href="${process.env.FRONTEND_URL}/auth/activate/${jwt}">here</a> to activate your account`,
|
||||
'top'
|
||||
oauthLink(provider: string) {
|
||||
const providerInstance = ProvidersFactory.loadProvider(
|
||||
provider as Provider
|
||||
);
|
||||
|
||||
return true;
|
||||
return providerInstance.generateLink();
|
||||
}
|
||||
|
||||
oauthLink(provider: string, query?: any) {
|
||||
const providerInstance = this._providerManager.getProvider(provider);
|
||||
return providerInstance.generateLink(query);
|
||||
}
|
||||
|
||||
async checkExists(provider: string, code: string, redirectUri?: string) {
|
||||
const providerInstance = this._providerManager.getProvider(provider);
|
||||
const token = await providerInstance.getToken(code, redirectUri);
|
||||
async checkExists(provider: string, code: string) {
|
||||
const providerInstance = ProvidersFactory.loadProvider(
|
||||
provider as Provider
|
||||
);
|
||||
const token = await providerInstance.getToken(code);
|
||||
const user = await providerInstance.getUser(token);
|
||||
if (!user) {
|
||||
throw new Error('Invalid user');
|
||||
|
|
@ -312,9 +205,6 @@ export class AuthService {
|
|||
}
|
||||
|
||||
private async jwt(user: User) {
|
||||
if (user.password) {
|
||||
delete user.password;
|
||||
}
|
||||
return AuthChecker.signJWT(user);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +0,0 @@
|
|||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export enum Sections {
|
||||
CHANNEL = 'channel',
|
||||
POSTS_PER_MONTH = 'posts_per_month',
|
||||
VIDEOS_PER_MONTH = 'videos_per_month',
|
||||
TEAM_MEMBERS = 'team_members',
|
||||
COMMUNITY_FEATURES = 'community_features',
|
||||
FEATURED_BY_GITROOM = 'featured_by_gitroom',
|
||||
AI = 'ai',
|
||||
IMPORT_FROM_CHANNELS = 'import_from_channels',
|
||||
ADMIN = 'admin',
|
||||
WEBHOOKS = 'webhooks',
|
||||
}
|
||||
|
||||
export enum AuthorizationActions {
|
||||
Create = 'create',
|
||||
Read = 'read',
|
||||
Update = 'update',
|
||||
Delete = 'delete',
|
||||
}
|
||||
|
||||
export class SubscriptionException extends HttpException {
|
||||
constructor(message: { section: Sections; action: AuthorizationActions }) {
|
||||
super(message, HttpStatus.PAYMENT_REQUIRED);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
import { SetMetadata } from '@nestjs/common';
|
||||
import { AuthorizationActions, Sections } from './permission.exception.class';
|
||||
import {SetMetadata} from "@nestjs/common";
|
||||
import {AuthorizationActions, Sections} from "@gitroom/backend/services/auth/permissions/permissions.service";
|
||||
|
||||
export const CHECK_POLICIES_KEY = 'check_policy';
|
||||
export type AbilityPolicy = [AuthorizationActions, Sections];
|
||||
export const CheckPolicies = (...handlers: AbilityPolicy[]) =>
|
||||
SetMetadata(CHECK_POLICIES_KEY, handlers);
|
||||
export const CheckPolicies = (...handlers: AbilityPolicy[]) => SetMetadata(CHECK_POLICIES_KEY, handlers);
|
||||
|
|
|
|||
|
|
@ -1,39 +1,29 @@
|
|||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import {
|
||||
AppAbility,
|
||||
PermissionsService,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.service';
|
||||
import {
|
||||
AbilityPolicy,
|
||||
CHECK_POLICIES_KEY,
|
||||
} from '@gitroom/backend/services/auth/permissions/permissions.ability';
|
||||
import { Organization } from '@prisma/client';
|
||||
import { Request } from 'express';
|
||||
import { SubscriptionException } from './permission.exception.class';
|
||||
import {CanActivate, ExecutionContext, Injectable} from "@nestjs/common";
|
||||
import {Reflector} from "@nestjs/core";
|
||||
import {AppAbility, PermissionsService} from "@gitroom/backend/services/auth/permissions/permissions.service";
|
||||
import {AbilityPolicy, CHECK_POLICIES_KEY} from "@gitroom/backend/services/auth/permissions/permissions.ability";
|
||||
import {Organization} from "@prisma/client";
|
||||
import {SubscriptionException} from "@gitroom/backend/services/auth/permissions/subscription.exception";
|
||||
import {Request} from "express";
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class PoliciesGuard implements CanActivate {
|
||||
constructor(
|
||||
private _reflector: Reflector,
|
||||
private _authorizationService: PermissionsService
|
||||
private _authorizationService: PermissionsService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request: Request = context.switchToHttp().getRequest();
|
||||
if (
|
||||
request.path.indexOf('/auth') > -1 ||
|
||||
request.path.indexOf('/auth') > -1 ||
|
||||
request.path.indexOf('/integrations/social-connect') > -1 ||
|
||||
request.path.indexOf('/integrations/provider') > -1
|
||||
) {
|
||||
if (request.path.indexOf('/auth') > -1 || request.path.indexOf('/stripe') > -1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const policyHandlers =
|
||||
this._reflector.get<AbilityPolicy[]>(
|
||||
CHECK_POLICIES_KEY,
|
||||
context.getHandler()
|
||||
context.getHandler(),
|
||||
) || [];
|
||||
|
||||
if (!policyHandlers || !policyHandlers.length) {
|
||||
|
|
@ -42,21 +32,19 @@ export class PoliciesGuard implements CanActivate {
|
|||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
const { org }: { org: Organization } = request;
|
||||
|
||||
const refreshChannelId = typeof request.query?.refresh === 'string' ? request.query.refresh : undefined;
|
||||
const { org } : {org: Organization} = request;
|
||||
|
||||
// @ts-ignore
|
||||
const ability = await this._authorizationService.check(org.id, org.createdAt, org.users[0].role, policyHandlers, refreshChannelId);
|
||||
const ability = await this._authorizationService.check(org.id, org.createdAt, org.users[0].role, policyHandlers);
|
||||
|
||||
const item = policyHandlers.find(
|
||||
(handler) => !this.execPolicyHandler(handler, ability)
|
||||
const item = policyHandlers.find((handler) =>
|
||||
!this.execPolicyHandler(handler, ability),
|
||||
);
|
||||
|
||||
if (item) {
|
||||
throw new SubscriptionException({
|
||||
section: item[1],
|
||||
action: item[0],
|
||||
action: item[0]
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,8 +5,24 @@ import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/s
|
|||
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
|
||||
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
|
||||
import dayjs from 'dayjs';
|
||||
import { WebhooksService } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.service';
|
||||
import { AuthorizationActions, Sections } from './permission.exception.class';
|
||||
|
||||
export enum Sections {
|
||||
CHANNEL = 'channel',
|
||||
POSTS_PER_MONTH = 'posts_per_month',
|
||||
TEAM_MEMBERS = 'team_members',
|
||||
COMMUNITY_FEATURES = 'community_features',
|
||||
FEATURED_BY_GITROOM = 'featured_by_gitroom',
|
||||
AI = 'ai',
|
||||
IMPORT_FROM_CHANNELS = 'import_from_channels',
|
||||
ADMIN = 'admin',
|
||||
}
|
||||
|
||||
export enum AuthorizationActions {
|
||||
Create = 'create',
|
||||
Read = 'read',
|
||||
Update = 'update',
|
||||
Delete = 'delete',
|
||||
}
|
||||
|
||||
export type AppAbility = Ability<[AuthorizationActions, Sections]>;
|
||||
|
||||
|
|
@ -15,8 +31,7 @@ export class PermissionsService {
|
|||
constructor(
|
||||
private _subscriptionService: SubscriptionService,
|
||||
private _postsService: PostsService,
|
||||
private _integrationService: IntegrationService,
|
||||
private _webhooksService: WebhooksService
|
||||
private _integrationService: IntegrationService
|
||||
) {}
|
||||
async getPackageOptions(orgId: string) {
|
||||
const subscription =
|
||||
|
|
@ -40,8 +55,7 @@ export class PermissionsService {
|
|||
orgId: string,
|
||||
created_at: Date,
|
||||
permission: 'USER' | 'ADMIN' | 'SUPERADMIN',
|
||||
requestedPermission: Array<[AuthorizationActions, Sections]>,
|
||||
refreshChannelId?: string
|
||||
requestedPermission: Array<[AuthorizationActions, Sections]>
|
||||
) {
|
||||
const { can, build } = new AbilityBuilder<
|
||||
Ability<[AuthorizationActions, Sections]>
|
||||
|
|
@ -66,23 +80,9 @@ export class PermissionsService {
|
|||
for (const [action, section] of requestedPermission) {
|
||||
// check for the amount of channels
|
||||
if (section === Sections.CHANNEL) {
|
||||
// Refreshing an existing channel doesn't add a new one, so skip the limit check
|
||||
// but only if the channel actually belongs to this org
|
||||
if (refreshChannelId) {
|
||||
const existingIntegration =
|
||||
await this._integrationService.getIntegrationById(
|
||||
orgId,
|
||||
refreshChannelId
|
||||
);
|
||||
if (existingIntegration) {
|
||||
can(action, section);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const totalChannels = (
|
||||
await this._integrationService.getIntegrationsList(orgId)
|
||||
).filter((f) => !f.refreshNeeded).length;
|
||||
).filter(f => !f.refreshNeeded).length;
|
||||
|
||||
if (
|
||||
(options.channel && options.channel > totalChannels) ||
|
||||
|
|
@ -93,14 +93,6 @@ export class PermissionsService {
|
|||
}
|
||||
}
|
||||
|
||||
if (section === Sections.WEBHOOKS) {
|
||||
const totalWebhooks = await this._webhooksService.getTotal(orgId);
|
||||
if (totalWebhooks < options.webhooks) {
|
||||
can(AuthorizationActions.Create, section);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// check for posts per month
|
||||
if (section === Sections.POSTS_PER_MONTH) {
|
||||
const createdAt =
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
} from '@nestjs/common';
|
||||
import { AuthorizationActions, Sections, SubscriptionException } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
|
||||
import {ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus} from "@nestjs/common";
|
||||
import {AuthorizationActions, Sections} from "@gitroom/backend/services/auth/permissions/permissions.service";
|
||||
|
||||
export class SubscriptionException extends HttpException {
|
||||
constructor(message: {
|
||||
section: Sections,
|
||||
action: AuthorizationActions
|
||||
}) {
|
||||
super(message, HttpStatus.PAYMENT_REQUIRED);
|
||||
}
|
||||
}
|
||||
|
||||
@Catch(SubscriptionException)
|
||||
export class SubscriptionExceptionFilter implements ExceptionFilter {
|
||||
|
|
@ -12,23 +16,19 @@ export class SubscriptionExceptionFilter implements ExceptionFilter {
|
|||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse();
|
||||
const status = exception.getStatus();
|
||||
const error: { section: Sections; action: AuthorizationActions } =
|
||||
exception.getResponse() as any;
|
||||
const error: {section: Sections, action: AuthorizationActions} = exception.getResponse() as any;
|
||||
|
||||
const message = getErrorMessage(error);
|
||||
|
||||
response.status(status).json({
|
||||
statusCode: status,
|
||||
message,
|
||||
url: process.env.FRONTEND_URL + '/billing',
|
||||
statusCode: status,
|
||||
message,
|
||||
url: process.env.FRONTEND_URL + '/billing',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const getErrorMessage = (error: {
|
||||
section: Sections;
|
||||
action: AuthorizationActions;
|
||||
}) => {
|
||||
const getErrorMessage = (error: {section: Sections, action: AuthorizationActions}) => {
|
||||
switch (error.section) {
|
||||
case Sections.POSTS_PER_MONTH:
|
||||
switch (error.action) {
|
||||
|
|
@ -40,15 +40,5 @@ const getErrorMessage = (error: {
|
|||
default:
|
||||
return 'You have reached the maximum number of channels for your subscription. Please upgrade your subscription to add more channels.';
|
||||
}
|
||||
case Sections.WEBHOOKS:
|
||||
switch (error.action) {
|
||||
default:
|
||||
return 'You have reached the maximum number of webhooks for your subscription. Please upgrade your subscription to add more webhooks.';
|
||||
}
|
||||
case Sections.VIDEOS_PER_MONTH:
|
||||
switch (error.action) {
|
||||
default:
|
||||
return 'You have reached the maximum number of generated videos for your subscription. Please upgrade your subscription to generate more videos.';
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,34 +1,5 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
export abstract class AuthProviderAbstract {
|
||||
abstract generateLink(query?: any): Promise<string> | string;
|
||||
abstract getToken(code: string, redirectUri?: string): Promise<string>;
|
||||
abstract getUser(
|
||||
providerToken: string
|
||||
): Promise<{ email: string; id: string }> | false;
|
||||
async postRegistration(
|
||||
providerToken: string,
|
||||
orgId: string
|
||||
): Promise<void> {}
|
||||
}
|
||||
|
||||
export interface AuthProviderParams {
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export function AuthProvider(params: AuthProviderParams) {
|
||||
return function (target: any) {
|
||||
Injectable()(target);
|
||||
|
||||
const existingMetadata =
|
||||
Reflect.getMetadata('auth-provider', AuthProviderAbstract) || [];
|
||||
|
||||
existingMetadata.push({ target, provider: params.provider });
|
||||
|
||||
Reflect.defineMetadata(
|
||||
'auth-provider',
|
||||
existingMetadata,
|
||||
AuthProviderAbstract
|
||||
);
|
||||
};
|
||||
}
|
||||
export interface ProvidersInterface {
|
||||
generateLink(): string;
|
||||
getToken(code: string): Promise<string>;
|
||||
getUser(providerToken: string): Promise<{email: string, id: string}> | false;
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { NeynarAPIClient } from '@neynar/nodejs-sdk';
|
||||
|
||||
const client = new NeynarAPIClient({
|
||||
apiKey: process.env.NEYNAR_SECRET_KEY || '00000000-000-0000-000-000000000000',
|
||||
});
|
||||
|
||||
@AuthProvider({ provider: 'FARCASTER' })
|
||||
export class FarcasterProvider extends AuthProviderAbstract {
|
||||
generateLink() {
|
||||
return '';
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string) {
|
||||
const data = JSON.parse(Buffer.from(code, 'base64').toString());
|
||||
const status = await client.lookupSigner({ signerUuid: data.signer_uuid });
|
||||
if (status.status === 'approved') {
|
||||
return data.signer_uuid;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
async getUser(providerToken: string) {
|
||||
const status = await client.lookupSigner({ signerUuid: providerToken });
|
||||
if (status.status !== 'approved') {
|
||||
return {
|
||||
id: '',
|
||||
email: '',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: String('farcaster_' + status.fid),
|
||||
email: String('farcaster_' + status.fid),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +1,6 @@
|
|||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { ProvidersInterface } from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
@AuthProvider({ provider: 'GITHUB' })
|
||||
export class GithubProvider extends AuthProviderAbstract {
|
||||
export class GithubProvider implements ProvidersInterface {
|
||||
generateLink(): string {
|
||||
return `https://github.com/login/oauth/authorize?client_id=${
|
||||
process.env.GITHUB_CLIENT_ID
|
||||
|
|
@ -13,7 +9,7 @@ export class GithubProvider extends AuthProviderAbstract {
|
|||
)}`;
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string): Promise<string> {
|
||||
async getToken(code: string): Promise<string> {
|
||||
const { access_token } = await (
|
||||
await fetch('https://github.com/login/oauth/access_token', {
|
||||
method: 'POST',
|
||||
|
|
|
|||
|
|
@ -1,28 +1,45 @@
|
|||
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
|
||||
import { google } from 'googleapis';
|
||||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { OAuth2Client } from 'google-auth-library/build/src/auth/oauth2client';
|
||||
import { ProvidersInterface } from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
const defaultRedirect = () =>
|
||||
`${process.env.FRONTEND_URL}/integrations/social/youtube`;
|
||||
|
||||
const makeClient = (redirectUri: string) =>
|
||||
new google.auth.OAuth2({
|
||||
const clientAndYoutube = () => {
|
||||
const client = new google.auth.OAuth2({
|
||||
clientId: process.env.YOUTUBE_CLIENT_ID,
|
||||
clientSecret: process.env.YOUTUBE_CLIENT_SECRET,
|
||||
redirectUri,
|
||||
redirectUri: `${process.env.FRONTEND_URL}/integrations/social/youtube`,
|
||||
});
|
||||
|
||||
@AuthProvider({ provider: 'GOOGLE' })
|
||||
export class GoogleProvider extends AuthProviderAbstract {
|
||||
generateLink(query?: { redirect_uri?: string }) {
|
||||
const redirectUri = query?.redirect_uri || defaultRedirect();
|
||||
return makeClient(redirectUri).generateAuthUrl({
|
||||
const youtube = (newClient: OAuth2Client) =>
|
||||
google.youtube({
|
||||
version: 'v3',
|
||||
auth: newClient,
|
||||
});
|
||||
|
||||
const youtubeAnalytics = (newClient: OAuth2Client) =>
|
||||
google.youtubeAnalytics({
|
||||
version: 'v2',
|
||||
auth: newClient,
|
||||
});
|
||||
|
||||
const oauth2 = (newClient: OAuth2Client) =>
|
||||
google.oauth2({
|
||||
version: 'v2',
|
||||
auth: newClient,
|
||||
});
|
||||
|
||||
return { client, youtube, oauth2, youtubeAnalytics };
|
||||
};
|
||||
|
||||
export class GoogleProvider implements ProvidersInterface {
|
||||
generateLink() {
|
||||
const state = makeId(7);
|
||||
const { client } = clientAndYoutube();
|
||||
return client.generateAuthUrl({
|
||||
access_type: 'online',
|
||||
prompt: 'consent',
|
||||
state: 'login',
|
||||
redirect_uri: redirectUri,
|
||||
state,
|
||||
redirect_uri: `${process.env.FRONTEND_URL}/integrations/social/youtube`,
|
||||
scope: [
|
||||
'https://www.googleapis.com/auth/userinfo.profile',
|
||||
'https://www.googleapis.com/auth/userinfo.email',
|
||||
|
|
@ -30,22 +47,21 @@ export class GoogleProvider extends AuthProviderAbstract {
|
|||
});
|
||||
}
|
||||
|
||||
async getToken(code: string, redirectUri?: string) {
|
||||
const client = makeClient(redirectUri || defaultRedirect());
|
||||
async getToken(code: string) {
|
||||
const { client, oauth2 } = clientAndYoutube();
|
||||
const { tokens } = await client.getToken(code);
|
||||
return tokens.access_token!;
|
||||
return tokens.access_token;
|
||||
}
|
||||
|
||||
async getUser(providerToken: string) {
|
||||
const client = makeClient(defaultRedirect());
|
||||
const { client, oauth2 } = clientAndYoutube();
|
||||
client.setCredentials({ access_token: providerToken });
|
||||
const { data } = await google
|
||||
.oauth2({ version: 'v2', auth: client })
|
||||
.userinfo.get();
|
||||
const user = oauth2(client);
|
||||
const { data } = await user.userinfo.get();
|
||||
|
||||
return {
|
||||
id: data.id!,
|
||||
email: data.email!,
|
||||
email: data.email,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,94 +0,0 @@
|
|||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
@AuthProvider({ provider: 'GENERIC' })
|
||||
export class OauthProvider extends AuthProviderAbstract {
|
||||
private getConfig() {
|
||||
const {
|
||||
POSTIZ_OAUTH_AUTH_URL,
|
||||
POSTIZ_OAUTH_CLIENT_ID,
|
||||
POSTIZ_OAUTH_CLIENT_SECRET,
|
||||
POSTIZ_OAUTH_TOKEN_URL,
|
||||
POSTIZ_OAUTH_USERINFO_URL,
|
||||
FRONTEND_URL,
|
||||
} = process.env;
|
||||
|
||||
if (
|
||||
!POSTIZ_OAUTH_USERINFO_URL ||
|
||||
!POSTIZ_OAUTH_TOKEN_URL ||
|
||||
!POSTIZ_OAUTH_CLIENT_ID ||
|
||||
!POSTIZ_OAUTH_CLIENT_SECRET ||
|
||||
!POSTIZ_OAUTH_AUTH_URL ||
|
||||
!FRONTEND_URL
|
||||
) {
|
||||
throw new Error('POSTIZ_OAUTH environment variables are not set');
|
||||
}
|
||||
|
||||
return {
|
||||
authUrl: POSTIZ_OAUTH_AUTH_URL,
|
||||
clientId: POSTIZ_OAUTH_CLIENT_ID,
|
||||
clientSecret: POSTIZ_OAUTH_CLIENT_SECRET,
|
||||
tokenUrl: POSTIZ_OAUTH_TOKEN_URL,
|
||||
userInfoUrl: POSTIZ_OAUTH_USERINFO_URL,
|
||||
frontendUrl: FRONTEND_URL,
|
||||
};
|
||||
}
|
||||
|
||||
generateLink(): string {
|
||||
const { authUrl, clientId, frontendUrl } = this.getConfig();
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
scope: 'openid profile email',
|
||||
response_type: 'code',
|
||||
redirect_uri: `${frontendUrl}/settings`,
|
||||
});
|
||||
|
||||
return `${authUrl}?${params.toString()}`;
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string): Promise<string> {
|
||||
const { tokenUrl, clientId, clientSecret, frontendUrl } = this.getConfig();
|
||||
const response = await fetch(`${tokenUrl}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code,
|
||||
redirect_uri: `${frontendUrl}/settings`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(`Token request failed: ${error}`);
|
||||
}
|
||||
|
||||
const { access_token } = await response.json();
|
||||
return access_token;
|
||||
}
|
||||
|
||||
async getUser(access_token: string): Promise<{ email: string; id: string }> {
|
||||
const { userInfoUrl } = this.getConfig();
|
||||
const response = await fetch(`${userInfoUrl}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${access_token}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
throw new Error(`User info request failed: ${error}`);
|
||||
}
|
||||
|
||||
const { email, sub: id } = await response.json();
|
||||
return { email, id };
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { Provider } from '@prisma/client';
|
||||
import { GithubProvider } from '@gitroom/backend/services/auth/providers/github.provider';
|
||||
import { ProvidersInterface } from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { GoogleProvider } from '@gitroom/backend/services/auth/providers/google.provider';
|
||||
|
||||
export class ProvidersFactory {
|
||||
static loadProvider(provider: Provider): ProvidersInterface {
|
||||
switch (provider) {
|
||||
case Provider.GITHUB:
|
||||
return new GithubProvider();
|
||||
case Provider.GOOGLE:
|
||||
return new GoogleProvider();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { ModuleRef } from '@nestjs/core';
|
||||
import { AuthProviderAbstract } from '@gitroom/backend/services/auth/providers.interface';
|
||||
|
||||
@Injectable()
|
||||
export class AuthProviderManager {
|
||||
constructor(private _moduleRef: ModuleRef) {}
|
||||
|
||||
getProvider(provider: string): AuthProviderAbstract {
|
||||
const metadata =
|
||||
Reflect.getMetadata('auth-provider', AuthProviderAbstract) || [];
|
||||
|
||||
const found = metadata.find(
|
||||
(m: any) => m.provider === provider
|
||||
);
|
||||
|
||||
if (!found) {
|
||||
throw new Error(`Auth provider ${provider} not found`);
|
||||
}
|
||||
|
||||
return this._moduleRef.get(found.target, { strict: false });
|
||||
}
|
||||
}
|
||||
|
|
@ -1,90 +0,0 @@
|
|||
import {
|
||||
AuthProvider,
|
||||
AuthProviderAbstract,
|
||||
} from '@gitroom/backend/services/auth/providers.interface';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
|
||||
import bs58 from 'bs58';
|
||||
import nacl from 'tweetnacl';
|
||||
|
||||
function hexToUint8Array(hex) {
|
||||
if (hex.startsWith('0x')) {
|
||||
hex = hex.slice(2);
|
||||
}
|
||||
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new Error('Invalid hex string. It must have an even length.');
|
||||
}
|
||||
|
||||
const byteLength = hex.length / 2;
|
||||
const uint8Array = new Uint8Array(byteLength);
|
||||
|
||||
for (let i = 0; i < byteLength; i++) {
|
||||
const byteHex = hex.substr(i * 2, 2);
|
||||
uint8Array[i] = parseInt(byteHex, 16);
|
||||
}
|
||||
|
||||
return uint8Array;
|
||||
}
|
||||
|
||||
@AuthProvider({ provider: 'WALLET' })
|
||||
export class WalletProvider extends AuthProviderAbstract {
|
||||
async generateLink(params: { publicKey: string }) {
|
||||
if (!params.publicKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const challenge = randomBytes(32).toString('hex');
|
||||
await ioRedis.set(`wallet:${params.publicKey}`, challenge, 'EX', 60);
|
||||
|
||||
return challenge;
|
||||
}
|
||||
|
||||
async getToken(code: string, _redirectUri?: string) {
|
||||
const { publicKey, challenge, signature } = JSON.parse(
|
||||
Buffer.from(code, 'base64').toString()
|
||||
);
|
||||
|
||||
if (!publicKey || !challenge || !signature) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const redisGet = await ioRedis.get(`wallet:${publicKey}`);
|
||||
if (redisGet !== challenge) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const publicKeyUint8 = bs58.decode(publicKey);
|
||||
const messageUint8 = new TextEncoder().encode(challenge);
|
||||
const signatureUint8 = hexToUint8Array(signature);
|
||||
const isValid = nacl.sign.detached.verify(
|
||||
messageUint8,
|
||||
signatureUint8,
|
||||
publicKeyUint8
|
||||
);
|
||||
|
||||
if (!isValid) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
async getUser(providerToken: string) {
|
||||
if ((await this.getToken(providerToken)) === '') {
|
||||
return {
|
||||
id: '',
|
||||
email: '',
|
||||
};
|
||||
}
|
||||
|
||||
const { publicKey } = JSON.parse(
|
||||
Buffer.from(providerToken, 'base64').toString()
|
||||
);
|
||||
|
||||
return {
|
||||
id: String(`wallet_${publicKey}`),
|
||||
email: String(`wallet_${publicKey}`),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
|
||||
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
|
||||
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
|
||||
|
||||
@Injectable()
|
||||
export class PublicAuthMiddleware implements NestMiddleware {
|
||||
constructor(
|
||||
private _organizationService: OrganizationService,
|
||||
private _oauthService: OAuthService
|
||||
) {}
|
||||
async use(req: Request, res: Response, next: NextFunction) {
|
||||
const auth = (req.headers.authorization ||
|
||||
req.headers.Authorization) as string;
|
||||
if (!auth) {
|
||||
res.status(HttpStatus.UNAUTHORIZED).json({ msg: 'No API Key found' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (auth.startsWith('pos_')) {
|
||||
const authorization = await this._oauthService.getOrgByOAuthToken(auth);
|
||||
if (!authorization) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'Invalid OAuth token' });
|
||||
return;
|
||||
}
|
||||
|
||||
const org = authorization.organization;
|
||||
if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'No subscription found' });
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
|
||||
} else {
|
||||
const org = await this._organizationService.getOrgByApiKey(auth);
|
||||
if (!org) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'Invalid API key' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
|
||||
res
|
||||
.status(HttpStatus.UNAUTHORIZED)
|
||||
.json({ msg: 'No subscription found' });
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
|
||||
}
|
||||
} catch (err) {
|
||||
throw new HttpForbiddenException();
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
12
apps/backend/tsconfig.app.json
Normal file
12
apps/backend/tsconfig.app.json
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"types": ["node", "multer"],
|
||||
"emitDecoratorMetadata": true,
|
||||
"target": "es2021"
|
||||
},
|
||||
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"],
|
||||
"compilerOptions": {
|
||||
"module": "CommonJS",
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"noImplicitAny": false,
|
||||
"strictBindCallApply": false,
|
||||
"forceConsistentCasingInFileNames": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
"outDir": "./dist"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +1,17 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
],
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "es2017",
|
||||
"sourceMap": true,
|
||||
"esModuleInterop": true
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
}
|
||||
}
|
||||
|
|
|
|||
14
apps/backend/tsconfig.spec.json
Normal file
14
apps/backend/tsconfig.spec.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": [
|
||||
"jest.config.ts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
13
apps/backend/webpack.config.js
Normal file
13
apps/backend/webpack.config.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
const { composePlugins, withNx } = require('@nx/webpack');
|
||||
|
||||
// Nx plugins for webpack.
|
||||
module.exports = composePlugins(
|
||||
withNx({
|
||||
target: 'node',
|
||||
}),
|
||||
(config) => {
|
||||
// Update the webpack config as needed here.
|
||||
// e.g. `config.plugins.push(new MyPlugin())`
|
||||
return config;
|
||||
}
|
||||
);
|
||||
18
apps/commands/.eslintrc.json
Normal file
18
apps/commands/.eslintrc.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"extends": ["../../.eslintrc.json"],
|
||||
"ignorePatterns": ["!**/*"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.ts", "*.tsx"],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": ["*.js", "*.jsx"],
|
||||
"rules": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
8
apps/commands/.gitignore
vendored
8
apps/commands/.gitignore
vendored
|
|
@ -1,8 +0,0 @@
|
|||
dist/
|
||||
node_modules/
|
||||
[._]*.s[a-v][a-z]
|
||||
[._]*.sw[a-p]
|
||||
[._]s[a-rt-v][a-z]
|
||||
[._]ss[a-gi-z]
|
||||
[._]sw[a-p]
|
||||
|
||||
11
apps/commands/jest.config.ts
Normal file
11
apps/commands/jest.config.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/* eslint-disable */
|
||||
export default {
|
||||
displayName: 'consumers',
|
||||
preset: '../../jest.preset.js',
|
||||
testEnvironment: 'node',
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../coverage/apps/consumers',
|
||||
};
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"monorepo": false,
|
||||
"sourceRoot": "src",
|
||||
"entryFile": "../../dist/commands/apps/commands/src/main",
|
||||
"language": "ts",
|
||||
"generateOptions": {
|
||||
"spec": false
|
||||
},
|
||||
"compilerOptions": {
|
||||
"manualRestart": true,
|
||||
"tsConfigPath": "./tsconfig.build.json",
|
||||
"webpack": false,
|
||||
"deleteOutDir": true,
|
||||
"assets": [],
|
||||
"watchAssets": false,
|
||||
"plugins": []
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue