Merge branch 'BetterDiscord:main' into fix-header

This commit is contained in:
Fede 2022-12-19 20:35:36 +01:00 committed by GitHub
commit 58024cb21f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 787 additions and 1374 deletions

4
.github/FUNDING.yml vendored
View File

@ -1,3 +1 @@
github: rauenzi
patreon: Zerebos
custom: ["https://paypal.me/ZackRauen"]
github: rauenzi

71
.github/ISSUE_TEMPLATE/BUG-REPORT.yml vendored Normal file
View File

@ -0,0 +1,71 @@
name: Bug Report
description: Create a bug report to help us find and fix bugs!
title: "[Bug]"
labels: [bug]
body:
- type: checkboxes
attributes:
label: Before Reporting
description: "I have double checked and agree with the following:"
options:
- label: I found no existing issues matching my bug
required: true
- label: My issue is not caused by a plugin or theme
required: true
- type: textarea
attributes:
label: Describe the Bug
description: A clear and concise description of what you're experiencing. If applicable, add screenshots to help explain your problem.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error...
validations:
required: true
- type: dropdown
attributes:
label: Operating System
options:
- Windows
- MacOS
- Linux
validations:
required: true
- type: dropdown
attributes:
label: Discord Version
options:
- Stable
- Canary
- PTB
validations:
required: true
- type: input
attributes:
label: BetterDiscord Version
description: This is found in `Settings > Updater` and will be labelled as the `Core` version.
placeholder: v1.x.x
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false

View File

@ -0,0 +1,27 @@
name: Feature Request
description: Suggest an idea for this project!
title: "[Feature]"
labels: [enhancement]
body:
- type: checkboxes
attributes:
label: Before Requesting
description: "I have double checked and agree with the following:"
options:
- label: I found no existing issue matching my feature request
required: true
- type: textarea
attributes:
label: Describe the feature you'd like!
description: A clear and concise description of what you want to see in BetterDiscord.
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the feature you are requesting!
Tip: You can attach images by clicking this area to highlight it and then dragging files in.
validations:
required: false

View File

@ -1,26 +0,0 @@
---
name: Bug Report
about: Create a report to help us find and fix bugs
title: "[Bug]"
labels: bug
assignees: ''
---
**Describe the Bug**
<!-- A clear and concise description of what the bug is. -->
**To Reproduce**
<!-- Steps to reproduce the behavior -->
**Expected Behavior**
<!-- A clear and concise description of what you expected to happen. -->
**Screenshots**
<!-- If applicable, add screenshots to help explain your problem. -->
**Discord Version**
<!-- Stable, Canary, PTB -->
**Additional Context**
<!-- Add any other context about the problem here. -->

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: BetterDiscord Support Server
url: https://betterdiscord.app/invite
about: The best place to get immediate support.
- name: Troubleshooting Guide
url: https://docs.betterdiscord.app/users/getting-started/troubleshooting
about: The user troubleshooting guide from the documentation.

View File

@ -1,17 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature]"
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
**Describe the feature you'd like**
<!-- A clear and concise description of what you want to happen. -->
**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->

63
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,63 @@
name: BetterDiscord CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 7
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
# - name: Lint
# run: pnpm lint
# - name: Run tests
# run: pnpm test
- name: Build asar
run: pnpm dist
- uses: actions/upload-artifact@v3
name: Upload artifact
# if: ${{ github.ref == 'refs/heads/main' }} # Only create artifacts when pushed to main
with:
name: betterdiscord.asar
path: dist/betterdiscord.asar
retention-days: 30
if-no-files-found: error

View File

@ -2,6 +2,48 @@
This changelog starts with the restructured 1.0.0 release that happened after context isolation changes. The changelogs here should more-or-less mirror the ones that get shown in the client but probably with less formatting and pizzazz.
## 1.8.4
### Added
### Removed
### Changed
### Fixed
- Fixed more bugs with context menu api
## 1.8.3
### Added
- Checking for old installs and deleting them
### Removed
- All references to Emotes, this will become a separate plugin
### Changed
- Moved to the more permissive Apache 2.0 license
- Now check for discord.asar for electron17+
- Handle setting module exports internally rather than maintaining getter references
### Fixed
- Fixed `inject` for electron17+
- Updater checking `>` which does not work for open versions
- Fixed a startup bug with the context menu api
## 1.8.2
### Added
### Removed
### Changed
### Fixed
- Fixed modals not working
- Fixed downloading binary files
- Fixed public server invites
## 1.8.1
### Added

12
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,12 @@
# Code of Conduct
- We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic.
- Please avoid using overtly sexual aliases or other nicknames that might detract from a friendly, safe and welcoming environment for all.
- Please be kind and courteous. Theres no need to be mean or rude.
- Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer.
- Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works.
- We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term `harassment` as including the definition in the [Citizen Code of Conduct](https://github.com/stumpsyn/policies/blob/master/citizen_code_of_conduct.md); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we dont tolerate behavior that excludes people in socially marginalized groups.
- Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [BetterDiscord staff](https://betterdiscord.app/invite) immediately. Whether youre a regular contributor or a newcomer, we care about making this community a safe place for you and weve got your back.
- Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.
This code of conduct is adapted from the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct).

View File

@ -28,21 +28,25 @@ The following is a set of guidelines for contributing to BetterDiscord. These ar
## Code of Conduct
This project and everyone participating in it is governed by the [Code of Conduct from the Contributor Covenant](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html). By participating, you are expected to uphold this code. Please report unacceptable behavior.
See our [Code of Conduct](https://github.com/BetterDiscord/BetterDiscord/blob/main/CODE_OF_CONDUCT.md) page for details.
## What should I know before I get started?
### BetterDiscord Architecture
BetterDiscord is currently broken up into two main pieces--the local injector, and the renderer application.
BetterDiscord is currently broken up into three packages--the local injector, the preload, and the renderer application. They form this miniature monorepo that is managed by [`pnpm`](https://pnpm.io/).
#### Injector
The injector is the piece that runs on the user's computer, and the piece added by the [installer](https://github.com/rauenzi/BBDInstaller). The main job of this package is to inject into Discord and load the renderer package. The injector and its code lives in the `injector` folder.
The main job of this package is to inject into Discord and load the renderer package. The injector and its code live in the `injector` folder.
#### Preload
Preload is the preload script for Discord's main `BrowserWindow` object. This sets up our cross-context APIs. The preload package and its code live in the `preload` folder.
#### Renderer Application
This is the main payload of BetterDiscord. This is what gets linked executed in the renderer context by the [injector](#injector). This portion is where most of the user interaction and development will be. This module is responsible for loading plugins and themes, as well as handling settings, emotes and more.
This is the main payload of BetterDiscord. This is what gets executed in the renderer context by the [injector](#injector). This portion is where most of the user interaction and development will be. This module is responsible for loading plugins and themes, as well as handling settings, and more. The renderer and its code live in the `renderer` folder.
## How Can I Contribute?
@ -50,19 +54,19 @@ This is the main payload of BetterDiscord. This is what gets linked executed in
This section guides you through submitting a bug report for BetterDiscord. Following these guidelines helps maintainers and the community understand your report, reproduce the behavior, and find related reports.
Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](https://github.com/rauenzi/BetterDiscordApp/blob/master/.github/ISSUE_TEMPLATE/bug-report.md), the information it asks for helps us resolve issues faster.
Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](https://github.com/BetterDiscord/BetterDiscord/blob/main/.github/ISSUE_TEMPLATE/BUG-REPORT.yml), the information it asks for helps us resolve issues faster.
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one.
#### Before Submitting A Bug Report
* **Try [repairing your installation](https://github.com/rauenzi/BetterDiscordApp#installation).** This can often fix issues where Discord has overwritten the injector or corrupted data files.
* **Check the [#faq channel](https://discord.gg/2HScm8j)** on our support server for answers to many questions. Also check the **#announcements** channel for any recent announcements about breaking changes.
* **Perform a [search](https://github.com/rauenzi/BetterDiscordApp/issues)** to see if the problem has already been reported. If it has **and the issue is still open**, add a :+1: to the existing issue instead of opening a new one.
* **Try [repairing your installation](https://docs.betterdiscord.app/users/getting-started/installation).** This can often fix issues where Discord has overwritten the injector or corrupted data files.
* **Check the [#faq channel](https://betterdiscord.app/invite)** on our support server for answers to many questions. Also check the **#announcements** channel for any recent announcements about breaking changes.
* **Perform a [search](https://github.com/BetterDiscord/BetterDiscord/issues)** to see if the problem has already been reported. If it has **and the issue is still open**, add a :+1: to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Bug Report?
Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined this is a new bug using the steps from above, create an issue and provide the following information by filling in [the template](https://github.com/rauenzi/BetterDiscordApp/blob/master/.github/ISSUE_TEMPLATE/bug-report.md).
Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined this is a new bug using the steps from above, create an issue and provide the following information by filling in [the template](https://github.com/BetterDiscord/BetterDiscord/blob/main/.github/ISSUE_TEMPLATE/BUG-REPORT.yml).
Explain the problem and include additional details to help maintainers reproduce the problem:
@ -91,7 +95,7 @@ Include details about your configuration and environment:
This section guides you through submitting an enhancement suggestion for BetterDiscord, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion and find related suggestions.
Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/rauenzi/BetterDiscordApp/blob/master/.github/ISSUE_TEMPLATE/feature_request.md), including the steps that you imagine you would take if the feature you're requesting existed.
Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/BetterDiscord/BetterDiscord/blob/main/.github/ISSUE_TEMPLATE/FEATURE-REQUEST.yml), including the steps that you imagine you would take if the feature you're requesting existed.
#### Before Submitting An Enhancement Suggestion
@ -115,7 +119,7 @@ Unsure where to begin contributing? You can start by looking through `help-wante
#### Local development
BetterDiscord and the injector can be developed locally. First, clone the repo and run `npm install && npm run build-all` and locate the `dist` folder. Next you'll need to setup the injector to use your local files. In order to do this, you'll need to locate your local injector installation. Relative to your `Discord.exe` it would be in `./resources/app`. Modify the `./resources/app/betterdiscord/config.json` file and set `localPath` to the **absolute** path of your `dist` folder from before. Then for this to take effect, you'll need to fully restart Discord. Any future modifications to the remote app (`dist` folder) will be picked up on Discord reload.
BetterDiscord can be developed and tested locally. First, clone the repo and run `pnpm install && pnpm build` this will generate a `dist` folder with compiled files. Next you'll need to inject your local setup to your desired release channel. There is a script in the repository to do this automatically for most cases. Just run `pnpm inject <channel>` where `<channel>` is the release channel--any of: stable, canary, ptb. Then for this to take effect, you'll need to fully restart Discord. Any future modifications to the renderer portion will be picked up on Discord reload. Preload and injector changes will require restarts.
### Pull Requests
@ -131,7 +135,8 @@ While the prerequisites above must be satisfied prior to having your pull reques
BetterDiscord supports a number of languages thanks to translations provided by the community. Translations for the BetterDiscord project should be submitted via [POEditor](https://poeditor.com/join/project?hash=nRljcnV0ET).
* Do not submit translations generated with a translation such as Google Translate, DeepL, or anything of the sorts,
* After joining the project, contact staff about your request being approved.
* Do not submit translations generated with a translation such as Google Translate, DeepL, or anything of the sorts.
* Only submit translations for languages you are at the very least fluent in, better yet if it's your first language.
## Styleguides
@ -146,7 +151,7 @@ BetterDiscord supports a number of languages thanks to translations provided by
### JavaScript Styleguide
All JavaScript must adhere to the [ESLint rules](https://github.com/rauenzi/BetterDiscordApp/blob/master/.eslintrc) of the repo.
All JavaScript must adhere to the [ESLint rules](https://github.com/BetterDiscord/BetterDiscord/blob/main/.eslintrc) of the repo.
Some other style related points not covered by ESLint:
@ -186,9 +191,9 @@ import {deepclone, isEmpty} from "./utilties"; // Avoid this
### CSS Styleguide
All CSS must adhere to the [Stylelint rules](https://github.com/rauenzi/BetterDiscordApp/blob/stable/.stylelintrc) of the repo.
All CSS must adhere to the [Stylelint rules](https://github.com/BetterDiscord/BetterDiscord/blob/main/renderer/.stylelintrc) of the repo.
Some other style related points not covered by ESLint:
Some other style related points not covered by StyleLint:
* Use verbose class names where applicable
* Keep css files modular
@ -200,20 +205,20 @@ Some other style related points not covered by ESLint:
This section lists the labels we use to help us track and manage issues. Please open an issue if you have suggestions for new labels.
[GitHub search](https://help.github.com/articles/searching-issues/) makes it easy to use labels for finding groups of issues or pull requests you're interested in. For example, you might be interested in [bugs that have not been able to be reproduced](https://github.com/rauenzi/BetterDiscordApp/issues?q=is%3Aopen+label%3A%22can%27t+reproduce%22+label%3A%22bug%22). To help you find issues, each label is listed with search links for finding open items with that label. We encourage you to read about [other search filters](https://help.github.com/articles/searching-issues/) which will help you write more focused queries.
[GitHub search](https://help.github.com/articles/searching-issues/) makes it easy to use labels for finding groups of issues or pull requests you're interested in. For example, you might be interested in [bugs that have not been able to be reproduced](https://github.com/BetterDiscord/BetterDiscord/issues?q=is%3Aopen+label%3A%22can%27t+reproduce%22+label%3A%22bug%22). To help you find issues, each label is listed with search links for finding open items with that label. We encourage you to read about [other search filters](https://help.github.com/articles/searching-issues/) which will help you write more focused queries.
#### Type of Issue and Issue State
| Label name | Description | View All |
| --- | --- | --- |
| `awaiting response` | Waiting for a response from the user, issues with this tag are prone to pruning. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/bug) |
| `bug` | Issue related to a bug report, may or may not be yet confirmed. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/awaiting%20response) |
| `can't fix` | Issues which are invalid or are a limitation of something else like Electron. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/can%27t%20fix) |
| `can't reproduce` | Reported bugs that could not be confirmed, help welcome. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/can%27t%20reproduce) |
| `confirmed` | Confirmed bugs to be actively worked. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/confirmed) |
| `duplicate` | Issues which are duplicates of other issues, i.e. they have been reported before. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/duplicate) |
| `enhancement` | Feature or improvement suggestion. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/enhancement) |
| `help wanted` | Help from the community appreciated. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/help%20wanted) |
| `needs info` | Issue did not supply enough information to take action on. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/needs%20info) |
| `question` | Questions more than bug reports or feature requests (e.g. how do I do X). | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/question) |
| `wontfix` | Decision has been made not to fix these issues at least for now. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/wontfix) |
| `awaiting response` | Waiting for a response from the user, issues with this tag are prone to pruning. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/bug) |
| `bug` | Issue related to a bug report, may or may not be yet confirmed. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/awaiting%20response) |
| `can't fix` | Issues which are invalid or are a limitation of something else like Electron. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/can%27t%20fix) |
| `can't reproduce` | Reported bugs that could not be confirmed, help welcome. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/can%27t%20reproduce) |
| `confirmed` | Confirmed bugs to be actively worked. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/confirmed) |
| `duplicate` | Issues which are duplicates of other issues, i.e. they have been reported before. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/duplicate) |
| `enhancement` | Feature or improvement suggestion. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/enhancement) |
| `help wanted` | Help from the community appreciated. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/help%20wanted) |
| `needs info` | Issue did not supply enough information to take action on. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/needs%20info) |
| `question` | Questions more than bug reports or feature requests (e.g. how do I do X). | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/question) |
| `wontfix` | Decision has been made not to fix these issues at least for now. | [View All](https://github.com/BetterDiscord/BetterDiscord/labels/wontfix) |

190
LICENSE
View File

@ -1,21 +1,177 @@
Copyright © 2019-2022, BetterDiscord Team
All rights reserved. Code may not be modified and redistributed, or otherwise
used for derivative works and redistributed without explicit permission.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software, including without limitation the rights to use, copy, and
distribute unmodified copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
The above copyright notice and this permission notice shall be included in all
copies or portions of the Software.
1. Definitions.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@ -1,6 +1,15 @@
import path from "path";
import {app} from "electron";
import Module from "module";
import path from "path";
import fs from "fs";
// Detect old install and delete it
const appPath = app.getAppPath(); // Should point to app or app.asar
const oldInstall = path.resolve(appPath, "..", "app");
if (fs.existsSync(oldInstall)) {
fs.rmdirSync(oldInstall, {recursive: true});
app.quit();
app.relaunch();
}
import ipc from "./modules/ipc";
import BrowserWindow from "./modules/browserwindow";
@ -18,30 +27,30 @@ if (!process.argv.includes("--vanilla")) {
// Remove CSP immediately on linux since they install to discord_desktop_core still
if (process.platform == "win32" || process.platform == "darwin") app.once("ready", CSP.remove);
else CSP.remove();
try {
CSP.remove();
}
catch (_) {
// Remove when everyone is moved to core
}
}
// Enable DevTools on Stable.
let fakeAppSettings;
Object.defineProperty(global, "appSettings", {
get() {
return fakeAppSettings;
},
set(value) {
if (!value.hasOwnProperty("settings")) value.settings = {};
value.settings.DANGEROUS_ENABLE_DEVTOOLS_ONLY_ENABLE_IF_YOU_KNOW_WHAT_YOURE_DOING = true;
fakeAppSettings = value;
},
});
// Use Discord's info to run the app
if (process.platform == "win32" || process.platform == "darwin") {
const basePath = path.join(app.getAppPath(), "..", "app.asar");
const pkg = __non_webpack_require__(path.join(basePath, "package.json"));
app.setAppPath(basePath);
app.name = pkg.name;
Module._load(path.join(basePath, pkg.main), null, true);
try {
let fakeAppSettings;
Object.defineProperty(global, "appSettings", {
get() {
return fakeAppSettings;
},
set(value) {
if (!value.hasOwnProperty("settings")) value.settings = {};
value.settings.DANGEROUS_ENABLE_DEVTOOLS_ONLY_ENABLE_IF_YOU_KNOW_WHAT_YOURE_DOING = true;
fakeAppSettings = value;
},
});
}
catch (_) {
// Remove when everyone is moved to core
}
// Needs to run this after Discord but before ready()

View File

@ -46,16 +46,6 @@ export default class BetterDiscord {
if (!fs.existsSync(path.join(dataPath, "themes"))) fs.mkdirSync(path.join(dataPath, "themes"));
}
static async ensureWebpackModules(browserWindow) {
await browserWindow.webContents.executeJavaScript(`new Promise(resolve => {
const check = function() {
if (window.webpackJsonp && window.webpackJsonp.flat().flat().length >= 7000) return resolve();
setTimeout(check, 100);
};
check();
});`);
}
static async injectRenderer(browserWindow) {
const location = path.join(__dirname, "renderer.js");
if (!fs.existsSync(location)) return; // TODO: cut a fatal log

View File

@ -128,17 +128,23 @@ const registerPreload = (event, path) => {
export default class IPCMain {
static registerEvents() {
ipc.on(IPCEvents.GET_PATH, getPath);
ipc.on(IPCEvents.RELAUNCH, relaunch);
ipc.on(IPCEvents.OPEN_DEVTOOLS, openDevTools);
ipc.on(IPCEvents.CLOSE_DEVTOOLS, closeDevTools);
ipc.on(IPCEvents.TOGGLE_DEVTOOLS, toggleDevTools);
ipc.on(IPCEvents.INSPECT_ELEMENT, inspectElement);
ipc.on(IPCEvents.MINIMUM_SIZE, setMinimumSize);
ipc.on(IPCEvents.DEVTOOLS_WARNING, stopDevtoolsWarning);
ipc.on(IPCEvents.REGISTER_PRELOAD, registerPreload);
ipc.handle(IPCEvents.RUN_SCRIPT, runScript);
ipc.handle(IPCEvents.OPEN_DIALOG, openDialog);
ipc.handle(IPCEvents.OPEN_WINDOW, createBrowserWindow);
try {
ipc.on(IPCEvents.GET_PATH, getPath);
ipc.on(IPCEvents.RELAUNCH, relaunch);
ipc.on(IPCEvents.OPEN_DEVTOOLS, openDevTools);
ipc.on(IPCEvents.CLOSE_DEVTOOLS, closeDevTools);
ipc.on(IPCEvents.TOGGLE_DEVTOOLS, toggleDevTools);
ipc.on(IPCEvents.INSPECT_ELEMENT, inspectElement);
ipc.on(IPCEvents.MINIMUM_SIZE, setMinimumSize);
ipc.on(IPCEvents.DEVTOOLS_WARNING, stopDevtoolsWarning);
ipc.on(IPCEvents.REGISTER_PRELOAD, registerPreload);
ipc.handle(IPCEvents.RUN_SCRIPT, runScript);
ipc.handle(IPCEvents.OPEN_DIALOG, openDialog);
ipc.handle(IPCEvents.OPEN_WINDOW, createBrowserWindow);
}
catch (err) {
// eslint-disable-next-line no-console
console.error(err);
}
}
}

View File

@ -1,6 +1,6 @@
{
"name": "betterdiscord",
"version": "1.8.2",
"version": "1.8.4",
"description": "Enhances Discord by adding functionality and themes.",
"main": "src/index.js",
"scripts": {
@ -9,7 +9,6 @@
"build-injector": "pnpm --filter injector build",
"build-renderer": "pnpm --filter renderer build",
"build-preload": "pnpm --filter preload build",
"pack-emotes": "node scripts/emotes.js",
"inject": "node scripts/inject.js",
"lint": "eslint --ext .js common/ && pnpm --filter injector lint && pnpm --filter preload lint && pnpm --filter renderer lint-js",
"test": "mocha --require @babel/register --recursive \"./tests/renderer/*.js\"",

View File

@ -1,37 +1,3 @@
import fs from "fs";
import path from "path";
import Module from "module";
// const Module = require("module");
Module.globalPaths.push(path.resolve(process.env.DISCORD_APP_PATH, "..", "app.asar", "node_modules"));
// module.paths.push(path.resolve(process.env.DISCORD_APP_PATH, "..", "app.asar", "node_modules"));
Module._load = (load => (req, parent, isMain) => {
if (req.includes("./") || req.includes("..")) return load(req, parent, isMain);
const found = Module.globalPaths.find(m => fs.existsSync(path.resolve(m, req)));
return found ? load(path.resolve(found, req), parent, isMain) : load(req, parent, isMain);
})(Module._load);
// const originalLoad = Module.prototype.load;
// Module.prototype.load = function() {
// const returnValue = Reflect.apply(originalLoad, this, arguments);
// console.log(this, arguments, returnValue);
// return returnValue;
// };
// const nodeModulePaths = Module._nodeModulePaths;
// console.log(nodeModulePaths);
// Module._nodeModulePaths = (from) => {
// return nodeModulePaths(from).concat([path.resolve(process.env.DISCORD_APP_PATH, "..", "app.asar", "node_modules")]);
// };
// console.log(Module._nodeModulePaths, Module._nodeModulePaths("request"));
// console.dir(Module);
// console.log(Object.keys(Module));
// console.log(require("request"));
export * as filesystem from "./filesystem";
export {default as https} from "./https";
export * as electron from "./electron";

View File

@ -41,7 +41,8 @@ export default function () {
if (!Reflect.has(exports, key) || target[key]) continue;
Object.defineProperty(target, key, {
get: exports[key],
get: () => exports[key](),
set: v => {exports[key] = () => v;},
enumerable: true,
configurable: true
});

View File

@ -1,27 +0,0 @@
import {React} from "modules";
import DownArrow from "../../ui/icons/downarrow";
export default class Category extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: true
};
}
render() {
return <div className="bd-emote-category">
<div className={`bd-emote-header ${this.state.expanded ? "expanded" : "collapsed"}`}>
<div className="bd-emote-header-inner" onClick={() => this.setState({expanded: !this.state.expanded})}>
<div className="bd-emote-header-icon">
{this.props.icon ? this.props.icon : null}
</div>
<div className="bd-emote-header-label">{this.props.label}</div>
<div className={`bd-emote-collapse-icon ${this.state.expanded ? "expanded" : "collapsed"}`}>
<DownArrow/>
</div>
</div>
</div>
{this.state.expanded && this.props.children}
</div>;
}
}

View File

@ -1,95 +0,0 @@
import Builtin from "../../structs/builtin";
import {Utilities, WebpackModules, React} from "modules";
import EmoteModule from "./emotes";
import EmoteMenuCard from "../../ui/emotemenucard";
import EmoteIcon from "../../ui/emoteicon";
import Category from "./category";
import Favorite from "../../ui/icons/favorite";
import Twitch from "../../ui/icons/twitch";
const EmojiPicker = WebpackModules.find(m => m.type && m.type.displayName == "ExpressionPicker");
const {useExpressionPickerStore} = WebpackModules.getByProps("useExpressionPickerStore") ?? {};
export default new class EmoteMenu extends Builtin {
get name() {return "EmoteMenu";}
get collection() {return "emotes";}
get category() {return "general";}
get id() {return "emoteMenu";}
get hideEmojisID() {return "hideEmojiMenu";}
get hideEmojis() {return this.get(this.hideEmojisID);}
enabled() {
this.after(EmojiPicker, "type", (_, __, returnValue) => {
const originalChildren = returnValue?.props?.children?.props?.children;
if (!originalChildren || originalChildren.__patched) return;
const activePicker = useExpressionPickerStore((state) => state.activeView);
returnValue.props.children.props.children = (props) => {
const childrenReturn = Reflect.apply(originalChildren, null, [props]);
// Attach a try {} catch {} because this might crash the user.
try {
const head = Utilities.findInTree(childrenReturn, (e) => e?.role === "tablist", {walkable: ["props", "children", "return", "stateNode"]})?.children;
const body = Utilities.findInTree(childrenReturn, (e) => e?.[0]?.type === "nav", {walkable: ["props", "children", "return", "stateNode"]});
if (!head || !body) return childrenReturn;
const isActive = activePicker == "bd-emotes";
const TabItem = head[0]?.type ?? (() => null);
if (!isActive && activePicker == "emoji" && this.hideEmojis) {
useExpressionPickerStore.setState({activeView: "bd-emotes"});
}
if (this.hideEmojis) {
const emojiTabIndex = head.findIndex((e) => e?.props?.id == "emoji-picker-tab");
if (emojiTabIndex > -1) head.splice(emojiTabIndex, 1);
}
head.push(
React.createElement(TabItem, {
"aria-controls": "bd-emotes",
"id": "bd-emotes",
"aria-selected": isActive,
"isActive": isActive,
"viewType": "bd-emotes"
}, "Twitch")
);
if (isActive) {
body.push(
React.createElement(EmoteMenuCard, {
type: "twitch",
}, [
React.createElement(Category, {
label: "Favorites",
icon: React.createElement(Favorite, {}),
}, Object.entries(EmoteModule.favorites).map(([emote, url]) => {
return React.createElement(EmoteIcon, {emote, url});
})),
React.createElement(Category, {
label: "Twitch Emotes",
icon: React.createElement(Twitch, {})
}, Object.keys(EmoteModule.getCategory("TwitchGlobal")).map((emote) => {
const url = EmoteModule.getUrl("TwitchGlobal", emote);
return React.createElement(EmoteIcon, {emote, url});
}))
])
);
}
}
catch (error) {
this.error("Error in EmojiPicker patch:\n", error);
}
return childrenReturn;
};
returnValue.props.children.props.children.__patched = true;
});
}
disabled() {
this.unpatchAll();
}
};

View File

@ -1,260 +0,0 @@
import Builtin from "../../structs/builtin";
import {EmoteConfig, Config} from "data";
import {WebpackModules, DataStore, DiscordModules, Events, Settings, Strings} from "modules";
import BDEmote from "../../ui/emote";
import Modals from "../../ui/modals";
import Toasts from "../../ui/toasts";
import FormattableString from "../../structs/string";
const request = require("request");
const path = require("path");
const fs = require("fs");
const EmoteURLs = {
TwitchGlobal: new FormattableString(`https://static-cdn.jtvnw.net/emoticons/v1/{{id}}/1.0`),
TwitchSubscriber: new FormattableString(`https://static-cdn.jtvnw.net/emoticons/v1/{{id}}/1.0`),
FrankerFaceZ: new FormattableString(`https://cdn.frankerfacez.com/emoticon/{{id}}/1`),
BTTV: new FormattableString(`https://cdn.betterttv.net/emote/{{id}}/1x`),
};
const Emotes = {
TwitchGlobal: {},
TwitchSubscriber: {},
BTTV: {},
FrankerFaceZ: {}
};
const escape = (s) => {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
};
const blocklist = [];
const overrides = ["twitch", "subscriber", "bttv", "ffz"];
const modifiers = ["flip", "spin", "pulse", "spin2", "spin3", "1spin", "2spin", "3spin", "tr", "bl", "br", "shake", "shake2", "shake3", "flap"];
export default new class EmoteModule extends Builtin {
get name() {return "Emotes";}
get collection() {return "settings";}
get category() {return "general";}
get id() {return "emotes";}
get categories() {return Object.keys(Emotes).filter(k => this.isCategoryEnabled(k));}
get shouldDownload() {return Settings.get("emotes", this.category, "download");}
get asarPath() {return path.join(DataStore.baseFolder, "emotes.asar");}
isCategoryEnabled(id) {return super.get("emotes", "categories", id.toLowerCase());}
get(id) {return super.get("emotes", "general", id);}
get MessageComponent() {return WebpackModules.find(m => m.default && m.default.toString().search("childrenRepliedMessage") > -1);}
get Emotes() {return Emotes;}
get TwitchGlobal() {return Emotes.TwitchGlobal;}
get TwitchSubscriber() {return Emotes.TwitchSubscriber;}
get BTTV() {return Emotes.BTTV;}
get FrankerFaceZ() {return Emotes.FrankerFaceZ;}
get blocklist() {return blocklist;}
get favorites() {return this.favoriteEmotes;}
getUrl(category, name) {return EmoteURLs[category].format({id: Emotes[category][name]});}
getCategory(category) {return Emotes[category];}
getRemoteFile(category) {return `https://cdn.staticaly.com/gh/BetterDiscord/BetterDiscord/${Config.hash}/assets/emotes/${category.toLowerCase()}.json`;}
initialize() {
super.initialize();
const storedFavorites = DataStore.getBDData("favoriteEmotes");
this.favoriteEmotes = storedFavorites || {};
this.addFavorite = this.addFavorite.bind(this);
this.removeFavorite = this.removeFavorite.bind(this);
this.onCategoryToggle = this.onCategoryToggle.bind(this);
this.resetEmotes = this.resetEmotes.bind(this);
}
async enabled() {
Settings.registerCollection("emotes", "Emotes", EmoteConfig, {title: Strings.Emotes.clearEmotes, onClick: this.resetEmotes.bind(this)});
// await this.getBlocklist();
await this.loadEmoteData();
Events.on("emotes-favorite-added", this.addFavorite);
Events.on("emotes-favorite-removed", this.removeFavorite);
Events.on("setting-updated", this.onCategoryToggle);
this.patchMessageContent();
}
disabled() {
Events.off("setting-updated", this.onCategoryToggle);
Events.off("emotes-favorite-added", this.addFavorite);
Events.off("emotes-favorite-removed", this.removeFavorite);
Settings.removeCollection("emotes");
this.emptyEmotes();
if (!this.cancelEmoteRender) return;
this.cancelEmoteRender();
delete this.cancelEmoteRender;
}
onCategoryToggle(collection, cat, category, enabled) {
if (collection != "emotes" || cat != "categories") return;
if (enabled) return this.loadEmoteData(category);
return this.unloadEmoteData(category);
}
addFavorite(name, url) {
if (!this.favoriteEmotes.hasOwnProperty(name)) this.favoriteEmotes[name] = url;
this.saveFavorites();
}
removeFavorite(name) {
if (!this.favoriteEmotes.hasOwnProperty(name)) return;
delete this.favoriteEmotes[name];
this.saveFavorites();
}
isFavorite(name) {
return this.favoriteEmotes.hasOwnProperty(name);
}
saveFavorites() {
DataStore.setBDData("favoriteEmotes", this.favoriteEmotes);
}
emptyEmotes() {
for (const cat in Emotes) Object.assign(Emotes, {[cat]: {}});
}
patchMessageContent() {
if (this.cancelEmoteRender) return;
this.cancelEmoteRender = this.before(this.MessageComponent, "default", (thisObj, args) => {
const nodes = args[0].childrenMessageContent.props.content;
if (!nodes || !nodes.length) return;
for (let n = 0; n < nodes.length; n++) {
const node = nodes[n];
if (typeof(node) !== "string") continue;
const words = node.split(/([^\s]+)([\s]|$)/g);
for (let c = 0, clen = this.categories.length; c < clen; c++) {
for (let w = 0, wlen = words.length; w < wlen; w++) {
const emote = words[w];
const emoteSplit = emote.split(":");
const emoteName = emoteSplit[0];
let emoteModifier = emoteSplit[1] ? emoteSplit[1] : "";
let emoteOverride = emoteModifier.slice(0);
if (emoteName.length < 4 || blocklist.includes(emoteName)) continue;
if (!modifiers.includes(emoteModifier) || !Settings.get("emotes", "general", "modifiers")) emoteModifier = "";
if (!overrides.includes(emoteOverride)) emoteOverride = "";
else emoteModifier = emoteOverride;
let current = this.categories[c];
if (emoteOverride === "twitch") {
if (Emotes.TwitchGlobal[emoteName]) current = "TwitchGlobal";
else if (Emotes.TwitchSubscriber[emoteName]) current = "TwitchSubscriber";
}
else if (emoteOverride === "subscriber") {
if (Emotes.TwitchSubscriber[emoteName]) current = "TwitchSubscriber";
}
else if (emoteOverride === "bttv") {
if (Emotes.BTTV[emoteName]) current = "BTTV";
}
else if (emoteOverride === "ffz") {
if (Emotes.FrankerFaceZ[emoteName]) current = "FrankerFaceZ";
}
if (!Emotes[current][emoteName]) continue;
const results = nodes[n].match(new RegExp(`([\\s]|^)${escape(emoteModifier ? emoteName + ":" + emoteModifier : emoteName)}([\\s]|$)`));
if (!results) continue;
const pre = nodes[n].substring(0, results.index + results[1].length);
const post = nodes[n].substring(results.index + results[0].length - results[2].length);
nodes[n] = pre;
const emoteComponent = DiscordModules.React.createElement(BDEmote, {name: emoteName, url: EmoteURLs[current].format({id: Emotes[current][emoteName]}), modifier: emoteModifier, isFavorite: this.isFavorite(emoteName)});
nodes.splice(n + 1, 0, post);
nodes.splice(n + 1, 0, emoteComponent);
}
}
}
const onlyEmotes = nodes.every(r => {
if (typeof(r) == "string" && r.replace(/\s*/, "") == "") return true;
else if (r.type && r.type.name == "BDEmote") return true;
else if (r.props && r.props.children && r.props.children.props && r.props.children.props.emojiName) return true;
return false;
});
if (!onlyEmotes) return;
for (const node of nodes) {
if (typeof(node) != "object") continue;
if (node.type.name == "BDEmote") node.props.jumboable = true;
else if (node.props && node.props.children && node.props.children.props && node.props.children.props.emojiName) node.props.children.props.jumboable = true;
}
});
}
async loadEmoteData(categories) {
if (!categories) categories = this.categories;
if (!Array.isArray(categories)) categories = [categories];
const all = Object.keys(Emotes);
categories = categories.map(k => all.find(c => c.toLowerCase() == k.toLowerCase()));
Toasts.show(Strings.Emotes.loading, {type: "info"});
this.emotesLoaded = false;
const localOutdated = Config.release.tag_name > DataStore.getBDData("emoteVersion");
if (!fs.existsSync(this.asarPath) || (localOutdated && this.shouldDownload)) await this.downloadEmotes();
try {
for (const category of categories) {
this.log(category);
const EmoteData = __non_webpack_require__(path.join(this.asarPath, category.toLowerCase()));
Object.assign(Emotes[category], EmoteData);
delete __non_webpack_require__.cache[path.join(this.asarPath, category.toLowerCase())];
await new Promise(r => setTimeout(r, 1000));
}
const EmoteData = __non_webpack_require__(path.join(this.asarPath, "blocklist"));
blocklist.push(...EmoteData);
delete __non_webpack_require__.cache[path.join(this.asarPath, "blocklist")];
}
catch (err) {
this.log("Failed to load emotes.");
}
this.emotesLoaded = true;
Events.dispatch("emotes-loaded");
Toasts.show(Strings.Emotes.loaded, {type: "success"});
}
unloadEmoteData(categories) {
if (!categories) categories = this.categories;
if (!Array.isArray(categories)) categories = [categories];
const all = Object.keys(Emotes);
categories = categories.map(k => all.find(c => c.toLowerCase() == k.toLowerCase()));
for (const category of categories) {
delete Emotes[category];
Emotes[category] = {};
}
}
async downloadEmotes() {
try {
const asar = Config.release.assets.find(a => a.name === "emotes.asar");
this.log(`Downloading emotes from: ${asar.url}`);
const buff = await new Promise((resolve, reject) =>
request(asar.url, {encoding: null, headers: {"User-Agent": "BetterDiscord Emotes", "Accept": "application/octet-stream"}}, (err, resp, body) => {
if (err || resp.statusCode != 200) return reject(err || `${resp.statusCode} ${resp.statusMessage}`);
return resolve(body);
}));
this.log("Successfully downloaded emotes.asar");
const asarPath = this.asarPath;
const originalFs = require("original-fs");
originalFs.writeFileSync(asarPath, buff);
this.log(`Saved emotes.asar to ${asarPath}`);
DataStore.setBDData("emoteVersion", Config.release.tag_name);
}
catch (err) {
this.stacktrace("Failed to download emotes.", err);
Modals.showConfirmationModal(Strings.Emotes.downloadFailed, Strings.Emotes.failureMessage, {cancelText: null});
}
}
resetEmotes() {
this.unloadEmoteData();
DataStore.setBDData("emoteVersion", "0");
this.loadEmoteData();
}
};

View File

@ -1,16 +1,12 @@
// fixed, improved, added, progress
export default {
description: "Just some smaller fixes while we work on some big things in the background.",
description: "More features are coming soon!",
changes: [
{
title: "Bug Fixes",
type: "fixed",
items: [
"Fixed _even more_ issues with the built-in updater.",
"Fixed not being able to click support server links in plugin/theme pages.",
"Fixed some issues with not being able to join public servers.",
"Fixed plugin settings not being able to be displayed.",
"Fixed changelog modal not being able to be displayed."
"Fixed crashing on right click.",
]
}
]

View File

@ -1,4 +1,3 @@
export {default as Config} from "./config";
export {default as EmoteConfig} from "./emotesettings";
export {default as SettingsConfig} from "./settings";
export {default as Changelog} from "./changelog";

View File

@ -1,27 +0,0 @@
export default [
{
type: "category",
id: "general",
name: "General",
collapsible: true,
settings: [
{type: "switch", id: "download", value: true},
{type: "switch", id: "emoteMenu", value: true},
{type: "switch", id: "hideEmojiMenu", value: false, enableWith: "emoteMenu"},
{type: "switch", id: "modifiers", value: true},
{type: "switch", id: "animateOnHover", value: false}
]
},
{
type: "category",
id: "categories",
name: "Categories",
collapsible: true,
settings: [
{type: "switch", id: "twitchglobal", value: true},
{type: "switch", id: "twitchsubscriber", value: false},
{type: "switch", id: "frankerfacez", value: true},
{type: "switch", id: "bttv", value: true}
]
}
];

View File

@ -4,7 +4,6 @@ export default [
id: "general",
collapsible: true,
settings: [
{type: "switch", id: "emotes", value: true, disabled: true},
{type: "switch", id: "publicServers", value: true},
{type: "switch", id: "voiceDisconnect", value: false},
{type: "switch", id: "showToasts", value: true},

View File

@ -3,6 +3,8 @@ import Patcher from "../patcher";
import Logger from "common/logger";
import {React} from "../modules";
let startupComplete = false;
const MenuComponents = (() => {
const out = {};
const componentMap = {
@ -14,14 +16,25 @@ const MenuComponents = (() => {
customitem: "Item"
};
let ContextMenuIndex = null;
const ContextMenuModule = WebpackModules.getModule((m, _, id) => Object.values(m).some(v => v?.FLEXIBLE) && (ContextMenuIndex = id), {searchExports: false});
const rawMatches = WebpackModules.require.m[ContextMenuIndex].toString().matchAll(/if\(\w+\.type===\w+\.(\w+)\).+?type:"(.+?)"/g);
out.Menu = Object.values(ContextMenuModule).find(v => v.toString().includes(".isUsingKeyboardNavigation"));
try {
let contextMenuId = Object.keys(WebpackModules.require.m).find(e => WebpackModules.require.m[e]?.toString().includes("menuitemcheckbox"));
const ContextMenuModule = WebpackModules.getModule((m, t, id) => id === contextMenuId);
const rawMatches = WebpackModules.require.m[contextMenuId].toString().matchAll(/if\(\w+\.type===\w+\.(\w+)\).+?type:"(.+?)"/g);
for (const [, identifier, type] of rawMatches) {
out[componentMap[type]] = ContextMenuModule[identifier];
out.Menu = Object.values(ContextMenuModule).find(v => v.toString().includes(".isUsingKeyboardNavigation"));
for (const [, identifier, type] of rawMatches) {
out[componentMap[type]] = ContextMenuModule[identifier];
}
startupComplete = Object.values(componentMap).every(k => out[k]) && !!out.Menu;
} catch (error) {
startupComplete = false;
Logger.stacktrace("ContextMenu~Components", "Fatal startup error:", error);
Object.assign(out, Object.fromEntries(
Object.values(componentMap).map(k => [k, () => null])
));
}
return out;
@ -30,15 +43,27 @@ const MenuComponents = (() => {
const ContextMenuActions = (() => {
const out = {};
const ActionsModule = WebpackModules.getModule(m => Object.values(m).some(v => typeof v === "function" && v.toString().includes("CONTEXT_MENU_CLOSE")), {searchExports: false});
try {
const ActionsModule = WebpackModules.getModule(m => Object.values(m).some(v => typeof v === "function" && v.toString().includes("CONTEXT_MENU_CLOSE")), {searchExports: false});
for (const key of Object.keys(ActionsModule)) {
if (ActionsModule[key].toString().includes("CONTEXT_MENU_CLOSE")) {
out.closeContextMenu = ActionsModule[key];
}
else if (ActionsModule[key].toString().includes("renderLazy")) {
out.openContextMenu = ActionsModule[key];
for (const key of Object.keys(ActionsModule)) {
if (ActionsModule[key].toString().includes("CONTEXT_MENU_CLOSE")) {
out.closeContextMenu = ActionsModule[key];
}
else if (ActionsModule[key].toString().includes("renderLazy")) {
out.openContextMenu = ActionsModule[key];
}
}
startupComplete = typeof(out.closeContextMenu) === "function" && typeof(out.openContextMenu) === "function";
} catch (error) {
startupComplete = false;
Logger.stacktrace("ContextMenu~Components", "Fatal startup error:", error);
Object.assign(out, {
closeContextMenu: () => {},
openContextMenu: () => {}
});
}
return out;
@ -50,6 +75,8 @@ class MenuPatcher {
static subPatches = new WeakMap();
static initialize() {
if (!startupComplete) return Logger.warn("ContextMenu~Patcher", "Startup wasn't successfully, aborting initialization.");
const {module, key} = (() => {
const foundModule = WebpackModules.getModule(m => Object.values(m).some(v => typeof v === "function" && v.toString().includes("CONTEXT_MENU_CLOSE")), {searchExports: false});
const foundKey = Object.keys(foundModule).find(k => foundModule[k].length === 3);
@ -320,6 +347,11 @@ class ContextMenu {
Object.assign(ContextMenu.prototype, MenuComponents);
Object.freeze(ContextMenu);
Object.freeze(ContextMenu.prototype);
MenuPatcher.initialize();
try {
MenuPatcher.initialize();
} catch (error) {
Logger.error("ContextMenu~Patcher", "Fatal error:", error);
}
export default ContextMenu;

View File

@ -9,7 +9,6 @@ import Modals from "../../ui/modals";
import Settings from "../settingsmanager";
import Logger from "common/logger";
import Patcher from "../patcher";
import Emotes from "../../builtins/emotes/emotes";
import ipc from "../ipc";
/**
@ -40,18 +39,7 @@ const settings = Settings.collections;
* @deprecated
* @memberof BdApi
*/
const emotes = new Proxy(Emotes.Emotes, {
get(obj, category) {
if (category === "blocklist") return Emotes.blocklist;
const group = Emotes.Emotes[category];
if (!group) return undefined;
return new Proxy(group, {
get(cat, emote) {return group[emote];},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
const emotes = {};
/**
* A reference string for BD's version.

View File

@ -60,11 +60,8 @@ export default new class DataStore {
const setChannelData = (channel, key, value, ext = "json") => fs.writeFileSync(path.resolve(this.baseFolder, channel, `${key}.${ext}`), JSON.stringify(value, null, 4));
const channels = ["stable", "canary", "ptb"];
let customcss = "";
let favoriteEmotes = {};
try {customcss = oldData.bdcustomcss ? atob(oldData.bdcustomcss) : "";}
catch (e) {Logger.stacktrace("DataStore:convertOldData", "Error decoding custom css", e);}
try {favoriteEmotes = oldData.bdfavemotes ? JSON.parse(atob(oldData.bdfavemotes)) : {};}
catch (e) {Logger.stacktrace("DataStore:convertOldData", "Error decoding favorite emotes", e);}
for (const channel of channels) {
if (!fs.existsSync(path.resolve(this.baseFolder, channel))) fs.mkdirSync(path.resolve(this.baseFolder, channel));
const channelData = oldData.settings[channel];
@ -77,16 +74,9 @@ export default new class DataStore {
developer: {debuggerHotkey: oldSettings["bda-gs-8"], reactDevTools: oldSettings.reactDevTools}
};
const newEmotes = {
general: {download: oldSettings["fork-es-3"], emoteMenu: oldSettings["bda-es-0"], hideEmojiMenu: !oldSettings["bda-es-9"], modifiers: oldSettings["bda-es-8"], animateOnHover: oldSettings["fork-es-2"]},
categories: {twitchglobal: oldSettings["bda-es-7"], twitchsubscriber: oldSettings["bda-es-7"], frankerfacez: oldSettings["bda-es-1"], bttv: oldSettings["bda-es-2"]}
};
setChannelData(channel, "settings", newSettings); // settingsCookie
setChannelData(channel, "emotes", newEmotes); // emotes (from settingsCookie)
setChannelData(channel, "plugins", channelData.plugins || {}); // pluginCookie
setChannelData(channel, "themes", channelData.themes || {}); // themeCookie
setChannelData(channel, "misc", {favoriteEmotes}); // favorite emotes
fs.writeFileSync(path.resolve(this.baseFolder, channel, "custom.css"), customcss); // customcss
}

View File

@ -1,282 +1,228 @@
/**
* Patcher that can patch other functions allowing you to run code before, after or
* instead of the original function. Can also alter arguments and return values.
*
* This is from Zerebos' library {@link https://github.com/rauenzi/BDPluginLibrary}
*
* @module Patcher
* @version 0.0.2
*/
import Logger from "common/logger";
import DiscordModules from "./discordmodules";
import WebpackModules from "./webpackmodules";
export default class Patcher {
static get patches() {return this._patches || (this._patches = []);}
/**
* Returns all the patches done by a specific caller
* @param {string} name - Name of the patch caller
* @method
*/
static getPatchesByCaller(name) {
if (!name) return [];
const patches = [];
for (const patch of this.patches) {
for (const childPatch of patch.children) {
if (childPatch.caller === name) patches.push(childPatch);
}
}
return patches;
}
/**
* Unpatches all patches passed, or when a string is passed unpatches all
* patches done by that specific caller.
* @param {Array|string} patches - Either an array of patches to unpatch or a caller name
*/
static unpatchAll(patches) {
if (typeof patches === "string") patches = this.getPatchesByCaller(patches);
for (const patch of patches) {
patch.unpatch();
}
}
static resolveModule(module) {
if (!module || typeof(module) === "function" || (typeof(module) === "object" && !Array.isArray(module))) return module;
if (typeof module === "string") return DiscordModules[module];
if (Array.isArray(module)) return WebpackModules.findByUniqueProperties(module);
return null;
}
static makeOverride(patch) {
return function () {
let returnValue;
if (!patch.children || !patch.children.length) return patch.originalFunction.apply(this, arguments);
for (const superPatch of patch.children.filter(c => c.type === "before")) {
try {
superPatch.callback(this, arguments);
}
catch (err) {
Logger.err("Patcher", `Could not fire before callback of ${patch.functionName} for ${superPatch.caller}`, err);
}
}
const insteads = patch.children.filter(c => c.type === "instead");
if (!insteads.length) {returnValue = patch.originalFunction.apply(this, arguments);}
else {
for (const insteadPatch of insteads) {
try {
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire instead callback of ${patch.functionName} for ${insteadPatch.caller}`, err);
}
}
}
for (const slavePatch of patch.children.filter(c => c.type === "after")) {
try {
const tempReturn = slavePatch.callback(this, arguments, returnValue);
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire after callback of ${patch.functionName} for ${slavePatch.caller}`, err);
}
}
return returnValue;
};
}
static rePatch(patch) {
patch.proxyFunction = patch.module[patch.functionName] = this.makeOverride(patch);
}
static makePatch(module, functionName, name) {
const patch = {
name,
module,
functionName,
originalFunction: module[functionName],
proxyFunction: null,
revert: () => { // Calling revert will destroy any patches added to the same module after this
if (patch.getter) {
Object.defineProperty(patch.module, functionName, {
...Object.getOwnPropertyDescriptor(patch.module, functionName),
get: () => patch.originalFunction,
set: undefined
});
}
else {
patch.module[patch.functionName] = patch.originalFunction;
}
patch.proxyFunction = null;
patch.children = [];
},
counter: 0,
children: []
};
patch.proxyFunction = this.makeOverride(patch);
const descriptor = Object.getOwnPropertyDescriptor(module, functionName);
if (descriptor?.get) {
patch.getter = true;
Object.defineProperty(module, functionName, {
configurable: true,
enumerable: true,
...descriptor,
get: () => patch.proxyFunction,
// eslint-disable-next-line no-setter-return
set: value => (patch.originalFunction = value)
});
}
else {
patch.getter = false;
module[functionName] = patch.proxyFunction;
}
const descriptors = Object.assign({}, Object.getOwnPropertyDescriptors(patch.originalFunction), {
__originalFunction: {
get: () => patch.originalFunction,
configurable: true,
enumerable: true,
writeable: true
},
toString: {
value: () => patch.originalFunction.toString(),
configurable: true,
enumerable: true,
writeable: true
}
});
Object.defineProperties(patch.proxyFunction, descriptors);
this.patches.push(patch);
return patch;
}
/**
* Function with no arguments and no return value that may be called to revert changes made by {@link module:Patcher}, restoring (unpatching) original method.
* @callback module:Patcher~unpatch
*/
/**
* A callback that modifies method logic. This callback is called on each call of the original method and is provided all data about original call. Any of the data can be modified if necessary, but do so wisely.
*
* The third argument for the callback will be `undefined` for `before` patches. `originalFunction` for `instead` patches and `returnValue` for `after` patches.
*
* @callback module:Patcher~patchCallback
* @param {object} thisObject - `this` in the context of the original function.
* @param {args} args - The original arguments of the original function.
* @param {(function|*)} extraValue - For `instead` patches, this is the original function from the module. For `after` patches, this is the return value of the function.
* @return {*} Makes sense only when using an `instead` or `after` patch. If something other than `undefined` is returned, the returned value replaces the value of `returnValue`. If used for `before` the return value is ignored.
*/
/**
* This method patches onto another function, allowing your code to run beforehand.
* Using this, you are also able to modify the incoming arguments before the original method is run.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run before the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static before(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "before"}));}
/**
* This method patches onto another function, allowing your code to run after.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run instead of the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static after(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "after"}));}
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static instead(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "instead"}));}
/**
* This method patches onto another function, allowing your code to run before, instead or after the original function.
* Using this you are able to modify the incoming arguments before the original function is run as well as the return
* value before the original function actually returns.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.type=after] - Determines whether to run the function `before`, `instead`, or `after` the original.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static pushChildPatch(caller, moduleToPatch, functionName, callback, options = {}) {
const {type = "after", forcePatch = true} = options;
const module = this.resolveModule(moduleToPatch);
if (!module) return null;
if (!module[functionName] && forcePatch) module[functionName] = function() {};
if (!(module[functionName] instanceof Function)) return null;
const descriptor = Object.getOwnPropertyDescriptor(module, functionName);
if (descriptor && !descriptor?.configurable) {
Logger.err("Patcher", `Cannot patch ${functionName} of Module, property is readonly.`);
return null;
}
if (typeof moduleToPatch === "string") options.displayName = moduleToPatch;
const displayName = options.displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
const patchId = `${displayName}.${functionName}`;
const patch = this.patches.find(p => p.module == module && p.functionName == functionName) || this.makePatch(module, functionName, patchId);
if (!patch.proxyFunction) this.rePatch(patch);
const child = {
caller,
type,
id: patch.counter,
callback,
unpatch: () => {
patch.children.splice(patch.children.findIndex(cpatch => cpatch.id === child.id && cpatch.type === type), 1);
if (patch.children.length <= 0) {
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
if (patchNum < 0) return;
this.patches[patchNum].revert();
this.patches.splice(patchNum, 1);
}
}
};
patch.children.push(child);
patch.counter++;
return child.unpatch;
}
}
import Logger from "common/logger";
import DiscordModules from "./discordmodules";
import WebpackModules from "./webpackmodules";
export default class Patcher {
static get patches() {return this._patches || (this._patches = []);}
/**
* Returns all the patches done by a specific caller
* @param {string} name - Name of the patch caller
* @method
*/
static getPatchesByCaller(name) {
if (!name) return [];
const patches = [];
for (const patch of this.patches) {
for (const childPatch of patch.children) {
if (childPatch.caller === name) patches.push(childPatch);
}
}
return patches;
}
/**
* Unpatches all patches passed, or when a string is passed unpatches all
* patches done by that specific caller.
* @param {Array|string} patches - Either an array of patches to unpatch or a caller name
*/
static unpatchAll(patches) {
if (typeof patches === "string") patches = this.getPatchesByCaller(patches);
for (const patch of patches) {
patch.unpatch();
}
}
static resolveModule(module) {
if (!module || typeof(module) === "function" || (typeof(module) === "object" && !Array.isArray(module))) return module;
if (typeof module === "string") return DiscordModules[module];
if (Array.isArray(module)) return WebpackModules.findByUniqueProperties(module);
return null;
}
static makeOverride(patch) {
return function () {
let returnValue;
if (!patch.children || !patch.children.length) return patch.originalFunction.apply(this, arguments);
for (const superPatch of patch.children.filter(c => c.type === "before")) {
try {
superPatch.callback(this, arguments);
}
catch (err) {
Logger.err("Patcher", `Could not fire before callback of ${patch.functionName} for ${superPatch.caller}`, err);
}
}
const insteads = patch.children.filter(c => c.type === "instead");
if (!insteads.length) {returnValue = patch.originalFunction.apply(this, arguments);}
else {
for (const insteadPatch of insteads) {
try {
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire instead callback of ${patch.functionName} for ${insteadPatch.caller}`, err);
}
}
}
for (const slavePatch of patch.children.filter(c => c.type === "after")) {
try {
const tempReturn = slavePatch.callback(this, arguments, returnValue);
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire after callback of ${patch.functionName} for ${slavePatch.caller}`, err);
}
}
return returnValue;
};
}
static rePatch(patch) {
patch.proxyFunction = patch.module[patch.functionName] = this.makeOverride(patch);
}
static makePatch(module, functionName, name) {
const patch = {
name,
module,
functionName,
originalFunction: module[functionName],
proxyFunction: null,
revert: () => { // Calling revert will destroy any patches added to the same module after this
patch.module[patch.functionName] = patch.originalFunction;
patch.proxyFunction = null;
patch.children = [];
},
counter: 0,
children: []
};
patch.proxyFunction = module[functionName] = this.makeOverride(patch);
Object.assign(module[functionName], patch.originalFunction);
module[functionName].__originalFunction = patch.originalFunction;
module[functionName].toString = () => patch.originalFunction.toString();
this.patches.push(patch);
return patch;
}
/**
* Function with no arguments and no return value that may be called to revert changes made by {@link module:Patcher}, restoring (unpatching) original method.
* @callback module:Patcher~unpatch
*/
/**
* A callback that modifies method logic. This callback is called on each call of the original method and is provided all data about original call. Any of the data can be modified if necessary, but do so wisely.
*
* The third argument for the callback will be `undefined` for `before` patches. `originalFunction` for `instead` patches and `returnValue` for `after` patches.
*
* @callback module:Patcher~patchCallback
* @param {object} thisObject - `this` in the context of the original function.
* @param {arguments} args - The original arguments of the original function.
* @param {(function|*)} extraValue - For `instead` patches, this is the original function from the module. For `after` patches, this is the return value of the function.
* @return {*} Makes sense only when using an `instead` or `after` patch. If something other than `undefined` is returned, the returned value replaces the value of `returnValue`. If used for `before` the return value is ignored.
*/
/**
* This method patches onto another function, allowing your code to run beforehand.
* Using this, you are also able to modify the incoming arguments before the original method is run.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run before the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static before(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "before"}));}
/**
* This method patches onto another function, allowing your code to run after.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run instead of the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static after(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "after"}));}
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static instead(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "instead"}));}
/**
* This method patches onto another function, allowing your code to run before, instead or after the original function.
* Using this you are able to modify the incoming arguments before the original function is run as well as the return
* value before the original function actually returns.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.type=after] - Determines whether to run the function `before`, `instead`, or `after` the original.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static pushChildPatch(caller, moduleToPatch, functionName, callback, options = {}) {
const {type = "after", forcePatch = true} = options;
const module = this.resolveModule(moduleToPatch);
if (!module) return null;
if (!module[functionName] && forcePatch) module[functionName] = function() {};
if (!(module[functionName] instanceof Function)) return null;
if (typeof moduleToPatch === "string") options.displayName = moduleToPatch;
const displayName = options.displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
const patchId = `${displayName}.${functionName}`;
const patch = this.patches.find(p => p.module == module && p.functionName == functionName) || this.makePatch(module, functionName, patchId);
if (!patch.proxyFunction) this.rePatch(patch);
const child = {
caller,
type,
id: patch.counter,
callback,
unpatch: () => {
patch.children.splice(patch.children.findIndex(cpatch => cpatch.id === child.id && cpatch.type === type), 1);
if (patch.children.length <= 0) {
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
if (patchNum < 0) return;
this.patches[patchNum].revert();
this.patches.splice(patchNum, 1);
}
}
};
patch.children.push(child);
patch.counter++;
return child.unpatch;
}
}

View File

@ -134,6 +134,25 @@ export class CoreUpdater {
}
}
const semverRegex = /^[0-9]+\.[0-9]+\.[0-9]+$/;
/**
* This works on basic semantic versioning e.g. "1.0.0".
*
* @param {string} currentVersion
* @param {string} content
* @returns {boolean} whether there is an update
*/
function semverComparator(currentVersion, remoteVersion) {
currentVersion = currentVersion.split(".").map((e) => {return parseInt(e);});
remoteVersion = remoteVersion.split(".").map((e) => {return parseInt(e);});
if (remoteVersion[0] > currentVersion[0]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] > currentVersion[1]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] == currentVersion[1] && remoteVersion[2] > currentVersion[2]) return true;
return false;
}
class AddonUpdater {
@ -176,7 +195,10 @@ class AddonUpdater {
if (this.pending.includes(filename)) return;
const info = this.cache[path.basename(filename)];
if (!info) return;
const hasUpdate = info.version > currentVersion;
let hasUpdate = info.update > currentVersion;
if (semverRegex.test(info.version) && semverRegex.test(currentVersion)) {
hasUpdate = semverComparator(currentVersion, info.version);
}
if (!hasUpdate) return;
this.pending.push(filename);
}

View File

@ -1,82 +0,0 @@
.bd-emote-menu {
min-height: 0;
}
.bd-emote-menu-inner {
padding: 8px 0 0 16px;
}
.bd-emote-scroller {
height: 100%;
}
.bd-emote-header {
display: flex;
align-items: center;
background: var(--background-secondary);
height: 32px;
padding: 0 4px;
position: sticky;
top: 0;
z-index: 2;
}
.bd-emote-header-inner {
cursor: pointer;
display: flex;
align-items: center;
color: var(--header-secondary);
font-size: 12px;
font-weight: 600;
transition: color 0.125s;
width: fit-content;
}
.bd-emote-header-inner:hover {
color: var(--header-primary);
}
.bd-emote-header-icon {
width: 16px;
height: 16px;
}
.bd-emote-header-icon svg {
max-height: 100%;
max-width: 100%;
}
.bd-emote-header-label {
overflow: hidden;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
margin: 0 8px;
}
.bd-emote-collapse-icon svg {
transition: transform 0.1s;
}
.bd-emote-collapse-icon.collapsed svg {
transform: rotate(-90deg);
}
.bd-emote-item {
display: inline-flex;
justify-content: center;
align-items: center;
padding: 2px;
border-radius: 5px;
width: 30px;
height: 30px;
position: relative;
}
.bd-emote-item:hover {
background: var(--background-accent);
}
.bd-emote-item img {
max-width: 100%;
}

View File

@ -1,208 +0,0 @@
.emotewrapper {
position: relative;
display: inline-flex;
object-fit: contain;
margin: -0.1em 0.05em -0.2em 0.1em;
vertical-align: top;
}
.emotewrapper.jumboable {
margin-bottom: 0;
margin-top: 0.2em;
vertical-align: -0.3em;
}
.emote {
object-fit: contain;
width: 1.375em;
height: 1.375em;
vertical-align: bottom;
}
.emote.jumboable {
width: 3rem;
height: 3rem;
min-height: 3rem;
}
.fav {
display: none;
position: absolute;
width: 15px;
height: 15px;
right: -7px;
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAzFBMVEUAAABQUFBMTExLS0tNTU1MTExNTU1NTU1MTExMTExNTU1LS0tEREBEREBEREBEREBJSUhLS0tLS0tEREBNTU1NTU1NTU1EREArKyhNTU1NTU0AAABMTExKSklMTExNTU1NTU1NTU1KSkpMTExKSkhNTU1KSkpISEZNTU1LS0tAQDxOTk5KSkpLS0tNTU1MTExMTEx/f39MTExMTExLS0pLS0tMTExNTU1NTU1LS0pNTU1NTU1NTU1NTU1NTU1NTUxNTU1NTU1NTUxMTEzB8C/5AAAAOnRSTlMAI8X96oWAgYSF68QBAg0PMCb9BIuLgQUD4N0Bh0mKhZSOQ4gcrKscaW8QRE6fmJyjAshASceG7cIpqQOxTQAAALVJREFUGFddx6FOA0EYAOGZvd07Qm6vVCAAgUUgQEDfX/YZMAigqaFN7iC5tsmPqGPUN/AvUVeoEbGOCElJz08Uzeixqu4AqomVVSNngOVjTqDGZSl3UFtPGV2ot2zaq96YM9p5Ddzcf/nTTAlj+/sNtNu8OcwkIsbPBtrUfMQeEhGQmHbmGIFMwLPzu6UMIwBNgToshgq8Nr2ki+Oy7ebDHp70LRPWB6OZgfWLWei7fJonOOsPCGA9kVlssOoAAAAASUVORK5CYII=");
border: none;
background-size: 100% 100%;
background-repeat: no-repeat;
background-color: #303030;
border-radius: 5px;
top: -7px;
cursor: pointer;
}
.fav.active {
background-color: yellow;
}
.emotewrapper:hover .fav {
display: block;
}
.emote.stop-animation {
animation: none;
}
.emoteflip,
.emotespinflip {
transform: scaleX(-1);
}
.emotespin {
animation: 1s emote-spin infinite linear;
}
.emote1spin {
animation: 1s emote-spin-reverse infinite linear;
}
.emotespin2 {
animation: 0.5s emote-spin infinite linear;
}
.emote2spin {
animation: 0.5s emote-spin-reverse infinite linear;
}
.emotespin3 {
animation: 0.2s emote-spin infinite linear;
}
.emote3spin {
animation: 0.2s emote-spin-reverse infinite linear;
}
.emotepulse {
animation: 1s emote-pulse infinite linear;
}
.emotetr {
transform: translateX(-3px);
}
.emotebl {
transform: translateY(-3px);
}
.emotebr {
transform: translate(-3px, -3px);
}
.emoteshake {
animation: 1s emote-shake infinite linear;
}
.emoteflap {
transform: scaleY(-1);
}
.emoteshake2 {
animation: emote-shake2 0.3s linear infinite;
}
.emoteshake3 {
animation: emote-shake3 0.1s linear infinite;
}
@keyframes emote-shake2 {
25% {
transform: translate(-1px, -1px);
}
50% {
transform: translate(-1px, 1px);
}
75% {
transform: translate(1px, 1px);
}
75% {
transform: translate(1px, -1px);
}
}
@keyframes emote-shake3 {
25% {
transform: translate(-1px, -1px);
}
50% {
transform: translate(-1px, 1px);
}
75% {
transform: translate(1px, 1px);
}
75% {
transform: translate(1px, -1px);
}
}
@keyframes emote-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes emote-spin-reverse {
from {
transform: rotate(0deg);
}
to {
transform: rotate(-360deg);
}
}
@keyframes emote-pulse {
0% {
-webkit-transform: scale(1, 1);
}
50% {
-webkit-transform: scale(1.2, 1.2);
}
100% {
-webkit-transform: scale(1, 1);
}
}
@keyframes emote-shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}

View File

@ -1,82 +0,0 @@
import {Settings, React, WebpackModules, Events, Strings} from "modules";
const TooltipWrapper = WebpackModules.getByPrototypes("renderTooltip");
export default class BDEmote extends React.Component {
constructor(props) {
super(props);
this.state = {
shouldAnimate: !this.animateOnHover,
isFavorite: this.props.isFavorite
};
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.onClick = this.onClick.bind(this);
this.toggleFavorite = this.toggleFavorite.bind(this);
}
get animateOnHover() {
return Settings.get("emotes", "general", "animateOnHover");
}
get label() {
return this.props.modifier ? `${this.props.name}:${this.props.modifier}` : this.props.name;
}
get modifierClass() {
return this.props.modifier ? ` emote${this.props.modifier}` : "";
}
onMouseEnter() {
if (!this.state.shouldAnimate && this.animateOnHover) this.setState({shouldAnimate: true});
}
onMouseLeave() {
if (this.state.shouldAnimate && this.animateOnHover) this.setState({shouldAnimate: false});
}
onClick(e) {
if (this.props.onClick) this.props.onClick(e);
}
toggleFavorite(e) {
e.preventDefault();
e.stopPropagation();
if (this.state.isFavorite) Events.emit("emotes-favorite-removed", this.label);
else Events.emit("emotes-favorite-added", this.label, this.props.url);
this.setState({isFavorite: !this.state.isFavorite});
}
render() {
return React.createElement(TooltipWrapper, {
color: "primary",
position: "top",
text: this.label,
delay: 750
},
(childProps) => {
return React.createElement("div", Object.assign({
className: "emotewrapper" + (this.props.jumboable ? " jumboable" : ""),
onMouseEnter: this.onMouseEnter,
onMouseLeave: this.onMouseLeave,
onClick: this.onClick
}, childProps),
React.createElement("img", {
draggable: false,
className: "emote" + this.modifierClass + (this.props.jumboable ? " jumboable" : "") + (!this.state.shouldAnimate ? " stop-animation" : ""),
dataModifier: this.props.modifier,
alt: this.label,
src: this.props.url
}),
React.createElement("input", {
className: "fav" + (this.state.isFavorite ? " active" : ""),
title: Strings.Emotes.favoriteAction,
type: "button",
onClick: this.toggleFavorite
})
);
});
}
}

View File

@ -1,36 +0,0 @@
import {React, WebpackModules} from "modules";
import EmoteModule from "../builtins/emotes/emotes";
const ContextMenuActions = WebpackModules.getByProps("openContextMenu");
const {MenuItem, MenuGroup} = WebpackModules.find(m => m.MenuRadioItem && !m.default) ?? {MenuItem: () => null, MenuGroup: () => null};
const ContextMenu = WebpackModules.getByProps("default", "MenuStyle")?.default;
const {ComponentDispatch} = WebpackModules.getByProps("ComponentDispatch") ?? {ComponentDispatch: () => null};
export default class EmoteIcon extends React.Component {
render() {
return <div className="bd-emote-item" onClick={this.handleOnClick.bind(this)} onContextMenu={this.handleOnContextMenu.bind(this)}>
<img src={this.props.url} alt={this.props.emote} title={this.props.emote}/>
</div>;
}
handleOnClick() {
this.insertText(this.props.emote);
}
handleOnContextMenu(e) {
ContextMenuActions.openContextMenu(e, () => <ContextMenu navId="EmoteContextMenu" onClose={ContextMenuActions.closeContextMenu}>
<MenuGroup>
<MenuItem label={EmoteModule.isFavorite(this.props.emote) ? "Remove Favorite" : "Add Favorite"} id="favorite" action={this.handlefavorite.bind(this)} onClose={ContextMenuActions.closeContextMenu}/>
</MenuGroup>
</ContextMenu>);
}
handlefavorite() {
ContextMenuActions.closeContextMenu();
EmoteModule.isFavorite(this.props.emote) ? EmoteModule.removeFavorite(this.props.emote) : EmoteModule.addFavorite(this.props.emote, this.props.url);
}
insertText(emote) {
ComponentDispatch.dispatchToLastSubscribed("INSERT_TEXT", {content: emote});
}
}

View File

@ -1,13 +0,0 @@
import {React, WebpackModules} from "modules";
const {ScrollerAuto: Scroller} = WebpackModules.getByProps("ScrollerAuto") ?? {ScrollerAuto: () => null};
export default class EmoteMenuCard extends React.Component {
render() {
return <div className={`bd-emote-menu`}>
<Scroller className="bd-emote-scroller">
<div className="bd-emote-menu-inner">
{this.props.children}
</div>
</Scroller>
</div>;
}
}

View File

@ -1,18 +0,0 @@
const path = require("path");
const asar = require("asar");
const emotes = path.resolve(__dirname, "..", "assets", "emotes");
const dist = path.resolve(__dirname, "..", "dist");
const bundleFile = path.join(dist, "emotes.asar");
const makeBundle = function() {
console.log("");
console.log("Generating bundle");
asar.createPackage(emotes, bundleFile).then(() => {
console.log(` ✅ Successfully created bundle ${bundleFile}`);
}).catch(err => {
console.log(` ❌ Could not build bundle: ${err.message}`);
});
};
makeBundle();

View File

@ -15,18 +15,13 @@ const discordPath = (function() {
const basedir = path.join(process.env.LOCALAPPDATA, release.replace(/ /g, ""));
if (!fs.existsSync(basedir)) throw new Error(`Cannot find directory for ${release}`);
const version = fs.readdirSync(basedir).filter(f => fs.lstatSync(path.join(basedir, f)).isDirectory() && f.split(".").length > 1).sort().reverse()[0];
resourcePath = path.join(basedir, version, "resources");
}
else if (process.platform === "darwin") {
const appPath = releaseInput === "canary" ? path.join("/Applications", "Discord Canary.app")
: releaseInput === "ptb" ? path.join("/Applications", "Discord PTB.app")
: useBdRelease && args[3] ? args[3] ? args[2] : args[2]
: path.join("/Applications", "Discord.app");
resourcePath = path.join(appPath, "Contents", "Resources");
// To account for discord_desktop_core-1 or any other number
const coreWrap = fs.readdirSync(path.join(basedir, version, "modules")).filter(e => e.indexOf("discord_desktop_core") === 0).sort().reverse()[0];
resourcePath = path.join(basedir, version, "modules", coreWrap, "discord_desktop_core");
}
else {
const userData = process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : path.join(process.env.HOME, ".config");
let userData = process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : path.join(process.env.HOME, ".config");
if (process.platform === "darwin") userData = path.join(process.env.HOME, "Library", "Application Support");
const basedir = path.join(userData, release.toLowerCase().replace(" ", ""));
if (!fs.existsSync(basedir)) return "";
const version = fs.readdirSync(basedir).filter(f => fs.lstatSync(path.join(basedir, f)).isDirectory() && f.split(".").length > 1).sort().reverse()[0];
@ -46,27 +41,11 @@ console.log(`Injecting into ${release}`);
if (!fs.existsSync(discordPath)) throw new Error(`Cannot find directory for ${release}`);
console.log(` ✅ Found ${release} in ${discordPath}`);
const appPath = process.platform === "win32" || process.platform === "darwin" ? path.join(discordPath, "app") : discordPath;
const packageJson = path.join(appPath, "package.json");
const indexJs = path.join(appPath, "index.js");
if (!fs.existsSync(appPath)) fs.mkdirSync(appPath);
if (fs.existsSync(packageJson)) fs.unlinkSync(packageJson);
const indexJs = path.join(discordPath, "index.js");
if (fs.existsSync(indexJs)) fs.unlinkSync(indexJs);
if (process.platform === "win32" || process.platform === "darwin") {
fs.writeFileSync(packageJson, JSON.stringify({
name: "betterdiscord",
main: "index.js",
}, null, 4));
console.log(" ✅ Wrote package.json");
fs.writeFileSync(indexJs, `require("${bdPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}");`);
}
else {
fs.writeFileSync(indexJs, `require("${bdPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}");\nmodule.exports = require("./core.asar");`);
}
fs.writeFileSync(indexJs, `require("${bdPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}");\nmodule.exports = require("./core.asar");`);
console.log(" ✅ Wrote index.js");
console.log("");
console.log(`Injection successful, please restart ${release}.`);
console.log(`Injection successful, please restart ${release}.`);