mirror of
https://github.com/neosubhamoy/pytubepp-helper.git
synced 2026-02-04 11:22:22 +05:30
Compare commits
41 Commits
v0.3.0-bet
...
v0.7.0-bet
51
.github/workflows/release.yml
vendored
51
.github/workflows/release.yml
vendored
@@ -12,14 +12,18 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# - platform: 'macos-latest'
|
||||
# args: '--target aarch64-apple-darwin'
|
||||
# - platform: 'macos-latest'
|
||||
# args: '--target x86_64-apple-darwin'
|
||||
- platform: 'macos-15'
|
||||
args: '--target aarch64-apple-darwin'
|
||||
arch: 'aarch64-apple-darwin'
|
||||
- platform: 'macos-15'
|
||||
args: '--target x86_64-apple-darwin'
|
||||
arch: 'x86_64-apple-darwin'
|
||||
- platform: 'ubuntu-22.04'
|
||||
args: ''
|
||||
arch: ''
|
||||
- platform: 'windows-latest'
|
||||
args: ''
|
||||
arch: ''
|
||||
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
@@ -35,13 +39,13 @@ jobs:
|
||||
- name: 📦 Setup node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: lts/*
|
||||
node-version: '22.11.0'
|
||||
cache: 'npm'
|
||||
|
||||
- name: 🛠️ install Rust stable
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
|
||||
targets: ${{ matrix.platform == 'macos-15' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
|
||||
|
||||
- name: 🛠️ Rust cache
|
||||
uses: swatinem/rust-cache@v2
|
||||
@@ -51,14 +55,47 @@ jobs:
|
||||
- name: 🛠️ Install frontend dependencies
|
||||
run: npm install
|
||||
|
||||
- name: 📄 Read CHANGELOG (Unix)
|
||||
if: matrix.platform != 'windows-latest'
|
||||
id: changelog_unix
|
||||
shell: bash
|
||||
run: |
|
||||
if [ -f CHANGELOG.md ]; then
|
||||
CONTENT=$(cat CHANGELOG.md)
|
||||
echo "content<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$CONTENT" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "content=No changelog found" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: 📄 Read CHANGELOG (Windows)
|
||||
if: matrix.platform == 'windows-latest'
|
||||
id: changelog_windows
|
||||
shell: pwsh
|
||||
run: |
|
||||
if (Test-Path "CHANGELOG.md") {
|
||||
$content = Get-Content -Path CHANGELOG.md -Raw
|
||||
"content<<EOF" >> $env:GITHUB_OUTPUT
|
||||
$content >> $env:GITHUB_OUTPUT
|
||||
"EOF" >> $env:GITHUB_OUTPUT
|
||||
} else {
|
||||
"content=No changelog found" >> $env:GITHUB_OUTPUT
|
||||
}
|
||||
|
||||
- name: 🚀 Build and publish
|
||||
uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TARGET_ARCH: ${{ matrix.arch }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
with:
|
||||
tagName: ${{ github.ref_name }}
|
||||
releaseName: ${{ github.event.repository.name }}-${{ github.ref_name }}
|
||||
releaseBody: 'See the assets to download this version and install.'
|
||||
releaseBody: ${{ matrix.platform == 'windows-latest' && steps.changelog_windows.outputs.content || steps.changelog_unix.outputs.content }}
|
||||
releaseDraft: true
|
||||
prerelease: false
|
||||
includeUpdaterJson: true
|
||||
updaterJsonPreferNsis: true
|
||||
args: ${{ matrix.args }}
|
||||
11
.gitignore
vendored
11
.gitignore
vendored
@@ -24,10 +24,13 @@ dist-ssr
|
||||
*.sw?
|
||||
|
||||
# Executables and manifests
|
||||
pytubepp-helper-msghost.exe
|
||||
pytubepp-helper-autostart.exe
|
||||
pytubepp-helper-msghost.json
|
||||
pytubepp-helper-msghost-moz.json
|
||||
src-tauri/pytubepp-helper-msghost.exe
|
||||
src-tauri/pytubepp-helper-autostart.exe
|
||||
src-tauri/pytubepp-helper-msghost.json
|
||||
src-tauri/pytubepp-helper-msghost-moz.json
|
||||
src-tauri/pytubepp-helper-msghost
|
||||
src-tauri/pytubepp-helper-autostart
|
||||
src-tauri/pytubepp-helper-autostart.plist
|
||||
|
||||
# Certificate files
|
||||
certificate.pfx
|
||||
|
||||
36
CHANGELOG.md
Normal file
36
CHANGELOG.md
Normal file
@@ -0,0 +1,36 @@
|
||||
### ✨ Changelog
|
||||
|
||||
- Migrated to Tauri v2
|
||||
- Added support for caption download
|
||||
- Added new Settings page
|
||||
- Added new Notifications page (will be used for app, component updates and broadcast messages)
|
||||
- Added dynamic websocket server port configuration option in settings
|
||||
- Added Node.js detection and installation option
|
||||
- Changed RPM ffmpeg-free dependency to ffmpeg (as full ffmpeg is required for embedding captions)
|
||||
- Improved single instance functionality by switching to tauri_plugin_single_instance from websocket based single instance detection
|
||||
- Enabled app-updater (for supported packaging formats in Windows - exe, msi, MacOS - app)
|
||||
- Minor fixes and improvements
|
||||
|
||||
### 📎 Minimum Requirements
|
||||
|
||||
- pytubepp v1.1.8
|
||||
- pytubepp-extension v0.2.0
|
||||
|
||||
### 📝 Notes
|
||||
|
||||
> IMPORTANT: Linux (Fedora) users must need to [enable](https://docs.fedoraproject.org/en-US/quick-docs/rpmfusion-setup/#_enabling_the_rpm_fusion_repositories_using_command_line_utilities) RPM Fusion free+nonfree repos before installing this update (to avoid 'ffmpeg not found' error while installing the RPM package)
|
||||
|
||||
> IMPORTANT: MacOS users must re-click the 'Register' button after updating
|
||||
|
||||
> This is an Un-Signed Build (Windows doesn't trust this Certificate so, it may flag this as malicious software, in that case, disable Windows SmartScreen and Defender, install it, and then re-enable them)
|
||||
|
||||
> This is an Un-Signed Build (MacOS doesn't trust this Certificate so, it may flag this as from 'unverified developer' and prevent it from opening, in that case, open Settings and allow it from 'Settings > Privacy and Security' section to get started)
|
||||
|
||||
### ⬇️ Download Section
|
||||
|
||||
| Arch\OS | Windows (msi) ⬆️ | Windows (exe) ⬆️ | Linux (deb) | Linux (rpm) | MacOS (dmg) | MacOS (app) ⬆️ |
|
||||
| :---- | :---- | :---- | :---- | :---- | :---- | :---- |
|
||||
| x86_64 | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_0.7.0_x64_en-US.msi) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_0.7.0_x64-setup.exe) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_0.7.0_amd64.deb) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper-0.7.0-1.x86_64.rpm) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_0.7.0_x64.dmg) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_x64.app.tar.gz) |
|
||||
| ARM64 | N/A | N/A | N/A | N/A | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_0.7.0_aarch64.dmg) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/download/v0.7.0-beta/pytubepp-helper_aarch64.app.tar.gz) |
|
||||
|
||||
> ⬆️ icon indicates this packaging format supports in-built app-updater
|
||||
89
README.md
89
README.md
@@ -8,67 +8,88 @@ A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Proces
|
||||
[](https://github.com/neosubhamoy/pytubepp-helper)
|
||||
[](https://github.com/neosubhamoy/pytubepp-helper)
|
||||
|
||||
#### **🌟 Loved this Project? Don't forget to Star this Repo to show us your appreciation !!**
|
||||
> **🥰 Liked this project? Please consider giving it a Star (🌟) on github to show us your appreciation and help the algorythm recommend this project to even more awesome people like you!**
|
||||
|
||||
### 💻 Supported Platforms
|
||||
- Windows 10 (v1803 or later) / 11
|
||||
- Linux (Debian / RHEL base) (GNOME only)
|
||||
- MacOS (Maybe Soon - looking for a MacBook user for testing :)
|
||||
- Linux (Debian/Ubuntu, Fedora/RHEL base)
|
||||
- MacOS (v10.13 or later)
|
||||
|
||||
### 📎 Pre-Requirements
|
||||
|
||||
- [Python (>3.8)](https://www.python.org/downloads/)
|
||||
- [Python](https://www.python.org/downloads/) (>3.8)
|
||||
- [FFmpeg](https://www.ffmpeg.org)
|
||||
- [Node.js](https://nodejs.org/en/download/)
|
||||
- [PytubePP](https://github.com/neosubhamoy/pytubepp)
|
||||
* These requirements can be installed using PytubePP Helper (post installation) if [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget) is installed in your system. *(for Windows users)
|
||||
* These requirements can be installed using PytubePP Helper (post installation) if [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget) (for Windows users) / [Homebrew](https://brew.sh) (for MacOS users) is installed in your system
|
||||
|
||||
### ⬇️ Download and Installation
|
||||
|
||||
1. Download the latest release based on your OS and CPU Architecture
|
||||
1. Download the latest [PytubePP Helper](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) release based on your OS and CPU Architecture
|
||||
|
||||
| Arch\OS | Windows | Linux | MacOS |
|
||||
| :---- | :---- | :---- | :---- |
|
||||
| x64 | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) | N/A |
|
||||
| x86 | N/A | N/A | N/A |
|
||||
| ARM | N/A | N/A | N/A |
|
||||
| x86_64 | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) |
|
||||
| ARM64 | ❌ N/A | ❌ N/A | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) |
|
||||
|
||||
* **>> Windows:**
|
||||
2. Install all [pre-requirements](https://github.com/neosubhamoy/pytubepp-helper#-pre-requirements) and [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) (follow next instructions based on your OS)
|
||||
|
||||
2. If you don't have any Pre-Requirements installed first install [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget). Then restart your Computer.
|
||||
> NOTE: You can install the pre-requirements from PytubePP Helper app GUI or manually running the commands in your system's terminal / command prompt, for manual installation follow this [guide](https://github.com/neosubhamoy/pytubepp#%EF%B8%8F-installation).
|
||||
|
||||
3. Now open PytubePP Helper (from system tray not from start menu or shotcut) you will see (blue) 'install' buttons. First click on the install button on the right side of 'Python', a cmd window will popup to install Python. after the installation is finished then close the cmd window and now install 'FFmpeg' by clicking on the next install button. after the installation is finished close the cmd window and restart your Computer.
|
||||
* **🪟 WINDOWS:**
|
||||
|
||||
4. Again open PytubePP Helper (from system tray not from start menu or shotcut) and install PytubePP at last. after it finishes you can close the cmd window. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper
|
||||
1. If you don't have any Pre-Requirements installed first install [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget). Then restart your Computer.
|
||||
|
||||
5. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
|
||||
2. Now open PytubePP Helper, you will see (blue) 'install' buttons. First click on the install button on the right side of 'Python', a cmd window will popup to install Python. after the installation is finished then close the cmd window and now install 'FFmpeg' by clicking on the next install button. after the installation is finished close the cmd window and restart your Computer (do same for Node.js).
|
||||
|
||||
6. PRO TIPS:
|
||||
- Make sure PytubePP Helper is always running in the background (system tray) otherwise PytubePP Extension will not work properly.
|
||||
- Always open PytubePP Helper from system tray if it's already running. if you open PytubePP Helper from start menu or shotcut when PytubePP Helper is already running in system tray then two instances of PytubePP Helper will run on the same time which may cause the app to malfunction!
|
||||
- PytubePP Helper by default always autostarts itself when Windows starts. Make sure autosart is not disabled for PytubePP Helper in Task Manager (Startup apps tab)
|
||||
3. Again open PytubePP Helper and install PytubePP at the end. after it finishes you can close the cmd window. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper
|
||||
|
||||
* **>> Linux:**
|
||||
4. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
|
||||
|
||||
> NOTE: Not all Debian / RHEL based distros are supported. Supported distros are: debian, ubuntu (tested on v24.04 LTS), pop, kali, rhel, fedora (tested on v40), centos, rocky. If your distro is not in the supported list it doesn't mean that 'the app will not run at all', so, test it yourself and if it doesn't work then you can request us to add support for your distro via creating a github issue.
|
||||
5. Pro Tips:
|
||||
- Make sure PytubePP Helper is always running in the background (system tray) otherwise PytubePP Extension will not work properly.
|
||||
- PytubePP Helper by default always autostarts itself when Windows starts. Make sure autostart is not disabled for PytubePP Helper in Task Manager (Startup apps tab)
|
||||
|
||||
> Sandboxed Browsers may not work properly (eg: Flatpak, Snaps) (have issue with: Browser NativeMessaging API [read here](https://github.com/flatpak/xdg-desktop-portal/issues/655))
|
||||
* **🐧 LINUX:**
|
||||
|
||||
2. For linux users Pre-Requirements are mostly fulfilled as 'Python' is pre installed in most linux distros and 'FFmpeg' is auto installed as a dependency while installing the .deb / .rpm package. You just need to install 'PytubePP' manually by clicking the blue 'install' button opening pytubepp-helper. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper.
|
||||
> ⚠️ NOTE: Most of the Debian / RHEL based distros are supported. Tested on: debian (v12), ubuntu (v24.04 LTS), fedora (v41). If your distro is not in the tested list it doesn't mean that 'the app will not run at all', so, test it yourself and if it doesn't work then you can request us to add support for your distro via creating a github issue.
|
||||
|
||||
> ⚠️ Sandboxed Browsers may not work properly (eg: Flatpak, Snaps) (have issue with: Browser NativeMessaging API [read here](https://github.com/flatpak/xdg-desktop-portal/issues/655)) (But, still try it yourself to see if it works)
|
||||
|
||||
1. For linux users Pre-Requirements are mostly fulfilled as 'Python' is pre installed in most linux distros and 'FFmpeg', 'Node.js' are auto installed as a dependency while installing the .deb / .rpm package. You just need to install 'PytubePP' manually by clicking the blue 'install' button opening pytubepp-helper. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper.
|
||||
|
||||
> Always make sure your system packages are up-to-date (you may face issues otherwise, the app may not open at all)
|
||||
|
||||
> If you are facing issues with installing 'libwebkit2gtk-4.0' as dependency of pytubepp-helper in Ubuntu 24.04 LTS follow this [guide](https://github.com/tauri-apps/tauri/issues/9662)
|
||||
> If you are facing issues with installing 'libwebkit2gtk-4.0' as dependency of pytubepp-helper in Ubuntu 24.04 LTS follow this [guide](https://github.com/tauri-apps/tauri/issues/9662) (* this issue is fixed in the latest version - v2 of tauri, this dependency is no longer required in the latest versions)
|
||||
|
||||
> 'AppIndicator' feature must be enabled for seemless experiance with pytubepp-helper. If your distro doesn't support this by default (eg: fedora) then you need to enable it for your GNOME desktop environment manually, using a GNOME shell extension: [AppIndicator and KStatusNotifierItem Support](https://extensions.gnome.org/extension/615/appindicator-support/)
|
||||
|
||||
3. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
|
||||
2. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
|
||||
|
||||
4. PRO TIPS:
|
||||
- Make sure PytubePP Helper is always running in the background (Appindicator) otherwise PytubePP Extension will not work properly.
|
||||
- Always open PytubePP Helper from Appindicator if it's already running. if you open PytubePP Helper from programs menu or shotcut when PytubePP Helper is already running in Appindicator then two instances of PytubePP Helper will run on the same time which may cause the app to malfunction!
|
||||
- PytubePP Helper by default always autostarts itself when Linux Distro starts. Make sure autosart is not disabled for PytubePP Helper in your distro's Startup Manager / Applications
|
||||
3. Pro Tips:
|
||||
- Make sure PytubePP Helper is always running in the background (Appindicator) otherwise PytubePP Extension will not work properly.
|
||||
- PytubePP Helper by default always autostarts itself when Linux Distro starts. Make sure autostart is not disabled for PytubePP Helper in your distro's Startup Manager / Applications
|
||||
|
||||
### ❔ How It Works
|
||||
* **🍎 MAC OS:**
|
||||
1. If you don't have any Pre-Requirements installed first install [Homebrew](https://brew.sh)
|
||||
|
||||
2. Python mostly comes pre-installed in MacOS, But on the case if you are running Python version older than 3.8 upgrade it to a newer version using Homebrew command: `brew upgrade python`
|
||||
|
||||
3. Now, open PytubePP Helper app and click on the (blue) install button on the right side of 'FFmpeg' to install it. Also, install 'Node.js' and 'PytubePP' following the same step.
|
||||
|
||||
4. Then, click on the 'Register' botton on the top right corner to register 'PytubePP Helper' in your system and also add it to your system's autostart entry. If you see a MacOS notification saying 'pytubepp-helper' is added as a startup app then it's done.
|
||||
|
||||
5. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper.
|
||||
|
||||
5. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
|
||||
|
||||
6. Pro Tips:
|
||||
- Make sure PytubePP Helper is always running in the background (top bar) otherwise PytubePP Extension will not work properly.
|
||||
- Always allow all the MacOS security popups if it's from 'pytubepp-helper' otherwise it will not function properly.
|
||||
- Don't quit 'pytubepp-helper' from the dock otherwise it will stop working (always use the close button to just hide the app window not fully quit it)
|
||||
- PytubePP Helper by default always autostarts itself when MacOS starts. Make sure autostart is not disabled for PytubePP Helper in Settings (General > Login Apps)
|
||||
|
||||
### 🤔 How It Works
|
||||
|
||||
- PytubePP Helper is an intermediate communicator between PytubePP Extension and Pytube Post Processor CLI interface. It is used as a bridge to estblish communication between the System Shell / CMD and Browser Extension, as a Browser Extension can not directly talk (execute commands) with System Shell / CMD for security reasons. Browser Extensions are isolated from the system too, the only way they can communicate with the system (native apps only) is nativeMessaging API provided by Chrome (other Browsers provides it too). So, PytubePP Helper uses that API to communicate with the Browser Extension and recives it's requests and processes the data from PytubePP CLI then genrates a response and sends it to the Browser Extension. For further understanding view the system design diagram of PytubePP Helper app below:
|
||||
|
||||
@@ -86,7 +107,6 @@ A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Proces
|
||||
|
||||
Want to be part of this? Feel free to contribute...!! Pull Requests are always welcome...!! (^_^) Follow these simple steps to start building:
|
||||
|
||||
* It is highly reccomended to use the same OS for which platform you want to build (eg: 'linux distro' for linux binaries, 'windows' for windows binaries)
|
||||
* Make sure to install Rust, Node.js and Git before proceeding.
|
||||
* Install tauri [Prerequisites](https://tauri.app/v1/guides/getting-started/prerequisites) for your OS / platform
|
||||
1. Fork this repo in your github account.
|
||||
@@ -96,12 +116,7 @@ Want to be part of this? Feel free to contribute...!! Pull Requests are always w
|
||||
```code
|
||||
npm install
|
||||
```
|
||||
4. Select the development platform directory (for which OS / platform you want to build / contribute now) (source code for each platform is separated) (eg: linux)
|
||||
```
|
||||
cd pytubepp-helper
|
||||
cd linux
|
||||
```
|
||||
5. Run development / build process
|
||||
4. Run development / build process
|
||||
```code
|
||||
npm run tauri dev
|
||||
```
|
||||
@@ -115,3 +130,5 @@ npm run tauri build
|
||||
### 📝 License
|
||||
|
||||
PytubePP Helper is Licensed under the [MIT license](https://github.com/neosubhamoy/pytubepp-helper/blob/main/LICENSE). Anyone can view, modify, use (personal and commercial) or distribute it's sources without any attribution and extra permissions.
|
||||
|
||||
⚖️ NOTE: YouTube is a trademark of Google LLC. Use of this trademark is subject to Google Permissions. Downloading and using Copyrighted YouTube Content for Commercial pourposes are not allowed by YouTube Terms without proper Permissions from the Creator. We don't promote this kinds of activity, You should use the downloaded contents wisely and at your own responsibility.
|
||||
22
copyFiles.aarch64-apple-darwin.js
Normal file
22
copyFiles.aarch64-apple-darwin.js
Normal file
@@ -0,0 +1,22 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const msghostSrc = path.join(__dirname, 'src-tauri', 'target', 'aarch64-apple-darwin', 'release', 'pytubepp-helper-msghost');
|
||||
const msghostDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost');
|
||||
const autostartPlistSrc = path.join(__dirname, 'src-tauri', 'autostart', 'pytubepp-helper-autostart.plist');
|
||||
const autostartPlistDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-autostart.plist');
|
||||
const msghostManifestMacChromeSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'chrome', 'com.neosubhamoy.pytubepp.helper.json');
|
||||
const msghostManifestMacChromeDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.json');
|
||||
const msghostManifestMacFirefoxSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'firefox', 'com.neosubhamoy.pytubepp.helper.json');
|
||||
const msghostManifestMacFirefoxDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost-moz.json');
|
||||
|
||||
fs.copyFileSync(msghostSrc, msghostDest);
|
||||
// fs.copyFileSync(autostartSrc, autostartDest);
|
||||
fs.copyFileSync(autostartPlistSrc, autostartPlistDest);
|
||||
fs.copyFileSync(msghostManifestMacChromeSrc, msghostManifestMacChromeDest);
|
||||
fs.copyFileSync(msghostManifestMacFirefoxSrc, msghostManifestMacFirefoxDest);
|
||||
console.log('Files copied successfully');
|
||||
@@ -7,15 +7,12 @@ const __dirname = path.dirname(__filename);
|
||||
|
||||
const msghostSrc = path.join(__dirname, 'src-tauri', 'target', 'release', 'pytubepp-helper-msghost.exe');
|
||||
const msghostDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.exe');
|
||||
const autostartSrc = path.join(__dirname, 'src-tauri', 'target', 'release', 'pytubepp-helper-autostart.exe');
|
||||
const autostartDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-autostart.exe');
|
||||
const msghostManifestWinChromeSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'windows', 'chrome', 'com.neosubhamoy.pytubepp.helper.json');
|
||||
const msghostManifestWinChromeDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.json');
|
||||
const msghostManifestWinFirefoxSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'windows', 'firefox', 'com.neosubhamoy.pytubepp.helper.json');
|
||||
const msghostManifestWinFirefoxDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost-moz.json');
|
||||
|
||||
fs.copyFileSync(msghostSrc, msghostDest);
|
||||
fs.copyFileSync(autostartSrc, autostartDest);
|
||||
fs.copyFileSync(msghostManifestWinChromeSrc, msghostManifestWinChromeDest);
|
||||
fs.copyFileSync(msghostManifestWinFirefoxSrc, msghostManifestWinFirefoxDest);
|
||||
console.log('Files copied successfully');
|
||||
21
copyFiles.x86_64-apple-darwin.js
Normal file
21
copyFiles.x86_64-apple-darwin.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const msghostSrc = path.join(__dirname, 'src-tauri', 'target', 'x86_64-apple-darwin', 'release', 'pytubepp-helper-msghost');
|
||||
const msghostDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost');
|
||||
const autostartPlistSrc = path.join(__dirname, 'src-tauri', 'autostart', 'pytubepp-helper-autostart.plist');
|
||||
const autostartPlistDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-autostart.plist');
|
||||
const msghostManifestMacChromeSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'chrome', 'com.neosubhamoy.pytubepp.helper.json');
|
||||
const msghostManifestMacChromeDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.json');
|
||||
const msghostManifestMacFirefoxSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'firefox', 'com.neosubhamoy.pytubepp.helper.json');
|
||||
const msghostManifestMacFirefoxDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost-moz.json');
|
||||
|
||||
fs.copyFileSync(msghostSrc, msghostDest);
|
||||
fs.copyFileSync(autostartPlistSrc, autostartPlistDest);
|
||||
fs.copyFileSync(msghostManifestMacChromeSrc, msghostManifestMacChromeDest);
|
||||
fs.copyFileSync(msghostManifestMacFirefoxSrc, msghostManifestMacFirefoxDest);
|
||||
console.log('Files copied successfully');
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Tauri + React + Typescript</title>
|
||||
<title>PytubePP Helper</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
1397
package-lock.json
generated
1397
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
24
package.json
24
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "pytubepp-helper",
|
||||
"private": true,
|
||||
"version": "0.3.0",
|
||||
"version": "0.7.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -10,20 +10,34 @@
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.10.0",
|
||||
"@radix-ui/react-icons": "^1.3.0",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@tauri-apps/api": "^1",
|
||||
"@radix-ui/react-label": "^2.1.1",
|
||||
"@radix-ui/react-progress": "^1.1.2",
|
||||
"@radix-ui/react-slot": "^1.1.1",
|
||||
"@radix-ui/react-toast": "^1.2.5",
|
||||
"@radix-ui/react-tooltip": "^1.1.7",
|
||||
"@tauri-apps/api": "^2.0.0",
|
||||
"@tauri-apps/plugin-fs": "^2.2.0",
|
||||
"@tauri-apps/plugin-notification": "^2.2.1",
|
||||
"@tauri-apps/plugin-os": "^2.2.0",
|
||||
"@tauri-apps/plugin-process": "^2.2.0",
|
||||
"@tauri-apps/plugin-shell": "^2.2.0",
|
||||
"@tauri-apps/plugin-updater": "^2.5.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.1",
|
||||
"dotenv": "^16.4.5",
|
||||
"lucide-react": "^0.436.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hook-form": "^7.54.2",
|
||||
"react-router-dom": "^7.1.3",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7"
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^1",
|
||||
"@tauri-apps/cli": "^2.2.7",
|
||||
"@types/node": "^22.2.0",
|
||||
"@types/react": "^18.2.15",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
3010
src-tauri/Cargo.lock
generated
3010
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,31 +1,45 @@
|
||||
[package]
|
||||
name = "pytubepp-helper"
|
||||
version = "0.3.0"
|
||||
version = "0.7.0"
|
||||
description = "PytubePP Helper"
|
||||
authors = ["neosubhamoy"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1", features = [] }
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "1", features = [ "os-all", "process-relaunch", "window-start-dragging", "window-close", "window-unmaximize", "process-exit", "window-show", "window-unminimize", "window-hide", "window-minimize", "window-maximize", "system-tray", "shell-all"] }
|
||||
tauri = { version = "2", features = ["tray-icon"] }
|
||||
directories = "5.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1.39.2", features = ["full"] }
|
||||
tokio-tungstenite = "*"
|
||||
futures-util = "0.3.30"
|
||||
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
|
||||
tauri-plugin-shell = "2"
|
||||
tauri-plugin-fs = "2"
|
||||
tauri-plugin-os = "2"
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-notification = "2"
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-single-instance = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
|
||||
[features]
|
||||
# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
|
||||
[lib]
|
||||
name = "pytubepp_helper_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
".",
|
||||
"msghost",
|
||||
"autostart"
|
||||
"msghost"
|
||||
]
|
||||
|
||||
7
src-tauri/autostart/Cargo.lock
generated
7
src-tauri/autostart/Cargo.lock
generated
@@ -1,7 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "pytubepp-helper-autostart"
|
||||
version = "0.1.0"
|
||||
@@ -1,12 +0,0 @@
|
||||
[package]
|
||||
name = "pytubepp-helper-autostart"
|
||||
version = "0.1.0"
|
||||
description = "PytubePP Helper (Autostart)"
|
||||
authors = ["neosubhamoy <hey@neosubhamoy.com>"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
websocket = "0.27.1"
|
||||
serde_json = "1.0"
|
||||
@@ -2,7 +2,7 @@
|
||||
Type=Application
|
||||
Name=pytubepp-helper
|
||||
Icon=pytubepp-helper
|
||||
Comment=pytubepp-helper autostart script
|
||||
Exec=/usr/bin/pytubepp-helper-autostart
|
||||
Comment=pytubepp-helper autostart
|
||||
Exec=/usr/bin/pytubepp-helper --hidden
|
||||
StartupNotify=false
|
||||
Terminal=false
|
||||
15
src-tauri/autostart/pytubepp-helper-autostart.plist
Normal file
15
src-tauri/autostart/pytubepp-helper-autostart.plist
Normal file
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.neosubhamoy.pytubepp.helper</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/Applications/pytubepp-helper.app/Contents/MacOS/pytubepp-helper</string>
|
||||
<string>--hidden</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,55 +0,0 @@
|
||||
#![windows_subsystem = "windows"]
|
||||
|
||||
use std::process::Command;
|
||||
use websocket::client::ClientBuilder;
|
||||
use websocket::OwnedMessage;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
|
||||
fn connect_with_retry(url: &str, max_attempts: u32) -> Result<websocket::sync::Client<std::net::TcpStream>, Box<dyn std::error::Error>> {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match ClientBuilder::new(url).unwrap().connect_insecure() {
|
||||
Ok(client) => {
|
||||
eprintln!("Successfully connected to Tauri app :)");
|
||||
return Ok(client);
|
||||
}
|
||||
Err(e) => {
|
||||
attempts += 1;
|
||||
if attempts >= max_attempts {
|
||||
return Err(Box::new(e));
|
||||
}
|
||||
let wait_time = Duration::from_secs(2u64.pow(attempts));
|
||||
eprintln!("Connection attempt {} failed. Retrying in {:?}...", attempts, wait_time);
|
||||
sleep(wait_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Launch the main application
|
||||
let _ = Command::new("pytubepp-helper")
|
||||
.spawn();
|
||||
|
||||
// Connect with the Tauri app
|
||||
let websocket_url = "ws://localhost:3030";
|
||||
eprintln!("Attempting to connect to {}", websocket_url);
|
||||
|
||||
let mut client = match connect_with_retry(websocket_url, 2) {
|
||||
Ok(client) => client,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to connect after multiple attempts: {:?}", e);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
// Send message to Tauri app
|
||||
client.send_message(&OwnedMessage::Text(serde_json::json!({
|
||||
"url": "",
|
||||
"command": "autostart",
|
||||
"argument": ""
|
||||
}).to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
21
src-tauri/capabilities/default.json
Normal file
21
src-tauri/capabilities/default.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "main-capability",
|
||||
"description": "default permissions",
|
||||
"local": true,
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"shell:default",
|
||||
"os:default",
|
||||
"fs:default",
|
||||
"process:default",
|
||||
"notification:default",
|
||||
"updater:default",
|
||||
"core:window:allow-hide",
|
||||
"fs:allow-app-write",
|
||||
"fs:allow-app-write-recursive"
|
||||
]
|
||||
}
|
||||
133
src-tauri/capabilities/shell.json
Normal file
133
src-tauri/capabilities/shell.json
Normal file
@@ -0,0 +1,133 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "shell-scope",
|
||||
"description": "allowed shell scopes",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
{
|
||||
"identifier": "shell:allow-execute",
|
||||
"allow": [
|
||||
{
|
||||
"name": "detect-windows",
|
||||
"cmd": "systeminfo",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-macos",
|
||||
"cmd": "sw_vers",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-distro",
|
||||
"cmd": "grep",
|
||||
"args": [
|
||||
"^ID=",
|
||||
"/etc/os-release"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "detect-pkgmngr",
|
||||
"cmd": "sh",
|
||||
"args": [
|
||||
"-c",
|
||||
"command -v apt || command -v dnf || command -v pacman"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-apt-installed",
|
||||
"cmd": "apt",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-dnf-installed",
|
||||
"cmd": "dnf",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-python3-installed",
|
||||
"cmd": "python3",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-pip3-installed",
|
||||
"cmd": "pip3",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-winget-installed",
|
||||
"cmd": "winget",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-homebrew-installed",
|
||||
"cmd": "brew",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-python-installed",
|
||||
"cmd": "python",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-pip-installed",
|
||||
"cmd": "pip",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-ffmpeg-installed",
|
||||
"cmd": "ffmpeg",
|
||||
"args": [
|
||||
"-version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-nodejs-installed",
|
||||
"cmd": "node",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "is-pytubepp-installed",
|
||||
"cmd": "pytubepp",
|
||||
"args": [
|
||||
"--version"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "fetch-video-info",
|
||||
"cmd": "pytubepp",
|
||||
"args": [
|
||||
{
|
||||
"validator": "\\S+"
|
||||
},
|
||||
"--raw-info"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"platforms": [
|
||||
"windows",
|
||||
"macOS",
|
||||
"linux"
|
||||
]
|
||||
}
|
||||
15
src-tauri/installer/windows/nsis-hooks.nsi
Normal file
15
src-tauri/installer/windows/nsis-hooks.nsi
Normal file
@@ -0,0 +1,15 @@
|
||||
!macro NSIS_HOOK_POSTINSTALL
|
||||
; Add Registry Keys for Chrome Native Messaging Host
|
||||
WriteRegStr HKCU "Software\Google\Chrome\NativeMessagingHosts\com.neosubhamoy.pytubepp.helper" "" "$INSTDIR\pytubepp-helper-msghost.json"
|
||||
; Add Registry Keys for Firefox Native Messaging Host
|
||||
WriteRegStr HKCU "Software\Mozilla\NativeMessagingHosts\com.neosubhamoy.pytubepp.helper" "" "$INSTDIR\pytubepp-helper-msghost-moz.json"
|
||||
; Add entry for automatic startup with Windows
|
||||
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}" "$\"$INSTDIR\pytubepp-helper.exe$\" --hidden"
|
||||
!macroend
|
||||
|
||||
!macro NSIS_HOOK_POSTUNINSTALL
|
||||
; Remove the Registry entries
|
||||
DeleteRegKey HKCU "Software\Google\Chrome\NativeMessagingHosts\com.neosubhamoy.pytubepp.helper"
|
||||
DeleteRegKey HKCU "Software\Mozilla\NativeMessagingHosts\com.neosubhamoy.pytubepp.helper"
|
||||
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
||||
!macroend
|
||||
@@ -1,770 +0,0 @@
|
||||
Unicode true
|
||||
; Set the compression algorithm. Default is LZMA.
|
||||
!if "" == ""
|
||||
SetCompressor /SOLID lzma
|
||||
!else
|
||||
SetCompressor /SOLID ""
|
||||
!endif
|
||||
|
||||
!include MUI2.nsh
|
||||
!include FileFunc.nsh
|
||||
!include x64.nsh
|
||||
!include WordFunc.nsh
|
||||
!include "StrFunc.nsh"
|
||||
!include "Win\COM.nsh"
|
||||
!include "Win\Propkey.nsh"
|
||||
${StrCase}
|
||||
${StrLoc}
|
||||
|
||||
!define MANUFACTURER "neosubhamoy"
|
||||
!define PRODUCTNAME "pytubepp-helper"
|
||||
!define VERSION "0.3.0"
|
||||
!define VERSIONWITHBUILD "0.3.0.0"
|
||||
!define SHORTDESCRIPTION "PytubePP Helper"
|
||||
!define INSTALLMODE "currentUser"
|
||||
!define LICENSE "..\..\..\..\..\LICENSE"
|
||||
!define INSTALLERICON ""
|
||||
!define SIDEBARIMAGE ""
|
||||
!define HEADERIMAGE ""
|
||||
!define MAINBINARYNAME "pytubepp-helper"
|
||||
!define MAINBINARYSRCPATH "..\..\pytubepp-helper.exe"
|
||||
!define BUNDLEID "com.neosubhamoy.pytubepp.helper"
|
||||
!define COPYRIGHT "© Subhamoy Biswas - All Rights Reserved"
|
||||
!define OUTFILE "nsis-output.exe"
|
||||
!define ARCH "x64"
|
||||
!define PLUGINSPATH ""
|
||||
!define ALLOWDOWNGRADES "true"
|
||||
!define DISPLAYLANGUAGESELECTOR ""
|
||||
!define INSTALLWEBVIEW2MODE "downloadBootstrapper"
|
||||
!define WEBVIEW2INSTALLERARGS "/silent"
|
||||
!define WEBVIEW2BOOTSTRAPPERPATH ""
|
||||
!define WEBVIEW2INSTALLERPATH ""
|
||||
!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}"
|
||||
!define MANUPRODUCTKEY "Software\${MANUFACTURER}\${PRODUCTNAME}"
|
||||
!define UNINSTALLERSIGNCOMMAND ""
|
||||
!define ESTIMATEDSIZE "0x002311"
|
||||
!define AUTOSTART_EXEC "pytubepp-helper-autostart.exe"
|
||||
!define CHROME_REG_PATH "Software\Google\Chrome\NativeMessagingHosts\com.neosubhamoy.pytubepp.helper"
|
||||
!define FIREFOX_REG_PATH "Software\Mozilla\NativeMessagingHosts\com.neosubhamoy.pytubepp.helper"
|
||||
!define RUN_REG_PATH "Software\Microsoft\Windows\CurrentVersion\Run"
|
||||
|
||||
Name "${PRODUCTNAME}"
|
||||
BrandingText "${COPYRIGHT}"
|
||||
OutFile "${OUTFILE}"
|
||||
|
||||
VIProductVersion "${VERSIONWITHBUILD}"
|
||||
VIAddVersionKey "ProductName" "${PRODUCTNAME}"
|
||||
VIAddVersionKey "FileDescription" "${SHORTDESCRIPTION}"
|
||||
VIAddVersionKey "LegalCopyright" "${COPYRIGHT}"
|
||||
VIAddVersionKey "FileVersion" "${VERSION}"
|
||||
VIAddVersionKey "ProductVersion" "${VERSION}"
|
||||
|
||||
; Plugins path, currently exists for linux only
|
||||
!if "${PLUGINSPATH}" != ""
|
||||
!addplugindir "${PLUGINSPATH}"
|
||||
!endif
|
||||
|
||||
!if "${UNINSTALLERSIGNCOMMAND}" != ""
|
||||
!uninstfinalize '${UNINSTALLERSIGNCOMMAND}'
|
||||
!endif
|
||||
|
||||
; Handle install mode, `perUser`, `perMachine` or `both`
|
||||
!if "${INSTALLMODE}" == "perMachine"
|
||||
RequestExecutionLevel highest
|
||||
!endif
|
||||
|
||||
!if "${INSTALLMODE}" == "currentUser"
|
||||
RequestExecutionLevel user
|
||||
!endif
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!define MULTIUSER_MUI
|
||||
!define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}"
|
||||
!define MULTIUSER_INSTALLMODE_COMMANDLINE
|
||||
!if "${ARCH}" == "x64"
|
||||
!define MULTIUSER_USE_PROGRAMFILES64
|
||||
!else if "${ARCH}" == "arm64"
|
||||
!define MULTIUSER_USE_PROGRAMFILES64
|
||||
!endif
|
||||
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}"
|
||||
!define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser"
|
||||
!define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME
|
||||
!define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation
|
||||
!define MULTIUSER_EXECUTIONLEVEL Highest
|
||||
!include MultiUser.nsh
|
||||
!endif
|
||||
|
||||
; installer icon
|
||||
!if "${INSTALLERICON}" != ""
|
||||
!define MUI_ICON "${INSTALLERICON}"
|
||||
!endif
|
||||
|
||||
; installer sidebar image
|
||||
!if "${SIDEBARIMAGE}" != ""
|
||||
!define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}"
|
||||
!endif
|
||||
|
||||
; installer header image
|
||||
!if "${HEADERIMAGE}" != ""
|
||||
!define MUI_HEADERIMAGE
|
||||
!define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}"
|
||||
!endif
|
||||
|
||||
; Define registry key to store installer language
|
||||
!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"
|
||||
!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}"
|
||||
!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"
|
||||
|
||||
; Installer pages, must be ordered as they appear
|
||||
; 1. Welcome Page
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
|
||||
; 2. License Page (if defined)
|
||||
!if "${LICENSE}" != ""
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_LICENSE "${LICENSE}"
|
||||
!endif
|
||||
|
||||
; 3. Install mode (if it is set to `both`)
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MULTIUSER_PAGE_INSTALLMODE
|
||||
!endif
|
||||
|
||||
|
||||
; 4. Custom page to ask user if he wants to reinstall/uninstall
|
||||
; only if a previous installtion was detected
|
||||
Var ReinstallPageCheck
|
||||
Page custom PageReinstall PageLeaveReinstall
|
||||
Function PageReinstall
|
||||
; Uninstall previous WiX installation if exists.
|
||||
;
|
||||
; A WiX installer stores the isntallation info in registry
|
||||
; using a UUID and so we have to loop through all keys under
|
||||
; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`
|
||||
; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER}
|
||||
;
|
||||
; This has a potentional issue that there maybe another installation that matches
|
||||
; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer,
|
||||
; however, this should be fine since the user will have to confirm the uninstallation
|
||||
; and they can chose to abort it if doesn't make sense.
|
||||
StrCpy $0 0
|
||||
wix_loop:
|
||||
EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0
|
||||
StrCmp $1 "" wix_done ; Exit loop if there is no more keys to loop on
|
||||
IntOp $0 $0 + 1
|
||||
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName"
|
||||
ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher"
|
||||
StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop
|
||||
ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString"
|
||||
${StrCase} $R1 $R0 "L"
|
||||
${StrLoc} $R0 $R1 "msiexec" ">"
|
||||
StrCmp $R0 0 0 wix_done
|
||||
StrCpy $R7 "wix"
|
||||
StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1"
|
||||
Goto compare_version
|
||||
wix_done:
|
||||
|
||||
; Check if there is an existing installation, if not, abort the reinstall page
|
||||
ReadRegStr $R0 SHCTX "${UNINSTKEY}" ""
|
||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||
${IfThen} "$R0$R1" == "" ${|} Abort ${|}
|
||||
|
||||
; Compare this installar version with the existing installation
|
||||
; and modify the messages presented to the user accordingly
|
||||
compare_version:
|
||||
StrCpy $R4 "$(older)"
|
||||
${If} $R7 == "wix"
|
||||
ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
|
||||
${Else}
|
||||
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
|
||||
${EndIf}
|
||||
${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
|
||||
|
||||
nsis_tauri_utils::SemverCompare "${VERSION}" $R0
|
||||
Pop $R0
|
||||
; Reinstalling the same version
|
||||
${If} $R0 == 0
|
||||
StrCpy $R1 "$(alreadyInstalledLong)"
|
||||
StrCpy $R2 "$(addOrReinstall)"
|
||||
StrCpy $R3 "$(uninstallApp)"
|
||||
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)"
|
||||
StrCpy $R5 "2"
|
||||
; Upgrading
|
||||
${ElseIf} $R0 == 1
|
||||
StrCpy $R1 "$(olderOrUnknownVersionInstalled)"
|
||||
StrCpy $R2 "$(uninstallBeforeInstalling)"
|
||||
StrCpy $R3 "$(dontUninstall)"
|
||||
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
|
||||
StrCpy $R5 "1"
|
||||
; Downgrading
|
||||
${ElseIf} $R0 == -1
|
||||
StrCpy $R1 "$(newerVersionInstalled)"
|
||||
StrCpy $R2 "$(uninstallBeforeInstalling)"
|
||||
!if "${ALLOWDOWNGRADES}" == "true"
|
||||
StrCpy $R3 "$(dontUninstall)"
|
||||
!else
|
||||
StrCpy $R3 "$(dontUninstallDowngrade)"
|
||||
!endif
|
||||
!insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)"
|
||||
StrCpy $R5 "1"
|
||||
${Else}
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
Call SkipIfPassive
|
||||
|
||||
nsDialogs::Create 1018
|
||||
Pop $R4
|
||||
${IfThen} $(^RTL) == 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
|
||||
|
||||
${NSD_CreateLabel} 0 0 100% 24u $R1
|
||||
Pop $R1
|
||||
|
||||
${NSD_CreateRadioButton} 30u 50u -30u 8u $R2
|
||||
Pop $R2
|
||||
${NSD_OnClick} $R2 PageReinstallUpdateSelection
|
||||
|
||||
${NSD_CreateRadioButton} 30u 70u -30u 8u $R3
|
||||
Pop $R3
|
||||
; disable this radio button if downgrading and downgrades are disabled
|
||||
!if "${ALLOWDOWNGRADES}" == "false"
|
||||
${IfThen} $R0 == -1 ${|} EnableWindow $R3 0 ${|}
|
||||
!endif
|
||||
${NSD_OnClick} $R3 PageReinstallUpdateSelection
|
||||
|
||||
; Check the first radio button if this the first time
|
||||
; we enter this page or if the second button wasn't
|
||||
; selected the last time we were on this page
|
||||
${If} $ReinstallPageCheck != 2
|
||||
SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0
|
||||
${Else}
|
||||
SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0
|
||||
${EndIf}
|
||||
|
||||
${NSD_SetFocus} $R2
|
||||
nsDialogs::Show
|
||||
FunctionEnd
|
||||
Function PageReinstallUpdateSelection
|
||||
${NSD_GetState} $R2 $R1
|
||||
${If} $R1 == ${BST_CHECKED}
|
||||
StrCpy $ReinstallPageCheck 1
|
||||
${Else}
|
||||
StrCpy $ReinstallPageCheck 2
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
Function PageLeaveReinstall
|
||||
${NSD_GetState} $R2 $R1
|
||||
|
||||
; $R5 holds whether we are reinstalling the same version or not
|
||||
; $R5 == "1" -> different versions
|
||||
; $R5 == "2" -> same version
|
||||
;
|
||||
; $R1 holds the radio buttons state. its meaning is dependant on the context
|
||||
StrCmp $R5 "1" 0 +2 ; Existing install is not the same version?
|
||||
StrCmp $R1 "1" reinst_uninstall reinst_done ; $R1 == "1", then user chose to uninstall existing version, otherwise skip uninstalling
|
||||
StrCmp $R1 "1" reinst_done ; Same version? skip uninstalling
|
||||
|
||||
reinst_uninstall:
|
||||
HideWindow
|
||||
ClearErrors
|
||||
|
||||
${If} $R7 == "wix"
|
||||
ReadRegStr $R1 HKLM "$R6" "UninstallString"
|
||||
ExecWait '$R1' $0
|
||||
${Else}
|
||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||
ExecWait '$R1 /P _?=$4' $0
|
||||
${EndIf}
|
||||
|
||||
BringToFront
|
||||
|
||||
${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code
|
||||
|
||||
${If} $0 <> 0
|
||||
${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
${If} $0 = 1 ; User aborted uninstaller?
|
||||
StrCmp $R5 "2" 0 +2 ; Is the existing install the same version?
|
||||
Quit ; ...yes, already installed, we are done
|
||||
Abort
|
||||
${EndIf}
|
||||
MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)"
|
||||
Abort
|
||||
${Else}
|
||||
StrCpy $0 $R1 1
|
||||
${IfThen} $0 == '"' ${|} StrCpy $R1 $R1 -1 1 ${|} ; Strip quotes from UninstallString
|
||||
Delete $R1
|
||||
RMDir $INSTDIR
|
||||
${EndIf}
|
||||
reinst_done:
|
||||
FunctionEnd
|
||||
|
||||
; 5. Choose install directoy page
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
|
||||
; 6. Start menu shortcut page
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
Var AppStartMenuFolder
|
||||
!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder
|
||||
|
||||
; 7. Installation page
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
|
||||
; 8. Finish page
|
||||
;
|
||||
; Don't auto jump to finish page after installation page,
|
||||
; because the installation page has useful info that can be used debug any issues with the installer.
|
||||
!define MUI_FINISHPAGE_NOAUTOCLOSE
|
||||
; Use show readme button in the finish page as a button create a desktop shortcut
|
||||
!define MUI_FINISHPAGE_SHOWREADME
|
||||
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateDesktopShortcut
|
||||
; Show run app after installation.
|
||||
!define MUI_FINISHPAGE_RUN
|
||||
!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
|
||||
Function RunMainBinary
|
||||
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" ""
|
||||
FunctionEnd
|
||||
|
||||
; Uninstaller Pages
|
||||
; 1. Confirm uninstall page
|
||||
Var DeleteAppDataCheckbox
|
||||
Var DeleteAppDataCheckboxState
|
||||
!define /ifndef WS_EX_LAYOUTRTL 0x00400000
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow
|
||||
Function un.ConfirmShow
|
||||
FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog
|
||||
${If} $(^RTL) == 1
|
||||
System::Call 'USER32::CreateWindowEx(i${__NSD_CheckBox_EXSTYLE}|${WS_EX_LAYOUTRTL},t"${__NSD_CheckBox_CLASS}",t "$(deleteAppData)",i${__NSD_CheckBox_STYLE},i 50,i 100,i 400, i 25,i$1,i0,i0,i0)i.s'
|
||||
${Else}
|
||||
System::Call 'USER32::CreateWindowEx(i${__NSD_CheckBox_EXSTYLE},t"${__NSD_CheckBox_CLASS}",t "$(deleteAppData)",i${__NSD_CheckBox_STYLE},i 0,i 100,i 400, i 25,i$1,i0,i0,i0)i.s'
|
||||
${EndIf}
|
||||
Pop $DeleteAppDataCheckbox
|
||||
SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1
|
||||
SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1
|
||||
FunctionEnd
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave
|
||||
Function un.ConfirmLeave
|
||||
SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState
|
||||
FunctionEnd
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
|
||||
; 2. Uninstalling Page
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
;Languages
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
!insertmacro MUI_RESERVEFILE_LANGDLL
|
||||
!include "English.nsh"
|
||||
|
||||
!macro SetContext
|
||||
!if "${INSTALLMODE}" == "currentUser"
|
||||
SetShellVarContext current
|
||||
!else if "${INSTALLMODE}" == "perMachine"
|
||||
SetShellVarContext all
|
||||
!endif
|
||||
|
||||
${If} ${RunningX64}
|
||||
!if "${ARCH}" == "x64"
|
||||
SetRegView 64
|
||||
!else if "${ARCH}" == "arm64"
|
||||
SetRegView 64
|
||||
!else
|
||||
SetRegView 32
|
||||
!endif
|
||||
${EndIf}
|
||||
!macroend
|
||||
|
||||
Var PassiveMode
|
||||
Function .onInit
|
||||
${GetOptions} $CMDLINE "/P" $PassiveMode
|
||||
IfErrors +2 0
|
||||
StrCpy $PassiveMode 1
|
||||
|
||||
!if "${DISPLAYLANGUAGESELECTOR}" == "true"
|
||||
!insertmacro MUI_LANGDLL_DISPLAY
|
||||
!endif
|
||||
|
||||
!insertmacro SetContext
|
||||
|
||||
${If} $INSTDIR == ""
|
||||
; Set default install location
|
||||
!if "${INSTALLMODE}" == "perMachine"
|
||||
${If} ${RunningX64}
|
||||
!if "${ARCH}" == "x64"
|
||||
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
|
||||
!else if "${ARCH}" == "arm64"
|
||||
StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}"
|
||||
!else
|
||||
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
|
||||
!endif
|
||||
${Else}
|
||||
StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}"
|
||||
${EndIf}
|
||||
!else if "${INSTALLMODE}" == "currentUser"
|
||||
StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}"
|
||||
!endif
|
||||
|
||||
Call RestorePreviousInstallLocation
|
||||
${EndIf}
|
||||
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!insertmacro MULTIUSER_INIT
|
||||
!endif
|
||||
FunctionEnd
|
||||
|
||||
|
||||
Section EarlyChecks
|
||||
; Abort silent installer if downgrades is disabled
|
||||
!if "${ALLOWDOWNGRADES}" == "false"
|
||||
IfSilent 0 silent_downgrades_done
|
||||
; If downgrading
|
||||
${If} $R0 == -1
|
||||
System::Call 'kernel32::AttachConsole(i -1)i.r0'
|
||||
${If} $0 != 0
|
||||
System::Call 'kernel32::GetStdHandle(i -11)i.r0'
|
||||
System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color
|
||||
FileWrite $0 "$(silentDowngrades)"
|
||||
${EndIf}
|
||||
Abort
|
||||
${EndIf}
|
||||
silent_downgrades_done:
|
||||
!endif
|
||||
|
||||
SectionEnd
|
||||
|
||||
Section WebView2
|
||||
; Check if Webview2 is already installed and skip this section
|
||||
${If} ${RunningX64}
|
||||
ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
|
||||
${Else}
|
||||
ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
|
||||
${EndIf}
|
||||
ReadRegStr $5 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
|
||||
|
||||
StrCmp $4 "" 0 webview2_done
|
||||
StrCmp $5 "" 0 webview2_done
|
||||
|
||||
; Webview2 install modes
|
||||
!if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper"
|
||||
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
DetailPrint "$(webview2Downloading)"
|
||||
NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
Pop $0
|
||||
${If} $0 == 0
|
||||
DetailPrint "$(webview2DownloadSuccess)"
|
||||
${Else}
|
||||
DetailPrint "$(webview2DownloadError)"
|
||||
Abort "$(webview2AbortError)"
|
||||
${EndIf}
|
||||
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
Goto install_webview2
|
||||
!endif
|
||||
|
||||
!if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper"
|
||||
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}"
|
||||
DetailPrint "$(installingWebview2)"
|
||||
StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe"
|
||||
Goto install_webview2
|
||||
!endif
|
||||
|
||||
!if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller"
|
||||
Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
|
||||
File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}"
|
||||
DetailPrint "$(installingWebview2)"
|
||||
StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe"
|
||||
Goto install_webview2
|
||||
!endif
|
||||
|
||||
Goto webview2_done
|
||||
|
||||
install_webview2:
|
||||
DetailPrint "$(installingWebview2)"
|
||||
; $6 holds the path to the webview2 installer
|
||||
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
|
||||
${If} $1 == 0
|
||||
DetailPrint "$(webview2InstallSuccess)"
|
||||
${Else}
|
||||
DetailPrint "$(webview2InstallError)"
|
||||
Abort "$(webview2AbortError)"
|
||||
${EndIf}
|
||||
webview2_done:
|
||||
SectionEnd
|
||||
|
||||
!macro CheckIfAppIsRunning
|
||||
!if "${INSTALLMODE}" == "currentUser"
|
||||
nsis_tauri_utils::FindProcessCurrentUser "${MAINBINARYNAME}.exe"
|
||||
!else
|
||||
nsis_tauri_utils::FindProcess "${MAINBINARYNAME}.exe"
|
||||
!endif
|
||||
Pop $R0
|
||||
${If} $R0 = 0
|
||||
IfSilent kill 0
|
||||
${IfThen} $PassiveMode != 1 ${|} MessageBox MB_OKCANCEL "$(appRunningOkKill)" IDOK kill IDCANCEL cancel ${|}
|
||||
kill:
|
||||
!if "${INSTALLMODE}" == "currentUser"
|
||||
nsis_tauri_utils::KillProcessCurrentUser "${MAINBINARYNAME}.exe"
|
||||
!else
|
||||
nsis_tauri_utils::KillProcess "${MAINBINARYNAME}.exe"
|
||||
!endif
|
||||
Pop $R0
|
||||
Sleep 500
|
||||
${If} $R0 = 0
|
||||
Goto app_check_done
|
||||
${Else}
|
||||
IfSilent silent ui
|
||||
silent:
|
||||
System::Call 'kernel32::AttachConsole(i -1)i.r0'
|
||||
${If} $0 != 0
|
||||
System::Call 'kernel32::GetStdHandle(i -11)i.r0'
|
||||
System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color
|
||||
FileWrite $0 "$(appRunning)$\n"
|
||||
${EndIf}
|
||||
Abort
|
||||
ui:
|
||||
Abort "$(failedToKillApp)"
|
||||
${EndIf}
|
||||
cancel:
|
||||
Abort "$(appRunning)"
|
||||
${EndIf}
|
||||
app_check_done:
|
||||
!macroend
|
||||
|
||||
Section Install
|
||||
SetOutPath $INSTDIR
|
||||
|
||||
!insertmacro CheckIfAppIsRunning
|
||||
|
||||
; Copy main executable
|
||||
File "${MAINBINARYSRCPATH}"
|
||||
|
||||
; Copy resources
|
||||
CreateDirectory "$INSTDIR\"
|
||||
File /a "/oname=pytubepp-helper-autostart.exe" "..\..\..\..\pytubepp-helper-autostart.exe"
|
||||
File /a "/oname=pytubepp-helper-msghost-moz.json" "..\..\..\..\pytubepp-helper-msghost-moz.json"
|
||||
File /a "/oname=pytubepp-helper-msghost.exe" "..\..\..\..\pytubepp-helper-msghost.exe"
|
||||
File /a "/oname=pytubepp-helper-msghost.json" "..\..\..\..\pytubepp-helper-msghost.json"
|
||||
|
||||
; Copy external binaries
|
||||
|
||||
; Create uninstaller
|
||||
WriteUninstaller "$INSTDIR\uninstall.exe"
|
||||
|
||||
; Save $INSTDIR in registry for future installations
|
||||
WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
; Save install mode to be selected by default for the next installation such as updating
|
||||
; or when uninstalling
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1
|
||||
!endif
|
||||
|
||||
; Registry information for add/remove programs
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}"
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\""
|
||||
WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
|
||||
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1"
|
||||
WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1"
|
||||
WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "${ESTIMATEDSIZE}"
|
||||
|
||||
; Add Registry Keys for Chrome Native Messaging Host
|
||||
WriteRegStr HKCU "${CHROME_REG_PATH}" "" "$INSTDIR\pytubepp-helper-msghost.json"
|
||||
|
||||
; Add Registry Keys for Firefox Native Messaging Host
|
||||
WriteRegStr HKCU "${FIREFOX_REG_PATH}" "" "$INSTDIR\pytubepp-helper-msghost-moz.json"
|
||||
|
||||
; Add entry for automatic startup with Windows
|
||||
WriteRegStr HKCU "${RUN_REG_PATH}" "${PRODUCTNAME}" "$\"$INSTDIR\${AUTOSTART_EXEC}$\""
|
||||
|
||||
; Create start menu shortcut (GUI)
|
||||
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application
|
||||
Call CreateStartMenuShortcut
|
||||
!insertmacro MUI_STARTMENU_WRITE_END
|
||||
|
||||
; Create shortcuts for silent and passive installers, which
|
||||
; can be disabled by passing `/NS` flag
|
||||
; GUI installer has buttons for users to control creating them
|
||||
IfSilent check_ns_flag 0
|
||||
${IfThen} $PassiveMode == 1 ${|} Goto check_ns_flag ${|}
|
||||
Goto shortcuts_done
|
||||
check_ns_flag:
|
||||
${GetOptions} $CMDLINE "/NS" $R0
|
||||
IfErrors 0 shortcuts_done
|
||||
Call CreateDesktopShortcut
|
||||
Call CreateStartMenuShortcut
|
||||
shortcuts_done:
|
||||
|
||||
; Auto close this page for passive mode
|
||||
${IfThen} $PassiveMode == 1 ${|} SetAutoClose true ${|}
|
||||
SectionEnd
|
||||
|
||||
Function .onInstSuccess
|
||||
; Check for `/R` flag only in silent and passive installers because
|
||||
; GUI installer has a toggle for the user to (re)start the app
|
||||
IfSilent check_r_flag 0
|
||||
${IfThen} $PassiveMode == 1 ${|} Goto check_r_flag ${|}
|
||||
Goto run_done
|
||||
check_r_flag:
|
||||
${GetOptions} $CMDLINE "/R" $R0
|
||||
IfErrors run_done 0
|
||||
${GetOptions} $CMDLINE "/ARGS" $R0
|
||||
nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0"
|
||||
run_done:
|
||||
FunctionEnd
|
||||
|
||||
Function un.onInit
|
||||
!insertmacro SetContext
|
||||
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
!insertmacro MULTIUSER_UNINIT
|
||||
!endif
|
||||
|
||||
!insertmacro MUI_UNGETLANGUAGE
|
||||
FunctionEnd
|
||||
|
||||
!macro DeleteAppUserModelId
|
||||
!insertmacro ComHlpr_CreateInProcInstance ${CLSID_DestinationList} ${IID_ICustomDestinationList} r1 ""
|
||||
${If} $1 P<> 0
|
||||
${ICustomDestinationList::DeleteList} $1 '("${BUNDLEID}")'
|
||||
${IUnknown::Release} $1 ""
|
||||
${EndIf}
|
||||
!insertmacro ComHlpr_CreateInProcInstance ${CLSID_ApplicationDestinations} ${IID_IApplicationDestinations} r1 ""
|
||||
${If} $1 P<> 0
|
||||
${IApplicationDestinations::SetAppID} $1 '("${BUNDLEID}")i.r0'
|
||||
${If} $0 >= 0
|
||||
${IApplicationDestinations::RemoveAllDestinations} $1 ''
|
||||
${EndIf}
|
||||
${IUnknown::Release} $1 ""
|
||||
${EndIf}
|
||||
!macroend
|
||||
|
||||
; From https://stackoverflow.com/a/42816728/16993372
|
||||
!macro UnpinShortcut shortcut
|
||||
!insertmacro ComHlpr_CreateInProcInstance ${CLSID_StartMenuPin} ${IID_IStartMenuPinnedList} r0 ""
|
||||
${If} $0 P<> 0
|
||||
System::Call 'SHELL32::SHCreateItemFromParsingName(ws, p0, g "${IID_IShellItem}", *p0r1)' "${shortcut}"
|
||||
${If} $1 P<> 0
|
||||
${IStartMenuPinnedList::RemoveFromList} $0 '(r1)'
|
||||
${IUnknown::Release} $1 ""
|
||||
${EndIf}
|
||||
${IUnknown::Release} $0 ""
|
||||
${EndIf}
|
||||
!macroend
|
||||
|
||||
Section Uninstall
|
||||
!insertmacro CheckIfAppIsRunning
|
||||
|
||||
; Delete the app directory and its content from disk
|
||||
; Copy main executable
|
||||
Delete "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
|
||||
; Delete resources
|
||||
Delete "$INSTDIR\pytubepp-helper-autostart.exe"
|
||||
Delete "$INSTDIR\pytubepp-helper-msghost-moz.json"
|
||||
Delete "$INSTDIR\pytubepp-helper-msghost.exe"
|
||||
Delete "$INSTDIR\pytubepp-helper-msghost.json"
|
||||
|
||||
; Delete external binaries
|
||||
|
||||
; Remove the Registry entries
|
||||
DeleteRegKey HKCU "${CHROME_REG_PATH}"
|
||||
DeleteRegKey HKCU "${FIREFOX_REG_PATH}"
|
||||
DeleteRegValue HKCU "${RUN_REG_PATH}" "${PRODUCTNAME}"
|
||||
|
||||
; Delete uninstaller
|
||||
Delete "$INSTDIR\uninstall.exe"
|
||||
|
||||
RMDir "$INSTDIR"
|
||||
|
||||
!insertmacro DeleteAppUserModelId
|
||||
!insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${MAINBINARYNAME}.lnk"
|
||||
!insertmacro UnpinShortcut "$DESKTOP\${MAINBINARYNAME}.lnk"
|
||||
|
||||
; Remove start menu shortcut
|
||||
!insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder
|
||||
Delete "$SMPROGRAMS\$AppStartMenuFolder\${MAINBINARYNAME}.lnk"
|
||||
RMDir "$SMPROGRAMS\$AppStartMenuFolder"
|
||||
|
||||
; Remove desktop shortcuts
|
||||
Delete "$DESKTOP\${MAINBINARYNAME}.lnk"
|
||||
|
||||
; Remove registry information for add/remove programs
|
||||
!if "${INSTALLMODE}" == "both"
|
||||
DeleteRegKey SHCTX "${UNINSTKEY}"
|
||||
!else if "${INSTALLMODE}" == "perMachine"
|
||||
DeleteRegKey HKLM "${UNINSTKEY}"
|
||||
!else
|
||||
DeleteRegKey HKCU "${UNINSTKEY}"
|
||||
!endif
|
||||
|
||||
DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language"
|
||||
|
||||
; Delete app data
|
||||
${If} $DeleteAppDataCheckboxState == 1
|
||||
SetShellVarContext current
|
||||
RmDir /r "$APPDATA\${BUNDLEID}"
|
||||
RmDir /r "$LOCALAPPDATA\${BUNDLEID}"
|
||||
${EndIf}
|
||||
|
||||
${GetOptions} $CMDLINE "/P" $R0
|
||||
IfErrors +2 0
|
||||
SetAutoClose true
|
||||
SectionEnd
|
||||
|
||||
Function RestorePreviousInstallLocation
|
||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||
StrCmp $4 "" +2 0
|
||||
StrCpy $INSTDIR $4
|
||||
FunctionEnd
|
||||
|
||||
Function SkipIfPassive
|
||||
${IfThen} $PassiveMode == 1 ${|} Abort ${|}
|
||||
FunctionEnd
|
||||
|
||||
!macro SetLnkAppUserModelId shortcut
|
||||
!insertmacro ComHlpr_CreateInProcInstance ${CLSID_ShellLink} ${IID_IShellLink} r0 ""
|
||||
${If} $0 P<> 0
|
||||
${IUnknown::QueryInterface} $0 '("${IID_IPersistFile}",.r1)'
|
||||
${If} $1 P<> 0
|
||||
${IPersistFile::Load} $1 '("${shortcut}", ${STGM_READWRITE})'
|
||||
${IUnknown::QueryInterface} $0 '("${IID_IPropertyStore}",.r2)'
|
||||
${If} $2 P<> 0
|
||||
System::Call 'Oleaut32::SysAllocString(w "${BUNDLEID}") i.r3'
|
||||
System::Call '*${SYSSTRUCT_PROPERTYKEY}(${PKEY_AppUserModel_ID})p.r4'
|
||||
System::Call '*${SYSSTRUCT_PROPVARIANT}(${VT_BSTR},,&i4 $3)p.r5'
|
||||
${IPropertyStore::SetValue} $2 '($4,$5)'
|
||||
|
||||
System::Call 'Oleaut32::SysFreeString($3)'
|
||||
System::Free $4
|
||||
System::Free $5
|
||||
${IPropertyStore::Commit} $2 ""
|
||||
${IUnknown::Release} $2 ""
|
||||
${IPersistFile::Save} $1 '("${shortcut}",1)'
|
||||
${EndIf}
|
||||
${IUnknown::Release} $1 ""
|
||||
${EndIf}
|
||||
${IUnknown::Release} $0 ""
|
||||
${EndIf}
|
||||
!macroend
|
||||
|
||||
Function CreateDesktopShortcut
|
||||
CreateShortcut "$DESKTOP\${MAINBINARYNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
!insertmacro SetLnkAppUserModelId "$DESKTOP\${MAINBINARYNAME}.lnk"
|
||||
FunctionEnd
|
||||
|
||||
Function CreateStartMenuShortcut
|
||||
CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder"
|
||||
CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${MAINBINARYNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe"
|
||||
!insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${MAINBINARYNAME}.lnk"
|
||||
FunctionEnd
|
||||
@@ -10,7 +10,7 @@
|
||||
<RegistryValue Type="string" Value="[INSTALLDIR]pytubepp-helper-msghost-moz.json" KeyPath="no" />
|
||||
</RegistryKey>
|
||||
<RegistryKey Root="HKCU" Key="Software\Microsoft\Windows\CurrentVersion\Run">
|
||||
<RegistryValue Name="pytubepp-helper" Type="string" Value="[INSTALLDIR]pytubepp-helper-autostart.exe" KeyPath="no" />
|
||||
<RegistryValue Name="pytubepp-helper" Type="string" Value=""[INSTALLDIR]pytubepp-helper.exe" --hidden" KeyPath="no" />
|
||||
</RegistryKey>
|
||||
</Component>
|
||||
</DirectoryRef>
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "com.neosubhamoy.pytubepp.helper",
|
||||
"description": "A helper app for pytubepp-extension to communicate with pytubepp-cli",
|
||||
"path": "/Applications/pytubepp-helper.app/Contents/Resources/pytubepp-helper-msghost",
|
||||
"type": "stdio",
|
||||
"allowed_origins": ["chrome-extension://adebedkaedobamilbbobbajepnnkkfcg/", "chrome-extension://mmhhbpdhkogpcieblpdilflfoimajepp/", "chrome-extension://ebneapoekcjelholncnlpdohjbjabhbi/", "chrome-extension://cohjehldppmnbfogjdjpbjknhlhmfhjj/"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "com.neosubhamoy.pytubepp.helper",
|
||||
"description": "A helper app for pytubepp-extention to communicate with pytubepp-cli",
|
||||
"path": "/Applications/pytubepp-helper.app/Contents/Resources/pytubepp-helper-msghost",
|
||||
"type": "stdio",
|
||||
"allowed_extensions": ["pytubepp-addon@neosubhamoy.com"]
|
||||
}
|
||||
@@ -9,4 +9,6 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
websocket = "0.27.1"
|
||||
directories = "5.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
35
src-tauri/msghost/src/config.rs
Normal file
35
src-tauri/msghost/src/config.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Config {
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self { port: 3030 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_config_dir() -> Option<PathBuf> {
|
||||
ProjectDirs::from("com", "neosubhamoy", "pytubepp-helper")
|
||||
.map(|proj_dirs| proj_dirs.config_dir().to_path_buf())
|
||||
}
|
||||
|
||||
pub fn get_config_path() -> Option<PathBuf> {
|
||||
get_config_dir().map(|dir| dir.join("config.json"))
|
||||
}
|
||||
|
||||
pub fn load_config() -> Config {
|
||||
if let Some(config_path) = get_config_path() {
|
||||
if let Ok(content) = fs::read_to_string(config_path) {
|
||||
if let Ok(config) = serde_json::from_str(&content) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
}
|
||||
Config::default()
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
mod config;
|
||||
use config::load_config;
|
||||
use serde_json::Value;
|
||||
use std::io::{self, Read, Write};
|
||||
use websocket::client::ClientBuilder;
|
||||
use websocket::OwnedMessage;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
use serde_json::Value;
|
||||
use websocket::client::ClientBuilder;
|
||||
use websocket::OwnedMessage;
|
||||
|
||||
fn connect_with_retry(url: &str, max_attempts: u32) -> Result<websocket::sync::Client<std::net::TcpStream>, Box<dyn std::error::Error>> {
|
||||
fn get_websocket_url() -> String {
|
||||
let config = load_config();
|
||||
format!("ws://localhost:{}", config.port)
|
||||
}
|
||||
|
||||
fn connect_with_retry(
|
||||
url: &str,
|
||||
max_attempts: u32,
|
||||
) -> Result<websocket::sync::Client<std::net::TcpStream>, Box<dyn std::error::Error>> {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match ClientBuilder::new(url).unwrap().connect_insecure() {
|
||||
@@ -19,7 +29,10 @@ fn connect_with_retry(url: &str, max_attempts: u32) -> Result<websocket::sync::C
|
||||
return Err(Box::new(e));
|
||||
}
|
||||
let wait_time = Duration::from_secs(2u64.pow(attempts));
|
||||
eprintln!("Connection attempt {} failed. Retrying in {:?}...", attempts, wait_time);
|
||||
eprintln!(
|
||||
"Connection attempt {} failed. Retrying in {:?}...",
|
||||
attempts, wait_time
|
||||
);
|
||||
sleep(wait_time);
|
||||
}
|
||||
}
|
||||
@@ -55,7 +68,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(msg) => {
|
||||
eprintln!("Received message: {}", msg);
|
||||
msg
|
||||
},
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error reading message: {:?}", e);
|
||||
return Err(e);
|
||||
@@ -63,24 +76,30 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
};
|
||||
|
||||
// Send immediate response to the extension
|
||||
write_stdout_message(&serde_json::json!({
|
||||
write_stdout_message(
|
||||
&serde_json::json!({
|
||||
"status": "received",
|
||||
"message": "Message received by native host"
|
||||
}).to_string())?;
|
||||
})
|
||||
.to_string(),
|
||||
)?;
|
||||
|
||||
let parsed: Value = serde_json::from_str(&input)?;
|
||||
|
||||
let websocket_url = "ws://localhost:3030";
|
||||
let websocket_url = get_websocket_url();
|
||||
eprintln!("Attempting to connect to {}", websocket_url);
|
||||
|
||||
let mut client = match connect_with_retry(websocket_url, 2) {
|
||||
let mut client = match connect_with_retry(&websocket_url, 2) {
|
||||
Ok(client) => client,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to connect after multiple attempts: {:?}", e);
|
||||
write_stdout_message(&serde_json::json!({
|
||||
write_stdout_message(
|
||||
&serde_json::json!({
|
||||
"status": "error",
|
||||
"message": "Failed to connect to Tauri app"
|
||||
}).to_string())?;
|
||||
})
|
||||
.to_string(),
|
||||
)?;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
@@ -93,10 +112,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
// Send Tauri app's response back to browser extension
|
||||
if let OwnedMessage::Text(text) = message {
|
||||
write_stdout_message(&serde_json::json!({
|
||||
write_stdout_message(
|
||||
&serde_json::json!({
|
||||
"status": "success",
|
||||
"response": text
|
||||
}).to_string())?;
|
||||
})
|
||||
.to_string(),
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
51
src-tauri/src/config.rs
Normal file
51
src-tauri/src/config.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Config {
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self { port: 3030 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_config_dir() -> Option<PathBuf> {
|
||||
ProjectDirs::from("com", "neosubhamoy", "pytubepp-helper")
|
||||
.map(|proj_dirs| proj_dirs.config_dir().to_path_buf())
|
||||
}
|
||||
|
||||
pub fn get_config_path() -> Option<PathBuf> {
|
||||
get_config_dir().map(|dir| dir.join("config.json"))
|
||||
}
|
||||
|
||||
pub fn load_config() -> Config {
|
||||
if let Some(config_path) = get_config_path() {
|
||||
if let Ok(content) = fs::read_to_string(config_path) {
|
||||
if let Ok(config) = serde_json::from_str(&content) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
}
|
||||
Config::default()
|
||||
}
|
||||
|
||||
pub fn save_config(config: &Config) -> Result<(), String> {
|
||||
let config_dir =
|
||||
get_config_dir().ok_or_else(|| "Could not determine config directory".to_string())?;
|
||||
|
||||
fs::create_dir_all(&config_dir)
|
||||
.map_err(|e| format!("Failed to create config directory: {}", e))?;
|
||||
|
||||
let config_path = config_dir.join("config.json");
|
||||
let content = serde_json::to_string_pretty(config)
|
||||
.map_err(|e| format!("Failed to serialize config: {}", e))?;
|
||||
|
||||
fs::write(config_path, content).map_err(|e| format!("Failed to write config file: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
470
src-tauri/src/lib.rs
Normal file
470
src-tauri/src/lib.rs
Normal file
@@ -0,0 +1,470 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod config;
|
||||
use config::{get_config_path, load_config, save_config, Config};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::Value;
|
||||
use std::{env, process::Command, sync::Arc, time::Duration};
|
||||
use tauri::{
|
||||
menu::{Menu, MenuItem},
|
||||
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
|
||||
Emitter, Manager,
|
||||
};
|
||||
use tokio::{
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::{oneshot, Mutex},
|
||||
time::sleep,
|
||||
};
|
||||
use tokio_tungstenite::accept_async;
|
||||
|
||||
struct ResponseChannel {
|
||||
sender: Option<oneshot::Sender<String>>,
|
||||
}
|
||||
|
||||
struct WebSocketState {
|
||||
sender: Option<
|
||||
futures_util::stream::SplitSink<
|
||||
tokio_tungstenite::WebSocketStream<TcpStream>,
|
||||
tokio_tungstenite::tungstenite::Message,
|
||||
>,
|
||||
>,
|
||||
response_channel: ResponseChannel,
|
||||
server_abort: Option<tokio::sync::oneshot::Sender<()>>,
|
||||
config: Config,
|
||||
}
|
||||
|
||||
async fn start_websocket_server(app_handle: tauri::AppHandle, port: u16) -> Result<(), String> {
|
||||
let addr = format!("127.0.0.1:{}", port);
|
||||
|
||||
// First ensure any existing server is stopped
|
||||
{
|
||||
let state = app_handle.state::<Arc<Mutex<WebSocketState>>>();
|
||||
let mut state = state.lock().await;
|
||||
if let Some(old_abort) = state.server_abort.take() {
|
||||
let _ = old_abort.send(());
|
||||
// Give it a moment to shut down
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Now try to bind to the port
|
||||
let listener = TcpListener::bind(&addr)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to bind to port {}: {}", port, e))?;
|
||||
|
||||
let (abort_sender, mut abort_receiver) = tokio::sync::oneshot::channel();
|
||||
|
||||
// Store the new abort sender
|
||||
{
|
||||
let state = app_handle.state::<Arc<Mutex<WebSocketState>>>();
|
||||
let mut state = state.lock().await;
|
||||
state.server_abort = Some(abort_sender);
|
||||
}
|
||||
|
||||
// Spawn the server task
|
||||
tokio::spawn(async move {
|
||||
println!("Starting WebSocket server on port {}", port);
|
||||
loop {
|
||||
tokio::select! {
|
||||
accept_result = listener.accept() => {
|
||||
match accept_result {
|
||||
Ok((stream, _)) => {
|
||||
let app_handle = app_handle.clone();
|
||||
tokio::spawn(handle_connection(stream, app_handle));
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Error accepting connection: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = &mut abort_receiver => {
|
||||
println!("WebSocket server shutting down on port {}...", port);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wait a moment to ensure the server has started
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_config(state: tauri::State<'_, Arc<Mutex<WebSocketState>>>) -> Result<Config, String> {
|
||||
let state = state.lock().await;
|
||||
Ok(state.config.clone())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_config_file_path() -> Result<String, String> {
|
||||
match get_config_path() {
|
||||
Some(path) => Ok(path.to_string_lossy().into_owned()),
|
||||
None => Err("Could not determine config path".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn update_config(
|
||||
new_config: Config,
|
||||
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
|
||||
app_handle: tauri::AppHandle,
|
||||
) -> Result<Config, String> {
|
||||
// Save the new config first
|
||||
save_config(&new_config)?;
|
||||
|
||||
// Update the state with new config
|
||||
{
|
||||
let mut state = state.lock().await;
|
||||
state.config = new_config.clone();
|
||||
}
|
||||
|
||||
// Start the new server (this will also handle stopping the old one)
|
||||
start_websocket_server(app_handle, new_config.port).await?;
|
||||
|
||||
Ok(new_config)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn reset_config(
|
||||
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
|
||||
app_handle: tauri::AppHandle,
|
||||
) -> Result<Config, String> {
|
||||
let config = Config::default();
|
||||
save_config(&config)?;
|
||||
|
||||
{
|
||||
let mut state = state.lock().await;
|
||||
state.config = config.clone();
|
||||
}
|
||||
|
||||
start_websocket_server(app_handle, config.port).await?;
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn send_to_extension(
|
||||
message: String,
|
||||
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
|
||||
) -> Result<(), String> {
|
||||
let mut state = state.lock().await;
|
||||
if let Some(sender) = &mut state.sender {
|
||||
sender
|
||||
.send(tokio_tungstenite::tungstenite::Message::Text(message))
|
||||
.await
|
||||
.map_err(|e| format!("Failed to send message: {}", e))?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err("No active WebSocket connection".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn receive_frontend_response(
|
||||
response: String,
|
||||
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
|
||||
) -> Result<(), String> {
|
||||
let mut state = state.lock().await;
|
||||
if let Some(sender) = state.response_channel.sender.take() {
|
||||
sender
|
||||
.send(response)
|
||||
.map_err(|e| format!("Failed to send response: {:?}", e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn fetch_video_info(url: String) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -i", &url);
|
||||
Command::new("cmd")
|
||||
.args(["/k", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -i", &url);
|
||||
Command::new("gnome-terminal")
|
||||
.args(["--", "bash", "-c", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -i", &url);
|
||||
let escaped_command = command.replace("\"", "\\\"");
|
||||
|
||||
let applescript = format!(
|
||||
"tell application \"Terminal\"\n\
|
||||
do script \"{}\"\n\
|
||||
activate\n\
|
||||
end tell",
|
||||
escaped_command
|
||||
);
|
||||
|
||||
Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(applescript)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn install_program(icommand: String) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let command = format!("{}", &icommand);
|
||||
Command::new("cmd")
|
||||
.args(["/k", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let command = format!("{}", &icommand);
|
||||
Command::new("gnome-terminal")
|
||||
.args(["--", "bash", "-c", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let command = format!("{}", &icommand);
|
||||
let escaped_command = command.replace("\"", "\\\"");
|
||||
|
||||
let applescript = format!(
|
||||
"tell application \"Terminal\"\n\
|
||||
do script \"{}\"\n\
|
||||
activate\n\
|
||||
end tell",
|
||||
escaped_command
|
||||
);
|
||||
|
||||
Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(applescript)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn download_stream(url: String, stream: String, caption: Option<String>) {
|
||||
let caption = caption.unwrap_or("none".to_string());
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -s {} -c {}", &url, &stream, &caption);
|
||||
Command::new("cmd")
|
||||
.args(["/k", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -s {} -c {}", &url, &stream, &caption);
|
||||
Command::new("gnome-terminal")
|
||||
.args(["--", "bash", "-c", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -s {} -c {}", &url, &stream, &caption);
|
||||
let escaped_command = command.replace("\"", "\\\"");
|
||||
|
||||
let applescript = format!(
|
||||
"tell application \"Terminal\"\n\
|
||||
do script \"{}\"\n\
|
||||
activate\n\
|
||||
end tell",
|
||||
escaped_command
|
||||
);
|
||||
|
||||
Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(applescript)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub async fn run() {
|
||||
let _ = fix_path_env::fix();
|
||||
|
||||
let config = load_config();
|
||||
let port = config.port;
|
||||
|
||||
let websocket_state = Arc::new(Mutex::new(WebSocketState {
|
||||
sender: None,
|
||||
response_channel: ResponseChannel { sender: None },
|
||||
server_abort: None,
|
||||
config,
|
||||
}));
|
||||
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let start_hidden = args.contains(&"--hidden".to_string());
|
||||
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||
// Focus the main window when attempting to launch another instance
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_os::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.manage(websocket_state.clone())
|
||||
.setup(move |app| {
|
||||
// Create menu items
|
||||
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)
|
||||
.map_err(|e| format!("Failed to create quit menu item: {}", e))?;
|
||||
let show = MenuItem::with_id(app, "show", "Show", true, None::<&str>)
|
||||
.map_err(|e| format!("Failed to create show menu item: {}", e))?;
|
||||
|
||||
// Create the menu
|
||||
let menu = Menu::with_items(app, &[&show, &quit])
|
||||
.map_err(|e| format!("Failed to create menu: {}", e))?;
|
||||
|
||||
// Create and store the tray icon
|
||||
let tray = TrayIconBuilder::with_id("main")
|
||||
.icon(app.default_window_icon().unwrap().clone())
|
||||
.menu(&menu)
|
||||
.tooltip("PytubePP Helper")
|
||||
.on_menu_event(|app, event| match event.id.as_ref() {
|
||||
"show" => {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
}
|
||||
"quit" => {
|
||||
app.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.on_tray_icon_event(|tray, event| {
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Up,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
let app = tray.app_handle();
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
}
|
||||
})
|
||||
.build(app)
|
||||
.map_err(|e| format!("Failed to create tray: {}", e))?;
|
||||
|
||||
// Store the tray handle in the app state
|
||||
app.manage(tray);
|
||||
|
||||
let window = app.get_webview_window("main").unwrap();
|
||||
if start_hidden {
|
||||
window.hide().unwrap();
|
||||
}
|
||||
|
||||
// Start the initial WebSocket server
|
||||
let app_handle = app.handle().clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = start_websocket_server(app_handle, port).await {
|
||||
println!("Failed to start initial WebSocket server: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
send_to_extension,
|
||||
fetch_video_info,
|
||||
install_program,
|
||||
download_stream,
|
||||
receive_frontend_response,
|
||||
get_config,
|
||||
update_config,
|
||||
reset_config,
|
||||
get_config_file_path
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
|
||||
async fn handle_connection(stream: TcpStream, app_handle: tauri::AppHandle) {
|
||||
let ws_stream = accept_async(stream).await.unwrap();
|
||||
let (ws_sender, mut ws_receiver) = ws_stream.split();
|
||||
|
||||
// Store the sender in the shared state
|
||||
{
|
||||
let state = app_handle.state::<Arc<Mutex<WebSocketState>>>();
|
||||
let mut state = state.lock().await;
|
||||
state.sender = Some(ws_sender);
|
||||
}
|
||||
|
||||
println!("New WebSocket connection established");
|
||||
|
||||
while let Some(msg) = ws_receiver.next().await {
|
||||
if let Ok(msg) = msg {
|
||||
if let Ok(text) = msg.to_text() {
|
||||
println!("Received message: {}", text);
|
||||
|
||||
// Parse the JSON message
|
||||
if let Ok(json_value) = serde_json::from_str::<Value>(text) {
|
||||
// Create a new channel for this request
|
||||
let (response_sender, response_receiver) = oneshot::channel();
|
||||
{
|
||||
let state = app_handle.state::<Arc<Mutex<WebSocketState>>>();
|
||||
let mut state = state.lock().await;
|
||||
state.response_channel.sender = Some(response_sender);
|
||||
}
|
||||
|
||||
// Emit an event to the frontend
|
||||
app_handle
|
||||
.emit_to("main", "websocket-message", json_value)
|
||||
.unwrap();
|
||||
|
||||
// Wait for the response from the frontend
|
||||
let response = response_receiver
|
||||
.await
|
||||
.unwrap_or_else(|e| format!("Error receiving response: {:?}", e));
|
||||
|
||||
// Send the response back through WebSocket
|
||||
let state = app_handle.state::<Arc<Mutex<WebSocketState>>>();
|
||||
let mut state = state.lock().await;
|
||||
if let Some(sender) = &mut state.sender {
|
||||
let _ = sender
|
||||
.send(tokio_tungstenite::tungstenite::Message::Text(response))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("WebSocket connection closed");
|
||||
|
||||
// Remove the sender from the shared state when the connection closes
|
||||
let state = app_handle.state::<Arc<Mutex<WebSocketState>>>();
|
||||
let mut state = state.lock().await;
|
||||
state.sender = None;
|
||||
}
|
||||
@@ -1,261 +1,6 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use std::{process::Command, sync::Arc, env};
|
||||
use serde_json::Value;
|
||||
use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu};
|
||||
use tokio::{net::{TcpListener, TcpStream}, sync::{Mutex, oneshot}};
|
||||
use tokio_tungstenite::accept_async;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
|
||||
struct ResponseChannel {
|
||||
sender: Option<oneshot::Sender<String>>,
|
||||
}
|
||||
|
||||
struct WebSocketState {
|
||||
sender: Option<futures_util::stream::SplitSink<tokio_tungstenite::WebSocketStream<TcpStream>, tokio_tungstenite::tungstenite::Message>>,
|
||||
response_channel: ResponseChannel,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn send_to_extension(
|
||||
message: String,
|
||||
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
|
||||
) -> Result<(), String> {
|
||||
let mut state = state.lock().await;
|
||||
if let Some(sender) = &mut state.sender {
|
||||
sender.send(tokio_tungstenite::tungstenite::Message::Text(message)).await
|
||||
.map_err(|e| format!("Failed to send message: {}", e))?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err("No active WebSocket connection".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn receive_frontend_response(
|
||||
response: String,
|
||||
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
|
||||
) -> Result<(), String> {
|
||||
let mut state = state.lock().await;
|
||||
if let Some(sender) = state.response_channel.sender.take() {
|
||||
sender.send(response).map_err(|e| format!("Failed to send response: {:?}", e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn fetch_video_info(url: String) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -i", &url);
|
||||
Command::new("cmd")
|
||||
.args(["/k", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -i", &url);
|
||||
Command::new("gnome-terminal")
|
||||
.args(["--", "bash", "-c", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -i", &url);
|
||||
Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(format!(
|
||||
"tell app \"Terminal\" to activate do script \"{}\"",
|
||||
command
|
||||
))
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn install_program(icommand: String) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let command = format!("{}", &icommand);
|
||||
Command::new("cmd")
|
||||
.args(["/k", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let command = format!("{}", &icommand);
|
||||
Command::new("gnome-terminal")
|
||||
.args(["--", "bash", "-c", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let command = format!("{}", &icommand);
|
||||
Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(format!(
|
||||
"tell app \"Terminal\" to activate do script \"{}\"",
|
||||
command
|
||||
))
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn download_stream(url: String, stream: String) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -s {}", &url, &stream);
|
||||
Command::new("cmd")
|
||||
.args(["/k", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -s {}", &url, &stream);
|
||||
Command::new("gnome-terminal")
|
||||
.args(["--", "bash", "-c", command.as_str()])
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let command = format!("pytubepp \"{}\" -s {}", &url, &stream);
|
||||
Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(format!(
|
||||
"tell app \"Terminal\" to activate do script \"{}\"",
|
||||
command
|
||||
))
|
||||
.spawn()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let _ = fix_path_env::fix();
|
||||
let websocket_state = Arc::new(Mutex::new(WebSocketState {
|
||||
sender: None,
|
||||
response_channel: ResponseChannel { sender: None },
|
||||
}));
|
||||
let tray_menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("show".to_string(), "Show"))
|
||||
.add_item(CustomMenuItem::new("quit".to_string(), "Quit"));
|
||||
|
||||
let system_tray = SystemTray::new().with_menu(tray_menu).with_tooltip("PytubePP Helper");
|
||||
|
||||
tauri::Builder::default()
|
||||
.system_tray(system_tray)
|
||||
.on_system_tray_event(|app, event| match event {
|
||||
SystemTrayEvent::LeftClick {
|
||||
position: _,
|
||||
size: _,
|
||||
..
|
||||
} => {
|
||||
let window = app.get_window("main").unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
"show" => {
|
||||
let window = app.get_window("main").unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
"quit" => {
|
||||
app.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
})
|
||||
.manage(websocket_state.clone())
|
||||
.setup(move |app| {
|
||||
let app_handle = app.handle();
|
||||
let ws_state = websocket_state.clone();
|
||||
tokio::spawn(async move {
|
||||
let listener = TcpListener::bind("127.0.0.1:3030").await.unwrap();
|
||||
println!("WebSocket server listening on ws://127.0.0.1:3030");
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let app_handle = app_handle.clone();
|
||||
let ws_state = ws_state.clone();
|
||||
tokio::spawn(handle_connection(stream, app_handle, ws_state));
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
send_to_extension,
|
||||
fetch_video_info,
|
||||
install_program,
|
||||
download_stream,
|
||||
receive_frontend_response
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
|
||||
async fn handle_connection(stream: TcpStream, app_handle: tauri::AppHandle, ws_state: Arc<Mutex<WebSocketState>>) {
|
||||
let ws_stream = accept_async(stream).await.unwrap();
|
||||
let (ws_sender, mut ws_receiver) = ws_stream.split();
|
||||
|
||||
// Store the sender in the shared state
|
||||
{
|
||||
let mut state = ws_state.lock().await;
|
||||
state.sender = Some(ws_sender);
|
||||
}
|
||||
|
||||
println!("New WebSocket connection established");
|
||||
|
||||
while let Some(msg) = ws_receiver.next().await {
|
||||
if let Ok(msg) = msg {
|
||||
if let Ok(text) = msg.to_text() {
|
||||
println!("Received message: {}", text);
|
||||
|
||||
// Parse the JSON message
|
||||
if let Ok(json_value) = serde_json::from_str::<Value>(text) {
|
||||
// Create a new channel for this request
|
||||
let (response_sender, response_receiver) = oneshot::channel();
|
||||
{
|
||||
let mut state = ws_state.lock().await;
|
||||
state.response_channel.sender = Some(response_sender);
|
||||
}
|
||||
|
||||
// Emit an event to the frontend
|
||||
app_handle.emit_all("websocket-message", json_value).unwrap();
|
||||
|
||||
// Wait for the response from the frontend
|
||||
let response = response_receiver.await
|
||||
.unwrap_or_else(|e| format!("Error receiving response: {:?}", e));
|
||||
|
||||
// Send the response back through WebSocket
|
||||
let mut state = ws_state.lock().await;
|
||||
if let Some(sender) = &mut state.sender {
|
||||
let _ = sender.send(tokio_tungstenite::tungstenite::Message::Text(response)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("WebSocket connection closed");
|
||||
|
||||
// Remove the sender from the shared state when the connection closes
|
||||
let mut state = ws_state.lock().await;
|
||||
state.sender = None;
|
||||
pytubepp_helper_lib::run().await;
|
||||
}
|
||||
@@ -1,32 +1,15 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"devPath": "http://localhost:1422",
|
||||
"distDir": "../dist"
|
||||
},
|
||||
"package": {
|
||||
"productName": "pytubepp-helper",
|
||||
"version": "0.3.0"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
"title": "PytubePP Helper",
|
||||
"width": 500,
|
||||
"height": 320
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"frontendDist": "../dist",
|
||||
"devUrl": "http://localhost:1422"
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -34,6 +17,33 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"productName": "pytubepp-helper",
|
||||
"mainBinaryName": "pytubepp-helper",
|
||||
"version": "0.7.0",
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEMwNjIwMjQ1OTk4NjJDRUMKUldUc0xJYVpSUUppd0Y5NGhyTUg0VDhDNFd3SFMzNnBYUlhZSlE1WGNjamcxS0tOMDE5M1dycWYK",
|
||||
"endpoints": [
|
||||
"https://github.com/neosubhamoy/pytubepp-helper/releases/latest/download/latest.json"
|
||||
],
|
||||
"windows": {
|
||||
"installMode": "passive"
|
||||
}
|
||||
}
|
||||
},
|
||||
"app": {
|
||||
"security": {
|
||||
"csp": null
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
"title": "PytubePP Helper",
|
||||
"width": 510,
|
||||
"height": 345,
|
||||
"useHttpsScheme": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,125 +1,33 @@
|
||||
{
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev && cargo build --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --manifest-path=./src-tauri/autostart/Cargo.toml",
|
||||
"beforeBuildCommand": "npm run build && cargo build --release --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --release --manifest-path=./src-tauri/autostart/Cargo.toml",
|
||||
"devPath": "http://localhost:1422",
|
||||
"distDir": "../dist"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false,
|
||||
"os": {
|
||||
"all": true
|
||||
},
|
||||
"shell": {
|
||||
"all": true,
|
||||
"execute": true,
|
||||
"sidecar": true,
|
||||
"open": true,
|
||||
"scope": [
|
||||
{
|
||||
"name": "detect-windows",
|
||||
"cmd": "systeminfo",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-macos",
|
||||
"cmd": "sw_vers",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-distro",
|
||||
"cmd": "grep",
|
||||
"args": ["^ID=", "/etc/os-release"]
|
||||
},
|
||||
{
|
||||
"name": "is-apt-installed",
|
||||
"cmd": "apt",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-dnf-installed",
|
||||
"cmd": "dnf",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-python3-installed",
|
||||
"cmd": "python3",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pip3-installed",
|
||||
"cmd": "pip3",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-winget-installed",
|
||||
"cmd": "winget",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-homebrew-installed",
|
||||
"cmd": "brew",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-python-installed",
|
||||
"cmd": "python",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pip-installed",
|
||||
"cmd": "pip",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-ffmpeg-installed",
|
||||
"cmd": "ffmpeg",
|
||||
"args": ["-version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pytubepp-installed",
|
||||
"cmd": "pytubepp",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "fetch-video-info",
|
||||
"cmd": "pytubepp",
|
||||
"args": [{ "validator": "\\S+" }, "--raw-info"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"window": {
|
||||
"all": false,
|
||||
"close": true,
|
||||
"hide": true,
|
||||
"show": true,
|
||||
"maximize": true,
|
||||
"minimize": true,
|
||||
"unmaximize": true,
|
||||
"unminimize": true,
|
||||
"startDragging": true
|
||||
},
|
||||
"process": {
|
||||
"all": false,
|
||||
"exit": true,
|
||||
"relaunch": true
|
||||
}
|
||||
"beforeDevCommand": "npm run dev && cargo build --manifest-path=./src-tauri/msghost/Cargo.toml",
|
||||
"beforeBuildCommand": "npm run build && cargo build --release --manifest-path=./src-tauri/msghost/Cargo.toml",
|
||||
"devUrl": "http://localhost:1422",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "PytubePP Helper",
|
||||
"width": 500,
|
||||
"height": 320
|
||||
"width": 510,
|
||||
"height": 345,
|
||||
"useHttpsScheme": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"capabilities": [
|
||||
"main-capability",
|
||||
"shell-scope"
|
||||
]
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["deb", "rpm"],
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"createUpdaterArtifacts": true,
|
||||
"licenseFile": "../LICENSE",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -127,35 +35,29 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"linux": {
|
||||
"deb": {
|
||||
"depends": ["python3-pip", "ffmpeg"],
|
||||
"depends": ["python3-pip", "nodejs", "ffmpeg", "gnome-terminal"],
|
||||
"files": {
|
||||
"/etc/opt/chrome/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
|
||||
"/etc/chromium/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
|
||||
"/usr/lib/mozilla/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/firefox/com.neosubhamoy.pytubepp.helper.json",
|
||||
"/usr/bin/pytubepp-helper-msghost": "./target/release/pytubepp-helper-msghost",
|
||||
"/usr/bin/pytubepp-helper-autostart": "./target/release/pytubepp-helper-autostart",
|
||||
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
|
||||
}
|
||||
},
|
||||
"rpm": {
|
||||
"epoch": 0,
|
||||
"release": "1",
|
||||
"license": "MIT",
|
||||
"depends": ["python3-pip", "ffmpeg-free"],
|
||||
"depends": ["python3-pip", "nodejs", "ffmpeg", "gnome-terminal"],
|
||||
"files": {
|
||||
"/etc/opt/chrome/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
|
||||
"/etc/chromium/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
|
||||
"/usr/lib/mozilla/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/firefox/com.neosubhamoy.pytubepp.helper.json",
|
||||
"/usr/bin/pytubepp-helper-msghost": "./target/release/pytubepp-helper-msghost",
|
||||
"/usr/bin/pytubepp-helper-autostart": "./target/release/pytubepp-helper-autostart",
|
||||
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
|
||||
}
|
||||
}
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/32x32.png",
|
||||
"iconAsTemplate": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,125 +1,56 @@
|
||||
{
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev && cargo build --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --manifest-path=./src-tauri/autostart/Cargo.toml",
|
||||
"beforeBuildCommand": "npm run build && cargo build --release --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --release --manifest-path=./src-tauri/autostart/Cargo.toml",
|
||||
"devPath": "http://localhost:1422",
|
||||
"distDir": "../dist"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false,
|
||||
"os": {
|
||||
"all": true
|
||||
},
|
||||
"shell": {
|
||||
"all": true,
|
||||
"execute": true,
|
||||
"sidecar": true,
|
||||
"open": true,
|
||||
"scope": [
|
||||
{
|
||||
"name": "detect-windows",
|
||||
"cmd": "systeminfo",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-macos",
|
||||
"cmd": "sw_vers",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-distro",
|
||||
"cmd": "grep",
|
||||
"args": ["^ID=", "/etc/os-release"]
|
||||
},
|
||||
{
|
||||
"name": "is-apt-installed",
|
||||
"cmd": "apt",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-dnf-installed",
|
||||
"cmd": "dnf",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-python3-installed",
|
||||
"cmd": "python3",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pip3-installed",
|
||||
"cmd": "pip3",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-winget-installed",
|
||||
"cmd": "winget",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-homebrew-installed",
|
||||
"cmd": "brew",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-python-installed",
|
||||
"cmd": "python",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pip-installed",
|
||||
"cmd": "pip",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-ffmpeg-installed",
|
||||
"cmd": "ffmpeg",
|
||||
"args": ["-version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pytubepp-installed",
|
||||
"cmd": "pytubepp",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "fetch-video-info",
|
||||
"cmd": "pytubepp",
|
||||
"args": [{ "validator": "\\S+" }, "--raw-info"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"window": {
|
||||
"all": false,
|
||||
"close": true,
|
||||
"hide": true,
|
||||
"show": true,
|
||||
"maximize": true,
|
||||
"minimize": true,
|
||||
"unmaximize": true,
|
||||
"unminimize": true,
|
||||
"startDragging": true
|
||||
},
|
||||
"process": {
|
||||
"all": false,
|
||||
"exit": true,
|
||||
"relaunch": true
|
||||
}
|
||||
"beforeDevCommand": "[[ -n \"$TARGET_ARCH\" ]] && ARCH=\"$TARGET_ARCH\" || ARCH=\"$(uname -m | sed 's/^arm64$/aarch64/')-apple-darwin\" && cargo build --target=$ARCH --manifest-path=./src-tauri/msghost/Cargo.toml && npm run dev",
|
||||
"beforeBuildCommand": "[[ -n \"$TARGET_ARCH\" ]] && ARCH=\"$TARGET_ARCH\" || ARCH=\"$(uname -m | sed 's/^arm64$/aarch64/')-apple-darwin\" && cargo build --release --target=$ARCH --manifest-path=./src-tauri/msghost/Cargo.toml && node copyFiles.${ARCH}.js && npm run build",
|
||||
"devUrl": "http://localhost:1422",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "PytubePP Helper",
|
||||
"width": 500,
|
||||
"height": 320
|
||||
"width": 515,
|
||||
"height": 365,
|
||||
"useHttpsScheme": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"capabilities": [
|
||||
"main-capability",
|
||||
"shell-scope",
|
||||
{
|
||||
"identifier": "fs-scope",
|
||||
"description": "allowed file system scopes",
|
||||
"permissions": [
|
||||
{
|
||||
"identifier": "fs:scope",
|
||||
"allow": [
|
||||
{ "path": "$HOME/Library/LaunchAgents/" },
|
||||
{ "path": "$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts/" },
|
||||
{ "path": "$HOME/Library/Application Support/Chromium/NativeMessagingHosts/" },
|
||||
{ "path": "$HOME/Library/Application Support/Mozilla/NativeMessagingHosts/" },
|
||||
{ "path": "$HOME/Library/LaunchAgents/*" },
|
||||
{ "path": "$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts/*" },
|
||||
{ "path": "$HOME/Library/Application Support/Chromium/NativeMessagingHosts/*" },
|
||||
{ "path": "$HOME/Library/Application Support/Mozilla/NativeMessagingHosts/*" },
|
||||
{ "path": "$RESOURCE/pytubepp-helper-msghost.json" },
|
||||
{ "path": "$RESOURCE/pytubepp-helper-msghost-moz.json" },
|
||||
{ "path": "$RESOURCE/pytubepp-helper-msghost" },
|
||||
{ "path": "$RESOURCE/pytubepp-helper-autostart.plist" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["app", "dmg"],
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"createUpdaterArtifacts": true,
|
||||
"licenseFile": "../LICENSE",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -129,13 +60,13 @@
|
||||
],
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "10.13",
|
||||
"license": "../LICENSE",
|
||||
"providerShortName": "neosubhamoy"
|
||||
}
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/32x32.png",
|
||||
"iconAsTemplate": true
|
||||
}
|
||||
"resources": [
|
||||
"pytubepp-helper-msghost.json",
|
||||
"pytubepp-helper-msghost-moz.json",
|
||||
"pytubepp-helper-msghost",
|
||||
"pytubepp-helper-autostart.plist"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,133 +1,47 @@
|
||||
{
|
||||
"build": {
|
||||
"beforeDevCommand": "cargo build --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --manifest-path=./src-tauri/autostart/Cargo.toml && npm run dev",
|
||||
"beforeBuildCommand": "cargo build --release --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --release --manifest-path=./src-tauri/autostart/Cargo.toml && node copyFiles.js && npm run build",
|
||||
"devPath": "http://localhost:1422",
|
||||
"distDir": "../dist"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false,
|
||||
"os": {
|
||||
"all": true
|
||||
},
|
||||
"shell": {
|
||||
"all": true,
|
||||
"execute": true,
|
||||
"sidecar": true,
|
||||
"open": true,
|
||||
"scope": [
|
||||
{
|
||||
"name": "detect-windows",
|
||||
"cmd": "systeminfo",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-macos",
|
||||
"cmd": "sw_vers",
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "detect-distro",
|
||||
"cmd": "grep",
|
||||
"args": ["^ID=", "/etc/os-release"]
|
||||
},
|
||||
{
|
||||
"name": "is-apt-installed",
|
||||
"cmd": "apt",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-dnf-installed",
|
||||
"cmd": "dnf",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-python3-installed",
|
||||
"cmd": "python3",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pip3-installed",
|
||||
"cmd": "pip3",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-winget-installed",
|
||||
"cmd": "winget",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-homebrew-installed",
|
||||
"cmd": "brew",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-python-installed",
|
||||
"cmd": "python",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pip-installed",
|
||||
"cmd": "pip",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "is-ffmpeg-installed",
|
||||
"cmd": "ffmpeg",
|
||||
"args": ["-version"]
|
||||
},
|
||||
{
|
||||
"name": "is-pytubepp-installed",
|
||||
"cmd": "pytubepp",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "fetch-video-info",
|
||||
"cmd": "pytubepp",
|
||||
"args": [{ "validator": "\\S+" }, "--raw-info"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"fs": {
|
||||
"scope": [
|
||||
"$RESOURCE/pytubepp-helper-msghost.json",
|
||||
"$RESOURCE/pytubepp-helper-msghost-moz.json",
|
||||
"$RESOURCE/pytubepp-helper-msghost.exe",
|
||||
"$RESOURCE/pytubepp-helper-autostart.exe"
|
||||
]
|
||||
},
|
||||
"window": {
|
||||
"all": false,
|
||||
"close": true,
|
||||
"hide": true,
|
||||
"show": true,
|
||||
"maximize": true,
|
||||
"minimize": true,
|
||||
"unmaximize": true,
|
||||
"unminimize": true,
|
||||
"startDragging": true
|
||||
},
|
||||
"process": {
|
||||
"all": false,
|
||||
"exit": true,
|
||||
"relaunch": true
|
||||
}
|
||||
"beforeDevCommand": "cargo build --manifest-path=./src-tauri/msghost/Cargo.toml && npm run dev",
|
||||
"beforeBuildCommand": "cargo build --release --manifest-path=./src-tauri/msghost/Cargo.toml && node copyFiles.js && npm run build",
|
||||
"devUrl": "http://localhost:1422",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "PytubePP Helper",
|
||||
"width": 500,
|
||||
"height": 320
|
||||
"width": 510,
|
||||
"height": 345,
|
||||
"useHttpsScheme": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"capabilities": [
|
||||
"main-capability",
|
||||
"shell-scope",
|
||||
{
|
||||
"identifier": "fs-scope",
|
||||
"description": "allowed file system scopes",
|
||||
"permissions": [
|
||||
{
|
||||
"identifier": "fs:scope",
|
||||
"allow": [
|
||||
{ "path": "$RESOURCE/pytubepp-helper-msghost.json" },
|
||||
{ "path": "$RESOURCE/pytubepp-helper-msghost-moz.json" },
|
||||
{ "path": "$RESOURCE/pytubepp-helper-msghost.exe" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["msi", "nsis"],
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"createUpdaterArtifacts": true,
|
||||
"licenseFile": "../LICENSE",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -137,24 +51,17 @@
|
||||
],
|
||||
"windows": {
|
||||
"wix": {
|
||||
"fragmentPaths": ["installer/windows/wix-fragment-registry.wxs"],
|
||||
"componentRefs": ["PytubeppHelperFragmentRegistryEntries"],
|
||||
"license": "../LICENSE"
|
||||
"fragmentPaths": ["installer/windows/wix-fragment.wxs"],
|
||||
"componentRefs": ["PytubeppHelperFragmentRegistryEntries"]
|
||||
},
|
||||
"nsis": {
|
||||
"template": "installer/windows/nsis-template.nsi"
|
||||
"installerHooks": "installer/windows/nsis-hooks.nsi"
|
||||
}
|
||||
},
|
||||
"resources": [
|
||||
"pytubepp-helper-msghost.json",
|
||||
"pytubepp-helper-msghost-moz.json",
|
||||
"pytubepp-helper-msghost.exe",
|
||||
"pytubepp-helper-autostart.exe"
|
||||
"pytubepp-helper-msghost.exe"
|
||||
]
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/icon.ico",
|
||||
"iconAsTemplate": true
|
||||
}
|
||||
}
|
||||
}
|
||||
406
src/App.tsx
406
src/App.tsx
@@ -1,18 +1,27 @@
|
||||
import clsx from "clsx";
|
||||
import { useState, useEffect } from "react";
|
||||
import "./index.css";
|
||||
import { invoke } from "@tauri-apps/api/tauri";
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { appWindow } from '@tauri-apps/api/window';
|
||||
import { platform } from '@tauri-apps/api/os';
|
||||
import React from "react"
|
||||
import { useEffect, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
|
||||
import { InstalledPrograms, WebSocketMessage, } from "./types";
|
||||
import { compareVersions, extractVersion, isInstalled, sendStreamInfo, detectWindows, detectDistro, extractDistroId, detectDistroBase, detectMacOs } from "./lib/utils";
|
||||
import { CircleCheck, TriangleAlert, CircleAlert } from 'lucide-react';
|
||||
import { WebSocketMessage } from "@/types";
|
||||
import { sendStreamInfo } from "@/lib/utils";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { check as checkAppUpdate } from "@tauri-apps/plugin-updater";
|
||||
import { isPermissionGranted, requestPermission, sendNotification } from "@tauri-apps/plugin-notification";
|
||||
|
||||
function App({ children }: { children: React.ReactNode }) {
|
||||
const appWindow = getCurrentWebviewWindow()
|
||||
const [isAppUpdateChecked, setIsAppUpdateChecked] = useState(false);
|
||||
|
||||
// Prevent right click context menu in production
|
||||
if (!import.meta.env.DEV) {
|
||||
document.oncontextmenu = (event) => {
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
const handleCloseRequested = (event: any) => {
|
||||
event.preventDefault();
|
||||
@@ -22,55 +31,6 @@ function App() {
|
||||
appWindow.onCloseRequested(handleCloseRequested);
|
||||
}, []);
|
||||
|
||||
const [isWindows, setIsWindows] = useState<boolean>(false)
|
||||
const [windowsVersion, setWindowsVersion] = useState<string | null>(null)
|
||||
const [isMacOs, setIsMacOs] = useState<boolean>(false)
|
||||
const [macOsVersion, setMacOsVersion] = useState<string | null>(null)
|
||||
const [distroId, setDistroId] = useState<string | null>(null)
|
||||
const [distroBase, setDistroBase] = useState<string | null>(null)
|
||||
const [installedPrograms, setInstalledPrograms] = useState<InstalledPrograms>({
|
||||
winget: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
apt: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
dnf: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
brew: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
python: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
pip: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
python3: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
pip3: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
ffmpeg: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
pytubepp: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const unlisten = listen<WebSocketMessage>('websocket-message', (event) => {
|
||||
if(event.payload.command === 'send-stream-info') {
|
||||
@@ -78,7 +38,7 @@ function App() {
|
||||
} else if(event.payload.command === 'download-stream') {
|
||||
const startDownload = async () => {
|
||||
try {
|
||||
await invoke('download_stream', { url: event.payload.url, stream: event.payload.argument });
|
||||
await invoke('download_stream', { url: event.payload.url, stream: event.payload.argument.split(' ')[0], caption: event.payload.argument.split(' ')[1] });
|
||||
await invoke('receive_frontend_response', { response: 'Download started' });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@@ -99,314 +59,38 @@ function App() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
function checkAllPrograms() {
|
||||
isInstalled('winget', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
winget: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('apt', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
apt: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('dnf', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
dnf: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('homebrew', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
brew: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('python', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
python: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('pip', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
pip: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('python3', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
python3: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('pip3', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
pip3: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('ffmpeg', '-version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
ffmpeg: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
isInstalled('pytubepp', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
pytubepp: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
checkAllPrograms();
|
||||
const runPlatformSpecificChecks = async () => {
|
||||
const currentPlatform = await platform();
|
||||
|
||||
switch (currentPlatform) {
|
||||
case 'win32':
|
||||
const windowsResult = await detectWindows();
|
||||
if (windowsResult) {
|
||||
setIsWindows(true);
|
||||
setWindowsVersion(extractVersion(windowsResult));
|
||||
const checkForUpdates = async () => {
|
||||
let permissionGranted = await isPermissionGranted();
|
||||
if (!permissionGranted) {
|
||||
const permission = await requestPermission();
|
||||
permissionGranted = permission === 'granted';
|
||||
}
|
||||
break;
|
||||
|
||||
case 'darwin':
|
||||
const macResult = await detectMacOs();
|
||||
if (macResult) {
|
||||
setIsMacOs(true);
|
||||
setMacOsVersion(extractVersion(macResult));
|
||||
try {
|
||||
setIsAppUpdateChecked(true);
|
||||
const update = await checkAppUpdate();
|
||||
if (update) {
|
||||
console.log(`app update available v${update.version}`);
|
||||
if (permissionGranted) {
|
||||
sendNotification({ title: `Update Available (v${update.version})`, body: `A newer version of PytubePP Helper is available. Please update to the latest version to get the best experience!` });
|
||||
}
|
||||
break;
|
||||
|
||||
case 'linux':
|
||||
const distroResult = await detectDistro();
|
||||
if (distroResult) {
|
||||
setDistroId(extractDistroId(distroResult));
|
||||
setDistroBase(detectDistroBase(extractDistroId(distroResult)));
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Unsupported platform');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
runPlatformSpecificChecks().catch(console.error);
|
||||
|
||||
if (!isAppUpdateChecked) {
|
||||
checkForUpdates();
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
|
||||
<div className="container">
|
||||
<div className={clsx("topbar flex justify-between items-center mt-5", !isWindows && "mx-3")}>
|
||||
<h1 className="text-xl font-bold">PytubePP Helper</h1>
|
||||
<Button size="sm" onClick={checkAllPrograms}>Refresh</Button>
|
||||
</div>
|
||||
{ distroId && distroBase && distroBase === 'debian' ? /* Section for Debian */
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python3.installed ? 'installed' : 'not installed'} {installedPrograms.python3.version ? `(${installedPrograms.python3.version})` : ''}</p>
|
||||
{installedPrograms.python3.installed ? installedPrograms.python3.version ? compareVersions(installedPrograms.python3.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.apt.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install python3 -y'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.apt.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install ffmpeg -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip3.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip3 install pytubepp --break-system-packages'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.apt.installed && (!installedPrograms.python3.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>APT Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
APT is required to install necessary debian packages. Please install it manually for your distro.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(!installedPrograms.pip3.installed && !installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>PIP Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
PIP is required to install necessary python packages. Please install it now to continue: <Button variant="link" className="text-blue-600 p-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install python3-pip -y'})}}>install</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python3.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
: distroId && distroBase && distroBase === 'rhel' ? /* Section for RHEL */
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python3.installed ? 'installed' : 'not installed'} {installedPrograms.python3.version ? `(${installedPrograms.python3.version})` : ''}</p>
|
||||
{installedPrograms.python3.installed ? installedPrograms.python3.version ? compareVersions(installedPrograms.python3.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.dnf.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install python3 -y'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.dnf.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install ffmpeg-free -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip3.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip3 install pytubepp'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.dnf.installed && (!installedPrograms.python3.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>DNF Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
DNF is required to install necessary rpm packages. Please install it manually for your distro.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(!installedPrograms.pip3.installed && !installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>PIP Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
PIP is required to install necessary python packages. Please install it now to continue: <Button variant="link" className="text-blue-600 p-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install python3-pip -y'})}}>install</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python3.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
: isWindows && windowsVersion && parseInt(windowsVersion) >= 17134 ? /* Section for Windows */
|
||||
<div className="programstats mt-5">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python.installed ? 'installed' : 'not installed'} {installedPrograms.python.version ? `(${installedPrograms.python.version})` : ''}</p>
|
||||
{installedPrograms.python.installed ? installedPrograms.python.version ? compareVersions(installedPrograms.python.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.winget.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'winget install Python.Python.3.12'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.winget.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'winget install ffmpeg'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip install pytubepp'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.winget.installed && (!installedPrograms.python.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>WinGet Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
WinGet is required to install necessary packages. Please install it manually from <a className="underline" href="https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget" target="_blank">here</a>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
: isMacOs && macOsVersion && compareVersions(macOsVersion, '10.13') > 0 ? /* Section for macOS */
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python3.installed ? 'installed' : 'not installed'} {installedPrograms.python3.version ? `(${installedPrograms.python3.version})` : ''}</p>
|
||||
{installedPrograms.python3.installed ? installedPrograms.python3.version ? compareVersions(installedPrograms.python3.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.brew.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install python3 -y'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.brew.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install ffmpeg -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip3.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip3 install pytubepp --break-system-packages'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.brew.installed && (!installedPrograms.python3.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>Homebrew Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
Homebrew is required to install necessary unix packages. Please install it manually for your mac.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(!installedPrograms.pip3.installed && !installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>PIP Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
PIP is required to install necessary python packages. Please install it now to continue: <Button variant="link" className="text-blue-600 p-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install python3-pip -y'})}}>install</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python3.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
:
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>Unsupported OS</AlertTitle>
|
||||
<AlertDescription>
|
||||
Sorry, your os/distro is currently not supported. If you think this is just a mistake or you want to request us to add support for your os/distro you can create a github issue <a className="underline" href="https://github.com/neosubhamoy/pytubepp-helper/issues" target="_blank">here</a>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<TooltipProvider delayDuration={1000}>
|
||||
{children}
|
||||
<Toaster />
|
||||
</TooltipProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
35
src/components/ui/badge.tsx
Normal file
35
src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
|
||||
outline: "text-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
|
||||
75
src/components/ui/card.tsx
Normal file
75
src/components/ui/card.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Card = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-xl border bg-card text-card-foreground shadow",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Card.displayName = "Card"
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardDescription.displayName = "CardDescription"
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
))
|
||||
CardContent.displayName = "CardContent"
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex items-center p-6 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardFooter.displayName = "CardFooter"
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||
176
src/components/ui/form.tsx
Normal file
176
src/components/ui/form.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
ControllerProps,
|
||||
FieldPath,
|
||||
FieldValues,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState, formState } = useFormContext()
|
||||
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
const FormItem = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div ref={ref} className={cn("space-y-2", className)} {...props} />
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
})
|
||||
FormItem.displayName = "FormItem"
|
||||
|
||||
const FormLabel = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
ref={ref}
|
||||
className={cn(error && "text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormLabel.displayName = "FormLabel"
|
||||
|
||||
const FormControl = React.forwardRef<
|
||||
React.ElementRef<typeof Slot>,
|
||||
React.ComponentPropsWithoutRef<typeof Slot>
|
||||
>(({ ...props }, ref) => {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
ref={ref}
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormControl.displayName = "FormControl"
|
||||
|
||||
const FormDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formDescriptionId}
|
||||
className={cn("text-[0.8rem] text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
FormDescription.displayName = "FormDescription"
|
||||
|
||||
const FormMessage = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, children, ...props }, ref) => {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message) : children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
ref={ref}
|
||||
id={formMessageId}
|
||||
className={cn("text-[0.8rem] font-medium text-destructive", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
})
|
||||
FormMessage.displayName = "FormMessage"
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
22
src/components/ui/input.tsx
Normal file
22
src/components/ui/input.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
24
src/components/ui/label.tsx
Normal file
24
src/components/ui/label.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const labelVariants = cva(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
)
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||
VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Label.displayName = LabelPrimitive.Root.displayName
|
||||
|
||||
export { Label }
|
||||
37
src/components/ui/notification-badge.tsx
Normal file
37
src/components/ui/notification-badge.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Badge, BadgeProps } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface NotificationBadgeProps extends BadgeProps {
|
||||
label?: string | number;
|
||||
show?: boolean;
|
||||
}
|
||||
|
||||
export const NotificationBadge = ({
|
||||
label,
|
||||
className,
|
||||
show,
|
||||
children,
|
||||
...props
|
||||
}: NotificationBadgeProps) => {
|
||||
const showBadge =
|
||||
typeof label !== 'undefined' && (typeof show === 'undefined' || show);
|
||||
return (
|
||||
<div className='inline-flex relative'>
|
||||
{children}
|
||||
{showBadge && (
|
||||
<Badge
|
||||
className={cn(
|
||||
'absolute top-0 right-0 rounded-full',
|
||||
typeof label !== 'undefined' && ('' + label).length === 0
|
||||
? 'translate-x-1 -translate-y-1 px-1.5 py-1.5'
|
||||
: 'translate-x-1.5 -translate-y-1.5 px-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{'' + label}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
27
src/components/ui/progress.tsx
Normal file
27
src/components/ui/progress.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Progress = React.forwardRef<
|
||||
React.ElementRef<typeof ProgressPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
|
||||
>(({ className, value, ...props }, ref) => (
|
||||
<ProgressPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
className="h-full w-full flex-1 bg-primary transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
))
|
||||
Progress.displayName = ProgressPrimitive.Root.displayName
|
||||
|
||||
export { Progress }
|
||||
126
src/components/ui/toast.tsx
Normal file
126
src/components/ui/toast.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Cross2Icon } from "@radix-ui/react-icons"
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
|
||||
const toastVariants = cva(
|
||||
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border bg-background text-foreground",
|
||||
destructive:
|
||||
"destructive group border-destructive bg-destructive text-destructive-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
||||
VariantProps<typeof toastVariants>
|
||||
>(({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<ToastPrimitives.Root
|
||||
ref={ref}
|
||||
className={cn(toastVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Toast.displayName = ToastPrimitives.Root.displayName
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Action
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
||||
|
||||
const ToastClose = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
|
||||
className
|
||||
)}
|
||||
toast-close=""
|
||||
{...props}
|
||||
>
|
||||
<Cross2Icon className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Title
|
||||
ref={ref}
|
||||
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm opacity-90", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
||||
|
||||
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
||||
|
||||
type ToastActionElement = React.ReactElement<typeof ToastAction>
|
||||
|
||||
export {
|
||||
type ToastProps,
|
||||
type ToastActionElement,
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastAction,
|
||||
}
|
||||
33
src/components/ui/toaster.tsx
Normal file
33
src/components/ui/toaster.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import {
|
||||
Toast,
|
||||
ToastClose,
|
||||
ToastDescription,
|
||||
ToastProvider,
|
||||
ToastTitle,
|
||||
ToastViewport,
|
||||
} from "@/components/ui/toast"
|
||||
|
||||
export function Toaster() {
|
||||
const { toasts } = useToast()
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
{toasts.map(function ({ id, title, description, action, ...props }) {
|
||||
return (
|
||||
<Toast key={id} {...props}>
|
||||
<div className="grid gap-1">
|
||||
{title && <ToastTitle>{title}</ToastTitle>}
|
||||
{description && (
|
||||
<ToastDescription>{description}</ToastDescription>
|
||||
)}
|
||||
</div>
|
||||
{action}
|
||||
<ToastClose />
|
||||
</Toast>
|
||||
)
|
||||
})}
|
||||
<ToastViewport />
|
||||
</ToastProvider>
|
||||
)
|
||||
}
|
||||
30
src/components/ui/tooltip.tsx
Normal file
30
src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root
|
||||
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</TooltipPrimitive.Portal>
|
||||
))
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
194
src/hooks/use-toast.ts
Normal file
194
src/hooks/use-toast.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
"use client"
|
||||
|
||||
// Inspired by react-hot-toast library
|
||||
import * as React from "react"
|
||||
|
||||
import type {
|
||||
ToastActionElement,
|
||||
ToastProps,
|
||||
} from "@/components/ui/toast"
|
||||
|
||||
const TOAST_LIMIT = 1
|
||||
const TOAST_REMOVE_DELAY = 1000000
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
title?: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
action?: ToastActionElement
|
||||
}
|
||||
|
||||
const actionTypes = {
|
||||
ADD_TOAST: "ADD_TOAST",
|
||||
UPDATE_TOAST: "UPDATE_TOAST",
|
||||
DISMISS_TOAST: "DISMISS_TOAST",
|
||||
REMOVE_TOAST: "REMOVE_TOAST",
|
||||
} as const
|
||||
|
||||
let count = 0
|
||||
|
||||
function genId() {
|
||||
count = (count + 1) % Number.MAX_SAFE_INTEGER
|
||||
return count.toString()
|
||||
}
|
||||
|
||||
type ActionType = typeof actionTypes
|
||||
|
||||
type Action =
|
||||
| {
|
||||
type: ActionType["ADD_TOAST"]
|
||||
toast: ToasterToast
|
||||
}
|
||||
| {
|
||||
type: ActionType["UPDATE_TOAST"]
|
||||
toast: Partial<ToasterToast>
|
||||
}
|
||||
| {
|
||||
type: ActionType["DISMISS_TOAST"]
|
||||
toastId?: ToasterToast["id"]
|
||||
}
|
||||
| {
|
||||
type: ActionType["REMOVE_TOAST"]
|
||||
toastId?: ToasterToast["id"]
|
||||
}
|
||||
|
||||
interface State {
|
||||
toasts: ToasterToast[]
|
||||
}
|
||||
|
||||
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
const addToRemoveQueue = (toastId: string) => {
|
||||
if (toastTimeouts.has(toastId)) {
|
||||
return
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
toastTimeouts.delete(toastId)
|
||||
dispatch({
|
||||
type: "REMOVE_TOAST",
|
||||
toastId: toastId,
|
||||
})
|
||||
}, TOAST_REMOVE_DELAY)
|
||||
|
||||
toastTimeouts.set(toastId, timeout)
|
||||
}
|
||||
|
||||
export const reducer = (state: State, action: Action): State => {
|
||||
switch (action.type) {
|
||||
case "ADD_TOAST":
|
||||
return {
|
||||
...state,
|
||||
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
|
||||
}
|
||||
|
||||
case "UPDATE_TOAST":
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((t) =>
|
||||
t.id === action.toast.id ? { ...t, ...action.toast } : t
|
||||
),
|
||||
}
|
||||
|
||||
case "DISMISS_TOAST": {
|
||||
const { toastId } = action
|
||||
|
||||
// ! Side effects ! - This could be extracted into a dismissToast() action,
|
||||
// but I'll keep it here for simplicity
|
||||
if (toastId) {
|
||||
addToRemoveQueue(toastId)
|
||||
} else {
|
||||
state.toasts.forEach((toast) => {
|
||||
addToRemoveQueue(toast.id)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((t) =>
|
||||
t.id === toastId || toastId === undefined
|
||||
? {
|
||||
...t,
|
||||
open: false,
|
||||
}
|
||||
: t
|
||||
),
|
||||
}
|
||||
}
|
||||
case "REMOVE_TOAST":
|
||||
if (action.toastId === undefined) {
|
||||
return {
|
||||
...state,
|
||||
toasts: [],
|
||||
}
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.filter((t) => t.id !== action.toastId),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const listeners: Array<(state: State) => void> = []
|
||||
|
||||
let memoryState: State = { toasts: [] }
|
||||
|
||||
function dispatch(action: Action) {
|
||||
memoryState = reducer(memoryState, action)
|
||||
listeners.forEach((listener) => {
|
||||
listener(memoryState)
|
||||
})
|
||||
}
|
||||
|
||||
type Toast = Omit<ToasterToast, "id">
|
||||
|
||||
function toast({ ...props }: Toast) {
|
||||
const id = genId()
|
||||
|
||||
const update = (props: ToasterToast) =>
|
||||
dispatch({
|
||||
type: "UPDATE_TOAST",
|
||||
toast: { ...props, id },
|
||||
})
|
||||
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
|
||||
|
||||
dispatch({
|
||||
type: "ADD_TOAST",
|
||||
toast: {
|
||||
...props,
|
||||
id,
|
||||
open: true,
|
||||
onOpenChange: (open) => {
|
||||
if (!open) dismiss()
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
id: id,
|
||||
dismiss,
|
||||
update,
|
||||
}
|
||||
}
|
||||
|
||||
function useToast() {
|
||||
const [state, setState] = React.useState<State>(memoryState)
|
||||
|
||||
React.useEffect(() => {
|
||||
listeners.push(setState)
|
||||
return () => {
|
||||
const index = listeners.indexOf(setState)
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}, [state])
|
||||
|
||||
return {
|
||||
...state,
|
||||
toast,
|
||||
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
|
||||
}
|
||||
}
|
||||
|
||||
export { useToast, toast }
|
||||
79
src/lib/platform-utils.ts
Normal file
79
src/lib/platform-utils.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { platform } from "@tauri-apps/plugin-os";
|
||||
import { detectDistro, detectMacOs, detectPackageManager, detectWindows, extractDistroId, extractPkgMngrName, extractVersion } from "@/lib/utils";
|
||||
import { PlatformInfo } from "@/types";
|
||||
|
||||
export async function getPlatformInfo(): Promise<PlatformInfo> {
|
||||
const defaultInfo: PlatformInfo = {
|
||||
isWindows: false,
|
||||
windowsVersion: null,
|
||||
isMacOs: false,
|
||||
macOsVersion: null,
|
||||
distroId: null,
|
||||
distroPkgMngr: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const currentPlatform = await platform();
|
||||
|
||||
switch (currentPlatform) {
|
||||
case 'windows': {
|
||||
const windowsResult = await detectWindows();
|
||||
if (windowsResult) {
|
||||
return {
|
||||
...defaultInfo,
|
||||
isWindows: true,
|
||||
windowsVersion: extractVersion(windowsResult),
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'macos': {
|
||||
const macResult = await detectMacOs();
|
||||
if (macResult) {
|
||||
return {
|
||||
...defaultInfo,
|
||||
isMacOs: true,
|
||||
macOsVersion: extractVersion(macResult),
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'linux': {
|
||||
const distroResult = await detectDistro();
|
||||
if (distroResult) {
|
||||
const distroPkgMngrResult = await detectPackageManager();
|
||||
return {
|
||||
...defaultInfo,
|
||||
distroId: extractDistroId(distroResult),
|
||||
distroPkgMngr: distroPkgMngrResult ? extractPkgMngrName(distroPkgMngrResult) : null,
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
console.log('Unsupported platform');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error detecting platform:', error);
|
||||
}
|
||||
|
||||
return defaultInfo;
|
||||
}
|
||||
|
||||
// Individual getters for specific platforms
|
||||
export async function isWindowsPlatform(): Promise<{ isWindows: boolean; version: string | null }> {
|
||||
const info = await getPlatformInfo();
|
||||
return { isWindows: info.isWindows, version: info.windowsVersion };
|
||||
}
|
||||
|
||||
export async function isMacOsPlatform(): Promise<{ isMacOs: boolean; version: string | null }> {
|
||||
const info = await getPlatformInfo();
|
||||
return { isMacOs: info.isMacOs, version: info.macOsVersion };
|
||||
}
|
||||
|
||||
export async function getLinuxInfo(): Promise<{ distroId: string | null; packageManager: string | null }> {
|
||||
const info = await getPlatformInfo();
|
||||
return { distroId: info.distroId, packageManager: info.distroPkgMngr };
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { Command } from '@tauri-apps/api/shell';
|
||||
import { invoke } from "@tauri-apps/api";
|
||||
import { Command } from "@tauri-apps/plugin-shell";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { join, resourceDir, homeDir } from "@tauri-apps/api/path";
|
||||
import * as fs from "@tauri-apps/plugin-fs"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
@@ -9,7 +11,7 @@ export function cn(...inputs: ClassValue[]) {
|
||||
|
||||
export async function isInstalled(program: string, arg: string): Promise<{ installed: boolean, output: string | null }> {
|
||||
try{
|
||||
const output = await new Command('is-' + program + '-installed', [arg]).execute();
|
||||
const output = await Command.create('is-' + program + '-installed', [arg]).execute();
|
||||
if (output.code === 0) {
|
||||
return { installed: true, output: output.stdout };
|
||||
} else {
|
||||
@@ -23,7 +25,7 @@ export async function isInstalled(program: string, arg: string): Promise<{ insta
|
||||
|
||||
export async function detectWindows(): Promise<string | null> {
|
||||
try{
|
||||
const output = await new Command('detect-windows', []).execute();
|
||||
const output = await Command.create('detect-windows', []).execute();
|
||||
if (output.code === 0) {
|
||||
return output.stdout;
|
||||
} else {
|
||||
@@ -37,7 +39,7 @@ export async function detectWindows(): Promise<string | null> {
|
||||
|
||||
export async function detectMacOs(): Promise<string | null> {
|
||||
try{
|
||||
const output = await new Command('detect-macos', []).execute();
|
||||
const output = await Command.create('detect-macos', []).execute();
|
||||
if (output.code === 0) {
|
||||
return output.stdout;
|
||||
} else {
|
||||
@@ -51,7 +53,7 @@ export async function detectMacOs(): Promise<string | null> {
|
||||
|
||||
export async function detectDistro(): Promise<string | null> {
|
||||
try{
|
||||
const output = await new Command('detect-distro', ['^ID=', '/etc/os-release']).execute();
|
||||
const output = await Command.create('detect-distro', ['^ID=', '/etc/os-release']).execute();
|
||||
if (output.code === 0) {
|
||||
return output.stdout;
|
||||
} else {
|
||||
@@ -63,20 +65,27 @@ export async function detectDistro(): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
export function detectDistroBase(distro: string | null): string | null{
|
||||
if(distro) {
|
||||
if(['debian', 'ubuntu', 'pop', 'kali'].includes(distro)) {
|
||||
return 'debian';
|
||||
} else if (['rhel', 'fedora', 'centos', 'rocky'].includes(distro)) {
|
||||
return 'rhel';
|
||||
export async function detectPackageManager(): Promise<string | null> {
|
||||
try{
|
||||
const output = await Command.create('detect-pkgmngr', ['-c', 'command -v apt || command -v dnf || command -v pacman']).execute();
|
||||
if (output.code === 0) {
|
||||
return output.stdout;
|
||||
} else {
|
||||
return 'other';
|
||||
return output.stdout;
|
||||
}
|
||||
} else {
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function extractPkgMngrName(path: string): string | null {
|
||||
const pattern = /^\s*(.*\/)?([^\/\s]+)\s*$/;
|
||||
const match = path.trim().match(pattern);
|
||||
if (!match) return null;
|
||||
return match[2];
|
||||
}
|
||||
|
||||
export function extractDistroId(input: string): string | null {
|
||||
const regex = /ID=([a-zA-Z]+)/;
|
||||
const match = input.match(regex);
|
||||
@@ -89,7 +98,7 @@ export function extractVersion(output: string): string | null {
|
||||
/Python (\d+\.\d+\.\d+)/, // Pattern for Python
|
||||
/pytubefix (\d+\.\d+\.\d+)/, // Pattern for pytubefix
|
||||
/pytubepp (\d+\.\d+\.\d+)/, // Pattern for pytubepp
|
||||
/v(\d+\.\d+\.\d+)/, // Pattern for winget
|
||||
/v(\d+\.\d+\.\d+)/, // Pattern for winget, Node.js
|
||||
/pip (\d+\.\d+)/, // Pattern for pip
|
||||
/OS Version:.*Build (\d+)/, // Pattern for Windows build
|
||||
/apt (\d+\.\d+\.\d+)/, // Pattern for apt
|
||||
@@ -109,7 +118,7 @@ export function extractVersion(output: string): string | null {
|
||||
export async function sendStreamInfo(url: string) {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const output = await new Command('fetch-video-info', [url, '--raw-info']).execute();
|
||||
const output = await Command.create('fetch-video-info', [url, '--raw-info']).execute();
|
||||
if (output.code === 0) {
|
||||
console.log(output.stdout);
|
||||
const sendStreamData = async () => {
|
||||
@@ -142,3 +151,38 @@ export function compareVersions (v1: string, v2: string) {
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
export async function registerMacFiles() {
|
||||
try {
|
||||
const filesToCopy = [
|
||||
{ source: 'pytubepp-helper-autostart.plist', destination: 'Library/LaunchAgents/com.neosubhamoy.pytubepp.helper.plist', dir: 'Library/LaunchAgents/' },
|
||||
{ source: 'pytubepp-helper-msghost.json', destination: 'Library/Application Support/Google/Chrome/NativeMessagingHosts/com.neosubhamoy.pytubepp.helper.json', dir: 'Library/Application Support/Google/Chrome/NativeMessagingHosts/' },
|
||||
{ source: 'pytubepp-helper-msghost.json', destination: 'Library/Application Support/Chromium/NativeMessagingHosts/com.neosubhamoy.pytubepp.helper.json', dir: 'Library/Application Support/Chromium/NativeMessagingHosts/' },
|
||||
{ source: 'pytubepp-helper-msghost-moz.json', destination: 'Library/Application Support/Mozilla/NativeMessagingHosts/com.neosubhamoy.pytubepp.helper.json', dir: 'Library/Application Support/Mozilla/NativeMessagingHosts/' },
|
||||
];
|
||||
|
||||
const resourceDirPath = await resourceDir();
|
||||
const homeDirPath = await homeDir();
|
||||
|
||||
for (const file of filesToCopy) {
|
||||
const sourcePath = await join(resourceDirPath, file.source);
|
||||
const destinationDir = await join(homeDirPath, file.dir);
|
||||
const destinationPath = await join(homeDirPath, file.destination);
|
||||
|
||||
const dirExists = await fs.exists(destinationDir);
|
||||
if (dirExists) {
|
||||
await fs.copyFile(sourcePath, destinationPath);
|
||||
console.log(`File ${file.source} copied successfully to ${destinationPath}`);
|
||||
} else {
|
||||
await fs.mkdir(destinationDir, { recursive: true })
|
||||
console.log(`Created dir ${destinationDir}`);
|
||||
await fs.copyFile(sourcePath, destinationPath);
|
||||
console.log(`File ${file.source} copied successfully to ${destinationPath}`);
|
||||
}
|
||||
}
|
||||
return { success: true, message: 'Registered successfully' }
|
||||
} catch (error) {
|
||||
console.error('Error copying files:', error);
|
||||
return { success: false, message: 'Failed to register' }
|
||||
}
|
||||
}
|
||||
19
src/main.tsx
19
src/main.tsx
@@ -1,9 +1,22 @@
|
||||
import React from "react";
|
||||
import "@/index.css";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import App from "./App";
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import App from "@/App";
|
||||
import HomePage from "@/pages/home";
|
||||
import SettingsPage from "@/pages/settings";
|
||||
import NotificationsPage from "@/pages/notifications";
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
<App>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
<Route path="/notifications" element={<NotificationsPage />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</App>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
||||
472
src/pages/home.tsx
Normal file
472
src/pages/home.tsx
Normal file
@@ -0,0 +1,472 @@
|
||||
import clsx from "clsx";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
|
||||
import { InstalledPrograms } from "@/types";
|
||||
import { compareVersions, extractVersion, isInstalled, registerMacFiles } from "@/lib/utils";
|
||||
import { CircleCheck, TriangleAlert, CircleAlert, Settings, RefreshCcw, Loader2, PackagePlus, Bell } from "lucide-react";
|
||||
import { getPlatformInfo } from "@/lib/platform-utils";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { NotificationBadge } from "@/components/ui/notification-badge";
|
||||
import { check as checkAppUpdate } from "@tauri-apps/plugin-updater";
|
||||
|
||||
export default function HomePage() {
|
||||
const { toast } = useToast();
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isWindows, setIsWindows] = useState<boolean>(false)
|
||||
const [windowsVersion, setWindowsVersion] = useState<string | null>(null)
|
||||
const [isMacOs, setIsMacOs] = useState<boolean>(false)
|
||||
const [macOsVersion, setMacOsVersion] = useState<string | null>(null)
|
||||
const [distroId, setDistroId] = useState<string | null>(null)
|
||||
const [distroPkgMngr, setDistroPkgMngr] = useState<string | null>(null)
|
||||
const [isAppUpdateAvailable, setIsAppUpdateAvailable] = useState(false);
|
||||
const [installedPrograms, setInstalledPrograms] = useState<InstalledPrograms>({
|
||||
winget: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
apt: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
dnf: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
brew: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
python: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
pip: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
python3: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
pip3: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
ffmpeg: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
nodejs: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
pytubepp: {
|
||||
installed: false,
|
||||
version: null,
|
||||
},
|
||||
});
|
||||
|
||||
function checkAllPrograms() {
|
||||
return Promise.all([
|
||||
isInstalled('winget', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
winget: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('apt', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
apt: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('dnf', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
dnf: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('homebrew', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
brew: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('python', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
python: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('pip', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
pip: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('python3', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
python3: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('pip3', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
pip3: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('ffmpeg', '-version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
ffmpeg: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('nodejs', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
nodejs: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
}),
|
||||
isInstalled('pytubepp', '--version').then((result) => {
|
||||
setInstalledPrograms((prevState) => ({
|
||||
...prevState,
|
||||
pytubepp: {
|
||||
installed: result.installed,
|
||||
version: result.output ? extractVersion(result.output) : null,
|
||||
}
|
||||
}));
|
||||
})
|
||||
]);
|
||||
}
|
||||
|
||||
const fetchPlatformInfo = async () => {
|
||||
const info = await getPlatformInfo();
|
||||
setIsWindows(info.isWindows);
|
||||
setWindowsVersion(info.windowsVersion);
|
||||
setIsMacOs(info.isMacOs);
|
||||
setMacOsVersion(info.macOsVersion);
|
||||
setDistroId(info.distroId);
|
||||
setDistroPkgMngr(info.distroPkgMngr);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await Promise.all([
|
||||
checkAllPrograms(),
|
||||
fetchPlatformInfo()
|
||||
]);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
init();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const checkForUpdates = async () => {
|
||||
try {
|
||||
const update = await checkAppUpdate();
|
||||
setIsAppUpdateAvailable(update ? true : false);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
checkForUpdates();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<div className={clsx("topbar flex justify-between items-center mt-5", !isWindows && "mx-3")}>
|
||||
<h1 className="text-xl font-bold">PytubePP Helper</h1>
|
||||
<div className="flex items-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<NotificationBadge
|
||||
label='1'
|
||||
className='bg-green-700 text-white hover:bg-green-700 hover:cursor-default'
|
||||
show={isAppUpdateAvailable}
|
||||
>
|
||||
<Button variant="outline" size="icon" asChild>
|
||||
<Link to="/notifications">
|
||||
<Bell className="w-5 h-5"/>
|
||||
</Link>
|
||||
</Button>
|
||||
</NotificationBadge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>notifications</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Button className="ml-3" variant="outline" size="icon" asChild>
|
||||
<Link to="/settings">
|
||||
<Settings className="w-5 h-5"/>
|
||||
</Link>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent><p>settings</p></TooltipContent>
|
||||
</Tooltip>
|
||||
{ isMacOs && macOsVersion && compareVersions(macOsVersion, '10.13') > 0 ?
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Button className="ml-3" size="icon" onClick={async () => {
|
||||
const result = await registerMacFiles();
|
||||
toast({ title: result.message, variant: result.success ? 'default' : 'destructive' });
|
||||
}}>
|
||||
<PackagePlus className="w-5 h-5"/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent><p>register to mac</p></TooltipContent>
|
||||
</Tooltip>
|
||||
:
|
||||
null
|
||||
}
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Button className="ml-3" size="icon" disabled={isLoading} onClick={checkAllPrograms}>
|
||||
<RefreshCcw className="w-5 h-5"/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent><p>refresh</p></TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{ isLoading ?
|
||||
<div className="mt-5 mx-3">
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center justify-center py-[4.3rem]">
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin"/>
|
||||
<p className="ml-3 mt-2 text-muted-foreground">checking...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
: distroId && distroPkgMngr && distroPkgMngr === 'apt' ? /* Section for Debian */
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python3.installed ? 'installed' : 'not installed'} {installedPrograms.python3.version ? `(${installedPrograms.python3.version})` : ''}</p>
|
||||
{installedPrograms.python3.installed ? installedPrograms.python3.version ? compareVersions(installedPrograms.python3.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.apt.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install python3 -y'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.apt.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install ffmpeg -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Node.js:</b> {installedPrograms.nodejs.installed ? 'installed' : 'not installed'} {installedPrograms.nodejs.version ? `(${installedPrograms.nodejs.version})` : ''}</p>
|
||||
{installedPrograms.nodejs.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.apt.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install nodejs -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip3.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip3 install pytubepp || pip3 install pytubepp --break-system-packages'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.apt.installed && (!installedPrograms.python3.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>APT Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
APT is required to install necessary debian packages. Please install it manually for your distro.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(!installedPrograms.pip3.installed && !installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>PIP Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
PIP is required to install necessary python packages. Please install it now to continue: <Button variant="link" className="text-blue-600 p-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install python3-pip -y'})}}>install</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python3.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
: distroId && distroPkgMngr && distroPkgMngr === 'dnf' ? /* Section for RHEL */
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python3.installed ? 'installed' : 'not installed'} {installedPrograms.python3.version ? `(${installedPrograms.python3.version})` : ''}</p>
|
||||
{installedPrograms.python3.installed ? installedPrograms.python3.version ? compareVersions(installedPrograms.python3.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.dnf.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install python3 -y'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.dnf.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install ffmpeg -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Node.js:</b> {installedPrograms.nodejs.installed ? 'installed' : 'not installed'} {installedPrograms.nodejs.version ? `(${installedPrograms.nodejs.version})` : ''}</p>
|
||||
{installedPrograms.nodejs.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.dnf.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install nodejs -y'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip3.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip3 install pytubepp || pip3 install pytubepp --break-system-packages'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.dnf.installed && (!installedPrograms.python3.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>DNF Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
DNF is required to install necessary rpm packages. Please install it manually for your distro.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(!installedPrograms.pip3.installed && !installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>PIP Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
PIP is required to install necessary python packages. Please install it now to continue: <Button variant="link" className="text-blue-600 p-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install python3-pip -y'})}}>install</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python3.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
: isWindows && windowsVersion && parseInt(windowsVersion) >= 17134 ? /* Section for Windows */
|
||||
<div className="programstats mt-5">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python.installed ? 'installed' : 'not installed'} {installedPrograms.python.version ? `(${installedPrograms.python.version})` : ''}</p>
|
||||
{installedPrograms.python.installed ? installedPrograms.python.version ? compareVersions(installedPrograms.python.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.winget.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'winget install Python.Python.3.12'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.winget.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'winget install ffmpeg'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Node.js:</b> {installedPrograms.nodejs.installed ? 'installed' : 'not installed'} {installedPrograms.nodejs.version ? `(${installedPrograms.nodejs.version})` : ''}</p>
|
||||
{installedPrograms.nodejs.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.winget.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'winget install OpenJS.NodeJS.LTS'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip install pytubepp'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.winget.installed && (!installedPrograms.python.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>WinGet Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
WinGet is required to install necessary packages. Please install it manually from <a className="underline" href="https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget" target="_blank">here</a>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python.installed && installedPrograms.ffmpeg.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
: isMacOs && macOsVersion && compareVersions(macOsVersion, '10.13') > 0 ? /* Section for macOS */
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Python:</b> {installedPrograms.python3.installed ? 'installed' : 'not installed'} {installedPrograms.python3.version ? `(${installedPrograms.python3.version})` : ''}</p>
|
||||
{installedPrograms.python3.installed ? installedPrograms.python3.version ? compareVersions(installedPrograms.python3.version, '3.8') < 0 ? <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.brew.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install python'})}}>install</Button> : <TriangleAlert className="w-5 h-5 my-2 text-orange-400"/> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>FFmpeg:</b> {installedPrograms.ffmpeg.installed ? 'installed' : 'not installed'} {installedPrograms.ffmpeg.version ? `(${installedPrograms.ffmpeg.version})` : ''}</p>
|
||||
{installedPrograms.ffmpeg.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.brew.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install ffmpeg'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>Node.js:</b> {installedPrograms.nodejs.installed ? 'installed' : 'not installed'} {installedPrograms.nodejs.version ? `(${installedPrograms.nodejs.version})` : ''}</p>
|
||||
{installedPrograms.nodejs.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.brew.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install node'})}}>install</Button> : null}
|
||||
</div>
|
||||
<div className="programitem flex items-center justify-between">
|
||||
<p><b>PytubePP:</b> {installedPrograms.pytubepp.installed ? 'installed' : 'not installed'} {installedPrograms.pytubepp.version ? `(${installedPrograms.pytubepp.version})` : ''}</p>
|
||||
{installedPrograms.pytubepp.installed ? <CircleCheck className="w-5 h-5 my-2 text-green-400"/> : installedPrograms.pip3.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip3 install pytubepp || pip3 install pytubepp --break-system-packages'})}}>install</Button> : null}
|
||||
</div>
|
||||
{(!installedPrograms.brew.installed && (!installedPrograms.python3.installed || !installedPrograms.ffmpeg.installed)) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>Homebrew Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
Homebrew is required to install necessary unix packages. Please install it manually for your mac.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(!installedPrograms.pip3.installed && !installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>PIP Not Found</AlertTitle>
|
||||
<AlertDescription>
|
||||
PIP is required to install necessary python packages. Please install it now to continue: <Button variant="link" className="text-blue-600 p-0" onClick={async () => { await invoke('install_program', {icommand: 'brew install python3-pip -y'})}}>install</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
{(installedPrograms.python3.installed && installedPrograms.ffmpeg.installed && installedPrograms.nodejs.installed && installedPrograms.pytubepp.installed) ?
|
||||
<Alert className="mt-5">
|
||||
<CircleCheck className="h-5 w-5" />
|
||||
<AlertTitle>Ready</AlertTitle>
|
||||
<AlertDescription>
|
||||
Everything looks ok! You can close this window now. Make sure it's always running in the background.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
: null}
|
||||
</div>
|
||||
:
|
||||
<div className="programstats mt-5 mx-3">
|
||||
<Alert className="mt-5" variant="destructive">
|
||||
<CircleAlert className="h-5 w-5" />
|
||||
<AlertTitle>Unsupported OS</AlertTitle>
|
||||
<AlertDescription>
|
||||
Sorry, your os/distro is currently not supported. If you think this is just a mistake or you want to request us to add support for your os/distro you can create a github issue <a className="underline" href="https://github.com/neosubhamoy/pytubepp-helper/issues" target="_blank">here</a>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
151
src/pages/notifications.tsx
Normal file
151
src/pages/notifications.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import clsx from "clsx";
|
||||
import { useState, useEffect } from "react";
|
||||
import { getPlatformInfo } from "@/lib/platform-utils";
|
||||
import { PlatformInfo } from "@/types";
|
||||
import { ArrowLeft, Download, Loader2, RefreshCcw } from "lucide-react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { check as checkAppUpdate, Update } from "@tauri-apps/plugin-updater";
|
||||
import { relaunch as relaunchApp } from "@tauri-apps/plugin-process";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
|
||||
export default function NotificationsPage() {
|
||||
const [platformInfo, setPlatformInfo] = useState<PlatformInfo | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [appUpdate, setAppUpdate] = useState<Update | null>(null);
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
const [downloadProgress, setDownloadProgress] = useState(0);
|
||||
|
||||
async function checkForUpdates() {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const update = await checkAppUpdate();
|
||||
if (update) {
|
||||
setAppUpdate(update);
|
||||
console.log(`app update available v${update.version}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadAndInstallUpdate(update: Update) {
|
||||
setIsUpdating(true);
|
||||
let downloaded = 0;
|
||||
let contentLength: number | undefined = 0;
|
||||
await update.downloadAndInstall((event) => {
|
||||
switch (event.event) {
|
||||
case 'Started':
|
||||
contentLength = event.data.contentLength;
|
||||
console.log(`started downloading ${event.data.contentLength} bytes`);
|
||||
break;
|
||||
case 'Progress':
|
||||
downloaded += event.data.chunkLength;
|
||||
setDownloadProgress(downloaded / (contentLength || 0));
|
||||
console.log(`downloaded ${downloaded} from ${contentLength}`);
|
||||
break;
|
||||
case 'Finished':
|
||||
console.log('download finished');
|
||||
setIsUpdating(false);
|
||||
break;
|
||||
}
|
||||
});
|
||||
await relaunchApp();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
getPlatformInfo().then(setPlatformInfo).catch(console.error);
|
||||
checkForUpdates();
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<div className={clsx("topbar flex justify-between items-center mt-5", !platformInfo?.isWindows && "mx-3")}>
|
||||
<div className="flex items-center">
|
||||
<Link to="/" className={clsx(isUpdating && "pointer-events-none opacity-50")}>
|
||||
<ArrowLeft className="w-5 h-5 mr-3"/>
|
||||
</Link>
|
||||
<h1 className="text-xl font-bold">Notifications</h1>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Button className="ml-3" size="icon" disabled={isLoading || isUpdating} onClick={checkForUpdates}>
|
||||
<RefreshCcw className="w-5 h-5"/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent><p>refresh</p></TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className={clsx("mt-5", !platformInfo?.isWindows && "mx-3")}>
|
||||
{
|
||||
isLoading ? (
|
||||
<div className="mt-5 mx-3">
|
||||
<div className="flex flex-col min-h-[55vh]">
|
||||
<div className="flex items-center justify-center py-[4.3rem]">
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin"/>
|
||||
<p className="ml-3 mt-2 text-muted-foreground">ckecking...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : appUpdate ? (
|
||||
<div className="mt-5">
|
||||
<div className="flex flex-col min-h-[55vh]">
|
||||
<Card className="">
|
||||
<CardHeader>
|
||||
<CardTitle>PytubePP Helper v{appUpdate.version} - Update Available</CardTitle>
|
||||
<CardDescription>A newer version of PytubePP Helper is available. Please update to the latest version to get the best experience!</CardDescription>
|
||||
{
|
||||
isUpdating && (
|
||||
<Progress value={downloadProgress * 100}/>
|
||||
)
|
||||
}
|
||||
</CardHeader>
|
||||
<CardFooter className="flex justify-between">
|
||||
<div>
|
||||
{
|
||||
isUpdating && (
|
||||
<div className="flex items-center">
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin"/>
|
||||
<p className="text-sm text-muted-foreground">Downloading...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
<div>
|
||||
<Button variant="link" size="sm" asChild>
|
||||
<a href="https://github.com/neosubhamoy/pytubepp-helper/releases/latest" target="_blank">✨ Changelog</a>
|
||||
</Button>
|
||||
<Button className="ml-3" size="sm" disabled={isUpdating} onClick={() => downloadAndInstallUpdate(appUpdate)}>
|
||||
<Download className="w-4 h-4 mr-2"/>
|
||||
Update
|
||||
</Button>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-5 mx-3">
|
||||
<div className="flex flex-col min-h-[55vh]">
|
||||
<div className="flex items-center justify-center py-[4.3rem]">
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<p className="font-semibold ml-3 mt-2">No Notifications</p>
|
||||
<p className="text-sm ml-3 mt-1 text-muted-foreground">You are all caught up! for now 😉</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
206
src/pages/settings.tsx
Normal file
206
src/pages/settings.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
import clsx from "clsx";
|
||||
import { z } from "zod";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { getVersion } from "@tauri-apps/api/app";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArrowLeft, Github, Globe, History, Save } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Config, PlatformInfo } from "@/types";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { getPlatformInfo } from "@/lib/platform-utils";
|
||||
|
||||
const DEFAULT_PORT = 3030;
|
||||
const settingsFormSchema = z.object({
|
||||
port: z.number().min(3000, { message: "Port must be greater than 3000" }).max(3999, { message: "Port must be less than 3999" }),
|
||||
})
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { toast } = useToast();
|
||||
const [platformInfo, setPlatformInfo] = useState<PlatformInfo | null>(null);
|
||||
const [appConfig, setAppConfig] = useState<Config | null>(null);
|
||||
const [appVersion, setAppVersion] = useState<string | null>(null);
|
||||
const [isFormDirty, setIsFormDirty] = useState(false);
|
||||
const saveButtonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const settingsForm = useForm<z.infer<typeof settingsFormSchema>>({
|
||||
resolver: zodResolver(settingsFormSchema),
|
||||
defaultValues: {
|
||||
port: DEFAULT_PORT,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = settingsForm.watch((value) => {
|
||||
if (appConfig) {
|
||||
setIsFormDirty(value.port !== appConfig.port);
|
||||
}
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
}, [settingsForm, appConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
const getConfig = async () => {
|
||||
const config: Config = await invoke("get_config");
|
||||
if (config) {
|
||||
setAppConfig(config);
|
||||
settingsForm.reset({ port: config.port });
|
||||
}
|
||||
}
|
||||
getConfig().catch(console.error);
|
||||
}, [settingsForm]);
|
||||
|
||||
useEffect(() => {
|
||||
getPlatformInfo().then(setPlatformInfo).catch(console.error);
|
||||
const getAppVersion = async () => {
|
||||
const version = await getVersion();
|
||||
setAppVersion(version);
|
||||
}
|
||||
getAppVersion().catch(console.error);
|
||||
}, [])
|
||||
|
||||
const updateConfig = async () => {
|
||||
try {
|
||||
const updatedConfig: Config = await invoke("update_config", {
|
||||
newConfig: {
|
||||
port: Number(settingsForm.getValues().port)
|
||||
}
|
||||
});
|
||||
setAppConfig(updatedConfig);
|
||||
setIsFormDirty(false);
|
||||
toast({
|
||||
title: "Settings updated"
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to update config:", error);
|
||||
toast({
|
||||
title: "Failed to update settings",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const resetConfig = async () => {
|
||||
try {
|
||||
const config: Config = await invoke("reset_config");
|
||||
setAppConfig(config);
|
||||
settingsForm.reset({ port: config.port });
|
||||
setIsFormDirty(false);
|
||||
toast({
|
||||
title: "Using default settings"
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to reset config:", error);
|
||||
toast({
|
||||
title: "Failed to reset settings",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const isUsingDefaultConfig = appConfig?.port === DEFAULT_PORT;
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<div className={clsx("topbar flex justify-between items-center mt-5", !platformInfo?.isWindows && "mx-3")}>
|
||||
<div className="flex items-center">
|
||||
<Link to="/">
|
||||
<ArrowLeft className="w-5 h-5 mr-3"/>
|
||||
</Link>
|
||||
<h1 className="text-xl font-bold">Settings</h1>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Button
|
||||
className="ml-3"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => resetConfig()}
|
||||
disabled={isUsingDefaultConfig}
|
||||
>
|
||||
<History className="w-5 h-5"/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isUsingDefaultConfig ? "using default settings" : "reset to default"}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<Button
|
||||
className="ml-3"
|
||||
size="icon"
|
||||
onClick={() => saveButtonRef.current?.click()}
|
||||
disabled={!isFormDirty}
|
||||
>
|
||||
<Save className="w-5 h-5"/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isFormDirty ? "save changes" : "no changes to save"}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className={clsx("mt-5", !platformInfo?.isWindows && "mx-3")}>
|
||||
<div className="flex flex-col min-h-[55vh]">
|
||||
<Form {...settingsForm}>
|
||||
<form onSubmit={settingsForm.handleSubmit(updateConfig)}>
|
||||
<FormField
|
||||
control={settingsForm.control}
|
||||
name="port"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Port</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="text"
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
field.onChange(value ? Number(value) : DEFAULT_PORT);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
The port to use for the websocket server
|
||||
</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button className="hidden" ref={saveButtonRef} type="submit">Save</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
<div className="flex justify-between items-center border-t border-muted-foreground/50 pt-2">
|
||||
<div className="flex flex-col">
|
||||
<p>PytubePP Helper <span className="text-muted-foreground">|</span> <span className="text-sm text-muted-foreground">v{appVersion}-beta</span></p>
|
||||
<p className="text-xs text-muted-foreground">© {new Date().getFullYear()} - <a href="https://github.com/neosubhamoy/pytubepp-helper/blob/main/LICENSE" target="_blank">MIT License</a> - Made with ❤️ by <a href="https://neosubhamoy.com" target="_blank">Subhamoy</a></p>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="flex justify-center items-center gap-2">
|
||||
<a href="https://pytubepp.neosubhamoy.com" target="_blank" title="website">
|
||||
<Globe className="w-4 h-4 text-muted-foreground"/>
|
||||
</a>
|
||||
<a href="https://github.com/neosubhamoy/pytubepp-helper" target="_blank" title="github">
|
||||
<Github className="w-4 h-4 text-muted-foreground"/>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
17
src/types.ts
17
src/types.ts
@@ -1,3 +1,16 @@
|
||||
export interface Config {
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface PlatformInfo {
|
||||
isWindows: boolean;
|
||||
windowsVersion: string | null;
|
||||
isMacOs: boolean;
|
||||
macOsVersion: string | null;
|
||||
distroId: string | null;
|
||||
distroPkgMngr: string | null;
|
||||
}
|
||||
|
||||
export interface InstalledPrograms {
|
||||
winget: {
|
||||
installed: boolean;
|
||||
@@ -35,6 +48,10 @@ export interface InstalledPrograms {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
};
|
||||
nodejs: {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
};
|
||||
pytubepp: {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
|
||||
Reference in New Issue
Block a user