mirror of
https://github.com/neosubhamoy/pytubepp-helper.git
synced 2026-02-04 11:22:22 +05:30
Compare commits
19 Commits
v0.6.0-bet
...
v0.7.0-bet
34
.github/workflows/release.yml
vendored
34
.github/workflows/release.yml
vendored
@@ -55,15 +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 }}
|
||||
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
|
||||
35
README.md
35
README.md
@@ -8,34 +8,39 @@ 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)
|
||||
- Linux (Debian/Ubuntu, Fedora/RHEL base)
|
||||
- MacOS (v10.13 or later)
|
||||
|
||||
### 📎 Pre-Requirements
|
||||
|
||||
- [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) (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) | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) |
|
||||
| ARM | ❌ N/A | ❌ N/A | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) |
|
||||
| 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)
|
||||
|
||||
> 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).
|
||||
|
||||
* **🪟 WINDOWS:**
|
||||
|
||||
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.
|
||||
|
||||
2. 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.
|
||||
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).
|
||||
|
||||
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
|
||||
|
||||
@@ -45,17 +50,17 @@ A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Proces
|
||||
- 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)
|
||||
|
||||
* **>> LINUX:**
|
||||
* **🐧 LINUX:**
|
||||
|
||||
> NOTE: Not all Debian / RHEL based distros are supported. Supported distros are: debian (tested on v12), 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.
|
||||
> ⚠️ 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))
|
||||
> ⚠️ 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' 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.
|
||||
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/)
|
||||
|
||||
@@ -65,12 +70,12 @@ A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Proces
|
||||
- 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
|
||||
|
||||
* **>> MAC OS:**
|
||||
* **🍎 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 'PytubePP' following the same step.
|
||||
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.
|
||||
|
||||
@@ -84,7 +89,7 @@ A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Proces
|
||||
- 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
|
||||
### 🤔 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:
|
||||
|
||||
|
||||
1210
package-lock.json
generated
1210
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.6.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",
|
||||
|
||||
3002
src-tauri/Cargo.lock
generated
3002
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,28 +1,43 @@
|
||||
[package]
|
||||
name = "pytubepp-helper"
|
||||
version = "0.6.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 = [
|
||||
".",
|
||||
|
||||
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.6.0"
|
||||
!define VERSIONWITHBUILD "0.6.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.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}$\" --hidden"
|
||||
|
||||
; 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
|
||||
@@ -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,332 +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, time::Duration};
|
||||
use serde_json::Value;
|
||||
use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu};
|
||||
use tokio::{net::{TcpListener, TcpStream}, sync::{Mutex, oneshot}, time::sleep};
|
||||
use tokio_tungstenite::{accept_async, connect_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,
|
||||
}
|
||||
|
||||
async fn is_another_instance_running() -> bool {
|
||||
match connect_async("ws://127.0.0.1:3030").await {
|
||||
Ok(_) => true,
|
||||
Err(_) => false
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_bind_ws_port() -> Option<TcpListener> {
|
||||
match TcpListener::bind("127.0.0.1:3030").await {
|
||||
Ok(listener) => Some(listener),
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
|
||||
#[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) {
|
||||
#[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);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let _ = fix_path_env::fix();
|
||||
|
||||
// Check if another instance is running
|
||||
if is_another_instance_running().await {
|
||||
println!("Another instance is already running. Exiting...");
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
// Try to bind to the WebSocket port with a few retries
|
||||
let mut listener = None;
|
||||
for _ in 0..3 {
|
||||
if let Some(l) = try_bind_ws_port().await {
|
||||
listener = Some(l);
|
||||
break;
|
||||
}
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
// If we couldn't bind to the port after retries, assume another instance is running
|
||||
let listener = match listener {
|
||||
Some(l) => l,
|
||||
None => {
|
||||
println!("Could not bind to WebSocket port. Another instance might be running. Exiting...");
|
||||
std::process::exit(0);
|
||||
}
|
||||
};
|
||||
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let start_hidden = args.contains(&"--hidden".to_string());
|
||||
|
||||
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 window = app.get_window("main").unwrap();
|
||||
|
||||
if start_hidden {
|
||||
window.hide().unwrap();
|
||||
}
|
||||
|
||||
let app_handle = app.handle();
|
||||
let ws_state = websocket_state.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
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.6.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
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -2,129 +2,32 @@
|
||||
"build": {
|
||||
"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",
|
||||
"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": "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-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
|
||||
}
|
||||
"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",
|
||||
@@ -132,8 +35,9 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"linux": {
|
||||
"deb": {
|
||||
"depends": ["python3-pip", "ffmpeg", "gnome-terminal"],
|
||||
"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",
|
||||
@@ -145,8 +49,7 @@
|
||||
"rpm": {
|
||||
"epoch": 0,
|
||||
"release": "1",
|
||||
"license": "MIT",
|
||||
"depends": ["python3-pip", "ffmpeg-free", "gnome-terminal"],
|
||||
"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",
|
||||
@@ -155,10 +58,6 @@
|
||||
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
|
||||
}
|
||||
}
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/32x32.png",
|
||||
"iconAsTemplate": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,148 +2,55 @@
|
||||
"build": {
|
||||
"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",
|
||||
"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": "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-pytubepp-installed",
|
||||
"cmd": "pytubepp",
|
||||
"args": ["--version"]
|
||||
},
|
||||
{
|
||||
"name": "fetch-video-info",
|
||||
"cmd": "pytubepp",
|
||||
"args": [{ "validator": "\\S+" }, "--raw-info"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"fs": {
|
||||
"all": true,
|
||||
"copyFile": true,
|
||||
"exists": true,
|
||||
"createDir": true,
|
||||
"scope": [
|
||||
"$HOME/Library/LaunchAgents/",
|
||||
"$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts/",
|
||||
"$HOME/Library/Application Support/Chromium/NativeMessagingHosts/",
|
||||
"$HOME/Library/Application Support/Mozilla/NativeMessagingHosts/",
|
||||
"$RESOURCE/pytubepp-helper-msghost.json",
|
||||
"$RESOURCE/pytubepp-helper-msghost-moz.json",
|
||||
"$RESOURCE/pytubepp-helper-msghost",
|
||||
"$RESOURCE/pytubepp-helper-autostart.plist"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
"all": true
|
||||
},
|
||||
"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
|
||||
}
|
||||
"devUrl": "http://localhost:1422",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"identifier": "com.neosubhamoy.pytubepp.helper",
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "PytubePP Helper",
|
||||
"width": 500,
|
||||
"height": 335
|
||||
"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",
|
||||
@@ -153,7 +60,6 @@
|
||||
],
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "10.13",
|
||||
"license": "../LICENSE",
|
||||
"providerShortName": "neosubhamoy"
|
||||
},
|
||||
"resources": [
|
||||
@@ -162,10 +68,5 @@
|
||||
"pytubepp-helper-msghost",
|
||||
"pytubepp-helper-autostart.plist"
|
||||
]
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/32x32.png",
|
||||
"iconAsTemplate": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,136 +2,46 @@
|
||||
"build": {
|
||||
"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",
|
||||
"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": "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-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"
|
||||
]
|
||||
},
|
||||
"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
|
||||
}
|
||||
"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",
|
||||
@@ -141,12 +51,11 @@
|
||||
],
|
||||
"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": [
|
||||
@@ -154,10 +63,5 @@
|
||||
"pytubepp-helper-msghost-moz.json",
|
||||
"pytubepp-helper-msghost.exe"
|
||||
]
|
||||
},
|
||||
"systemTray": {
|
||||
"iconPath": "icons/icon.ico",
|
||||
"iconAsTemplate": true
|
||||
}
|
||||
}
|
||||
}
|
||||
416
src/App.tsx
416
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, detectMacOs, registerMacFiles, detectPackageManager, extractPkgMngrName } 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 [distroPkgMngr, setDistroPkgMngr] = 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,324 +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));
|
||||
}
|
||||
break;
|
||||
|
||||
case 'linux':
|
||||
const distroResult = await detectDistro();
|
||||
if (distroResult) {
|
||||
setDistroId(extractDistroId(distroResult));
|
||||
const distroPkgMngrResult = await detectPackageManager();
|
||||
if (distroPkgMngrResult) {
|
||||
setDistroPkgMngr(extractPkgMngrName(distroPkgMngrResult));
|
||||
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;
|
||||
|
||||
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>
|
||||
<div>
|
||||
{ isMacOs && macOsVersion && compareVersions(macOsVersion, '10.13') > 0 ?
|
||||
<Button size="sm" onClick={registerMacFiles}>Register</Button>
|
||||
:
|
||||
null
|
||||
}
|
||||
<Button className="ml-3" size="sm" onClick={checkAllPrograms}>Refresh</Button>
|
||||
</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>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 && 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-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>
|
||||
);
|
||||
}
|
||||
|
||||
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,9 +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 { fs } from '@tauri-apps/api';
|
||||
import { join, resourceDir, homeDir } from '@tauri-apps/api/path';
|
||||
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))
|
||||
@@ -11,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 {
|
||||
@@ -25,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 {
|
||||
@@ -39,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 {
|
||||
@@ -53,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 {
|
||||
@@ -67,7 +67,7 @@ export async function detectDistro(): Promise<string | null> {
|
||||
|
||||
export async function detectPackageManager(): Promise<string | null> {
|
||||
try{
|
||||
const output = await new Command('detect-pkgmngr', ['-c', 'command -v apt || command -v dnf || command -v pacman']).execute();
|
||||
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 {
|
||||
@@ -98,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
|
||||
@@ -118,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 () => {
|
||||
@@ -174,13 +174,15 @@ export async function registerMacFiles() {
|
||||
await fs.copyFile(sourcePath, destinationPath);
|
||||
console.log(`File ${file.source} copied successfully to ${destinationPath}`);
|
||||
} else {
|
||||
await fs.createDir(destinationDir, { recursive: true })
|
||||
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