Initial commit
Test / Test (pull_request) Has been cancelled

This commit is contained in:
macdev
2026-05-31 01:55:36 +02:00
commit 6e4dc5ae6b
2023 changed files with 277407 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
+25
View File
@@ -0,0 +1,25 @@
name: Blank Issue
description: Create a blank issue. ALWAYS FIRST USE OUR SUPPORT CHANNEL! ONLY USE THIS FORM IF YOU ARE A CONTRIBUTOR OR WERE TOLD TO DO SO IN THE SUPPORT CHANNEL.
body:
- type: markdown
attributes:
value: |
![Are you a developer? No? This form is not for you!](https://github.com/Equicord/Equicord/blob/main/.github/ISSUE_TEMPLATE/developer-banner.png?raw=true)
GitHub Issues are for development, not support! Please use our [support server](https://equicord.org/discord) unless you are a Vencord Developer.
- type: textarea
id: content
attributes:
label: Content
validations:
required: true
- type: checkboxes
id: agreement-check
attributes:
label: Request Agreement
options:
- label: I have read the requirements for opening an issue above
required: true
+66
View File
@@ -0,0 +1,66 @@
name: Bug/Crash Report
description: Create a bug or crash report for Equicord. ALWAYS FIRST USE OUR SUPPORT CHANNEL! ONLY USE THIS FORM IF YOU ARE A CONTRIBUTOR OR WERE TOLD TO DO SO IN THE SUPPORT CHANNEL.
labels: [bug]
title: "[Bug] <title>"
body:
- type: markdown
attributes:
value: |
![Are you a developer? No? This form is not for you!](https://github.com/Equicord/Equicord/blob/main/.github/ISSUE_TEMPLATE/developer-banner.png?raw=true)
GitHub Issues are for development, not support! Please use our [support server](https://equicord.org/discord) unless you are a Equicord/Vencord Developer.
- type: textarea
id: bug-description
attributes:
label: What happens when the bug or crash occurs?
description: Where does this bug or crash occur, when does it occur, etc.
placeholder: The bug/crash happens sometimes when I do ..., causing this to not work/the app to crash. I think it happens because of ...
validations:
required: true
- type: textarea
id: expected-behaviour
attributes:
label: What is the expected behaviour?
description: Simply detail what the expected behaviour is.
placeholder: I expect Equicord/Discord to open the ... page instead of ..., it prevents me from doing ...
validations:
required: true
- type: textarea
id: steps-to-take
attributes:
label: How do you recreate this bug or crash?
description: Give us a list of steps in order to recreate the bug or crash.
placeholder: |
1. Do ...
2. Then ...
3. Do this ..., ... and then ...
4. Observe "the bug" or "the crash"
validations:
required: true
- type: textarea
id: crash-log
attributes:
label: Errors
description: Open the Developer Console with Ctrl/Cmd + Shift + i. Then look for any red errors (Ignore network errors like Failed to load resource) and paste them between the "```".
value: |
```
Replace this text with your crash-log.
```
validations:
required: false
- type: checkboxes
id: agreement-check
attributes:
label: Request Agreement
description: We only accept reports for bugs that happen on Discord Stable. Canary and PTB are Development branches and may be unstable
options:
- label: I am using Discord Stable or tried on Stable and this bug happens there as well
required: true
- label: I am a Equicord/Vencord Developer
required: true
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Equicord Support Server
url: https://equicord.org/discord
about: If you need help regarding Equicord, please join our support server!
- name: Equicord Installer
url: https://github.com/Equicord/Equilotl
about: You can find the Equicord Installer here
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+85
View File
@@ -0,0 +1,85 @@
name: Release
on:
push:
branches:
- main
env:
FORCE_COLOR: true
GITHUB_TOKEN: ${{ secrets.ETOKEN }}
REPO: Equicord/Equibored
USERNAME: GitHub-Actions
permissions:
contents: write
jobs:
Build:
name: Build Equicord
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build web
run: pnpm buildWebStandalone
- name: Build
run: pnpm buildStandalone
- name: Generate plugin lists
run: |
pnpm generatePluginJson dist/plugins.json
pnpm generateEquicordPluginJson dist/equicordplugins.json
pnpm generateVencordPluginJson dist/vencordplugins.json
pnpm generateDevsList dist/devs.json
- name: Collect files to be released
run: |
cd dist
mkdir release
cp browser/browser.* release
cp Equicord.user.{js,js.LEGAL.txt} release
# copy the plugin data jsons, the extension zips and the desktop/vesktop asars
cp *.{json,zip,asar} release
# legacy un-asared files
cp desktop/* release
for file in equibop/*; do
filename=$(basename "$file")
cp "$file" "release/equibop${filename^}"
done
find release -size 0 -delete
rm release/package.json
rm release/*.map
- name: Upload Equicord Stable
run: |
gh release upload latest --clobber dist/release/*
- name: Upload Plugin JSONs to Equibored repo
run: |
git config --global user.name "GitHub-Actions"
git config --global user.email actions@github.com
git clone https://$USERNAME:$GITHUB_TOKEN@github.com/$REPO.git plugins
cd plugins
cp ../dist/release/*.json .
git add -A
git commit -m "Plugins for https://github.com/$GITHUB_REPOSITORY/commit/$GITHUB_SHA"
git push --force https://$USERNAME:$GITHUB_TOKEN@github.com/$REPO.git
@@ -0,0 +1,47 @@
name: Generate plugins.json
on:
push:
branches: [master]
paths:
- "src/nightcordplugins/**"
- "src/plugins/**"
- "src/utils/constants.ts"
- "scripts/generatePluginList.ts"
- "scripts/utils.ts"
workflow_dispatch: {}
jobs:
generate:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Generate plugins.json
run: pnpm generatePluginJson plugins.json
- name: Commit and push plugins.json
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "chore: update plugins.json [skip ci]"
file_pattern: plugins.json
commit_user_name: github-actions[bot]
commit_user_email: github-actions[bot]@users.noreply.github.com
+74
View File
@@ -0,0 +1,74 @@
name: NixOS Build
on:
workflow_dispatch:
schedule:
- cron: 0 0 * * *
env:
FORCE_COLOR: true
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
permissions:
contents: write
jobs:
Build:
name: Build Equicord
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build web
run: pnpm buildWebStandalone
- name: Build
run: pnpm buildStandalone
- name: Generate plugin lists
run: |
pnpm generatePluginJson dist/plugins.json
pnpm generateEquicordPluginJson dist/equicordplugins.json
pnpm generateVencordPluginJson dist/vencordplugins.json
pnpm generateDevsList dist/devs.json
- name: Collect files to be released
run: |
cd dist
mkdir release
cp browser/browser.* release
cp Equicord.user.{js,js.LEGAL.txt} release
# copy the plugin data jsons, the extension zips and the desktop/vesktop asars
cp *.{json,zip,asar} release
# legacy un-asared files
cp desktop/* release
for file in equibop/*; do
filename=$(basename "$file")
cp "$file" "release/equibop${filename^}"
done
find release -size 0 -delete
rm release/package.json
rm release/*.map
- name: Get current date
id: date
run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
- name: Upload Equicord Stable
run: |
gh release create ${{ steps.date.outputs.date }} --latest=false
gh release upload ${{ steps.date.outputs.date }} --clobber dist/release/*
+99
View File
@@ -0,0 +1,99 @@
name: Release Browser Extension
on:
push:
branches:
- main
env:
FORCE_COLOR: true
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get package.json version
id: pkg
run: echo "version=v$(jq -r .version < package.json)" >> $GITHUB_OUTPUT
- name: Get latest Git tag
id: tag
run: |
latest_tag=$(git tag --list 'v*' --sort=-v:refname | head -n 1 || echo "v0.0.0")
echo "latest=$latest_tag" >> $GITHUB_OUTPUT
- name: Check if package.json version is newer
id: check
run: |
pkg="${{ steps.pkg.outputs.version }}"
latest="${{ steps.tag.outputs.latest }}"
echo "Latest tag: $latest"
echo "Package version: $pkg"
if [ "$pkg" != "$latest" ] && [ "$(sort -V <<<"$latest"$'\n'"$pkg" | tail -n1)" = "$pkg" ]; then
echo "release=true" >> $GITHUB_OUTPUT
else
echo "release=false" >> $GITHUB_OUTPUT
fi
- name: Stop if not newer
if: steps.check.outputs.release == 'false'
run: |
echo "No new version to release (package.json ${{ steps.pkg.outputs.version }} <= latest tag ${{ steps.tag.outputs.latest }})"
exit 0
- name: Create Tag
if: steps.check.outputs.release == 'true'
uses: butlerlogic/action-autotag@1.1.2
env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
with:
tag_prefix: "v"
- name: Setup PNPM
if: steps.check.outputs.release == 'true'
uses: pnpm/action-setup@v3
- name: Use Node.js 20
if: steps.check.outputs.release == 'true'
uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
- name: Install dependencies
if: steps.check.outputs.release == 'true'
run: pnpm install --frozen-lockfile
- name: Build web
if: steps.check.outputs.release == 'true'
run: pnpm buildWebStandalone
- name: Create sources zip
if: steps.check.outputs.release == 'true'
run: zip -r dist/extension-sources.zip . -x "node_modules/*" -x "dist/*" -x ".git/*"
- name: Publish extension
if: steps.check.outputs.release == 'true'
run: pnpx @equicord/publish-browser-extension@latest --chrome-zip dist/extension-chrome.zip --firefox-zip dist/extension-firefox.zip --firefox-sources-zip dist/extension-sources.zip --edge-zip dist/extension-chrome.zip
env:
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
CHROME_PUBLISHER_ID: ${{ secrets.CHROME_PUBLISHER_ID }}
CHROME_CLIENT_ID: ${{ secrets.CHROME_CLIENT_ID }}
CHROME_CLIENT_SECRET: ${{ secrets.CHROME_CLIENT_SECRET }}
CHROME_REFRESH_TOKEN: ${{ secrets.CHROME_REFRESH_TOKEN }}
FIREFOX_EXTENSION_ID: ${{ secrets.FIREFOX_EXTENSION_ID }}
FIREFOX_JWT_ISSUER: ${{ secrets.FIREFOX_JWT_ISSUER }}
FIREFOX_JWT_SECRET: ${{ secrets.FIREFOX_JWT_SECRET }}
EDGE_PRODUCT_ID: ${{ secrets.EDGE_PRODUCT_ID }}
EDGE_CLIENT_ID: ${{ secrets.EDGE_CLIENT_ID }}
EDGE_API_KEY: ${{ secrets.EDGE_API_KEY }}
+79
View File
@@ -0,0 +1,79 @@
name: Build & Release Nightcord
on:
push:
tags:
- "v*" # déclenché sur : git tag v1.0.0 && git push --tags
permissions:
contents: write # nécessaire pour créer la GitHub Release
jobs:
build:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10.30.3
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build Equicord renderer (standalone)
run: pnpm buildStandalone
- name: Build & Package Electron
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
node electron-builder.config.cjs || true
npx electron-builder --config electron-builder.config.cjs --win --publish always
- name: Package nightcord-dist.zip
shell: pwsh
run: |
# Gather everything the launcher needs: patcher.js, dist/, ghost-server/, modules/, binaries
$staging = "nightcord-dist-staging"
New-Item -ItemType Directory -Path $staging -Force | Out-Null
# Core JS dist output (patcher.js, renderer.js, preload.js …)
if (Test-Path "dist") {
Copy-Item "dist" "$staging\dist" -Recurse
}
# Ghost-server (voice/stream server)
if (Test-Path "ghost-server") {
Copy-Item "ghost-server" "$staging\ghost-server" -Recurse
}
# Static assets from release/nightcord-dist (ffmpeg.dll, modules, etc.)
if (Test-Path "release\nightcord-dist") {
Copy-Item "release\nightcord-dist\*" "$staging\" -Recurse -Force
}
# Entry-point files
foreach ($f in @("nightcord-index.js", "nightcord-preload.js")) {
if (Test-Path $f) { Copy-Item $f "$staging\" }
}
Compress-Archive -Path "$staging\*" -DestinationPath "nightcord-dist.zip" -Force
Write-Host "nightcord-dist.zip created ($($(Get-Item nightcord-dist.zip).Length / 1MB) MB)"
- name: Upload nightcord-dist.zip to Release
uses: softprops/action-gh-release@v2
with:
files: nightcord-dist.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+88
View File
@@ -0,0 +1,88 @@
name: Test Patches
on:
workflow_dispatch:
inputs:
discord_branch:
type: choice
description: "Discord Branch to test patches on"
options:
- both
- stable
- canary
default: both
webhook_url:
type: string
description: "Webhook URL that the report will be posted to. This will be visible for everyone, so DO NOT pass sensitive webhooks like discord webhook. This is meant to be used by Venbot."
required: false
schedule:
# # Every day at midnight
- cron: 0 0 * * *
env:
FORCE_COLOR: true
jobs:
TestPlugins:
name: Test Patches
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'schedule' && 'dev' || github.ref }}
- uses: pnpm/action-setup@v3 # Install pnpm using packageManager key in package.json
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
- name: Install dependencies
run: |
pnpm install --frozen-lockfile --prefer-offline
- name: Build Equicord Reporter Version
run: pnpm buildReporter
- name: Run Reporter
timeout-minutes: 10
run: |
export PATH="$PWD/node_modules/.bin:$PATH"
export CHROMIUM_BIN=/usr/bin/google-chrome
esbuild scripts/generateReport.ts > dist/report.mjs
stable_output_file=$(mktemp)
canary_output_file=$(mktemp)
pids=""
branch="${{ inputs.discord_branch }}"
if [[ "${{ github.event_name }}" = "schedule" ]]; then
branch="both"
fi
if [[ "$branch" = "both" || "$branch" = "stable" ]]; then
node dist/report.mjs > "$stable_output_file" &
pids+=" $!"
fi
if [[ "$branch" = "both" || "$branch" = "canary" ]]; then
USE_CANARY=true node dist/report.mjs > "$canary_output_file" &
pids+=" $!"
fi
exit_code=0
for pid in $pids; do
if ! wait "$pid"; then
exit_code=1
fi
done
cat "$stable_output_file" "$canary_output_file" >> $GITHUB_STEP_SUMMARY
exit $exit_code
env:
WEBHOOK_URL: ${{ inputs.webhook_url || secrets.WEBHOOK_URL }}
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
+37
View File
@@ -0,0 +1,37 @@
name: Test
on:
push:
branches:
- main
- dev
pull_request:
branches:
- main
- dev
jobs:
Test:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3 # Install pnpm using packageManager key in package.json
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
cache: "pnpm"
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Lint & Test if desktop version compiles
run: pnpm test
- name: Test if web version compiles
run: pnpm buildWeb
- name: Test if plugin structure is valid
run: pnpm generatePluginJson
+73
View File
@@ -0,0 +1,73 @@
dist
node_modules
.VSCodeCounter
*.exe
vencord_installer
equicord_installer
.idea
.DS_Store
yarn.lock
bun.lock
package-lock.json
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
*.tsbuildinfo
.modules/
src/userplugins
ExtensionCache/
/settings
# vencord companion module cache
.modules
# wakatime related stuff
.wakatime-project
# build outputs & binaries
release/
dist/
# Exception : scripts/build/ contient les scripts de compilation et doit être versionné
!scripts/build/
# Build resources needed by electron-builder
build/*
!build/icon.icns
# IDE settings
.vscode/
# backup & temp files
*.patch.txt
*backup*/
*Backup*/
*bak*/
*old*/
static/modules_backup_working_stereo/
installer-src/bin/
installer-src/obj/
# Test and local dev directories
test-dist/
test-userdata/
test-app/
# Environment & credentials
.env
.env.*
*.env
*.pem
*.key
certs/
# System files
Thumbs.db
Desktop.ini
+3
View File
@@ -0,0 +1,3 @@
strict-peer-dependencies=false
package-manager-strict=false
shamefully-hoist=true
+213
View File
@@ -0,0 +1,213 @@
# Equicord Development Guidelines
## Critical Rules
- **NEVER** edit existing license headers. New files use 2026.
- Push back when the user idea is wrong or not correct.
- **NEVER** git checkout files without explicit permission.
- Always verify components/functions arent deprecated before using.
- **NEVER** use `any` for Discord objects. Import proper types from `@vencord/discord-types`.
- Fix with smallest possible change. No refactoring unless explicitly asked.
- Solve the problem at hand only. No patterns for patterns sake.
- **NEVER** overengineer. No premature abstractions, no helpers for one-time operations, no building for hypothetical futures. Three similar lines is better than a premature abstraction.
- Write modern, robust, professional code. Use current language features, proper error handling, and clean structure.
- Write natural human text in errors, descriptions, messages. No dashes or robotic formatting. Write like "Module not found" not "Module - not found". Keep it simple and conversational.
## Code Rules
- **DELETE** dead code, dont comment it. Git preserves history.
- No hardcoded values, unused imports, magic numbers.
- Import `classNameFactory` from `@utils/css` (NOT `@api/Styles` which is deprecated). **ALWAYS** use `cl()` for class names, never hardcode strings like `"vc-plugin-name-class"`.
- When combining multiple class names use `classes()` from `@utils/misc`, not template strings like `` `${a} ${b}` ``.
- Use utilities from `@utils/`, `@api/`, `@components/`.
- Use `Logger` from `@utils/Logger`, not `console.log`.
- Descriptions: capital first letter, end with period.
- Less code with same functionality is **ALWAYS** better. If it can be done in fewer lines without losing clarity, do it.
- Keep logic flat. Avoid deep nesting, prefer early returns, guard clauses, and simple control flow.
- **NEVER** add comments unless explicitly asked.
- Keep existing comments, they contain important context.
- Use `Map`/`Set`, `.some`/`.find`, no spread in loops, `Promise.all`.
- KISS over clever, flat over nested, explicit over implicit.
## TypeScript
- **Prefer:** optional chaining (`?.`), nullish coalescing (`??`), `const`, arrow functions
- **Use:** destructuring, template literals, object shorthand, array methods
- **Style:** early returns, trust inference, inline single-use variables
## React
- Wrap complex components with `ErrorBoundary.wrap(Component, { noop: true })`.
- Return `null` for conditional rendering, not `undefined`.
- **Forbidden:** `React.cloneElement`, `React.isValidElement`, `React.memo()`, `React.lazy`, `React.Children`
- Always return cleanup functions in `useEffect`.
## Forbidden
### Code
- **No raw DOM manipulation.** No `document.querySelector`, no `MutationObserver`, no `element.style`. Always use webpack patches and React.
- Empty catch blocks.
- Hardcoded minified vars in patches (`e,t,n`).
- **NEVER** use `settings.use()` with arrays. Mutate then reassign.
### Plugins
- **No selfbot or API abuse.** Nothing that automates user actions, spoofs client state, or abuses Discord's API in any way.
- No plugins that only do something trivially achievable with existing built-in plugins or Discord features.
- No CSS-only plugins that only hide or redesign UI elements.
- No plugins targeting specific third-party bots (official Discord apps are fine).
- No untrusted third-party APIs. No plugins requiring users to supply their own API keys.
- Do not introduce new dependencies unless strictly necessary and well justified.
## Anti-Patterns
- `value !== null && value !== undefined` ⟹ `value != null`
- `array && array.length > 0` ⟹ `array.length` (only when array is guaranteed to exist)
- `settings?.store?.value` ⟹ `settings.store.value`
- `value || defaultValue` ⟹ `value ?? defaultValue`
## Patching
### Core Principles
- Minimum code touched. Stability over cleverness. One patch per concern.
- Try multiple approaches, keep simplifying until you find the cleanest solution.
- Remove any regex character that doesnt change the match result.
- Not overengineered, not overlooked, just clean and future-proof.
### Find Strings
- Use `#{intl::KEY}` in find when possible, most stable anchor.
- If find matches multiple modules, add nearby stable string like `"),icon:"` or function name.
- `"#{intl::PIN_MESSAGE}),icon:"` is better than generic strings.
### Match Patterns
- Match only what you need to replace, let find do the targeting.
- Can use `#{intl::KEY}` in match too, gets canonicalized to hash.
- `/#{intl::KEY}\)/` beats `/label:\i\.pinned\?.{0,60}#{intl::KEY}\)/`
- `$&` keeps original, append/prepend to it.
- Use bounded gaps: `.{0,50}` not `.+?` or `.*?`
- Only use capture groups if reusing in replace.
### NEVER Do
- **Hardcoded minified vars:** `e,t,n,r,i,o,s,l,c,u,$_,xx,eD,eH,eW` — use `\i` instead
- **Minified chains:** `\i\.\i` alone — surround with stable strings
- **Unbounded gaps:** `.+?` or `.*?` — use `.{0,N}`
- **Generic patterns:** `/className:\i/` alone — add anchor
- **Raw intl hashes:** `.aA4Vce` — use `#{intl::KEY_NAME}`
### Patch Examples
**Clean replacement:**
```js
find: "#{intl::PIN_MESSAGE}),icon:"
match: /#{intl::PIN_MESSAGE}\)/
replace: "$self.getPinLabel(arguments[0]))"
```
**Appending:**
```js
find: "#{intl::VIEW_AS_ROLES_MENTIONS_WARNING}"
match: /#{intl::VIEW_AS_ROLES_MENTIONS_WARNING}.{0,100}(?=])/
replace: "$&,$self.renderTooltip(arguments[0].guild)"
```
**Wrapping:**
```js
find: "#{intl::SEVERAL_USERS_TYPING_STRONG}"
match: /(?<="aria-atomic":!0,children:)\i/
replace: "$self.renderTypingUsers({ children: $& })"
```
## Plugin Interop
- `isPluginEnabled(name)` from `@api/PluginManager` takes a string, checks required/isDependency/enabled.
- Import the plugin directly from its path to access `.name` and functions.
- Dont use `Vencord.Plugins.plugins` or `plugin.started`. Dont use `"as unknown as"` casting.
```ts
import { isPluginEnabled } from "@api/PluginManager";
import otherPlugin from "@equicordplugins/otherPlugin";
if (!isPluginEnabled(otherPlugin.name)) return null;
otherPlugin.someFunction();
```
## Reference
### Types
`Channel`, `Guild`, `GuildMember`, `User`, `Role`, `Message` from `@vencord/discord-types`
### Components
`Paragraph`, `BaseText`, `Flex`, `Button`, `ErrorCard` from `@components/`
### Settings
Use `definePluginSettings` from `@api/Settings`, not inline settings object.
### Utilities
- **@utils/clipboard** — `copyToClipboard`
- **@utils/discord** — `insertTextIntoChatInputBox`, `getCurrentChannel`, `getCurrentGuild`, `getIntlMessage`, `openUserProfile`, `openPrivateChannel`, `sendMessage`, `copyWithToast`, `getUniqueUsername`, `fetchUserProfile`
- **@utils/css** — `classNameFactory`, `classNameToSelector`
- **@utils/misc** — `classes`, `sleep`, `isObject`, `isObjectEmpty`, `pluralise`, `parseUrl`, `identity`
- **@utils/text** — `formatDuration`, `formatDurationMs`, `humanFriendlyJoin`, `makeCodeblock`, `toInlineCode`, `escapeRegExp`
- **@utils/modal** — `openModal`, `closeModal`, `ModalRoot`, `ModalHeader`, `ModalContent`, `ModalCloseButton`
- **@utils/margins** — `Margins` (`Margins.top8`, `Margins.bottom16`, etc.)
- **@utils/guards** — `isTruthy`, `isNonNullish`
- **@utils/web** — `saveFile`, `chooseFile`
### Webpack Common
#### IconUtils
From `@webpack/common`. **NEVER** hardcode `cdn.discordapp.com` URLs.
- `IconUtils.getUserAvatarURL(user, canAnimate?, size?)`
- `IconUtils.getDefaultAvatarURL(id)`
- `IconUtils.getUserBannerURL({ id, banner, canAnimate?, size })`
- `IconUtils.getGuildIconURL({ id, icon, size?, canAnimate? })`
- `IconUtils.getGuildBannerURL(guild, canAnimate?)`
- `IconUtils.getChannelIconURL({ id, icon })`
- `IconUtils.getEmojiURL({ id, animated, size })`
- `IconUtils.getApplicationIconURL(data)`
- `IconUtils.getGameAssetURL(data)`
#### Stores
`UserStore`, `GuildStore`, `ChannelStore`, `GuildMemberStore`, `SelectedChannelStore`, `SelectedGuildStore`, `PresenceStore`, `RelationshipStore`, `MessageStore`, `EmojiStore`, `ThemeStore`, `PermissionStore`, `VoiceStateStore` from `@webpack/common`
#### Actions
`RestAPI`, `FluxDispatcher`, `MessageActions`, `NavigationRouter`, `ChannelRouter`, `ChannelActionCreators`, `SettingsRouter` from `@webpack/common`
#### Utils
`Constants` (`Constants.Endpoints`), `SnowflakeUtils`, `Parser`, `PermissionsBits`, `moment`, `lodash`, `ColorUtils`, `ImageUtils`, `DateUtils`, `UsernameUtils`, `DisplayProfileUtils`, `URLUtils`, `Humanize`, `EmojiUtils` from `@webpack/common`
#### Components
`Tooltip`, `TextInput`, `TextArea`, `Select`, `Slider`, `Avatar`, `Menu`, `Popout`, `ScrollerThin`, `Timestamp` from `@webpack/common`
#### Toasts
`Toasts`, `showToast` from `@webpack/common`
### Imports
- **Lazy** from `@webpack` — `findByPropsLazy`, `findStoreLazy`, `findComponentByCodeLazy`, `findExportedComponentLazy`
- **Common** from `@webpack/common` — `useState`, `useEffect`, `useCallback`, `useStateFromStores`
### Never Hardcode
- `"cdn.discordapp.com/avatars/"` etc. ⟹ `IconUtils`
- `"/api/v9"`, `"/users/@me"` ⟹ `Constants.Endpoints` or `RestAPI`
- `console.log/warn/error` ⟹ `Logger` from `@utils/Logger`
- `` `${a} ${b}` `` for class names ⟹ `classes(a, b)` from `@utils/misc`
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "stylelint-config-standard",
"rules": {
"selector-class-pattern": [
"^[a-z][a-zA-Z0-9]*(-[a-z0-9][a-zA-Z0-9]*)*$",
{
"message": "Expected class selector to be kebab-case with camelCase segments"
}
]
}
}
+1
View File
@@ -0,0 +1 @@
.rules
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 General Public License for more details.
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+85
View File
@@ -0,0 +1,85 @@
CC=gcc
# GStreamer est optionnel — détecté automatiquement
GST_OK := $(shell pkg-config --exists gstreamer-1.0 gstreamer-app-1.0 gstreamer-video-1.0 2>/dev/null && echo yes || echo no)
ifeq ($(GST_OK),yes)
GST_CFLAGS := $(shell pkg-config --cflags gstreamer-1.0 gstreamer-app-1.0 gstreamer-video-1.0) -DHAVE_GSTREAMER
GST_LIBS := $(shell pkg-config --libs gstreamer-1.0 gstreamer-app-1.0 gstreamer-video-1.0)
$(info GStreamer détecté — décodage vidéo activé)
else
GST_CFLAGS :=
GST_LIBS :=
$(info GStreamer non trouvé — décodage vidéo désactivé)
endif
FLAGS=`pkg-config --cflags gtk+-3.0 libsoup-2.4 rtaudio json-glib-1.0 opus libsodium libsecret-1` $(GST_CFLAGS)
LIBS=`pkg-config --libs gtk+-3.0 libsoup-2.4 rtaudio json-glib-1.0 opus libsodium libsecret-1` -lleveldb -lm $(GST_LIBS) -lwinmm -lmsacm32
PREFIX=/usr
BUILD_DIR=build
SRCS = $(shell find ./src/*.c | grep -v updater.c)
# Ressource Windows (icône)
RC_OBJ = $(BUILD_DIR)/nightcord_rc.o
OBJS = $(patsubst %.c, $(BUILD_DIR)/%.o, $(SRCS))
OPTS=-O3
ifdef CACHE
OPTS+= -D USE_CACHE
endif
RTAUDIO_BELOW_6_0 := $(shell pkg-config --atleast-version=6.0.0 rtaudio && echo no || echo yes)
ifeq ($(RTAUDIO_BELOW_6_0), yes)
OPTS+= -D RTAUDIO_BELOW_6_0
endif
all: $(BUILD_DIR)/nightcord $(BUILD_DIR)/updater.exe
$(BUILD_DIR)/assets/: assets/
mkdir -p $(dir $@)
cp -r assets/* $(dir $@)
$(BUILD_DIR)/sounds/: assets/sounds/
mkdir -p $(BUILD_DIR)/sounds
cp assets/sounds/*.wav $(BUILD_DIR)/sounds/
$(BUILD_DIR)/themes/: themes/
mkdir -p $(BUILD_DIR)/themes
cp themes/*.css $(BUILD_DIR)/themes/
$(BUILD_DIR)/assets/gschemas.compiled: $(BUILD_DIR)/assets/
glib-compile-schemas $(dir $@)
$(BUILD_DIR)/resources.c: resources.xml $(BUILD_DIR)/assets/gschemas.compiled
glib-compile-resources --sourcedir=$(BUILD_DIR)/assets/ $< --target=$@ --generate-source
$(BUILD_DIR)/resources.o: $(BUILD_DIR)/resources.c
$(CC) -c -o $@ $^ $(FLAGS) $(OPTS)
# Compiler les ressources Windows (.rc → .o)
$(BUILD_DIR)/nightcord_rc.o: nightcord.rc assets/nightcord.ico
mkdir -p $(BUILD_DIR)
windres nightcord.rc -o $@
$(BUILD_DIR)/%.o: %.c
mkdir -p $(dir $@)
$(CC) -c -o $@ $(FLAGS) $< -Wall -Wno-unused-function -Wno-misleading-indentation $(OPTS)
$(BUILD_DIR)/nightcord: $(OBJS) $(BUILD_DIR)/resources.o $(RC_OBJ) $(BUILD_DIR)/themes/ $(BUILD_DIR)/sounds/
$(CC) -o $@ $(OBJS) $(BUILD_DIR)/resources.o $(RC_OBJ) $(LIBS) -liphlpapi -lcrypt32 $(OPTS) -mwindows
# ── Updater ──────────────────────────────────────────────────────────────
$(BUILD_DIR)/updater.exe: src/updater.c
$(CC) -o $@ $< `pkg-config --cflags --libs gtk+-3.0 libsoup-2.4 json-glib-1.0` -lm $(OPTS) -mwindows
clean:
rm -rf build
uninstall:
rm -f $(PREFIX)/share/applications/nightcord.desktop
rm -f $(PREFIX)/share/pixmaps/nightcord.png
rm -f $(PREFIX)/share/pixmaps/nightcord.svg
rm -f $(PREFIX)/bin/nightcord
install: uninstall
cp nightcord.desktop $(PREFIX)/share/applications/nightcord.desktop
cp assets/icon.svg $(PREFIX)/share/pixmaps/nightcord.svg
cp $(BUILD_DIR)/nightcord $(PREFIX)/bin/nightcord
run: all
cp assets/nightcord.gschema.xml $(BUILD_DIR)/assets/nightcord.gschema.xml
glib-compile-schemas $(BUILD_DIR)/assets/
./build/nightcord
+1
View File
@@ -0,0 +1 @@
Equicord is designed with user privacy in mind and doesnt collect or share any personal data. Since its an extension for Discord, it operates entirely within the Discord platform. This means all interactions and data management follow Discords privacy policies, which you can check out at [discord.com/privacy](https://discord.com/privacy/). So, while Equicord doesnt handle your data, its a good idea to review Discords policy to understand how your information is managed. This setup ensures transparency and follows standard practices for third-party tools working within larger platforms.
+58
View File
@@ -0,0 +1,58 @@
<div align="center">
<img src="https://nightcord.su/image.png" width="96" height="96" alt="Nightcord Logo">
# Nightcord
**A custom Discord client built for people who actually care about how Discord runs.**
[![Discord](https://img.shields.io/badge/Discord-Join%20us-5865F2?logo=discord&logoColor=white)](https://discord.gg/nightcord)
[![License](https://img.shields.io/github/license/nightcordoff/nightcord?color=a855f7)](./LICENSE)
[![Platform](https://img.shields.io/badge/platform-Windows-3b82f6.svg?logo=windows&logoColor=white)](https://github.com/nightcordoff/nightcord-macos)
[![Website](https://img.shields.io/badge/website-nightcord.su-5865F2?logo=googlechrome&logoColor=white)](https://nightcord.su)
---
</div>
Nightcord is a fork of [Equicord](https://github.com/Equicord/Equicord), which itself builds on top of [Vencord](https://github.com/Vendicated/Vencord). We stripped out the obfuscation, cleaned things up, added our own stuff, and kept what works. No bloat, no nonsense.
---
## What's in it
* **Faster startup** — no obfuscation means the client loads noticeably quicker and sits lighter on your CPU and RAM.
* **Auto-updates** — checks for updates in the background on launch and applies them silently. You don't have to think about it.
* **Plugin support** — compatible with the existing plugin ecosystem. Install community plugins straight from Git links.
* **Better audio** — hardware-optimized voice modules for cleaner, louder audio out of the box.
* **Custom styling** — our own visual tweaks on top of the base: smoother UI, custom icons, a few quality-of-life details here and there.
> 📢 **macOS Note:** A lot of plugin fixes are rolling out for macOS, including stability improvements for plugins like **Word Bomb** and **Multi-Instance** support.
---
## Installation (macOS ARM64)
**You'll need:**
* [Git](https://git-scm.com/download)
* [Node.js (LTS)](https://nodejs.dev/en/)
* [pnpm](https://pnpm.io/installation) — `npm install -g pnpm`
```bash
git clone https://github.com/20ch/nightcord.git
cd nightcord
pnpm install -r
pnpm add -D react react-dom
pnpm approve-builds
pnpm run package:dir
```
Once the build is finished:
1. Open the `nightcord` folder
2. Go into the `release` folder
3. Open the `arm64` folder
Your built Nightcord application will be there.
If the app launches correctly, you're good to go.
+70
View File
@@ -0,0 +1,70 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
function parseHeaders(headers) {
const result = new Headers();
if (!headers)
return result;
const headersArr = headers.trim().split("\n");
for (var i = 0; i < headersArr.length; i++) {
var row = headersArr[i];
var index = row.indexOf(":")
, key = row.slice(0, index).trim().toLowerCase()
, value = row.slice(index + 1).trim();
result.append(key, value);
}
return result;
}
function blobTo(to, blob) {
if (to === "arrayBuffer" && blob.arrayBuffer) return blob.arrayBuffer();
return new Promise((resolve, reject) => {
var fileReader = new FileReader();
fileReader.onload = event => resolve(event.target.result);
if (to === "arrayBuffer") fileReader.readAsArrayBuffer(blob);
else if (to === "text") fileReader.readAsText(blob, "utf-8");
else reject("unknown to");
});
}
function GM_fetch(url, opt) {
return new Promise((resolve, reject) => {
// https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest
const options = opt || {};
options.url = url;
options.data = options.body;
options.responseType = "blob";
options.onload = resp => {
var blob = resp.response;
resp.blob = () => Promise.resolve(blob);
resp.arrayBuffer = () => blobTo("arrayBuffer", blob);
resp.text = () => blobTo("text", blob);
resp.json = async () => JSON.parse(await blobTo("text", blob));
resp.headers = parseHeaders(resp.responseHeaders);
resp.ok = resp.status >= 200 && resp.status < 300;
resolve(resp);
};
options.ontimeout = () => reject("fetch timeout");
options.onerror = () => reject("fetch error");
options.onabort = () => reject("fetch abort");
GM_xmlhttpRequest(options);
});
}
export const fetch = GM_fetch;
+21
View File
@@ -0,0 +1,21 @@
/*!
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "./VencordNativeStub";
export * from "../src/Vencord";
+143
View File
@@ -0,0 +1,143 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/// <reference path="../src/modules.d.ts" />
/// <reference path="../src/globals.d.ts" />
// Be very careful with imports in this file to avoid circular dependency issues.
// Only import pure modules that don't import other parts of Vencord.
import monacoHtmlLocal from "file://monacoWin.html?minify";
import * as DataStore from "@api/DataStore";
import type { Settings } from "@api/Settings";
import { debounce } from "@shared/debounce";
import { localStorage } from "@utils/localStorage";
import { getStylusWebStoreUrl } from "@utils/web";
import { EXTENSION_BASE_URL, metaReady, RENDERER_CSS_URL } from "@utils/web-metadata";
// listeners for ipc.on
const cssListeners = new Set<(css: string) => void>();
const NOOP = () => { };
const NOOP_ASYNC = async () => { };
const setCssDebounced = debounce((css: string) => VencordNative.quickCss.set(css));
const themeStore = DataStore.createStore("VencordThemes", "VencordThemeData");
// probably should make this less cursed at some point
window.VencordNative = {
themes: {
uploadTheme: (fileName: string, fileData: string) => DataStore.set(fileName, fileData, themeStore),
deleteTheme: (fileName: string) => DataStore.del(fileName, themeStore),
getThemesDir: async () => "",
getThemesList: () => DataStore.entries(themeStore).then(entries =>
entries.map(([name, css]) => ({ fileName: name as string, content: css }))
),
getThemeData: (fileName: string) => DataStore.get(fileName, themeStore),
getSystemValues: async () => ({}),
openFolder: async () => Promise.reject("themes:openFolder is not supported on web"),
},
native: {
getVersions: () => ({}),
openExternal: async (url) => void open(url, "_blank"),
getRendererCss: async () => {
if (IS_USERSCRIPT)
// need to wait for next tick for _vcUserScriptRendererCss to be set
return Promise.resolve().then(() => window._vcUserScriptRendererCss);
await metaReady;
return fetch(RENDERER_CSS_URL)
.then(res => res.text());
},
onRendererCssUpdate: NOOP,
},
updater: {
getRepo: async () => ({ ok: true, value: "https://github.com/Equicord/Equicord" }),
getUpdates: async () => ({ ok: true, value: [] }),
update: async () => ({ ok: true, value: false }),
rebuild: async () => ({ ok: true, value: true }),
},
quickCss: {
get: () => DataStore.get("VencordQuickCss").then(s => s ?? ""),
set: async (css: string) => {
await DataStore.set("VencordQuickCss", css);
cssListeners.forEach(l => l(css));
},
addChangeListener(cb) {
cssListeners.add(cb);
},
addThemeChangeListener: NOOP,
openFile: NOOP_ASYNC,
async openEditor() {
if (IS_USERSCRIPT) {
const shouldOpenWebStore = confirm("QuickCSS is not supported on the Userscript. You can instead use the Stylus extension.\n\nDo you want to open the Stylus web store page?");
if (shouldOpenWebStore) {
window.open(getStylusWebStoreUrl(), "_blank");
}
return;
}
const features = `popup,width=${Math.min(window.innerWidth, 1000)},height=${Math.min(window.innerHeight, 1000)}`;
const win = open("about:blank", "VencordQuickCss", features);
if (!win) {
alert("Failed to open QuickCSS popup. Make sure to allow popups!");
return;
}
win.baseUrl = EXTENSION_BASE_URL;
win.setCss = setCssDebounced;
win.getCurrentCss = () => VencordNative.quickCss.get();
win.getTheme = this.getEditorTheme;
win.document.write(monacoHtmlLocal);
},
getEditorTheme: () => {
const { getTheme, Theme } = require("@utils/discord");
return getTheme() === Theme.Light
? "vs-light"
: "vs-dark";
}
},
settings: {
get: () => {
try {
return JSON.parse(localStorage.getItem("EquicordSettings") || "{}");
} catch (e) {
console.error("Failed to parse settings from localStorage: ", e);
return {};
}
},
set: async (s: Settings) => localStorage.setItem("EquicordSettings", JSON.stringify(s)),
getSettingsDir: async () => "LocalStorage",
openFolder: async () => Promise.reject("settings:openFolder is not supported on web"),
},
pluginHelpers: {} as any,
csp: {} as any,
tray: {
setUpdateState: NOOP,
onCheckUpdates: NOOP,
onRepair: NOOP,
},
};
+32
View File
@@ -0,0 +1,32 @@
/**
* @template T
* @param {T[]} arr
* @param {(v: T) => boolean} predicate
*/
function removeFirst(arr, predicate) {
const idx = arr.findIndex(predicate);
if (idx !== -1) arr.splice(idx, 1);
}
chrome.webRequest.onHeadersReceived.addListener(
({ responseHeaders, type, url }) => {
if (!responseHeaders) return;
if (type === "main_frame" && url.includes("discord.com")) {
// In main frame requests, the CSP needs to be removed to enable fetching of custom css
// as desired by the user
removeFirst(responseHeaders, h => h.name.toLowerCase() === "content-security-policy");
} else if (type === "stylesheet" && url.startsWith("https://raw.githubusercontent.com/")) {
// Most users will load css from GitHub, but GitHub doesn't set the correct content type,
// so we fix it here
removeFirst(responseHeaders, h => h.name.toLowerCase() === "content-type");
responseHeaders.push({
name: "Content-Type",
value: "text/css"
});
}
return { responseHeaders };
},
{ urls: ["https://raw.githubusercontent.com/*", "*://*.discord.com/*"], types: ["main_frame", "stylesheet"] },
["blocking", "responseHeaders"]
);
+18
View File
@@ -0,0 +1,18 @@
if (typeof browser === "undefined") {
var browser = chrome;
}
document.addEventListener(
"DOMContentLoaded",
() => {
window.postMessage({
type: "vencord:meta",
meta: {
EXTENSION_VERSION: browser.runtime.getManifest().version,
EXTENSION_BASE_URL: browser.runtime.getURL(""),
RENDERER_CSS_URL: browser.runtime.getURL("dist/Equicord.css"),
}
});
},
{ once: true }
);
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+62
View File
@@ -0,0 +1,62 @@
{
"manifest_version": 3,
"minimum_chrome_version": "111",
"name": "Equicord Web",
"description": "The other cutest Discord mod now in your browser",
"author": "Equicord",
"homepage_url": "https://github.com/Equicord/Equicord",
"icons": {
"128": "icon.png"
},
"host_permissions": [
"*://*.discord.com/*",
"https://raw.githubusercontent.com/*"
],
"permissions": [
"declarativeNetRequest"
],
"content_scripts": [
{
"run_at": "document_start",
"matches": [
"*://*.discord.com/*"
],
"js": [
"content.js"
],
"all_frames": true,
"world": "ISOLATED"
},
{
"run_at": "document_start",
"matches": [
"*://*.discord.com/*"
],
"js": [
"dist/Equicord.js"
],
"all_frames": true,
"world": "MAIN"
}
],
"web_accessible_resources": [
{
"resources": [
"dist/*",
"vendor/*"
],
"matches": [
"*://*.discord.com/*"
]
}
],
"declarative_net_request": {
"rule_resources": [
{
"id": "modifyResponseHeaders",
"enabled": true,
"path": "modifyResponseHeaders.json"
}
]
}
}
+65
View File
@@ -0,0 +1,65 @@
{
"manifest_version": 2,
"minimum_chrome_version": "91",
"name": "Equicord Web",
"description": "The other cutest Discord mod now in your browser",
"author": "Equicord",
"homepage_url": "https://github.com/Equicord/Equicord",
"icons": {
"128": "icon.png"
},
"permissions": [
"webRequest",
"webRequestBlocking",
"*://*.discord.com/*",
"https://raw.githubusercontent.com/*"
],
"content_scripts": [
{
"run_at": "document_start",
"matches": [
"*://*.discord.com/*"
],
"js": [
"content.js"
],
"all_frames": true,
"world": "ISOLATED"
},
{
"run_at": "document_start",
"matches": [
"*://*.discord.com/*"
],
"js": [
"dist/Equicord.js"
],
"all_frames": true,
"world": "MAIN"
}
],
"background": {
"scripts": [
"background.js"
]
},
"web_accessible_resources": [
"dist/Equicord.js",
"dist/Equicord.css"
],
"browser_specific_settings": {
"gecko": {
"id": "firefox@equicord.org",
"strict_min_version": "128.0",
"data_collection_permissions": {
"required": [
"none"
],
"optional": [
"authenticationInfo",
"locationInfo"
]
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
[
{
"id": 1,
"action": {
"type": "modifyHeaders",
"responseHeaders": [
{
"header": "content-security-policy",
"operation": "remove"
},
{
"header": "content-security-policy-report-only",
"operation": "remove"
}
]
},
"condition": {
"resourceTypes": ["main_frame", "sub_frame"],
"urlFilter": "||discord.com^"
}
},
{
"id": 2,
"action": {
"type": "modifyHeaders",
"responseHeaders": [
{
"header": "content-type",
"operation": "set",
"value": "text/css"
}
]
},
"condition": {
"resourceTypes": ["stylesheet"],
"urlFilter": "||raw.githubusercontent.com^"
}
}
]
+43
View File
@@ -0,0 +1,43 @@
/*
* Vencord, a Discord client mod
* Copyright (c) 2023 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import "./patch-worker";
import * as monaco from "monaco-editor/esm/vs/editor/editor.main.js";
declare global {
const baseUrl: string;
const getCurrentCss: () => Promise<string>;
const setCss: (css: string) => void;
const getTheme: () => string;
}
const BASE = "/vendor/monaco/vs";
self.MonacoEnvironment = {
getWorkerUrl(_moduleId: unknown, label: string) {
const path = label === "css" ? "/language/css/css.worker.js" : "/editor/editor.worker.js";
return new URL(BASE + path, baseUrl).toString();
}
};
getCurrentCss().then(css => {
const editor = monaco.editor.create(
document.getElementById("container")!,
{
value: css,
language: "css",
theme: getTheme(),
}
);
editor.onDidChangeModelContent(() =>
setCss(editor.getValue())
);
window.addEventListener("resize", () => {
// make monaco re-layout
editor.layout();
});
});
+129
View File
@@ -0,0 +1,129 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Equicord QuickCSS Editor</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs/editor/editor.main.css"
integrity="sha256-tiJPQ2O04z/pZ/AwdyIghrOMzewf+PIvEl1YKbQvsZk=" crossorigin="anonymous"
referrerpolicy="no-referrer">
<style>
html,
body,
#container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
header {
position: fixed;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
background: #1e1e1e;
color: #1e1e1e;
border-bottom: 1px solid #444;
width: 100%;
z-index: 10;
}
#container {
margin-top: 45px;
background-color: #1e1e1e;
border: 1px solid #1e1e1e;
}
.toolbar button:hover {
background: rgba(255, 255, 255, 0.1);
}
</style>
</head>
<body>
<header>
<div>
<button id="selectAllButton"
style="background: #1e1e1e; color: #ffffff; border: 1px solid transparent; padding: 5px 10px; margin-right: 5px; border-radius: 4px; transition: background 0.3s, border 0.3s;">Select
All</button>
<button id="saveButton"
style="background: #1e1e1e; color: #ffffff; border: 1px solid transparent; padding: 5px 10px; margin-right: 5px; border-radius: 4px; transition: background 0.3s, border 0.3s;">Save</button>
<button id="copyButton"
style="background: #1e1e1e; color: #ffffff; border: 1px solid transparent; padding: 5px 10px; border-radius: 4px; transition: background 0.3s, border 0.3s;">Copy</button>
<button id="undoButton"
style="background: #1e1e1e; color: #ffffff; border: 1px solid transparent; padding: 5px 10px; border-radius: 4px; transition: background 0.3s, border 0.3s;">Undo</button>
<button id="redoButton"
style="background: #1e1e1e; color: #ffffff; border: 1px solid transparent; padding: 5px 10px; border-radius: 4px; transition: background 0.3s, border 0.3s;">Redo</button>
</div>
</header>
<div id="container"></div>
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs/loader.js"
integrity="sha256-KcU48TGr84r7unF7J5IgBo95aeVrEbrGe04S7TcFUjs=" crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<script>
require.config({
paths: {
vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs"
}
});
require(["vs/editor/editor.main"], () => {
getCurrentCss().then((css) => {
const editor = monaco.editor.create(document.getElementById("container"), {
value: css,
language: "css",
theme: getTheme()
});
editor.onDidChangeModelContent(() => setCss(editor.getValue()));
document.getElementById('selectAllButton').onclick = () => {
editor.setSelection(editor.getModel().getFullModelRange());
editor.focus();
};
document.getElementById('saveButton').onclick = () => {
const css = editor.getValue();
const blob = new Blob([css], { type: 'text/css' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'style.css';
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
};
document.getElementById('copyButton').onclick = () => {
editor.focus();
const selection = editor.getSelection();
editor.setSelection(selection);
document.execCommand('copy');
};
document.getElementById('undoButton').onclick = () => {
editor.trigger('keyboard', 'undo');
};
document.getElementById('redoButton').onclick = () => {
editor.trigger('keyboard', 'redo');
};
window.addEventListener("resize", () => {
editor.layout();
});
});
});
</script>
</body>
</html>
+135
View File
@@ -0,0 +1,135 @@
/*
Copyright 2013 Rob Wu <gwnRob@gmail.com>
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.
*/
// Target: Chrome 20+
// W3-compliant Worker proxy.
// This module replaces the global Worker object.
// When invoked, the default Worker object is called.
// If this call fails with SECURITY_ERR, the script is fetched
// using async XHR, and transparently proxies all calls and
// setters/getters to the new Worker object.
// Note: This script does not magically circumvent the Same origin policy.
(function () {
'use strict';
var Worker_ = window.Worker;
var URL = window.URL || window.webkitURL;
// Create dummy worker for the following purposes:
// 1. Don't override the global Worker object if the fallback isn't
// going to work (future API changes?)
// 2. Use it to trigger early validation of postMessage calls
// Note: Blob constructor is supported since Chrome 20, but since
// some of the used Chrome APIs are only supported as of Chrome 20,
// I don't bother adding a BlobBuilder fallback.
var dummyWorker = new Worker_(
URL.createObjectURL(new Blob([], { type: 'text/javascript' })));
window.Worker = function Worker(scriptURL) {
if (arguments.length === 0) {
throw new TypeError('Not enough arguments');
}
try {
return new Worker_(scriptURL);
} catch (e) {
if (e.code === 18/*DOMException.SECURITY_ERR*/) {
return new WorkerXHR(scriptURL);
} else {
throw e;
}
}
};
// Bind events and replay queued messages
function bindWorker(worker, workerURL) {
if (worker._terminated) {
return;
}
worker.Worker = new Worker_(workerURL);
worker.Worker.onerror = worker._onerror;
worker.Worker.onmessage = worker._onmessage;
var o;
while ((o = worker._replayQueue.shift())) {
worker.Worker[o.method].apply(worker.Worker, o.arguments);
}
while ((o = worker._messageQueue.shift())) {
worker.Worker.postMessage.apply(worker.Worker, o);
}
}
function WorkerXHR(scriptURL) {
var worker = this;
var x = new XMLHttpRequest();
x.responseType = 'blob';
x.onload = function () {
// http://stackoverflow.com/a/10372280/938089
var workerURL = URL.createObjectURL(x.response);
bindWorker(worker, workerURL);
};
x.open('GET', scriptURL);
x.send();
worker._replayQueue = [];
worker._messageQueue = [];
}
WorkerXHR.prototype = {
constructor: Worker_,
terminate: function () {
if (!this._terminated) {
this._terminated = true;
if (this.Worker)
this.Worker.terminate();
}
},
postMessage: function (message, transfer) {
if (!(this instanceof WorkerXHR))
throw new TypeError('Illegal invocation');
if (this.Worker) {
this.Worker.postMessage.apply(this.Worker, arguments);
} else {
// Trigger validation:
dummyWorker.postMessage(message);
// Alright, push the valid message to the queue.
this._messageQueue.push(arguments);
}
}
};
// Implement the EventTarget interface
[
'addEventListener',
'removeEventListener',
'dispatchEvent'
].forEach(function (method) {
WorkerXHR.prototype[method] = function () {
if (!(this instanceof WorkerXHR)) {
throw new TypeError('Illegal invocation');
}
if (this.Worker) {
this.Worker[method].apply(this.Worker, arguments);
} else {
this._replayQueue.push({ method: method, arguments: arguments });
}
};
});
Object.defineProperties(WorkerXHR.prototype, {
onmessage: {
get: function () { return this._onmessage || null; },
set: function (func) {
this._onmessage = typeof func === 'function' ? func : null;
}
},
onerror: {
get: function () { return this._onerror || null; },
set: function (func) {
this._onerror = typeof func === 'function' ? func : null;
}
}
});
})();
+26
View File
@@ -0,0 +1,26 @@
// ==UserScript==
// @name Equicord
// @description A Discord client mod - Web version
// @version %version%
// @author Equicord (https://github.com/Equicord)
// @namespace https://github.com/Equicord/Equicord
// @supportURL https://github.com/Equicord/Equicord
// @icon https://raw.githubusercontent.com/Equicord/Equicord/refs/heads/main/browser/icon.png
// @license GPL-3.0
// @match *://*.discord.com/*
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @run-at document-start
// @compatible chrome Chrome + Tampermonkey or Violentmonkey
// @compatible firefox Firefox Tampermonkey
// @compatible opera Opera + Tampermonkey or Violentmonkey
// @compatible edge Edge + Tampermonkey or Violentmonkey
// @compatible safari Safari + Tampermonkey or Violentmonkey
// ==/UserScript==
// this UserScript DOES NOT work on Firefox with Violentmonkey or Greasemonkey due to a bug that makes it impossible
// to overwrite stuff on the window on sites that use CSP. Use Tampermonkey or use a chromium based browser
// https://github.com/violentmonkey/violentmonkey/issues/997
// this is a compiled and minified version of Equicord. For the source code, visit the GitHub repo
+32
View File
@@ -0,0 +1,32 @@
@echo off
title Nightcord Installer - Build
cd /d "%~dp0"
echo.
echo Building Nightcord Installer...
echo ================================
echo.
dotnet publish installer-src\NightcordInstaller.csproj ^
-c Release ^
-r win-x64 ^
--self-contained false ^
-p:PublishSingleFile=true ^
-o installer-src\bin\publish
if %ERRORLEVEL% neq 0 (
echo.
echo [ERROR] Build failed.
pause
exit /b 1
)
echo.
echo [OK] Build successful!
echo Output: installer-src\bin\publish\Nightcord-Installer.exe
echo.
:: Ouvre le dossier de sortie
explorer installer-src\bin\publish
pause
+104
View File
@@ -0,0 +1,104 @@
# build-installer.ps1 - Compile Nightcord-Installer.exe
# Usage: .\build-installer.ps1
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$SrcDir = Join-Path $Root "installer-src"
$OutDir = Join-Path $Root "release\installer"
$OutExe = Join-Path $OutDir "Nightcord-Installer.exe"
Write-Host ""
Write-Host " [Nightcord] Compiling installer..." -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
# Method 1: dotnet SDK
$hasDotnet = $null
try { $hasDotnet = & dotnet --version 2>$null } catch { }
if ($hasDotnet) {
Write-Host " [1/1] dotnet build (SDK $hasDotnet)..." -ForegroundColor DarkGray
& dotnet publish "$SrcDir\NightcordInstaller.csproj" `
-c Release `
-o $OutDir `
--nologo `
-v quiet `
-p:PublishSingleFile=true `
-p:SelfContained=false `
-r win-x64
if ($LASTEXITCODE -ne 0) {
Write-Host " [ERROR] dotnet build failed." -ForegroundColor Red
exit 1
}
# dotnet may place the .exe in a subdirectory
$built = Get-ChildItem $OutDir -Recurse -Filter "Nightcord-Installer.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($built -and $built.FullName -ne $OutExe) {
Copy-Item $built.FullName $OutExe -Force
}
}
# Method 2: csc.exe (.NET Framework - always present on Windows)
else {
Write-Host " dotnet SDK not found - using csc.exe (.NET Framework)..." -ForegroundColor Yellow
$fxDir = "${env:SystemRoot}\Microsoft.NET\Framework64"
$csc = Get-ChildItem "$fxDir\v4*\csc.exe" -ErrorAction SilentlyContinue |
Sort-Object FullName -Descending |
Select-Object -First 1 -ExpandProperty FullName
if (-not $csc) {
$fxDir32 = "${env:SystemRoot}\Microsoft.NET\Framework"
$csc = Get-ChildItem "$fxDir32\v4*\csc.exe" -ErrorAction SilentlyContinue |
Sort-Object FullName -Descending |
Select-Object -First 1 -ExpandProperty FullName
}
if (-not $csc) {
Write-Host " [ERROR] Neither dotnet SDK nor csc.exe found." -ForegroundColor Red
Write-Host " -> Install .NET SDK: https://dotnet.microsoft.com/download" -ForegroundColor Yellow
exit 1
}
Write-Host " [1/1] Compiling with $csc..." -ForegroundColor DarkGray
$ico = Join-Path $Root "nightcord.ico"
$icoArg = if (Test-Path $ico) { "/win32icon:`"$ico`"" } else { "" }
$refs = @(
"System.Net.Http.dll",
"System.IO.Compression.dll",
"System.IO.Compression.FileSystem.dll",
"System.Windows.Forms.dll",
"System.Drawing.dll",
"System.dll"
) | ForEach-Object { "/r:$_" }
$args = @(
"/target:winexe",
"/platform:anycpu",
"/optimize+",
"/nologo",
"/out:`"$OutExe`"",
"/utf8output"
) + $refs
if ($icoArg) { $args += $icoArg }
$args += "`"$SrcDir\Program.cs`""
& $csc @args
if ($LASTEXITCODE -ne 0) {
Write-Host " [ERROR] Compilation failed." -ForegroundColor Red
exit 1
}
}
# Result
if (Test-Path $OutExe) {
$size = [math]::Round((Get-Item $OutExe).Length / 1KB, 0)
Write-Host ""
Write-Host " OK Nightcord-Installer.exe compiled ($size KB)" -ForegroundColor Green
Write-Host " -> $OutExe" -ForegroundColor DarkGray
Write-Host ""
} else {
Write-Host " [ERROR] Nightcord-Installer.exe not found after compilation." -ForegroundColor Red
exit 1
}
+45
View File
@@ -0,0 +1,45 @@
$ErrorActionPreference = "Stop"
$DISCORD = "C:\Users\zzafi\AppData\Local\Discord\app-1.0.9228"
$OUT = "C:\Users\zzafi\Desktop\equicord\release\win-unpacked"
$RES = "$OUT\resources"
Write-Host "=== ETAPE 1 : Build ===" -ForegroundColor Cyan
Set-Location "C:\Users\zzafi\Desktop\equicord"
npx electron-builder --config electron-builder.config.cjs --win dir --x64
Write-Host "=== ETAPE 2 : Copie _app.asar ===" -ForegroundColor Cyan
Copy-Item "$DISCORD\resources\_app.asar" "$RES\_app.asar" -Force
Write-Host "_app.asar OK"
Write-Host "=== ETAPE 3 : standalone_modules ===" -ForegroundColor Cyan
$MOD_SRC = "$DISCORD\modules"
$MOD_DST = "$RES\standalone_modules"
New-Item -ItemType Directory -Path $MOD_DST -Force | Out-Null
$modules = Get-ChildItem -Path $MOD_SRC -Directory
foreach ($mod in $modules) {
$cleanName = $mod.Name -replace '-\d+$', ''
$innerSrc = Join-Path $mod.FullName $cleanName
$dst = Join-Path $MOD_DST $cleanName
if (Test-Path $innerSrc) {
Copy-Item -Recurse -Force -Path $innerSrc -Destination $dst
Write-Host " $cleanName OK"
}
}
Write-Host "=== ETAPE 4 : build_info.json ===" -ForegroundColor Cyan
$buildInfo = '{"newUpdater":false,"releaseChannel":"stable","version":"1.0.9228","standaloneModules":true}'
Set-Content -Path "$RES\build_info.json" -Value $buildInfo -Encoding UTF8
Write-Host "build_info.json OK"
Write-Host "=== ETAPE 5 : app/dist/_app.asar ===" -ForegroundColor Cyan
$APP_DIST = "$RES\app\dist"
New-Item -ItemType Directory -Path $APP_DIST -Force | Out-Null
Copy-Item "$DISCORD\resources\_app.asar" "$APP_DIST\_app.asar" -Force
Write-Host "app/dist/_app.asar OK"
Write-Host "=== ETAPE 6 : Creation portable exe ===" -ForegroundColor Cyan
npx electron-builder --config electron-builder.config.cjs --win portable --x64 --prepackaged release\win-unpacked
Write-Host "=== DONE ===" -ForegroundColor Green
Write-Host "Fichier : release\Nightcord-1.14.5-portable.exe" -ForegroundColor Green
BIN
View File
Binary file not shown.
+67
View File
@@ -0,0 +1,67 @@
@echo off
title Nightcord — Dev Rebuild + Inject
cd /d "%~dp0"
echo.
echo [1/4] Fermeture de Discord...
taskkill /F /IM Discord.exe /T >nul 2>&1
taskkill /F /IM DiscordPTB.exe /T >nul 2>&1
taskkill /F /IM DiscordCanary.exe /T >nul 2>&1
taskkill /F /IM Update.exe /T >nul 2>&1
ping 127.0.0.1 -n 4 >nul
:waitloop
tasklist /FI "IMAGENAME eq Discord.exe" 2>nul | find /i "Discord.exe" >nul
if not errorlevel 1 (
ping 127.0.0.1 -n 2 >nul
goto :waitloop
)
echo Discord ferme.
echo.
echo [2/4] Build en cours...
call pnpm build
if %errorlevel% neq 0 (
echo.
echo [ERREUR] pnpm build a echoue. Arret.
pause
exit /b 1
)
echo Build termine.
echo.
echo [3/4] Injection...
call pnpm inject
if %errorlevel% neq 0 (
echo.
echo [ERREUR] pnpm inject a echoue. Arret.
pause
exit /b 1
)
echo Injection terminee.
echo.
echo [4/4] Relancement de Discord...
set "DISCORD_PATH=%LOCALAPPDATA%\Discord"
if exist "%DISCORD_PATH%\Update.exe" (
start "" "%DISCORD_PATH%\Update.exe" --processStart Discord.exe
echo Discord relance via Update.exe.
) else (
for /f "delims=" %%i in ('dir /b /ad /o-n "%DISCORD_PATH%\app-*" 2^>nul') do (
set "LATEST_APP=%%i"
goto :found
)
:found
if defined LATEST_APP (
start "" "%DISCORD_PATH%\%LATEST_APP%\Discord.exe"
echo Discord relance via app direct.
) else (
echo [WARN] Discord introuvable dans %DISCORD_PATH%, relancement manuel requis.
)
)
echo.
echo ================================================
echo Nightcord mis a jour et injecte avec succes !
echo ================================================
echo.
timeout /t 3 /nobreak >nul
+48
View File
@@ -0,0 +1,48 @@
module.exports = {
appId: "com.nightcord.app",
productName: "Nightcord",
copyright: "Copyright 2026 Nightcord",
extraMetadata: {
main: "dist/js/main.js",
name: "nightcord"
},
asar: true,
npmRebuild: false,
files: [
"package.json",
"dist/js/**/*",
"static/**/*",
"!**/*.map",
"!**/*.ts"
],
extraResources: [
{
from: "dist/desktop.asar",
to: "desktop.asar"
},
{
from: "dist/nightcord.asar",
to: "nightcord.asar"
},
{
from: "ghost-server",
to: "ghost-server",
filter: [
"server.js",
"package.json"
]
}
],
directories: {
output: "release",
buildResources: "build"
},
mac: {
target: ["dir"],
icon: "build/icon.icns",
category: "public.app-category.social-networking",
identity: null,
hardenedRuntime: false,
gatekeeperAssess: false
}
};
+148
View File
@@ -0,0 +1,148 @@
/*
* Vencord, a Discord client mod
* Copyright (c) 2023 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import stylistic from "@stylistic/eslint-plugin";
import { defineConfig } from "eslint/config";
import react from "eslint-plugin-react";
import header from "eslint-plugin-simple-header";
import simpleImportSort from "eslint-plugin-simple-import-sort";
import unusedImports from "eslint-plugin-unused-imports";
import tseslint from "typescript-eslint";
export default defineConfig(
{ ignores: ["dist", "browser", "packages/vencord-types"] },
{
files: ["src/**/*.{tsx,ts,mts,mjs,js,jsx}", "eslint.config.mjs"],
settings: {
react: {
version: "18"
}
},
...react.configs.flat.recommended,
rules: {
...react.configs.flat.recommended.rules,
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",
"react/display-name": "off",
"react/no-unescaped-entities": "off",
}
},
{
files: ["src/**/*.{tsx,ts,mts,mjs,js,jsx}", "eslint.config.mjs"],
plugins: {
"simple-header": header,
"@stylistic": stylistic,
"@typescript-eslint": tseslint.plugin,
"simple-import-sort": simpleImportSort,
"unused-imports": unusedImports
},
settings: {
"import/resolver": {
map: [
["@webpack", "./src/webpack"],
["@webpack/common", "./src/webpack/common"],
["@utils", "./src/utils"],
["@api", "./src/api"],
["@components", "./src/components"]
]
}
},
languageOptions: {
parser: tseslint.parser,
parserOptions: {
project: ["./tsconfig.json"],
tsconfigRootDir: import.meta.dirname
}
},
rules: {
/*
* Since it's only been a month and Vencord has already been stolen
* by random skids who rebranded it to "AlphaCord" and erased all license
* information
*/
"simple-header/header": [
"error",
{
"files": [`${import.meta.dirname}/scripts/header-new.txt`, `${import.meta.dirname}/scripts/header-old.txt`],
"templates": { "author": [".*", "Vendicated and contributors"] }
}
],
// Style Rules
"@stylistic/jsx-quotes": ["error", "prefer-double"],
"@stylistic/quotes": ["error", "double", { "avoidEscape": true }],
"@stylistic/no-mixed-spaces-and-tabs": "error",
"@stylistic/arrow-parens": ["error", "as-needed"],
"@stylistic/eol-last": ["error", "always"],
"@stylistic/no-multi-spaces": "error",
"@stylistic/no-trailing-spaces": "error",
"@stylistic/no-whitespace-before-property": "error",
"@stylistic/semi": ["error", "always"],
"@stylistic/semi-style": ["error", "last"],
"@stylistic/space-in-parens": ["error", "never"],
"@stylistic/block-spacing": ["error", "always"],
"@stylistic/object-curly-spacing": ["error", "always"],
"@stylistic/spaced-comment": ["error", "always", { "markers": ["!"] }],
"@stylistic/no-extra-semi": "error",
"no-multiple-empty-lines": ["error", { "max": 1, "maxBOF": 0, "maxEOF": 0 }],
// TS Rules
"@stylistic/function-call-spacing": ["error", "never"],
// ESLint Rules
"yoda": "error",
"eqeqeq": ["error", "always", { "null": "ignore" }],
"prefer-destructuring": ["error", {
"VariableDeclarator": { "array": false, "object": true },
"AssignmentExpression": { "array": false, "object": false }
}],
"operator-assignment": ["error", "always"],
"no-useless-computed-key": "error",
"no-unneeded-ternary": ["error", { "defaultAssignment": false }],
"no-invalid-regexp": "error",
"no-constant-condition": ["error", { "checkLoops": false }],
"no-duplicate-imports": "error",
"@typescript-eslint/dot-notation": [
"error",
{
"allowPrivateClassPropertyAccess": true,
"allowProtectedClassPropertyAccess": true
}
],
"no-useless-escape": [
"error",
{
"allowRegexCharacters": ["i"]
}
],
"no-fallthrough": "error",
"for-direction": "error",
"no-async-promise-executor": "error",
"no-cond-assign": "error",
"no-dupe-else-if": "error",
"no-duplicate-case": "error",
"no-irregular-whitespace": "error",
"no-loss-of-precision": "error",
"no-misleading-character-class": "error",
"no-prototype-builtins": "error",
"no-regex-spaces": "error",
"no-shadow-restricted-names": "error",
"no-unexpected-multiline": "error",
"no-unsafe-optional-chaining": "error",
"no-useless-backreference": "error",
"use-isnan": "error",
"prefer-const": ["error", { destructuring: "all" }],
"prefer-spread": "error",
// These are old deprecated browser globals which may be used by mistake, e.g. `addEventListener(e => console.log(event))`
"no-restricted-globals": ["error", "event", "name"],
// Plugin Rules
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error",
"unused-imports/no-unused-imports": "error"
}
}
);
+6
View File
@@ -0,0 +1,6 @@
// Script temporaire pour installer discord-video-stream et voir ses fichiers
// Lance: node _install.js
const { execSync } = require("child_process");
try {
execSync("npm install @dank074/discord-video-stream@latest --no-save", { stdio: "inherit", cwd: __dirname });
} catch(e) {}
+13
View File
@@ -0,0 +1,13 @@
{
"name": "nightcord-ghost-server",
"version": "1.0.0",
"main": "server.js",
"type": "module",
"dependencies": {
"@dank074/discord-video-stream": "^5.0.2",
"discord.js-selfbot-v13": "^3.7.1",
"fluent-ffmpeg": "^2.1.3",
"opusscript": "^0.1.1",
"ws": "^8.19.0"
}
}
+847
View File
@@ -0,0 +1,847 @@
import http from "http";
import https from "https";
import { Client } from "discord.js-selfbot-v13";
import { spawn, spawnSync, execSync } from "child_process";
import fs from "fs";
import path from "path";
import os from "os";
import { createRequire } from "module";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);
const PORT = 47821;
let DVS = null;
let OpusScript = null;
let _ffmpegCache = null;
let _ytdlpCache = null;
let _dshowDevicesCache = null;
let _fluentFfmpeg = null;
import("@dank074/discord-video-stream").then(m => {
DVS = m;
console.log("[GhostServer] DVS OK");
import("fluent-ffmpeg").then(m2 => {
_fluentFfmpeg = m2.default ?? m2;
console.log("[GhostServer] fluent-ffmpeg pré-chargé OK");
}).catch(() => { });
}).catch(e => console.error("[GhostServer] DVS introuvable: " + e.message));
try { OpusScript = require("opusscript"); console.log("[GhostServer] opusscript OK"); }
catch (e) { console.error("[GhostServer] opusscript introuvable: " + e.message); }
try {
os.setPriority(process.pid, os.constants.priority.PRIORITY_ABOVE_NORMAL);
console.log("[GhostServer] Priorité processeur augmentée ✓");
} catch (e) {
console.warn("[GhostServer] Impossible de régler la priorité process:", e.message);
}
function findFfmpeg() {
if (_ffmpegCache !== null) return _ffmpegCache;
const candidates = [
path.join(__dirname, "..", "..", "ffmpeg.exe"),
path.join(__dirname, "..", "ffmpeg.exe"),
path.join(__dirname, "ffmpeg.exe")
];
for (const c of candidates) { if (fs.existsSync(c)) { _ffmpegCache = c; return c; } }
try { let p = require("ffmpeg-static"); p = p?.default ?? p; if (p && fs.existsSync(p)) { _ffmpegCache = p; return p; } } catch { }
for (const c of ["ffmpeg", "C:\\ffmpeg\\bin\\ffmpeg.exe"]) {
try { execSync('"' + c + '" -version', { stdio: "ignore", timeout: 2000 }); _ffmpegCache = c; return c; } catch { }
}
_ffmpegCache = null;
return null;
}
function listDshowDevices(ffmpeg) {
if (_dshowDevicesCache !== null) return _dshowDevicesCache;
const res = spawnSync(ffmpeg, ["-list_devices", "true", "-f", "dshow", "-i", "dummy"],
{ timeout: 5000, encoding: "buffer" });
const text = [res.stderr, res.stdout].map(b => (b || Buffer.alloc(0)).toString("utf8")).join("\n");
const devices = [];
for (const line of text.split(/\r?\n/)) {
if (!/\(audio\)/i.test(line) || /Alternative name/i.test(line)) continue;
const m = line.match(/"([^"]+)"/);
if (!m) continue;
const name = m[1].trim();
if (!name.startsWith("@") && name.length >= 2 && !devices.includes(name)) devices.push(name);
}
_dshowDevicesCache = devices;
return devices;
}
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const request = (u) => {
https.get(u, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
return request(res.headers.location);
}
if (res.statusCode !== 200) return reject(new Error("HTTP " + res.statusCode));
const file = fs.createWriteStream(dest);
res.pipe(file);
file.on("finish", () => { file.close(); resolve(); });
file.on("error", (err) => { fs.unlink(dest, () => { }); reject(err); });
}).on("error", reject);
};
request(url);
});
}
let _ytdlpDownloadPromise = null;
async function findYtDlp() {
if (_ytdlpCache) return _ytdlpCache;
const candidates = [
path.join(__dirname, "yt-dlp.exe"),
path.join(__dirname, "..", "yt-dlp.exe"),
path.join(__dirname, "..", "..", "yt-dlp.exe"),
"C:\\yt-dlp\\yt-dlp.exe", "yt-dlp.exe", "yt-dlp",
];
for (const c of candidates) {
try {
if (c.includes(path.sep) && !fs.existsSync(c)) continue;
execSync('"' + c + '" --version', { stdio: "ignore", timeout: 3000 });
_ytdlpCache = c;
return c;
} catch { }
}
if (_ytdlpDownloadPromise) return _ytdlpDownloadPromise;
const target = path.join(__dirname, "yt-dlp.exe");
console.log("[GhostServer] yt-dlp.exe introuvable, téléchargement automatique...");
_ytdlpDownloadPromise = (async () => {
try {
await downloadFile("https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe", target);
console.log("[GhostServer] yt-dlp.exe téléchargé ✓");
_ytdlpCache = target;
_ytdlpDownloadPromise = null;
return target;
} catch (e) {
console.error("[GhostServer] Échec téléchargement yt-dlp:", e.message);
_ytdlpDownloadPromise = null;
return null;
}
})();
return _ytdlpDownloadPromise;
}
const _resolvedUrlCache = new Map();
const MAX_CACHE_SIZE = 100;
async function resolveVideoUrl(url) {
if (/\.(mp4|mkv|webm|m3u8|mov|avi)(\?|$)/i.test(url)) return url;
const cached = _resolvedUrlCache.get(url);
if (cached && (Date.now() - cached.ts) < 5 * 60 * 1000) return cached.resolved;
const ytdlp = await findYtDlp();
if (!ytdlp) throw new Error("yt-dlp manquant (échec du téléchargement)");
if (typeof ytdlp !== "string") throw new Error("yt-dlp en cours de téléchargement, réessaie dans 10 secondes...");
return new Promise((resolve, reject) => {
const proc = spawn(ytdlp, [
"-g",
"--no-playlist",
"--no-warnings",
"-f", "bestvideo[ext=mp4][height<=720]+bestaudio/best[ext=mp4][height<=720]/best[height<=720]/best",
url
], { windowsHide: true });
const timer = setTimeout(() => { try { proc.kill(); } catch { } reject(new Error("yt-dlp timeout 30s")); }, 30000);
let out = "";
proc.stdout.on("data", d => { out += d.toString(); });
proc.stderr.on("data", d => { const m = d.toString().trim(); if (m && !m.includes("WARNING")) console.warn("[yt-dlp] " + m); });
proc.on("close", code => {
clearTimeout(timer);
const lines = out.trim().split("\n").filter(Boolean);
if (!lines.length || code !== 0) { reject(new Error("yt-dlp échoué code=" + code)); return; }
const resolved = lines[0].trim();
if (_resolvedUrlCache.size >= MAX_CACHE_SIZE) {
const firstKey = _resolvedUrlCache.keys().next().value;
_resolvedUrlCache.delete(firstKey);
}
_resolvedUrlCache.set(url, { resolved, ts: Date.now() });
resolve(resolved);
});
proc.on("error", e => { clearTimeout(timer); reject(e); });
});
}
setImmediate(() => {
const ff = findFfmpeg();
if (ff) {
listDshowDevices(ff);
findYtDlp();
console.log("[GhostServer] Cache: ffmpeg=" + ff + " devices=" + (_dshowDevicesCache?.length ?? 0));
}
});
const sessions = new Map();
const audioPipelines = new Map();
const sharedAudios = new Map();
const streamJobs = new Map();
async function preconnectGhost({ userId, token, micLabel, micDevice }) {
micLabel = micLabel || micDevice || "default";
if (sessions.has(userId)) {
return { ok: true, already: true };
}
if (!DVS) {
for (let i = 0; i < 300; i++) {
await new Promise(r => setTimeout(r, 200));
if (DVS) break;
}
}
if (!DVS) return { ok: false, error: "DVS non chargé" };
if (!OpusScript) return { ok: false, error: "opusscript non chargé" };
const client = new Client({ checkUpdate: false });
const streamer = new DVS.Streamer(client);
await new Promise((resolve, reject) => {
const t = setTimeout(() => {
client.destroy().catch(() => {});
reject(new Error("Login timeout"));
}, 20000);
client.once("ready", () => { clearTimeout(t); resolve(); });
client.once("error", e => { clearTimeout(t); reject(e); });
client.login(token).catch(reject);
});
console.log("[GhostServer] Pré-connecté: " + client.user.tag);
const session = {
client, streamer, userId,
ffmpegProc: null, videoProc: null, ffmpegCommand: null,
udpConn: null, streamUdp: null, streamAbort: null,
micLabel, streaming: false,
};
sessions.set(userId, session);
client.on("shardDisconnect", (event) => {
console.warn(`[GhostServer] ${userId} shardDisconnect code=${event?.code}`);
});
client.on("error", e => console.error(`[GhostServer] ${userId} error: ${e.message}`));
startPermanentAudio(session, null);
return { ok: true, username: client.user.tag };
}
async function connectGhost({ userId, token, guildId, channelId, micLabel, micDevice }) {
micLabel = micLabel || micDevice || "default";
if (sessions.has(userId)) {
return joinVoice(userId, guildId, channelId, micLabel, micDevice);
}
const pre = await preconnectGhost({ userId, token, micLabel, micDevice });
if (!pre.ok) return pre;
return joinVoice(userId, guildId, channelId, micLabel, micDevice);
}
async function joinVoice(userId, guildId, channelId, micLabel, micDevice) {
const s = sessions.get(userId);
if (!s) return { ok: false, error: "Session introuvable" };
if (s.udpConn) {
await leaveVoice(userId);
await new Promise(r => setTimeout(r, 500));
}
if (micLabel || micDevice) s.micLabel = micLabel || micDevice;
try {
await doJoinVoice(s, guildId, channelId);
return { ok: true };
} catch (e) {
console.error("[GhostServer] joinVoice erreur: " + e.message);
return { ok: false, error: e.message };
}
}
async function doJoinVoice(session, guildId, channelId) {
stopStream(session);
const guild = session.client.guilds.cache.get(guildId);
const channel = guild?.channels.cache.get(channelId);
if (channel) console.log("[GhostServer] Rejoindre: " + channel.name);
else console.log("[GhostServer] Rejoindre salon ID: " + channelId);
if (session.udpConn) {
const pipe = audioPipelines.get(session.userId);
if (pipe) pipe.udpTarget = null;
try { session.streamer.leaveVoice(); } catch { }
session.udpConn = null;
await new Promise(r => setTimeout(r, 150));
}
let udpConn = null;
let attempts = 0;
while (attempts < 2) {
attempts++;
try {
console.log("[GhostServer] Appel joinVoice tentative " + attempts + " pour " + guildId + "/" + channelId);
udpConn = await Promise.race([
session.streamer.joinVoice(guildId, channelId, { receiveAudio: true }).then(u => { console.log("[GhostServer] joinVoice resolved! ready=" + u?.ready); return u; }),
new Promise((_, r) => setTimeout(() => r(new Error("Timeout connexion WebRTC")), 15000))
]);
break;
} catch (e) {
console.error(`[GhostServer] ❌ joinVoice tentative ${attempts} a echoue:`, e.message);
if (attempts >= 2) throw e;
try { session.streamer.voiceConnection?.stop(); } catch { }
try { session.streamer._voiceConnection = undefined; } catch { }
try { session.streamer._gatewayEmitter.removeAllListeners("VOICE_STATE_UPDATE"); } catch { }
try { session.streamer._gatewayEmitter.removeAllListeners("VOICE_SERVER_UPDATE"); } catch { }
await new Promise(r => setTimeout(r, 1500));
}
}
session.udpConn = udpConn;
try { udpConn.setPacketizer("H264"); } catch { }
console.log("[GhostServer] Voice connecte (avec reception audio) ✓");
function setSpeaking(udpTarget, session, enabled) {
try {
if (udpTarget?.mediaConnection?.setSpeaking) {
udpTarget.mediaConnection.setSpeaking(enabled);
} else if (session?.streamer?.voiceConnection?.setSpeaking) {
session.streamer.voiceConnection.setSpeaking(enabled);
} else if (session?.client?.voice?.setSpeaking) {
session.client.voice.setSpeaking(enabled);
} else {
console.warn("[GhostServer] Aucun moyen d'appeler setSpeaking pour " + session?.userId);
}
} catch { }
}
function activateAudio() {
console.log("[GhostServer] ✅ WebRTC connected — audio + speaking actifs pour " + session.userId);
setSpeaking(udpConn, session, true);
audioPipelines.set(session.userId, { udpTarget: udpConn });
const audioOk = startPermanentAudio(session, udpConn);
if (!audioOk) {
console.error("[GhostServer] Échec du démarrage du pipeline audio pour " + session.userId);
}
}
if (udpConn.ready) {
activateAudio();
} else {
let activated = false;
try {
const webRtcConn = udpConn?.webRtcConn?.webRtcConn ?? udpConn?.webRtcConn;
if (webRtcConn && typeof webRtcConn.onStateChange === 'function') {
webRtcConn.onStateChange((state) => {
console.log('[GhostServer] WebRTC State:', state);
if (state === 'connected' && !activated) { activated = true; activateAudio(); }
});
}
} catch {}
let polls = 0;
const poll = setInterval(() => {
polls++;
if (udpConn.ready && !activated) {
clearInterval(poll);
activated = true;
console.log('[GhostServer] udpConn.ready=true apres ' + (polls*200) + 'ms');
activateAudio();
} else if (polls >= 50 && !activated) {
clearInterval(poll);
activated = true;
console.warn('[GhostServer] Timeout 10s - activation forcee (ready=' + udpConn.ready + ')');
activateAudio();
}
}, 200);
}
}
async function joinVoiceSilent(userId, guildId, channelId, micLabel, micDevice, retryCount = 0) {
const s = sessions.get(userId);
if (!s) return { ok: false, error: "Session introuvable" };
if (micLabel || micDevice) s.micLabel = micLabel || micDevice;
let guild = s.client.guilds.cache.get(guildId);
if (!guild) {
for (let i = 0; i < 50; i++) {
await new Promise(r => setTimeout(r, 200));
guild = s.client.guilds.cache.get(guildId);
if (guild) break;
}
}
if (!guild) guild = await s.client.guilds.fetch(guildId).catch(() => null);
if (!guild) return { ok: false, error: "Guild introuvable: " + guildId };
let channel = s.client.guilds.cache.get(guildId)?.channels.cache.get(channelId)
?? await s.client.guilds.cache.get(guildId)?.channels.fetch(channelId).catch(() => null);
if (!channel) return { ok: false, error: "Channel introuvable: " + channelId };
try {
let udpConn = null;
let attempts = 0;
while (attempts < 2) {
attempts++;
try {
udpConn = await Promise.race([
s.streamer.joinVoice(guildId, channelId, { receiveAudio: true }),
new Promise((_, r) => setTimeout(() => r(new Error("Timeout WebRTC")), 15000))
]);
break;
} catch (e) {
if (attempts >= 2) throw e;
try { s.streamer.leaveVoice(); } catch { }
await new Promise(r => setTimeout(r, 1000));
}
}
s.udpConn = udpConn;
try { udpConn.setPacketizer("H264"); } catch { }
function activateAudio() {
setSpeaking(udpConn, s, true);
audioPipelines.set(userId, { udpTarget: udpConn });
const audioOk = startPermanentAudio(s, udpConn);
if (!audioOk) {
console.error("[GhostServer] Échec du démarrage du pipeline audio pour " + userId);
}
}
if (udpConn.ready) {
activateAudio();
} else {
try {
const webRtcConn = udpConn.webRtcConn;
if (webRtcConn) {
let activated = false;
webRtcConn.onStateChange((state) => {
if (state === "connected" && !activated) {
activated = true;
activateAudio();
} else if (state === "failed" && !activated) {
console.warn(`[GhostServer] WebRTC failed for ${userId}, will try activation timeout`);
}
});
setTimeout(() => { if (!activated) { activated = true; activateAudio(); } }, 5000);
} else activateAudio();
} catch { activateAudio(); }
}
return { ok: true };
} catch (e) {
return { ok: false, error: e.message };
}
}
async function leaveVoice(userId) {
const s = sessions.get(userId);
if (!s) return;
stopMic(s);
stopStream(s);
if (s.udpConn) {
setSpeaking(s.udpConn, s, false);
try { s.streamer.leaveVoice(); } catch { }
s.udpConn = null;
}
await new Promise(r => setTimeout(r, 200));
console.log("[GhostServer] " + userId + " quitté le salon");
}
async function destroyGhost(userId) {
const s = sessions.get(userId);
if (!s) return;
stopAll(s);
sessions.delete(userId);
setImmediate(() => { try { s.client.destroy(); } catch { } });
}
const FRAME_SIZE = 960;
const SAMPLE_RATE = 48000;
const CHANNELS = 2;
const PCM_BYTES = FRAME_SIZE * CHANNELS * 2;
const FRAME_DUR = 20;
const RING_SIZE = PCM_BYTES * 8;
function resolveDevice(session) {
const ffmpeg = findFfmpeg();
if (!ffmpeg) return { ffmpeg: null, device: null };
const devs = listDshowDevices(ffmpeg);
let device = (session.micLabel && session.micLabel !== "default") ? session.micLabel : null;
if (device && devs.length > 0 && !devs.includes(device)) {
const clean = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
const targetClean = clean(device);
const best = devs.find(d => clean(d).includes(targetClean) || targetClean.includes(clean(d)));
if (best) device = best;
}
if (!device) device = devs.find(d => /cable|virtual|vb/i.test(d)) ?? devs[0] ?? null;
return { ffmpeg, device };
}
function startPermanentAudio(session, initialUdpConn) {
const { ffmpeg, device } = resolveDevice(session);
if (!ffmpeg || !OpusScript || !device) {
console.warn("[GhostServer] Pipeline impossible: ffmpeg=" + !!ffmpeg + " opus=" + !!OpusScript + " device=" + device);
return false;
}
if (sharedAudios.has(device)) {
const shared = sharedAudios.get(device);
if (shared) {
shared.users.set(session.userId, initialUdpConn);
console.log(`[GhostServer] Micro ${device} déjà actif, ajout de l'utilisateur ${session.userId} au flux partagé`);
return true;
}
}
console.log("[GhostServer] Nouveau flux ffmpeg pour micro: " + device);
const proc = spawn(ffmpeg, [
"-fflags", "nobuffer+fastseek", "-flags", "low_delay", "-probesize", "32", "-analyzeduration", "0",
"-thread_queue_size", "1024", "-f", "dshow", "-audio_buffer_size", "50", "-i", "audio=" + device,
"-vn", "-ar", String(SAMPLE_RATE), "-ac", String(CHANNELS), "-f", "s16le", "-loglevel", "error", "pipe:1",
], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
const encoder = new OpusScript(SAMPLE_RATE, CHANNELS, OpusScript.Application.VOIP);
const usersMap = new Map();
if (initialUdpConn) usersMap.set(session.userId, initialUdpConn);
const shared = { proc, encoder, users: usersMap };
sharedAudios.set(device, shared);
console.log("[GhostServer] Pipeline partagé créé pour device:", device);
proc.stderr.on("data", d => {
const msg = d.toString().trim();
if (msg && !msg.includes("Guessed Channel Layout") && !msg.includes("size=")) console.warn("[ffmpeg] " + msg);
});
proc.on("exit", code => {
sharedAudios.delete(device);
try { encoder.delete(); } catch { }
if (code !== 0 && code !== null) console.log("[GhostServer] ffmpeg micro " + device + " exit: " + code);
});
const ring = Buffer.allocUnsafe(RING_SIZE);
let writePos = 0, dataLen = 0;
proc.stdout.on("data", chunk => {
if (shared.users.size === 0) { writePos = 0; dataLen = 0; return; }
let srcPos = 0;
while (srcPos < chunk.length) {
const space = RING_SIZE - writePos;
const toCopy = Math.min(chunk.length - srcPos, space);
chunk.copy(ring, writePos, srcPos, srcPos + toCopy);
srcPos += toCopy;
writePos = (writePos + toCopy) % RING_SIZE;
dataLen = Math.min(dataLen + toCopy, RING_SIZE);
}
const readStart = (writePos - dataLen + RING_SIZE) % RING_SIZE;
let readPos = readStart;
while (dataLen >= PCM_BYTES) {
let frame;
if (readPos + PCM_BYTES <= RING_SIZE) {
frame = ring.slice(readPos, readPos + PCM_BYTES);
} else {
frame = Buffer.allocUnsafe(PCM_BYTES);
const firstPart = RING_SIZE - readPos;
ring.copy(frame, 0, readPos, RING_SIZE);
ring.copy(frame, firstPart, 0, PCM_BYTES - firstPart);
}
readPos = (readPos + PCM_BYTES) % RING_SIZE;
dataLen -= PCM_BYTES;
const opusFrame = encoder.encode(frame, FRAME_SIZE);
for (const [uid, target] of shared.users) {
if (target?.ready) {
try { target.sendAudioFrame(opusFrame, FRAME_DUR); } catch { }
} else {
const pipe = audioPipelines.get(uid);
if (pipe?.udpTarget) shared.users.set(uid, pipe.udpTarget);
}
}
}
});
console.log("[GhostServer] Pipeline audio partagé actif ✓");
return true;
}
function stopMic(session) {
audioPipelines.delete(session.userId);
for (const [device, shared] of sharedAudios) {
if (shared.users.has(session.userId)) {
shared.users.delete(session.userId);
console.log(`[GhostServer] Retrait de ${session.userId} du micro ${device}`);
if (shared.users.size === 0) {
try { shared.proc.kill("SIGKILL"); } catch { }
sharedAudios.delete(device);
console.log(`[GhostServer] Plus d'auditeurs pour ${device}, arrêt du flux`);
}
break;
}
}
}
function stopStream(session) {
if (session.videoProc) { try { session.videoProc.kill("SIGKILL"); } catch { } session.videoProc = null; }
if (session.streamAbort) { try { session.streamAbort.abort(); } catch { } session.streamAbort = null; }
if (session.ffmpegCommand) { try { session.ffmpegCommand.kill("SIGKILL"); } catch { } session.ffmpegCommand = null; }
if (session.streamUdp && session.streamUdp !== session.udpConn) {
try { session.streamer.stopStream(); } catch { }
session.streamUdp = null;
}
session.streaming = false;
streamJobs.delete(session.userId);
}
function stopAll(session) {
stopMic(session);
stopStream(session);
if (session.udpConn) {
setSpeaking(session.udpConn, session, false);
try { session.streamer.leaveVoice(); } catch { }
session.udpConn = null;
}
session.streaming = false;
}
async function startVideoStream(session, videoUrl) {
if (!session.udpConn) throw new Error("Pas connecté au vocal");
if (!DVS) throw new Error("DVS non chargé");
const ffmpeg = findFfmpeg();
if (!ffmpeg) throw new Error("ffmpeg introuvable");
stopStream(session);
const resolvedUrl = await resolveVideoUrl(videoUrl);
if (typeof DVS.prepareStream === "function" && typeof DVS.playStream === "function") {
try { if (_fluentFfmpeg) { _fluentFfmpeg.setFfmpegPath(ffmpeg); } else { const { default: ff } = await import("fluent-ffmpeg"); ff.setFfmpegPath(ffmpeg); _fluentFfmpeg = ff; } } catch { }
const abortCtrl = new AbortController();
session.streamAbort = abortCtrl;
session.streaming = true;
const { command, output } = DVS.prepareStream(resolvedUrl, {
width: 1280, height: 720, frameRate: 24, videoCodec: "H264",
bitrateVideo: 2000, bitrateVideoMax: 2500, includeAudio: false, minimizeLatency: true,
}, abortCtrl.signal);
session.ffmpegCommand = command;
DVS.playStream(output, session.streamer, {
type: "go-live", format: "nut", width: 1280, height: 720, frameRate: 24,
}, abortCtrl.signal).then(() => {
session.streaming = false; session.streamAbort = null; session.ffmpegCommand = null;
streamJobs.delete(session.userId);
}).catch(e => {
if (e?.name !== "AbortError") console.error("[GhostServer] playStream: " + (e?.message ?? e));
session.streaming = false; session.streamAbort = null; session.ffmpegCommand = null;
streamJobs.delete(session.userId);
});
return;
}
if (!OpusScript) throw new Error("opusscript introuvable");
const streamConn = await session.streamer.createStream();
session.streamUdp = streamConn;
const FPS = 24, W = 1280, H = 720;
streamConn.setPacketizer("H264");
const vProc = spawn(ffmpeg, [
"-re", "-i", resolvedUrl, "-an",
"-vf", `scale=${W}:${H},format=yuv420p`,
"-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency",
"-profile:v", "baseline", "-level", "3.1",
"-b:v", "2000k", "-maxrate", "2500k", "-bufsize", "4000k",
"-g", String(FPS * 2), "-f", "h264", "-loglevel", "error", "pipe:1",
], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
session.videoProc = vProc;
vProc.on("exit", () => {
if (session.videoProc === vProc) {
session.videoProc = null;
session.streaming = false;
streamJobs.delete(session.userId);
}
});
vProc.stdout.on("data", chunk => { try { streamConn.sendVideoFrame(chunk, 1000 / FPS); } catch { } });
session.streaming = true;
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", c => body += c);
req.on("end", () => {
try { resolve(JSON.parse(body || "{}")); }
catch (e) { reject(new Error("JSON invalide: " + e.message)); }
});
req.on("error", reject);
});
}
function send(res, code, data) {
res.writeHead(code, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
res.end(JSON.stringify(data));
}
http.createServer(async (req, res) => {
if (req.method === "OPTIONS") { send(res, 200, {}); return; }
try {
if (req.url === "/status" && req.method === "GET") {
send(res, 200, { ok: true, sessions: [...sessions.keys()], pipelines: [...audioPipelines.keys()], ffmpeg: !!findFfmpeg(), dvs: !!DVS, opus: !!OpusScript });
return;
}
if (req.url === "/devices" && req.method === "GET") {
const ff = findFfmpeg();
_dshowDevicesCache = null;
send(res, 200, { ok: true, devices: ff ? listDshowDevices(ff) : [] });
return;
}
const body = await readBody(req);
if (req.url === "/preconnect") { send(res, 200, await preconnectGhost(body)); return; }
if (req.url === "/connect") { send(res, 200, await connectGhost(body)); return; }
if (req.url === "/join") { send(res, 200, await joinVoice(body.userId, body.guildId, body.channelId, body.micLabel, body.micDevice)); return; }
if (req.url === "/join-all") {
const ids = Array.isArray(body.userIds) ? body.userIds : [];
send(res, 200, { ok: true });
(async () => {
await Promise.allSettled(ids.map(id => {
const s = sessions.get(id);
if (!s?.udpConn) return Promise.resolve();
const pipe = audioPipelines.get(id);
if (pipe) pipe.udpTarget = null;
try { s.streamer.leaveVoice(); } catch { }
s.udpConn = null;
return new Promise(r => setTimeout(r, 150));
}));
const joinResults = await Promise.allSettled(
ids.map(id => joinVoiceSilent(id, body.guildId, body.channelId, body.micLabel, body.micDevice))
);
await new Promise(r => setTimeout(r, 500));
const joined = ids.filter((_, i) => joinResults[i].status === "fulfilled" && joinResults[i].value?.ok);
for (const userId of joined) {
const s = sessions.get(userId);
const pipe = audioPipelines.get(userId);
if (s?.udpConn && pipe) {
pipe.udpTarget = s.udpConn;
setSpeaking(s.udpConn, s, true);
}
}
console.log(`[GhostServer] Audio sync ${joined.length}/${ids.length}`);
})();
return;
}
if (req.url === "/leave") { await leaveVoice(body.userId); send(res, 200, { ok: true }); return; }
if (req.url === "/leave-all") { await Promise.all((body.userIds ?? []).map(id => leaveVoice(id))); send(res, 200, { ok: true }); return; }
if (req.url === "/disconnect") { await leaveVoice(body.userId); send(res, 200, { ok: true }); return; }
if (req.url === "/destroy") { await destroyGhost(body.userId); send(res, 200, { ok: true }); return; }
if (req.url === "/stream-start") {
const s = sessions.get(body.userId);
if (!s) { send(res, 200, { ok: false, error: "Session introuvable" }); return; }
const jobId = Date.now().toString();
streamJobs.set(body.userId, { state: "resolving", jobId });
send(res, 200, { ok: true, resolving: true, jobId });
setImmediate(async () => {
try {
streamJobs.set(body.userId, { state: "starting", jobId });
await startVideoStream(s, body.url);
streamJobs.set(body.userId, { state: "active", jobId });
console.log("[GhostServer] Stream démarré pour " + body.userId);
} catch (e) {
console.error("[GhostServer] stream-start erreur: " + (e?.message ?? e));
streamJobs.set(body.userId, { state: "error", error: e?.message ?? String(e), jobId });
if (s) s.streaming = false;
}
});
return;
}
if (req.url === "/stream-status") {
const s = sessions.get(body.userId);
if (!s) { send(res, 200, { ok: false, error: "Session introuvable" }); return; }
const job = streamJobs.get(body.userId);
if (!job) {
send(res, 200, { ok: true, state: s.streaming ? "active" : "idle" });
} else {
send(res, 200, { ok: true, ...job });
}
return;
}
if (req.url === "/stream-stop") {
const s = sessions.get(body.userId);
if (!s) { send(res, 200, { ok: false, error: "Session introuvable" }); return; }
stopStream(s); send(res, 200, { ok: true }); return;
}
if (req.url?.startsWith("/playback/")) {
const uid = req.url.split("/").pop();
const s = sessions.get(uid);
if (!s?.udpConn) { send(res, 404, { error: "Non connecté" }); return; }
console.log("[GhostServer] Début streaming WAV playback pour " + uid);
res.writeHead(200, {
"Content-Type": "audio/wav",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
});
const wavHeader = Buffer.alloc(44);
wavHeader.write("RIFF", 0);
wavHeader.writeUInt32LE(0xFFFFFFFF, 4);
wavHeader.write("WAVE", 8);
wavHeader.write("fmt ", 12);
wavHeader.writeUInt32LE(16, 16);
wavHeader.writeUInt16LE(1, 20);
wavHeader.writeUInt16LE(2, 22);
wavHeader.writeUInt32LE(48000, 24);
wavHeader.writeUInt32LE(48000 * 2 * 2, 28);
wavHeader.writeUInt16LE(4, 32);
wavHeader.writeUInt16LE(16, 34);
wavHeader.write("data", 36);
wavHeader.writeUInt32LE(0xFFFFFFFF, 40);
res.write(wavHeader);
const decoder = new OpusScript(48000, 2, OpusScript.Application.VOIP);
const udp = s.udpConn;
if (udp?.mediaConnection?.on) {
udp.mediaConnection.on("audio", (id, frame) => {
if (!res.writable) return;
try {
const pcm = decoder.decode(frame, 960);
res.write(pcm);
} catch { }
});
} else {
const silence = Buffer.alloc(960 * 4, 0);
const int = setInterval(() => { if (!res.writable) clearInterval(int); else res.write(silence); }, 20);
req.on("close", () => clearInterval(int));
}
req.on("close", () => {
try { decoder.delete(); } catch { }
});
return;
}
if (req.url === "/shutdown") {
send(res, 200, { ok: true });
setTimeout(() => process.exit(0), 100);
return;
}
send(res, 404, { ok: false, error: "Not found" });
} catch (e) {
console.error("[GhostServer] HTTP: " + e.message);
send(res, 500, { ok: false, error: e.message });
}
}).listen(PORT, "127.0.0.1", () => {
console.log("[GhostServer] Prêt sur port " + PORT + " ✓");
});
process.on("uncaughtException", e => console.error("[GhostServer] Uncaught: " + e.message));
process.on("unhandledRejection", e => console.error("[GhostServer] Rejection: " + (e?.message ?? e)));
+65
View File
@@ -0,0 +1,65 @@
# ==============================================================================
# Nightcord — Script d'injection Post-Installation
# Utilisé par l'installateur Inno Setup pour injecter Nightcord dans Discord.
# ==============================================================================
param(
[string]$AppDir = $PSScriptRoot
)
$ErrorActionPreference = "Continue"
# 1. Localiser Discord Stable
$DiscordPath = Join-Path $env:LOCALAPPDATA "Discord"
if (-not (Test-Path $DiscordPath)) {
exit 0
}
# Trouver la version la plus récente (app-*)
$LatestApp = Get-ChildItem $DiscordPath -Filter "app-*" | Sort-Object Name -Descending | Select-Object -First 1
if (-not $LatestApp) {
exit 0
}
$CoreDir = Join-Path $LatestApp.FullName "resources"
$InjectDir = Join-Path $CoreDir "app"
# 2. Créer l'injection
if (-not (Test-Path $InjectDir)) {
New-Item -ItemType Directory -Path $InjectDir -Force | Out-Null
}
# Générer le package.json d'injection
$PackageJson = @{
name = "discord"
main = "index.js"
} | ConvertTo-Json
Set-Content -Path (Join-Path $InjectDir "package.json") -Value $PackageJson
# Générer le index.js d'injection
# On pointe vers le patcher.js dans le dossier d'installation de Nightcord
$NightcordPatcher = Join-Path $AppDir "dist\desktop\patcher.js"
$NightcordPatcher = $NightcordPatcher.Replace("\", "\\")
$IndexJs = @"
\"use strict\";
const path = require(\"path\");
const fs = require(\"fs\");
// Injection Nightcord
try {
require(\"$NightcordPatcher\");
} catch (e) {
console.error(\"Nightcord injection failed:\", e);
// Fallback sur Discord original si possible
const originalAsar = path.join(__dirname, \"..\", \"_app.asar\");
if (fs.existsSync(originalAsar)) {
require(originalAsar);
}
}
"@
Set-Content -Path (Join-Path $InjectDir "index.js") -Value $IndexJs
exit 0
+37
View File
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<AssemblyName>Nightcord-Installer</AssemblyName>
<RootNamespace>NightcordInstaller</RootNamespace>
<LangVersion>latest</LangVersion>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<ApplicationIcon>icon.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Version>2.0.0</Version>
<!-- Single File configuration -->
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>false</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishReadyToRun>true</PublishReadyToRun>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<Product>Nightcord Installer</Product>
<Company>Nightcord</Company>
<Description>Installs Nightcord into Discord Desktop</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2420.47" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="icon.ico" />
<EmbeddedResource Include="index.html" />
</ItemGroup>
</Project>
+839
View File
@@ -0,0 +1,839 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Drawing;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Reflection;
namespace NightcordInstaller
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LauncherForm());
}
}
public class LauncherForm : Form
{
private WebView2 _webView;
private NightcordBackend _backend;
public LauncherForm()
{
this.Text = "Nightcord Installer";
this.Size = new Size(740, 620); // Enlarged to prevent text clipping
this.FormBorderStyle = FormBorderStyle.None;
this.StartPosition = FormStartPosition.CenterScreen;
this.BackColor = Color.FromArgb(11, 11, 24); // matching HTML root
var iconStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NightcordInstaller.icon.ico");
if (iconStream != null) this.Icon = new Icon(iconStream);
_webView = new WebView2
{
Dock = DockStyle.Fill,
DefaultBackgroundColor = Color.Transparent
};
this.Controls.Add(_webView);
// Drag window from HTML
_webView.NavigationCompleted += (s, e) => {
_webView.CoreWebView2.WebMessageReceived += (sender, args) => {
if (args.TryGetWebMessageAsString() == "drag") {
ReleaseCapture();
SendMessage(this.Handle, 0xA1, 0x2, 0);
}
};
};
InitializeWebView();
}
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
private async void InitializeWebView()
{
var userDataFolder = Path.Combine(Path.GetTempPath(), "NightcordInstaller_WebView2");
CoreWebView2Environment env;
try
{
env = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
await _webView.EnsureCoreWebView2Async(env);
}
catch (Exception ex) when (
ex is System.Runtime.InteropServices.COMException ||
ex.HResult == unchecked((int)0x80070002) ||
ex.Message.Contains("WebView2") ||
ex.Message.Contains("0x80070002")
)
{
// WebView2 Runtime not installed on this machine
MessageBox.Show(
"Microsoft Edge WebView2 Runtime is required to run the Nightcord Installer but was not found on your system.\n\n" +
"Please download and install it from:\nhttps://aka.ms/webview2\n\n" +
"After installing, restart the Nightcord Installer.",
"WebView2 Runtime Required",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
Application.Exit();
return;
}
_backend = new NightcordBackend(this, _webView);
_webView.CoreWebView2.AddHostObjectToScript("backend", _backend);
// Wrap COM proxy into exactly what index.html expects, and add drag support
await _webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(@"
window.nightcord = {
detectDiscord: async () => JSON.parse(await chrome.webview.hostObjects.backend.DetectDiscord()),
isInjected: async (path) => await chrome.webview.hostObjects.backend.IsInjected(path),
hasThirdPartyMod: async (path) => await chrome.webview.hostObjects.backend.HasThirdPartyMod(path),
inject: async (path) => JSON.parse(await chrome.webview.hostObjects.backend.Inject(path)),
startInject: (path) => JSON.parse(chrome.webview.hostObjects.sync.backend.StartInject(path)),
getInjectStatus: () => JSON.parse(chrome.webview.hostObjects.sync.backend.GetInjectStatus()),
uninject: async (path) => JSON.parse(await chrome.webview.hostObjects.backend.Uninject(path)),
minimizeApp: () => chrome.webview.hostObjects.backend.MinimizeApp(),
closeApp: () => chrome.webview.hostObjects.backend.CloseApp(),
openUrl: (url) => chrome.webview.hostObjects.backend.OpenUrl(url)
};
// Add drag support to titlebar
document.addEventListener('DOMContentLoaded', () => {
const titlebar = document.querySelector('.titlebar');
if (titlebar) {
titlebar.addEventListener('mousedown', (e) => {
if(e.target.tagName !== 'BUTTON' && !e.target.classList.contains('titlebar-title')) {
window.chrome.webview.postMessage('drag');
}
});
}
});
");
// Disable context menu and dev tools
_webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
// Load HTML from embedded resource and inject Icon
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NightcordInstaller.index.html"))
using (var reader = new StreamReader(stream))
{
var html = reader.ReadToEnd();
// Convert Icon to Base64 PNG for HTML
try {
using (var iconStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NightcordInstaller.icon.ico"))
{
var icon = new Icon(iconStream);
using (var bmp = icon.ToBitmap())
using (var ms = new MemoryStream())
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var base64 = Convert.ToBase64String(ms.ToArray());
html = html.Replace("{{ICON_BASE64}}", "data:image/png;base64," + base64);
}
}
} catch { }
_webView.NavigateToString(html);
}
}
}
[ComVisible(true)]
public class NightcordBackend
{
private LauncherForm _form;
private WebView2 _webView;
private HttpClient _http;
private string _distDir;
private string _exeDir;
const string GITHUB_REPO = "nightcordoff/nightcord";
const string DIST_ZIP = "nightcord-dist.zip";
public NightcordBackend(LauncherForm form, WebView2 webView)
{
_form = form;
_webView = webView;
_http = new HttpClient();
_http.Timeout = TimeSpan.FromSeconds(30); // Prevent infinite hang on GitHub API
_exeDir = Path.GetDirectoryName(Application.ExecutablePath);
_distDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Nightcord", "dist");
}
public void MinimizeApp() { _form.Invoke(new Action(() => _form.WindowState = FormWindowState.Minimized)); }
public void CloseApp() { _form.Invoke(new Action(() => Application.Exit())); }
public void OpenUrl(string url)
{
try
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = url,
UseShellExecute = true
});
}
catch { }
}
public void SetStatus(string type, string text)
{
_form.Invoke(new Action(() => {
var safeText = text.Replace("'", "\\'").Replace("\n", " ");
_webView.CoreWebView2.ExecuteScriptAsync($"if(typeof setStatus === 'function') setStatus('{type}', '{safeText}');");
}));
}
public void SetProgress(double percent, string text, double mbDownloaded = -1, double mbTotal = -1)
{
_form.Invoke(new Action(() => {
var safeText = text.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\n", " ");
var percentStr = percent.ToString("F1", System.Globalization.CultureInfo.InvariantCulture);
if (mbDownloaded >= 0 && mbTotal >= 0)
{
var mbDlStr = mbDownloaded.ToString("F1", System.Globalization.CultureInfo.InvariantCulture);
var mbTotalStr = mbTotal.ToString("F1", System.Globalization.CultureInfo.InvariantCulture);
_webView.CoreWebView2.ExecuteScriptAsync($"if(typeof setLoading === 'function') setLoading(true, '{safeText}', {percentStr}, {mbDlStr}, {mbTotalStr});");
}
else
{
_webView.CoreWebView2.ExecuteScriptAsync($"if(typeof setLoading === 'function') setLoading(true, '{safeText}', {percentStr});");
}
}));
}
public async Task<bool> IsInjected(string path)
{
return await Task.Run(() => {
var appDir = System.IO.Path.Combine(path, "app");
var pkgPath = System.IO.Path.Combine(appDir, "package.json");
return Directory.Exists(appDir) && File.Exists(pkgPath) && File.ReadAllText(pkgPath).Contains("\"nightcord\"");
});
}
/// <summary>
/// Returns true if a third-party mod (Vencord, Equicord, OpenAsar) is detected
/// but Nightcord is NOT yet injected.
/// </summary>
public async Task<bool> HasThirdPartyMod(string path)
{
return await Task.Run(() => {
var appDir = System.IO.Path.Combine(path, "app");
var pkgPath = System.IO.Path.Combine(appDir, "package.json");
if (!Directory.Exists(appDir) || !File.Exists(pkgPath)) return false;
var content = File.ReadAllText(pkgPath);
// Already Nightcord → not a third-party mod
if (content.Contains("\"nightcord\"")) return false;
return content.Contains("vencord", StringComparison.OrdinalIgnoreCase)
|| content.Contains("equicord", StringComparison.OrdinalIgnoreCase)
|| content.Contains("openasar", StringComparison.OrdinalIgnoreCase);
});
}
public async Task<string> DetectDiscord()
{
return await Task.Run(() => {
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string[] channels = { "Discord", "DiscordPTB", "DiscordCanary", "DiscordDevelopment" };
string[] names = { "Discord", "Discord PTB", "Discord Canary", "Discord Dev" };
var list = new List<object>();
for (int i = 0; i < channels.Length; i++)
{
var c = channels[i];
var dPath = Path.Combine(localAppData, c);
if (!Directory.Exists(dPath)) continue;
foreach (var dir in Directory.GetDirectories(dPath, "app-*"))
{
var resources = Path.Combine(dir, "resources");
if (!Directory.Exists(resources)) continue;
list.Add(new {
name = names[i],
path = resources,
asarPath = Path.Combine(resources, "app.asar"),
version = Path.GetFileName(dir).Replace("app-", "")
});
}
}
return JsonSerializer.Serialize(list);
});
}
// Job state for async inject (avoids WebView2 COM proxy timeout on large downloads)
private string _injectJobState = "idle"; // idle | running | done | error
private string _injectJobError = "";
public string StartInject(string resourcesPath)
{
if (_injectJobState == "running")
return JsonSerializer.Serialize(new { started = false, error = "Already running" });
_injectJobState = "running";
_injectJobError = "";
Task.Run(async () =>
{
try
{
await EnsureDistAsync();
await Task.Run(() => DoInject(resourcesPath));
_injectJobState = "done";
}
catch (Exception ex)
{
_injectJobError = ex.Message;
_injectJobState = "error";
}
});
return JsonSerializer.Serialize(new { started = true });
}
public string GetInjectStatus()
{
return JsonSerializer.Serialize(new
{
state = _injectJobState,
error = _injectJobError
});
}
// Keep old Inject for compat but it just delegates
public async Task<string> Inject(string resourcesPath)
{
try {
await EnsureDistAsync();
await Task.Run(() => DoInject(resourcesPath));
return JsonSerializer.Serialize(new { success = true });
} catch (Exception ex) {
return JsonSerializer.Serialize(new { success = false, error = ex.Message });
}
}
public async Task<string> Uninject(string resourcesPath)
{
try {
await Task.Run(() => DoUninject(resourcesPath));
return JsonSerializer.Serialize(new { success = true });
} catch (Exception ex) {
return JsonSerializer.Serialize(new { success = false, error = ex.Message });
}
}
private async Task EnsureDistAsync()
{
var localDist = Path.Combine(_exeDir, "dist");
if (Directory.Exists(localDist) && File.Exists(Path.Combine(localDist, "patcher.js")))
{
_distDir = localDist;
SetStatus("loading", "Files found locally...");
return;
}
SetProgress(2, "Fetching latest release information...");
Directory.CreateDirectory(Path.GetDirectoryName(_distDir));
var apiUrl = $"https://api.github.com/repos/{GITHUB_REPO}/releases/latest";
_http.DefaultRequestHeaders.Clear();
_http.DefaultRequestHeaders.Add("User-Agent", "Nightcord-Installer/2.0");
_http.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
string json;
try
{
json = await _http.GetStringAsync(apiUrl);
}
catch (TaskCanceledException)
{
throw new Exception("GitHub API timed out (30s). Check your internet connection and try again.");
}
catch (HttpRequestException ex)
{
throw new Exception($"Could not reach GitHub: {ex.Message}. Check your internet connection.");
}
var zipUrl = ExtractJsonValue(json, "browser_download_url", DIST_ZIP);
if (string.IsNullOrEmpty(zipUrl))
throw new Exception($"'{DIST_ZIP}' not found in the GitHub release. The release may not be published yet.");
SetProgress(5, "Starting download...");
var tmpZip = Path.Combine(Path.GetTempPath(), "nightcord-dist.zip");
using (var response = await _http.GetAsync(zipUrl, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength ?? (long)(348.0 * 1024 * 1024); // Fallback to 348MB if null
using (var contentStream = await response.Content.ReadAsStreamAsync())
using (var fs = new FileStream(tmpZip, FileMode.Create, FileAccess.Write, FileShare.None, 81920, true))
{
var buffer = new byte[81920];
long totalRead = 0;
int read;
double lastReportedPercent = 0;
while ((read = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fs.WriteAsync(buffer, 0, read);
totalRead += read;
double percent = (double)totalRead / totalBytes * 100.0;
if (percent - lastReportedPercent >= 0.5 || percent >= 100.0)
{
lastReportedPercent = percent;
// Map 0-100% of download to 5%-75% of overall progress
double overallPercent = 5.0 + (percent * 0.70);
double totalMB = (double)totalBytes / (1024.0 * 1024.0);
double readMB = (double)totalRead / (1024.0 * 1024.0);
SetProgress(overallPercent, "Downloading Nightcord...", readMB, totalMB);
}
}
}
}
SetProgress(75, "Preparing extraction...");
await Task.Run(() =>
{
if (Directory.Exists(_distDir)) Directory.Delete(_distDir, true);
Directory.CreateDirectory(_distDir);
// Normalize _distDir with a guaranteed trailing separator for safe StartsWith checks
var normalizedDistDir = _distDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
+ Path.DirectorySeparatorChar;
using (var archive = ZipFile.OpenRead(tmpZip))
{
int totalEntries = archive.Entries.Count;
int extractedEntries = 0;
double lastReportedPercent = 0;
foreach (var entry in archive.Entries)
{
// Normalize the zip entry path: replace forward slashes, strip leading slashes
var entryPath = entry.FullName
.Replace('/', Path.DirectorySeparatorChar)
.TrimStart(Path.DirectorySeparatorChar);
// Reject any entry that tries to traverse upward (e.g. ../../evil)
if (entryPath.Contains(".."))
continue;
var fullPath = Path.GetFullPath(Path.Combine(_distDir, entryPath));
// Security check: ensure resolved path stays inside _distDir
if (!fullPath.StartsWith(normalizedDistDir, StringComparison.OrdinalIgnoreCase))
continue;
if (entry.FullName.EndsWith("/") || entry.FullName.EndsWith("\\"))
{
Directory.CreateDirectory(fullPath);
}
else
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
entry.ExtractToFile(fullPath, true);
}
extractedEntries++;
double percent = (double)extractedEntries / totalEntries * 100.0;
if (percent - lastReportedPercent >= 1.0 || percent >= 100.0)
{
lastReportedPercent = percent;
// Map 0-100% of extraction to 75%-90% of overall progress
double overallPercent = 75.0 + (percent * 0.15);
SetProgress(overallPercent, $"Extracting files ({extractedEntries}/{totalEntries})...");
}
}
}
try { File.Delete(tmpZip); } catch { }
});
}
private void DoInject(string resPath)
{
var appDir = Path.Combine(resPath, "app");
var backup = Path.Combine(resPath, "_app.asar");
var appAsar = Path.Combine(resPath, "app.asar");
SetProgress(90, "Closing Discord...");
KillDiscord(resPath);
SetProgress(91, "Removing previous mod injection (Vencord / Equicord / OpenAsar)...");
// ── NETTOYAGE COMPLET DE TOUTE INJECTION PRÉCÉDENTE ──────────────────────
// 1. Supprimer le dossier app/ quel que soit le mod qui l'a créé
if (Directory.Exists(appDir))
{
// Déjà Nightcord → on réinjecte proprement sans bail-out partiel
try { Directory.Delete(appDir, true); } catch { }
}
// 2. Supprimer tout app.asar faux (< 2 MB) créé par Vencord/OpenAsar/Equicord
// Le vrai app.asar Discord fait entre 40 MB et 80 MB.
if (File.Exists(appAsar) && new FileInfo(appAsar).Length < 2_000_000)
{
File.Delete(appAsar);
}
// 3. Chercher un backup fait par un mod tiers (Vencord utilise _app.asar,
// Equicord aussi, OpenAsar utilise original_app.asar)
string[] thirdPartyBackups = { "_app.asar", "original_app.asar", "app.asar.bak" };
foreach (var bkName in thirdPartyBackups)
{
var bkPath = Path.Combine(resPath, bkName);
// C'est un vrai backup si sa taille est > 2 MB
if (File.Exists(bkPath) && new FileInfo(bkPath).Length > 2_000_000)
{
// Si app.asar est absent ou corrompu, restaurer ce backup en tant que app.asar
if (!File.Exists(appAsar) || new FileInfo(appAsar).Length < 2_000_000)
{
if (File.Exists(appAsar)) File.Delete(appAsar);
// Copier (pas déplacer) pour ne pas perdre le backup si une erreur survient
File.Copy(bkPath, appAsar);
}
break;
}
}
// 4. Nettoyer les patches dans discord_desktop_core que Vencord/Equicord injectent
// dans splashScreen.js et app_bootstrap (cause les settings parasites)
CleanModulePatches(resPath);
SetProgress(92, "Configuring Nightcord loader...");
// Vérification finale : on doit avoir un vrai app.asar ou un backup avant de continuer
if (!File.Exists(appAsar) && !File.Exists(backup))
{
throw new Exception(
"Critical error: no valid app.asar found. " +
"Please reinstall Discord from discord.com/download and try again."
);
}
// Créer le backup Nightcord si app.asar existe et qu'on n'a pas encore de backup
if (File.Exists(appAsar))
{
if (File.Exists(backup)) File.Delete(backup);
File.Move(appAsar, backup);
}
SetProgress(94, "Creating app directory...");
Directory.CreateDirectory(appDir);
WriteLoader(appDir);
CopyAssetsToDiscord(resPath);
SetProgress(99, "Starting Discord...");
StartDiscord(resPath);
}
/// <summary>
/// Nettoie les patches laissés par Vencord/Equicord dans les modules natifs Discord.
/// Ces patches (dans discord_desktop_core, etc.) font que les settings Discord affichent
/// encore l'interface Vencord/Equicord même après suppression de leur dossier app/.
/// </summary>
private void CleanModulePatches(string resPath)
{
try
{
// Chemins où Vencord/Equicord injectent leurs hooks
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var appBase = Path.GetDirectoryName(resPath);
// Chercher le dossier modules (dans app-X.X.XXXX/modules/)
string[] modulesSearchPaths = {
Path.Combine(appBase, "modules"),
Path.Combine(resPath, "modules")
};
foreach (var modulesDir in modulesSearchPaths)
{
if (!Directory.Exists(modulesDir)) continue;
// Chercher discord_desktop_core-*/discord_desktop_core/
foreach (var coreParent in Directory.GetDirectories(modulesDir, "discord_desktop_core*"))
{
var corePath = Path.Combine(coreParent, "discord_desktop_core");
if (!Directory.Exists(corePath)) continue;
// Fichiers patchés par Vencord/Equicord dans discord_desktop_core
string[] patchedFiles = {
Path.Combine(corePath, "index.js"),
Path.Combine(corePath, "app", "app_bootstrap", "splashScreen.js"),
Path.Combine(corePath, "app", "app_bootstrap", "index.js"),
};
foreach (var pf in patchedFiles)
{
if (!File.Exists(pf)) continue;
var content = File.ReadAllText(pf);
// Détecter la présence d'une injection Vencord/Equicord dans ce fichier
bool isPatched = content.Contains("vencord", StringComparison.OrdinalIgnoreCase)
|| content.Contains("equicord", StringComparison.OrdinalIgnoreCase)
|| content.Contains("require(\"vencord")
|| content.Contains("require('vencord")
|| content.Contains("VencordNative")
|| content.Contains("equilotl");
if (!isPatched) continue;
// Chercher un backup .orig ou .bak laissé par le mod
string[] backupExts = { ".orig", ".bak", ".vanilla" };
bool restored = false;
foreach (var ext in backupExts)
{
var bk = pf + ext;
if (File.Exists(bk))
{
File.Copy(bk, pf, true);
File.Delete(bk);
restored = true;
break;
}
}
if (!restored)
{
// Pas de backup → supprimer le fichier patché.
// Discord le recrée au prochain démarrage depuis app.asar.
try { File.Delete(pf); } catch { }
}
}
// Supprimer le dossier app/ à l'intérieur de discord_desktop_core si injecté
var innerAppDir = Path.Combine(corePath, "app");
if (Directory.Exists(innerAppDir))
{
var innerPkg = Path.Combine(innerAppDir, "package.json");
if (File.Exists(innerPkg))
{
var pkgContent = File.ReadAllText(innerPkg);
bool isModInjection = pkgContent.Contains("vencord", StringComparison.OrdinalIgnoreCase)
|| pkgContent.Contains("equicord", StringComparison.OrdinalIgnoreCase)
|| pkgContent.Contains("openasar", StringComparison.OrdinalIgnoreCase);
if (isModInjection)
{
try { Directory.Delete(innerAppDir, true); } catch { }
}
}
}
}
}
}
catch (Exception ex)
{
// Non-fatal : on log et on continue
Console.WriteLine($"[Nightcord] CleanModulePatches warning: {ex.Message}");
}
}
private void DoUninject(string resPath)
{
var appDir = Path.Combine(resPath, "app");
var backup = Path.Combine(resPath, "_app.asar");
var appAsar = Path.Combine(resPath, "app.asar");
SetProgress(10, "Closing Discord...");
KillDiscord(resPath);
SetProgress(30, "Removing injected folder...");
// 1. Remove the injected 'app' folder
if (Directory.Exists(appDir))
{
var pkg = Path.Combine(appDir, "package.json");
if (File.Exists(pkg) && File.ReadAllText(pkg).Contains("\"nightcord\""))
{
Directory.Delete(appDir, true);
}
}
SetProgress(50, "Restoring original files...");
// Nettoyage des faux app.asar avant de restaurer
if (File.Exists(appAsar) && new FileInfo(appAsar).Length < 1000000) {
File.Delete(appAsar);
}
// 2. Restore app.asar backup
if (File.Exists(backup))
{
if (!File.Exists(appAsar)) {
File.Move(backup, appAsar);
} else {
// S'il y a un vrai app.asar (taille > 1Mo), Discord s'est mis à jour, l'ancien backup est obsolète
File.Delete(backup);
}
}
SetProgress(70, "Cleaning up assets...");
// 3. Clean up Nightcord-specific assets (folders we added)
// We DON'T delete ffmpeg.dll because it's a native Discord file!
var appBase = Path.GetDirectoryName(resPath);
// Revert build_info.json patch
var buildInfoPath = Path.Combine(resPath, "build_info.json");
if (File.Exists(buildInfoPath)) {
try {
var json = File.ReadAllText(buildInfoPath);
if (json.Contains("\"localModulesRoot\"")) {
// Simple regex to remove the line
json = Regex.Replace(json, @",\s*""localModulesRoot""\s*:\s*""modules""\s*", "");
File.WriteAllText(buildInfoPath, json);
}
} catch { }
}
string[] filesToClean = { "node.exe", "yt-dlp.exe", "ffmpeg.exe" }; // safe to delete as Discord doesn't have these
foreach (var f in filesToClean) {
var p = Path.Combine(appBase, f);
if (File.Exists(p)) try { File.Delete(p); } catch { }
}
string[] dirsToClean = { "mac", "multi-instance-icons", "ghost-server" };
foreach (var dir in dirsToClean) {
var p = Path.Combine(appBase, dir);
if (Directory.Exists(p)) try { Directory.Delete(p, true); } catch { }
}
SetProgress(95, "Restarting Discord...");
// Relancer Discord proprement après la désinstallation
StartDiscord(resPath);
SetProgress(100, "Done!");
}
private void WriteLoader(string appDir)
{
// CRITICAL: use a relative path from appDir to patcher.js
// An absolute path breaks when the user's appdata path differs (e.g. Canary after update)
// appDir = {resources}\app\
// _distDir = %LOCALAPPDATA%\Nightcord\dist\
// We must use the absolute path BUT with forward slashes and proper escaping for require()
// The path is correct at install time; it only breaks if the user moves AppData.
// Real fix: use path.join(__dirname, ...) relative navigation from patcher.js location.
//
// Strategy: write index.js so it resolves patcher.js relative to _distDir stored in a sibling file,
// OR simply use the absolute path correctly escaped. The Canary bug is NOT the path —
// it's that the dist folder may not exist yet when Canary loads. We add an existence check.
var patcher = Path.Combine(_distDir, "patcher.js").Replace("\\", "/");
File.WriteAllText(Path.Combine(appDir, "package.json"), "{\"name\":\"nightcord\",\"main\":\"index.js\"}");
File.WriteAllText(Path.Combine(appDir, "index.js"),
$"// Nightcord Injector\n" +
$"\"use strict\";\n" +
$"const fs = require('fs');\n" +
$"const path = require('path');\n" +
$"// Primary: injected dist path\n" +
$"const primary = {JsonEscape(patcher)};\n" +
$"// Fallback: dist/ folder next to the exe (portable mode)\n" +
$"const exeDir = path.dirname(process.execPath);\n" +
$"const fallback = path.join(exeDir, 'resources', 'dist', 'patcher.js');\n" +
$"const fallback2 = path.join(exeDir, 'dist', 'patcher.js');\n" +
$"const patcherPath = fs.existsSync(primary) ? primary : fs.existsSync(fallback) ? fallback : fallback2;\n" +
$"if (!fs.existsSync(patcherPath)) throw new Error('[Nightcord] patcher.js not found. Expected at: ' + primary);\n" +
$"require(patcherPath);\n"
);
}
private string JsonEscape(string s)
{
// Produce a JSON string literal: "value" with proper escaping
return System.Text.Json.JsonSerializer.Serialize(s);
}
private void CopyAssetsToDiscord(string resPath)
{
SetProgress(95, "Copying binaries...");
var appBase = Path.GetDirectoryName(resPath);
string[] filesToCopy = { "ffmpeg.exe", "ffmpeg.dll", "node.exe", "yt-dlp.exe" };
foreach (var f in filesToCopy) {
var src = Path.Combine(_distDir, f);
if (File.Exists(src)) File.Copy(src, Path.Combine(appBase, f), true);
}
SetProgress(96, "Copying directories...");
string[] dirsToCopy = { "mac", "multi-instance-icons", "modules", "ghost-server" };
foreach (var dir in dirsToCopy) {
var src = Path.Combine(_distDir, dir);
if (Directory.Exists(src)) CopyDirectory(src, Path.Combine(appBase, dir));
}
SetProgress(98, "Patching build info...");
var buildInfoPath = Path.Combine(resPath, "build_info.json");
if (File.Exists(buildInfoPath)) {
try {
var json = File.ReadAllText(buildInfoPath);
if (!json.Contains("\"localModulesRoot\"")) {
var idx = json.LastIndexOf('}');
if (idx != -1) {
json = json.Insert(idx, ",\n \"localModulesRoot\": \"modules\"\n");
File.WriteAllText(buildInfoPath, json);
}
}
} catch { }
}
}
private void CopyDirectory(string sourceDir, string destinationDir)
{
Directory.CreateDirectory(destinationDir);
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(destinationDir, Path.GetFileName(file)), true);
foreach (var directory in Directory.GetDirectories(sourceDir))
CopyDirectory(directory, Path.Combine(destinationDir, Path.GetFileName(directory)));
}
private void KillDiscord(string resPath)
{
SetStatus("loading", "Closing Discord...");
var procName = resPath.Contains("DiscordPTB") ? "DiscordPTB" :
resPath.Contains("DiscordCanary") ? "DiscordCanary" :
resPath.Contains("DiscordDevelopment") ? "DiscordDevelopment" : "Discord";
foreach (var process in Process.GetProcessesByName(procName))
{
try { process.Kill(); process.WaitForExit(3000); } catch { }
}
System.Threading.Thread.Sleep(1000);
}
private void StartDiscord(string resPath)
{
try {
var exe = Path.Combine(Path.GetDirectoryName(resPath), "..", "Update.exe");
var procName = resPath.Contains("DiscordPTB") ? "DiscordPTB.exe" :
resPath.Contains("DiscordCanary") ? "DiscordCanary.exe" :
resPath.Contains("DiscordDevelopment") ? "DiscordDevelopment.exe" : "Discord.exe";
if (File.Exists(exe)) Process.Start(exe, $"--processStart {procName}");
} catch { }
}
private string ExtractJsonValue(string json, string key, string matchPattern = null)
{
var matches = Regex.Matches(json, $"\"{key}\"\\s*:\\s*\"([^\"]+)\"");
foreach (Match m in matches)
{
var val = m.Groups[1].Value;
if (matchPattern == null || val.EndsWith(matchPattern)) return val;
}
return null;
}
}
}
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="NightcordInstaller"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<!-- asInvoker = pas besoin d'admin, LocalAppData est accessible sans élévation -->
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 / 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
</application>
</compatibility>
<!-- DPI awareness for crisp rendering on HiDPI screens -->
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
</assembly>
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

+931
View File
@@ -0,0 +1,931 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Nightcord Installer</title>
<!-- Async font load: doesn't block first paint -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;700&display=swap" media="print" onload="this.media='all'">
<noscript><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;700&display=swap"></noscript>
<style>
/* Fonts loaded async via <link> above */
:root {
--bg: #0b0b18;
--surface: #11112a;
--border: #1e1e45;
--accent: #7b6cff;
--accent2: #c084fc;
--glow: rgba(123,108,255,0.25);
--text: #e2e0ff;
--muted: #6b6a99;
--success: #4ade80;
--error: #f87171;
--warn: #fbbf24;
--font: 'Inter', system-ui, sans-serif;
--font-mono: 'JetBrains Mono', monospace;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: var(--font);
background: var(--bg);
color: var(--text);
height: 100vh;
overflow: hidden;
user-select: none;
-webkit-app-region: no-drag;
}
body::before {
content: '';
position: fixed;
inset: 0;
background:
radial-gradient(ellipse 60% 50% at 20% 20%, rgba(123,108,255,0.12) 0%, transparent 70%),
radial-gradient(ellipse 50% 60% at 80% 80%, rgba(192,132,252,0.08) 0%, transparent 70%);
pointer-events: none;
z-index: 0;
}
body::after {
content: '';
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(123,108,255,0.04) 1px, transparent 1px),
linear-gradient(90deg, rgba(123,108,255,0.04) 1px, transparent 1px);
background-size: 40px 40px;
pointer-events: none;
z-index: 0;
}
.wrapper {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
height: 100vh;
}
.titlebar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
height: 42px;
-webkit-app-region: drag;
border-bottom: 1px solid var(--border);
background: rgba(11,11,24,0.8);
backdrop-filter: blur(10px);
}
.titlebar-left { display: flex; align-items: center; gap: 10px; }
.logo-mark {
width: 24px; height: 24px;
display: flex; align-items: center; justify-content: center;
}
.titlebar-title {
font-size: 12px; font-weight: 700;
letter-spacing: 0.15em; text-transform: uppercase; color: var(--muted);
}
.titlebar-version {
font-family: var(--font-mono); font-size: 9px; font-weight: 700;
color: var(--accent); background: rgba(123,108,255,0.12);
border: 1px solid rgba(123,108,255,0.2); border-radius: 4px;
padding: 2px 7px; letter-spacing: 0.04em;
opacity: 0; transition: opacity 0.3s;
}
.titlebar-version.loaded { opacity: 1; }
.titlebar-controls { display: flex; gap: 8px; -webkit-app-region: no-drag; }
.titlebar-controls button {
width: 12px; height: 12px; border-radius: 50%; border: none; cursor: pointer; transition: opacity .2s;
}
.titlebar-controls button:hover { opacity: 0.8; }
.btn-close { background: #ff5f57; }
.btn-minimize { background: #febc2e; }
.content {
flex: 1;
display: flex;
flex-direction: column;
padding: 28px 40px 24px;
gap: 20px;
overflow: hidden;
}
.header { display: flex; flex-direction: column; gap: 4px; }
.header h1 {
font-size: 34px; font-weight: 800; letter-spacing: -0.02em; line-height: 1;
background: linear-gradient(135deg, var(--text) 0%, var(--accent2) 100%);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.header p {
font-family: var(--font-mono); font-size: 11px; color: var(--muted); letter-spacing: 0.03em;
}
.section-row {
display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;
}
.section-label {
font-size: 10px; font-weight: 700; letter-spacing: 0.2em;
text-transform: uppercase; color: var(--muted);
}
.btn-manual {
font-family: var(--font); font-size: 10px; font-weight: 700;
letter-spacing: .1em; text-transform: uppercase;
background: rgba(123,108,255,0.1); color: var(--accent);
border: 1px solid rgba(123,108,255,0.25); border-radius: 5px;
padding: 3px 10px; cursor: pointer; transition: background .15s;
}
.btn-manual:hover { background: rgba(123,108,255,0.2); }
.manual-input-row {
display: none; gap: 8px; margin-bottom: 10px;
}
.manual-input-row.visible { display: flex; }
.manual-input-row input {
flex: 1; background: var(--surface); border: 1px solid var(--border);
border-radius: 8px; padding: 9px 12px; color: var(--text);
font-family: var(--font-mono); font-size: 10px; outline: none;
transition: border-color .15s;
}
.manual-input-row input:focus { border-color: var(--accent); }
.manual-input-row button {
font-family: var(--font); font-weight: 700; font-size: 12px;
background: linear-gradient(135deg, var(--accent), var(--accent2));
color: white; border: none; border-radius: 8px; padding: 9px 16px; cursor: pointer;
}
.discord-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 270px;
overflow-y: auto;
padding-right: 4px;
}
.discord-list::-webkit-scrollbar {
width: 6px;
}
.discord-list::-webkit-scrollbar-track {
background: transparent;
}
.discord-list::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}
.discord-list::-webkit-scrollbar-thumb:hover {
background: var(--muted);
}
.discord-card {
display: flex; align-items: center; justify-content: space-between;
padding: 12px 16px; background: var(--surface);
border: 1px solid var(--border); border-radius: 10px;
cursor: pointer; transition: all .15s ease;
position: relative; overflow: hidden;
animation: fadeSlide .3s ease both;
}
.discord-card::before {
content: ''; position: absolute; inset: 0;
background: linear-gradient(90deg, var(--glow), transparent);
opacity: 0; transition: opacity .2s;
}
.discord-card:hover { border-color: var(--accent); }
.discord-card:hover::before { opacity: 1; }
.discord-card.selected { border-color: var(--accent); background: rgba(123,108,255,0.08); }
.discord-card.selected::before { opacity: 1; }
.card-left { display: flex; align-items: center; gap: 12px; }
.card-icon {
width: 38px; height: 38px;
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
overflow: hidden;
}
.card-icon img {
width: 36px; height: 36px;
object-fit: contain;
display: block;
}
.card-icon.manual { background: rgba(107,106,153,0.2); border-radius: 8px; }
.card-info h3 { font-size: 13px; font-weight: 700; color: var(--text); }
.card-path {
font-family: var(--font-mono); font-size: 9px; color: var(--muted);
margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 360px;
}
.card-right { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.badge {
font-family: var(--font-mono); font-size: 9px;
padding: 3px 8px; border-radius: 4px; font-weight: 700; letter-spacing: 0.05em;
}
.badge-version { background: rgba(123,108,255,0.15); color: var(--accent); }
.badge-injected { background: rgba(74,222,128,0.15); color: var(--success); }
.badge-clean { background: rgba(107,106,153,0.15); color: var(--muted); }
.radio {
width: 16px; height: 16px; border-radius: 50%;
border: 2px solid var(--border); transition: all .15s; flex-shrink: 0;
}
.discord-card.selected .radio {
border-color: var(--accent); background: var(--accent); box-shadow: 0 0 8px var(--glow);
}
.empty-state { text-align: center; padding: 20px; color: var(--muted); font-size: 13px; }
.actions { display: flex; gap: 12px; margin-top: auto; }
.btn {
flex: 1; padding: 13px 24px; border-radius: 10px; border: none;
font-family: var(--font); font-size: 13px; font-weight: 700;
letter-spacing: 0.05em; cursor: pointer; transition: all .15s;
}
.btn:disabled { opacity: 0.35; cursor: not-allowed; }
.btn-primary {
background: linear-gradient(135deg, var(--accent), var(--accent2));
color: white; box-shadow: 0 4px 24px rgba(123,108,255,0.4);
}
.btn-primary:not(:disabled):hover { transform: translateY(-1px); box-shadow: 0 8px 32px rgba(123,108,255,0.5); }
.btn-primary:not(:disabled):active { transform: translateY(0); }
.btn-danger {
background: rgba(248,113,113,0.1); color: var(--error);
border: 1px solid rgba(248,113,113,0.25);
}
.btn-danger:not(:disabled):hover { background: rgba(248,113,113,0.18); border-color: var(--error); }
.status-bar {
font-family: var(--font-mono); font-size: 10px;
padding: 10px 40px; border-top: 1px solid var(--border);
display: flex; align-items: center; gap: 8px;
background: rgba(11,11,24,0.6);
}
.status-dot { width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; }
.status-dot.idle { background: var(--muted); }
.status-dot.success { background: var(--success); box-shadow: 0 0 6px var(--success); }
.status-dot.error { background: var(--error); box-shadow: 0 0 6px var(--error); }
.status-dot.loading { background: var(--accent); animation: pulse 1s infinite; }
@keyframes pulse { 0%,100%{opacity:1}50%{opacity:.3} }
.status-text { color: var(--muted); }
.progress-overlay {
position: fixed; top: 42px; left: 0; right: 0; bottom: 0; background: rgba(11,11,24,0.85);
display: flex; flex-direction: column; align-items: center; justify-content: center;
z-index: 100; backdrop-filter: blur(4px);
opacity: 0; pointer-events: none; transition: opacity .3s;
}
.progress-overlay.visible { opacity: 1; pointer-events: all; }
.loading-dots {
display: inline-flex;
align-items: center;
gap: 3px;
margin-left: 6px;
margin-right: 2px;
vertical-align: middle;
}
.loading-dots span {
width: 4px;
height: 4px;
background-color: var(--accent2);
border-radius: 50%;
display: inline-block;
animation: bounce 1.4s infinite ease-in-out both;
}
.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1.0); }
}
.progress-container {
width: 65%;
background: rgba(17, 17, 42, 0.95);
border: 1px solid var(--border);
border-radius: 12px;
padding: 24px;
box-shadow: 0 8px 32px rgba(0,0,0,0.5);
text-align: center;
animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.progress-label {
font-family: var(--font); font-size: 13px; font-weight: 600;
color: var(--text); display: block; margin-bottom: 10px;
}
.progress-stats {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
/* tabular-nums keeps digit widths stable — no layout shift */
font-variant-numeric: tabular-nums;
font-family: var(--font-mono);
font-size: 10px;
color: var(--muted);
letter-spacing: 0;
}
.progress-stats-left { text-align: left; min-width: 80px; }
.progress-stats-right { text-align: right; min-width: 50px; }
.progress-bar-bg {
width: 100%; height: 6px; background: rgba(123,108,255,0.1);
border-radius: 6px; overflow: hidden; position: relative;
}
.progress-bar-fill {
height: 100%; background: linear-gradient(90deg, var(--accent), var(--accent2));
width: 0%; border-radius: 6px; transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 0 12px var(--glow);
}
@keyframes popIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
@keyframes fadeSlide { from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none} }
.discord-card:nth-child(2) { animation-delay: .05s; }
.discord-card:nth-child(3) { animation-delay: .10s; }
.discord-card:nth-child(4) { animation-delay: .15s; }
/* Settings Titlebar and Modal Styles */
.titlebar-right {
display: flex;
align-items: center;
gap: 12px;
-webkit-app-region: no-drag;
}
.btn-settings {
background: transparent;
border: none;
color: var(--muted);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 14px;
border-radius: 6px;
transition: color 0.2s ease, transform 0.2s ease;
}
.btn-settings:hover {
color: var(--text);
transform: rotate(45deg);
}
.settings-overlay {
position: fixed; top: 42px; left: 0; right: 0; bottom: 0; background: rgba(11,11,24,0.85);
display: flex; align-items: center; justify-content: center;
z-index: 150; backdrop-filter: blur(4px);
opacity: 0; pointer-events: none; transition: opacity .3s;
}
.settings-overlay.visible { opacity: 1; pointer-events: all; }
.settings-container {
width: 65%;
background: rgba(17, 17, 42, 0.95);
border: 1px solid var(--border);
border-radius: 12px;
padding: 24px;
box-shadow: 0 8px 32px rgba(0,0,0,0.5);
animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.settings-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.settings-header h2 {
font-size: 18px;
font-weight: 700;
color: var(--text);
font-family: var(--font);
}
.settings-close-btn {
background: transparent;
border: none;
color: var(--muted);
cursor: pointer;
font-size: 16px;
transition: color 0.15s;
}
.settings-close-btn:hover {
color: var(--error);
}
.settings-desc {
font-size: 11px;
color: var(--muted);
margin-bottom: 20px;
font-family: var(--font);
}
.settings-buttons {
display: flex;
flex-direction: column;
gap: 12px;
}
.btn-setting-link {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: rgba(30, 30, 69, 0.4);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
font-family: var(--font);
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: all 0.2s ease;
text-align: left;
}
.btn-setting-link:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px var(--glow);
border-color: var(--accent);
}
.btn-setting-link:active {
transform: translateY(0);
}
.btn-discord:hover {
background: rgba(123, 108, 255, 0.15);
border-color: #5865F2;
}
.btn-website:hover {
background: rgba(192, 132, 252, 0.15);
border-color: var(--accent2);
}
.btn-github:hover {
background: rgba(255, 255, 255, 0.05);
border-color: #ffffff;
}
.btn-check-update {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: rgba(74,222,128,0.08);
border: 1px solid rgba(74,222,128,0.25);
border-radius: 8px;
color: var(--success);
font-family: var(--font);
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: all 0.2s ease;
text-align: left;
width: 100%;
}
.btn-check-update:hover {
background: rgba(74,222,128,0.15);
border-color: var(--success);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(74,222,128,0.15);
}
.btn-check-update:active { transform: translateY(0); }
.btn-check-update:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.update-result {
margin-top: 10px;
padding: 10px 14px;
border-radius: 8px;
font-family: var(--font-mono);
font-size: 11px;
display: none;
}
.update-result.visible { display: block; }
.update-result.success {
background: rgba(74,222,128,0.1);
border: 1px solid rgba(74,222,128,0.3);
color: var(--success);
}
.update-result.error {
background: rgba(248,113,113,0.1);
border: 1px solid rgba(248,113,113,0.3);
color: var(--error);
}
.settings-dev-footer {
margin-top: 18px;
text-align: center;
font-family: var(--font-mono);
font-size: 9px;
color: var(--muted);
opacity: 0.6;
letter-spacing: 0.05em;
}
.btn-link-icon {
width: 20px;
height: 20px;
flex-shrink: 0;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="titlebar">
<div class="titlebar-left">
<img src="{{ICON_BASE64}}" class="logo-mark" />
<span class="titlebar-title" style="cursor: pointer;" onclick="window.nightcord.openUrl('https://nightcord.su/')">Nightcord Installer</span>
<span class="titlebar-version" id="titlebar-version">...</span>
</div>
<div class="titlebar-right">
<button class="btn-settings" onclick="toggleSettingsModal()" title="Settings">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3"></circle>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
</svg>
</button>
<div class="titlebar-controls">
<button class="btn-minimize" onclick="window.nightcord.minimizeApp()"></button>
<button class="btn-close" onclick="window.nightcord.closeApp()"></button>
</div>
</div>
</div>
<div class="content">
<div class="header">
<h1>Nightcord</h1>
<p>// discord client mod — select your installation target</p>
</div>
<div>
<div class="section-row">
<div class="section-label">Detected Discord Installations</div>
<button class="btn-manual" onclick="toggleManual()">+ Manual Path</button>
</div>
<div class="manual-input-row" id="manual-row">
<input id="manual-path" type="text"
placeholder="C:\Users\You\AppData\Local\Discord\app-1.0.9171\resources" />
<button onclick="addManualPath()">OK</button>
</div>
<div class="discord-list" id="discord-list">
<div class="empty-state">Searching for Discord installations...</div>
</div>
</div>
<div class="actions">
<button class="btn btn-primary" id="btn-inject" disabled onclick="handleInject()">
Inject Nightcord
</button>
<button class="btn btn-danger" id="btn-uninject" disabled onclick="handleUninject()">
Uninject
</button>
</div>
</div>
<div class="status-bar">
<div class="status-dot idle" id="status-dot"></div>
<span class="status-text" id="status-text">Waiting for selection...</span>
</div>
</div>
<div class="progress-overlay" id="progress-overlay">
<div class="progress-container">
<span class="progress-label" id="progress-label">Preparing installation...</span>
<div class="progress-stats">
<span class="progress-stats-left" id="progress-mb"></span>
<span class="progress-stats-right" id="progress-pct">0%</span>
</div>
<div class="progress-bar-bg">
<div class="progress-bar-fill" id="progress-fill"></div>
</div>
</div>
</div>
<div class="settings-overlay" id="settings-overlay" onclick="closeSettingsModal(event)">
<div class="settings-container" onclick="event.stopPropagation()">
<div class="settings-header">
<h2>Nightcord Links & Settings</h2>
<button class="settings-close-btn" onclick="toggleSettingsModal()"></button>
</div>
<div class="settings-content">
<p class="settings-desc">Access official Nightcord links and community resources.</p>
<div class="settings-buttons">
<button class="btn-setting-link btn-discord" onclick="window.nightcord.openUrl('https://discord.gg/nightcord')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" class="btn-link-icon">
<path d="M19.27 5.33C17.94 4.71 16.5 4.26 15 4a.09.09 0 0 0-.07.03c-.18.33-.39.76-.53 1.09a16.09 16.09 0 0 0-4.8 0c-.14-.34-.35-.76-.54-1.09c-.01-.02-.04-.03-.07-.03c-1.5.26-2.93.71-4.27 1.33c-.01 0-.02.01-.03.02c-2.72 4.07-3.47 8.03-3.1 11.95c0 .02.01.04.03.05c1.8 1.32 3.53 2.12 5.24 2.65c.03.01.06 0 .07-.02c.4-.55.76-1.13 1.07-1.74c.02-.04 0-.08-.04-.09c-.57-.22-1.11-.48-1.64-.78c-.04-.02-.04-.08-.01-.11c.11-.08.22-.17.33-.25c.02-.02.05-.02.07-.01c3.44 1.57 7.15 1.57 10.55 0c.02-.01.05-.01.07.01c.11.09.22.17.33.26c.04.03.04.09-.01.11c-.52.31-1.07.56-1.64.78c-.04.01-.05.06-.04.09c.32.61.68 1.19 1.07 1.74c.03.02.06.03.09.02c1.72-.53 3.45-1.33 5.25-2.65c.02-.01.03-.03.03-.05c.44-4.53-.73-8.46-3.1-11.95c-.01-.01-.02-.02-.04-.02zM8.52 14.91c-1.03 0-1.89-.95-1.89-2.12s.84-2.12 1.89-2.12c1.06 0 1.9.96 1.89 2.12c0 1.17-.84 2.12-1.89 2.12zm6.97 0c-1.03 0-1.89-.95-1.89-2.12s.84-2.12 1.89-2.12c1.06 0 1.9.96 1.89 2.12c0 1.17-.84 2.12-1.89 2.12z"/>
</svg>
<span>Join Discord Server</span>
</button>
<button class="btn-setting-link btn-website" onclick="window.nightcord.openUrl('https://nightcord.su')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="btn-link-icon">
<circle cx="12" cy="12" r="10"></circle>
<line x1="2" y1="12" x2="22" y2="12"></line>
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path>
</svg>
<span>Official Website</span>
</button>
<button class="btn-setting-link btn-github" onclick="window.nightcord.openUrl('https://github.com/nightcordoff/nightcord')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" class="btn-link-icon">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.3 3.438 9.8 8.205 11.385.6.11.82-.26.82-.577v-2.17c-3.338.726-4.042-1.61-4.042-1.61-.546-1.387-1.333-1.757-1.333-1.757-1.09-.745.083-.73.083-.73 1.205.084 1.84 1.237 1.84 1.237 1.07 1.835 2.807 1.305 3.492.998.108-.775.42-1.305.763-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.467-2.38 1.235-3.22-.123-.303-.535-1.523.117-3.176 0 0 1.008-.322 3.3 1.23.957-.266 1.98-.398 3-.403 1.02.005 2.043.137 3 .403 2.29-1.552 3.297-1.23 3.297-1.23.653 1.653.24 2.873.118 3.176.77.84 1.233 1.91 1.233 3.22 0 4.61-2.803 5.625-5.475 5.92.43.37.823 1.102.823 2.222v3.293c0 .32.218.694.825.577C20.565 21.797 24 17.298 24 12c0-6.63-5.37-12-12-12z"/>
</svg>
<span>GitHub Repository</span>
</button>
<div class="update-result" id="update-result"></div>
</div>
</div>
<div class="settings-dev-footer">dev by ahki__ (nightcord)</div>
</div>
</div>
<script>
const ICONS = {
'Discord': { html: '<img src="https://i.imgur.com/IvXl3Iq.png" alt="Discord" />', cls: 'stable' },
'Discord PTB': { html: '<img src="https://i.imgur.com/IvXl3Iq.png" alt="Discord PTB" />', cls: 'ptb' },
'Discord Canary': { html: '<img src="https://i.imgur.com/QpoxYST.png" alt="Discord Canary" />', cls: 'canary' },
'Discord Dev': { html: '<img src="https://i.imgur.com/QpoxYST.png" alt="Discord Dev" />', cls: 'dev' },
};
let discords = [];
let selected = null;
function setStatus(type, text) {
document.getElementById('status-dot').className = `status-dot ${type}`;
document.getElementById('status-text').textContent = text;
}
// mbDownloaded / mbTotal can be passed optionally to show e.g. "47.3 / 347.0 MB"
function setLoading(v, text = "Loading...", percent = 100, mbDownloaded = null, mbTotal = null) {
document.getElementById('progress-overlay').classList.toggle('visible', v);
if (v) {
const pct = Math.round(percent);
document.getElementById('progress-label').textContent = text;
document.getElementById('progress-pct').textContent = pct + '%';
if (mbDownloaded !== null && mbTotal !== null) {
document.getElementById('progress-mb').textContent =
mbDownloaded.toFixed(1) + ' / ' + mbTotal.toFixed(1) + ' MB';
} else {
document.getElementById('progress-mb').textContent = '';
}
document.getElementById('progress-fill').style.width = percent + '%';
} else {
setTimeout(() => { document.getElementById('progress-fill').style.width = '0%'; }, 300);
}
}
function toggleManual() {
const row = document.getElementById('manual-row');
row.classList.toggle('visible');
if (row.classList.contains('visible')) document.getElementById('manual-path').focus();
}
async function addManualPath() {
const input = document.getElementById('manual-path');
const p = input.value.trim();
if (!p) return;
const injected = await window.nightcord.isInjected(p);
const entry = {
name: 'Manual',
path: p,
asarPath: p + '\\app.asar',
exePath: null,
version: '?'
};
discords.push(entry);
renderCard(entry, discords.length - 1, injected, 'manual');
selectDiscord(discords.length - 1);
input.value = '';
document.getElementById('manual-row').classList.remove('visible');
}
async function loadDiscords() {
setStatus('loading', 'Detecting Discord installations...');
try {
const found = await window.nightcord.detectDiscord();
discords = found || [];
} catch(e) {
discords = [];
}
const list = document.getElementById('discord-list');
list.innerHTML = '';
if (discords.length === 0) {
list.innerHTML = `
<div class="empty-state">
⚠️ No Discord installations found automatically.<br>
<span style="font-size:11px;margin-top:6px;display:block;">
Use the <strong style="color:var(--accent)">+ Manual Path</strong> button to enter the path manually.
</span>
</div>`;
setStatus('error', 'No installations auto-detected — use manual path.');
return;
}
for (let i = 0; i < discords.length; i++) {
const d = discords[i];
const icon = ICONS[d.name] || { emoji: '⚪', cls: 'stable' };
let injected = false;
let hasThirdParty = false;
try { injected = await window.nightcord.isInjected(d.path); } catch {}
if (!injected) {
try { hasThirdParty = await window.nightcord.hasThirdPartyMod(d.path); } catch {}
}
renderCard(d, i, injected, icon.cls, hasThirdParty);
}
setStatus('idle', 'Select an installation target.');
}
function renderCard(d, i, injected, iconCls, hasThirdParty = false) {
const list = document.getElementById('discord-list');
const icon = ICONS[d.name] || { emoji: '⚙️', cls: iconCls };
let statusBadge;
if (injected) {
statusBadge = `<span class="badge badge-injected">✓ injected</span>`;
} else if (hasThirdParty) {
statusBadge = `<span class="badge" style="background:rgba(251,191,36,0.15);color:var(--warn)">⚠ mod detected</span>`;
} else {
statusBadge = `<span class="badge badge-clean">clean</span>`;
}
const card = document.createElement('div');
card.className = 'discord-card';
if (hasThirdParty && !injected) card.style.borderColor = 'rgba(251,191,36,0.35)';
card.dataset.index = i;
card.dataset.thirdParty = hasThirdParty ? '1' : '0';
card.innerHTML = `
<div class="card-left">
<div class="card-icon ${icon.cls || iconCls}">${icon.html || icon.emoji || '⚙️'}</div>
<div class="card-info">
<h3>${d.name}</h3>
<div class="card-path">${d.path}</div>
</div>
</div>
<div class="card-right">
<span class="badge badge-version">v${d.version}</span>
${statusBadge}
<div class="radio"></div>
</div>
`;
card.addEventListener('click', () => selectDiscord(i));
list.appendChild(card);
}
function selectDiscord(index) {
selected = discords[index];
document.querySelectorAll('.discord-card').forEach((c, i) => {
c.classList.toggle('selected', i === index);
});
document.getElementById('btn-inject').disabled = false;
document.getElementById('btn-uninject').disabled = false;
// Warn if a third-party mod is detected
const card = document.querySelectorAll('.discord-card')[index];
const isThirdParty = card && card.dataset.thirdParty === '1';
if (isThirdParty) {
setStatus('loading', `${selected.name}: Vencord/Equicord detected — clicking Inject will replace it with Nightcord.`);
document.getElementById('btn-inject').textContent = 'Replace with Nightcord';
} else {
setStatus('idle', `Selected: ${selected.name}${selected.path}`);
document.getElementById('btn-inject').textContent = 'Inject Nightcord';
}
}
function toggleSettingsModal() {
const overlay = document.getElementById('settings-overlay');
overlay.classList.toggle('visible');
}
function closeSettingsModal(event) {
const overlay = document.getElementById('settings-overlay');
overlay.classList.remove('visible');
}
async function handleInject() {
if (!selected) return;
setLoading(true, "Starting installation...", 2);
setStatus('loading', `Injecting into ${selected.name}...`);
// Use startInject (non-blocking) + poll getInjectStatus
// This avoids the WebView2 COM proxy 30s timeout on large downloads
const started = window.nightcord.startInject(selected.path);
if (!started || !started.started) {
setLoading(false);
setStatus('error', `Error: ${started?.error || 'Could not start inject'}`);
return;
}
// Poll every 500ms for status
await new Promise((resolve) => {
const interval = setInterval(() => {
const status = window.nightcord.getInjectStatus();
if (status.state === 'done') {
clearInterval(interval);
resolve({ success: true });
} else if (status.state === 'error') {
clearInterval(interval);
resolve({ success: false, error: status.error });
}
// 'running' → keep polling (progress bar updated by SetProgress from C#)
}, 500);
}).then(result => {
if (result.success) {
setLoading(true, "Finalizing installation...", 100);
setTimeout(async () => {
setLoading(false);
setStatus('success', `✓ Nightcord injected into ${selected.name}! Restart Discord.`);
await loadDiscords();
const idx = discords.findIndex(d => d.path === selected.path);
if (idx !== -1) selectDiscord(idx);
}, 700);
} else {
setLoading(false);
setStatus('error', `Error: ${result.error}`);
}
});
}
async function handleUninject() {
if (!selected) return;
setLoading(true, "Preparing uninjection...", 5);
setStatus('loading', `Uninjecting from ${selected.name}...`);
// Real C# uninjection call
const result = await window.nightcord.uninject(selected.path);
if (result.success) {
setLoading(true, "Completed", 100);
setTimeout(async () => {
setLoading(false);
setStatus('success', `✓ Nightcord uninjected from ${selected.name}.`);
await loadDiscords();
}, 600);
} else {
setLoading(false);
setStatus('error', `Error: ${result.error}`);
}
}
// Fetch latest version from GitHub and show in titlebar badge
async function loadLatestVersion() {
try {
const res = await fetch('https://api.github.com/repos/nightcordoff/nightcord/releases/latest', {
headers: { 'Accept': 'application/vnd.github.v3+json' }
});
if (!res.ok) return;
const data = await res.json();
const tag = data.tag_name;
if (tag) {
const el = document.getElementById('titlebar-version');
el.textContent = tag;
el.classList.add('loaded');
}
} catch (e) {
// silently fail — not critical
}
}
// Init
loadDiscords();
loadLatestVersion();
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

@@ -0,0 +1,94 @@
; macOS hight DPI cursors made by antiden
; https://vk.com/antiden
[Version]
signature="$CHICAGO$"
macOS hight DPI cursors for Windows made by antiden
[DefaultInstall]
CopyFiles = Scheme.Cur
AddReg = Scheme.Reg,Wreg
[DestinationDirs]
Scheme.Cur = 10,"%CUR_DIR%"
[Scheme.Reg]
HKCU,"Control Panel\Cursors\Schemes","%SCHEME_NAME%",,"%10%\%CUR_DIR%\%pointer%,%10%\%CUR_DIR%\%help%,%10%\%CUR_DIR%\%work%,%10%\%CUR_DIR%\%busy%,%10%\%CUR_DIR%\%cross%,%10%\%CUR_DIR%\%Text%,%10%\%CUR_DIR%\%Hand%,%10%\%CUR_DIR%\%unavailiable%,%10%\%CUR_DIR%\%Vert%,%10%\%CUR_DIR%\%Horz%,%10%\%CUR_DIR%\%Dgn1%,%10%\%CUR_DIR%\%Dgn2%,%10%\%CUR_DIR%\%move%,%10%\%CUR_DIR%\%alternate%,%10%\%CUR_DIR%\%link%,%10%\%CUR_DIR%\%pin%,%10%\%CUR_DIR%\%person%,%10%\%CUR_DIR%\%pan%,%10%\%CUR_DIR%\%grab%,%10%\%CUR_DIR%\%grabbing%,%10%\%CUR_DIR%\%zoom-in%,%10%\%CUR_DIR%\%zoom-out%"
[Wreg]
HKCU,"Control Panel\Cursors",,0x00020000,"%SCHEME_NAME%"
HKCU,"Control Panel\Cursors",AppStarting,0x00020000,"%10%\%CUR_DIR%\%work%"
HKCU,"Control Panel\Cursors",Arrow,0x00020000,"%10%\%CUR_DIR%\%pointer%"
HKCU,"Control Panel\Cursors",crosshair,0x00020000,"%10%\%CUR_DIR%\%cross%"
HKCU,"Control Panel\Cursors",precisionhair,0x00020000,"%10%\%CUR_DIR%\%cross%"
HKCU,"Control Panel\Cursors",Hand,0x00020000,"%10%\%CUR_DIR%\%link%"
HKCU,"Control Panel\Cursors",Help,0x00020000,"%10%\%CUR_DIR%\%help%"
HKCU,"Control Panel\Cursors",IBeam,0x00020000,"%10%\%CUR_DIR%\%text%"
HKCU,"Control Panel\Cursors",No,0x00020000,"%10%\%CUR_DIR%\%unavailiable%"
HKCU,"Control Panel\Cursors",NWPen,0x00020000,"%10%\%CUR_DIR%\%hand%"
HKCU,"Control Panel\Cursors",SizeAll,0x00020000,"%10%\%CUR_DIR%\%move%"
HKCU,"Control Panel\Cursors",SizeNESW,0x00020000,"%10%\%CUR_DIR%\%dgn2%"
HKCU,"Control Panel\Cursors",SizeNS,0x00020000,"%10%\%CUR_DIR%\%vert%"
HKCU,"Control Panel\Cursors",SizeNWSE,0x00020000,"%10%\%CUR_DIR%\%dgn1%"
HKCU,"Control Panel\Cursors",SizeWE,0x00020000,"%10%\%CUR_DIR%\%horz%"
HKCU,"Control Panel\Cursors",UpArrow,0x00020000,"%10%\%CUR_DIR%\%alternate%"
HKCU,"Control Panel\Cursors",Wait,0x00020000,"%10%\%CUR_DIR%\%busy%"
HKCU,"Control Panel\Cursors",Pin,0x00020000,"%10%\%CUR_DIR%\%pin%"
HKCU,"Control Panel\Cursors",Person,0x00020000,"%10%\%CUR_DIR%\%person%"
HKCU,"Control Panel\Cursors",Pan,0x00020000,"%10%\%CUR_DIR%\%pan%"
HKCU,"Control Panel\Cursors",Grab,0x00020000,"%10%\%CUR_DIR%\%grab%"
HKCU,"Control Panel\Cursors",Grabbing,0x00020000,"%10%\%CUR_DIR%\%grabbing%"
HKCU,"Control Panel\Cursors",Zoom-in,0x00020000,"%10%\%CUR_DIR%\%zoom-in%"
HKCU,"Control Panel\Cursors",Zoom-out,0x00020000,"%10%\%CUR_DIR%\%zoom-out%"
HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Runonce\Setup\","",,"rundll32.exe shell32.dll,Control_RunDLL main.cpl @0,1"
[Scheme.Cur]
Normal.cur
Help.cur
Working.ani
Busy.ani
Text.cur
Unavailable.cur
Vertical Resize.cur
Horizontal Resize.cur
Diagonal Resize 1.cur
Diagonal Resize 2.cur
Move.cur
Pan.cur
Link.cur
Precision.cur
Handwriting.cur
Alternate.cur
Pin.cur
Person.cur
Closehand.cur
Zoom-in.cur
Zoom-out.cur
[Scheme.Txt]
[Strings]
CUR_DIR = "Cursors\macosCursors-ns-n"
SCHEME_NAME = "macOS Cursors - No Shadow Newer"
pointer = "Normal.cur"
help = "Help.cur"
work = "Working.ani"
busy = "Busy.ani"
text = "Text.cur"
unavailiable = "Unavailable.cur"
vert = "Vertical Resize.cur"
horz = "Horizontal Resize.cur"
dgn1 = "Diagonal Resize 1.cur"
dgn2 = "Diagonal Resize 2.cur"
move = "Move.cur"
link = "Link.cur"
cross = "Precision.cur"
hand = "Handwriting.cur"
alternate = "Alternate.cur"
pin = "Pin.cur"
person = "Person.cur"
pan = "Pan.cur"
grab = "Move.cur"
grabbing = "Closehand.cur"
zoom-in = "Zoom-in.cur"
zoom-out = "Zoom-out.cur"
Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

@@ -0,0 +1,92 @@
[Version]
signature="$CHICAGO$"
macOS hight DPI cursors for Windows
[DefaultInstall]
CopyFiles = Scheme.Cur
AddReg = Scheme.Reg,Wreg
[DestinationDirs]
Scheme.Cur = 10,"%CUR_DIR%"
[Scheme.Reg]
HKCU,"Control Panel\Cursors\Schemes","%SCHEME_NAME%",,"%10%\%CUR_DIR%\%pointer%,%10%\%CUR_DIR%\%help%,%10%\%CUR_DIR%\%work%,%10%\%CUR_DIR%\%busy%,%10%\%CUR_DIR%\%cross%,%10%\%CUR_DIR%\%Text%,%10%\%CUR_DIR%\%Hand%,%10%\%CUR_DIR%\%unavailiable%,%10%\%CUR_DIR%\%Vert%,%10%\%CUR_DIR%\%Horz%,%10%\%CUR_DIR%\%Dgn1%,%10%\%CUR_DIR%\%Dgn2%,%10%\%CUR_DIR%\%move%,%10%\%CUR_DIR%\%alternate%,%10%\%CUR_DIR%\%link%,%10%\%CUR_DIR%\%pin%,%10%\%CUR_DIR%\%person%,%10%\%CUR_DIR%\%pan%,%10%\%CUR_DIR%\%grab%,%10%\%CUR_DIR%\%grabbing%,%10%\%CUR_DIR%\%zoom-in%,%10%\%CUR_DIR%\%zoom-out%"
[Wreg]
HKCU,"Control Panel\Cursors",,0x00020000,"%SCHEME_NAME%"
HKCU,"Control Panel\Cursors",AppStarting,0x00020000,"%10%\%CUR_DIR%\%work%"
HKCU,"Control Panel\Cursors",Arrow,0x00020000,"%10%\%CUR_DIR%\%pointer%"
HKCU,"Control Panel\Cursors",crosshair,0x00020000,"%10%\%CUR_DIR%\%cross%"
HKCU,"Control Panel\Cursors",precisionhair,0x00020000,"%10%\%CUR_DIR%\%cross%"
HKCU,"Control Panel\Cursors",Hand,0x00020000,"%10%\%CUR_DIR%\%link%"
HKCU,"Control Panel\Cursors",Help,0x00020000,"%10%\%CUR_DIR%\%help%"
HKCU,"Control Panel\Cursors",IBeam,0x00020000,"%10%\%CUR_DIR%\%text%"
HKCU,"Control Panel\Cursors",No,0x00020000,"%10%\%CUR_DIR%\%unavailiable%"
HKCU,"Control Panel\Cursors",NWPen,0x00020000,"%10%\%CUR_DIR%\%hand%"
HKCU,"Control Panel\Cursors",SizeAll,0x00020000,"%10%\%CUR_DIR%\%move%"
HKCU,"Control Panel\Cursors",SizeNESW,0x00020000,"%10%\%CUR_DIR%\%dgn2%"
HKCU,"Control Panel\Cursors",SizeNS,0x00020000,"%10%\%CUR_DIR%\%vert%"
HKCU,"Control Panel\Cursors",SizeNWSE,0x00020000,"%10%\%CUR_DIR%\%dgn1%"
HKCU,"Control Panel\Cursors",SizeWE,0x00020000,"%10%\%CUR_DIR%\%horz%"
HKCU,"Control Panel\Cursors",UpArrow,0x00020000,"%10%\%CUR_DIR%\%alternate%"
HKCU,"Control Panel\Cursors",Wait,0x00020000,"%10%\%CUR_DIR%\%busy%"
HKCU,"Control Panel\Cursors",Pin,0x00020000,"%10%\%CUR_DIR%\%pin%"
HKCU,"Control Panel\Cursors",Person,0x00020000,"%10%\%CUR_DIR%\%person%"
HKCU,"Control Panel\Cursors",Pan,0x00020000,"%10%\%CUR_DIR%\%pan%"
HKCU,"Control Panel\Cursors",Grab,0x00020000,"%10%\%CUR_DIR%\%grab%"
HKCU,"Control Panel\Cursors",Grabbing,0x00020000,"%10%\%CUR_DIR%\%grabbing%"
HKCU,"Control Panel\Cursors",Zoom-in,0x00020000,"%10%\%CUR_DIR%\%zoom-in%"
HKCU,"Control Panel\Cursors",Zoom-out,0x00020000,"%10%\%CUR_DIR%\%zoom-out%"
HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Runonce\Setup\","",,"rundll32.exe shell32.dll,Control_RunDLL main.cpl @0,1"
[Scheme.Cur]
Normal.cur
Help.cur
Working.ani
Busy.ani
Text.cur
Unavailable.cur
Vertical Resize.cur
Horizontal Resize.cur
Diagonal Resize 1.cur
Diagonal Resize 2.cur
Move.cur
Pan.cur
Link.cur
Precision.cur
Handwriting.cur
Alternate.cur
Pin.cur
Person.cur
Closehand.cur
Zoom-in.cur
Zoom-out.cur
[Scheme.Txt]
[Strings]
CUR_DIR = "Cursors\macosCursors-s-n"
SCHEME_NAME = "macOS Cursors With Shadow Newer"
pointer = "Normal.cur"
help = "Help.cur"
work = "Working.ani"
busy = "Busy.ani"
text = "Text.cur"
unavailiable = "Unavailable.cur"
vert = "Vertical Resize.cur"
horz = "Horizontal Resize.cur"
dgn1 = "Diagonal Resize 1.cur"
dgn2 = "Diagonal Resize 2.cur"
move = "Move.cur"
link = "Link.cur"
cross = "Precision.cur"
hand = "Handwriting.cur"
alternate = "Alternate.cur"
pin = "Pin.cur"
person = "Person.cur"
pan = "Pan.cur"
grab = "Move.cur"
grabbing = "Closehand.cur"
zoom-in = "Zoom-in.cur"
zoom-out = "Zoom-out.cur"
zoom-out = "Zoom-out.cur"
Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Some files were not shown because too many files have changed in this diff Show More