1
1
mirror of https://github.com/neosubhamoy/pytubepp-helper.git synced 2026-02-04 19:32:21 +05:30

55 Commits

156 changed files with 7000 additions and 12668 deletions

101
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,101 @@
on:
push:
tags:
- 'v*.*.*-*'
name: 🚀 Release on GitHub
jobs:
release:
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- platform: 'macos-15'
args: '--target aarch64-apple-darwin'
arch: 'aarch64-apple-darwin'
- platform: 'macos-15'
args: '--target x86_64-apple-darwin'
arch: 'x86_64-apple-darwin'
- platform: 'ubuntu-22.04'
args: ''
arch: ''
- platform: 'windows-latest'
args: ''
arch: ''
runs-on: ${{ matrix.platform }}
steps:
- name: 🚚 Checkout repository
uses: actions/checkout@v4
- name: 🛠️ Install dependencies
if: matrix.platform == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
- name: 📦 Setup node
uses: actions/setup-node@v4
with:
node-version: '22.11.0'
cache: 'npm'
- name: 🛠️ install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform == 'macos-15' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
- name: 🛠️ Rust cache
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- 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: ${{ 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 }}

View File

@@ -23,9 +23,14 @@ dist-ssr
*.sln *.sln
*.sw? *.sw?
# Executables # Executables and manifests
pytubepp-helper-msghost.exe src-tauri/pytubepp-helper-msghost.exe
pytubepp-helper-autostart.exe src-tauri/pytubepp-helper-autostart.exe
src-tauri/pytubepp-helper-msghost.json
src-tauri/pytubepp-helper-msghost-moz.json
src-tauri/pytubepp-helper-msghost
src-tauri/pytubepp-helper-autostart
src-tauri/pytubepp-helper-autostart.plist
# Certificate files # Certificate files
certificate.pfx certificate.pfx

36
CHANGELOG.md Normal file
View 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

View File

@@ -5,70 +5,91 @@
A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Processor CLI A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Processor CLI
[![status](https://img.shields.io/badge/status-active-brightgreen.svg?style=flat)](https://github.com/neosubhamoy/pytubepp-helper) [![status](https://img.shields.io/badge/status-active-brightgreen.svg?style=flat)](https://github.com/neosubhamoy/pytubepp-helper)
[![verion](https://img.shields.io/badge/version-v0.2.0_beta-yellow.svg?style=flat)](https://github.com/neosubhamoy/pytubepp-helper) [![github tag](https://img.shields.io/github/v/tag/neosubhamoy/pytubepp-helper?color=yellow)](https://github.com/neosubhamoy/pytubepp-helper)
[![PRs](https://img.shields.io/badge/PRs-welcome-blue.svg?style=flat)](https://github.com/neosubhamoy/pytubepp-helper) [![PRs](https://img.shields.io/badge/PRs-welcome-blue.svg?style=flat)](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 ### 💻 Supported Platforms
- Windows 10 (v1803 or later) / 11 - Windows 10 (v1803 or later) / 11
- Linux (Debian / RHEL base) (GNOME only) - Linux (Debian/Ubuntu, Fedora/RHEL base)
- MacOS (Maybe Soon - looking for a MacBook user for testing :) - MacOS (v10.13 or later)
### 📎 Pre-Requirements ### 📎 Pre-Requirements
- [Python (>3.8)](https://www.python.org/downloads/) - [Python](https://www.python.org/downloads/) (>3.8)
- [FFmpeg](https://www.ffmpeg.org) - [FFmpeg](https://www.ffmpeg.org)
- [Node.js](https://nodejs.org/en/download/)
- [PytubePP](https://github.com/neosubhamoy/pytubepp) - [PytubePP](https://github.com/neosubhamoy/pytubepp)
* These requirements can be installed using PytubePP Helper (post installation) if [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget) is installed in your system. *(for Windows users) * These requirements can be installed using PytubePP Helper (post installation) if [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget) (for Windows users) / [Homebrew](https://brew.sh) (for MacOS users) is installed in your system
### ⬇️ Download and Installation ### ⬇️ 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 | | Arch\OS | Windows | Linux | MacOS |
| :---- | :---- | :---- | :---- | | :---- | :---- | :---- | :---- |
| x64 | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) | [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) | N/A | | x86_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) |
| x86 | N/A | N/A | N/A | | ARM64 | N/A | N/A | ✅ [Download](https://github.com/neosubhamoy/pytubepp-helper/releases/latest) |
| ARM | N/A | N/A | N/A |
* **>> Windows:** 2. Install all [pre-requirements](https://github.com/neosubhamoy/pytubepp-helper#-pre-requirements) and [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) (follow next instructions based on your OS)
2. If you don't have any Pre-Requirements installed first install [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget). Then restart your Computer. > NOTE: You can install the pre-requirements from PytubePP Helper app GUI or manually running the commands in your system's terminal / command prompt, for manual installation follow this [guide](https://github.com/neosubhamoy/pytubepp#%EF%B8%8F-installation).
3. Now open PytubePP Helper (from system tray not from start menu or shotcut) you will see (blue) 'install' buttons. First click on the install button on the right side of 'Python', a cmd window will popup to install Python. after the installation is finished then close the cmd window and now install 'FFmpeg' by clicking on the next install button. after the installation is finished close the cmd window and restart your Computer. * **🪟 WINDOWS:**
4. Again open PytubePP Helper (from system tray not from start menu or shotcut) and install PytubePP at last. after it finishes you can close the cmd window. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper 1. If you don't have any Pre-Requirements installed first install [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget). Then restart your Computer.
5. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp) 2. Now open PytubePP Helper, you will see (blue) 'install' buttons. First click on the install button on the right side of 'Python', a cmd window will popup to install Python. after the installation is finished then close the cmd window and now install 'FFmpeg' by clicking on the next install button. after the installation is finished close the cmd window and restart your Computer (do same for Node.js).
6. PRO TIPS: 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
- Make sure PytubePP Helper is always running in the background (system tray) otherwise PytubePP Extension will not work properly.
- Always open PytubePP Helper from system tray if it's already running. if you open PytubePP Helper from start menu or shotcut when PytubePP Helper is already running in system tray then two instances of PytubePP Helper will run on the same time which may cause the app to malfunction!
- PytubePP Helper by default always autostarts itself when Windows starts. Make sure autosart is not disabled for PytubePP Helper in Task Manager (Startup apps tab)
* **>> Linux:** 4. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
> NOTE: Not all Debian / RHEL based distros are supported. Supported distros are: debian, ubuntu (tested on v24.04 LTS), pop, kali, rhel, fedora (tested on v40), centos, rocky. If your distro is not in the supported list it doesn't mean that 'the app will not run at all', so, test it yourself and if it doesn't work then you can request us to add support for your distro via creating a github issue. 5. Pro Tips:
- Make sure PytubePP Helper is always running in the background (system tray) otherwise PytubePP Extension will not work properly.
- PytubePP Helper by default always autostarts itself when Windows starts. Make sure autostart is not disabled for PytubePP Helper in Task Manager (Startup apps tab)
> Sandboxed Browsers may not work properly (eg: Flatpak, Snaps) (have issue with: Browser NativeMessaging API [read here](https://github.com/flatpak/xdg-desktop-portal/issues/655)) * **🐧 LINUX:**
2. For linux users Pre-Requirements are mostly fulfilled as 'Python' is pre installed in most linux distros and 'FFmpeg' is auto installed as a dependency while installing the .deb / .rpm package. You just need to install 'PytubePP' manually by clicking the blue 'install' button opening pytubepp-helper. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper. > ⚠️ NOTE: Most of the Debian / RHEL based distros are supported. Tested on: debian (v12), ubuntu (v24.04 LTS), fedora (v41). If your distro is not in the tested list it doesn't mean that 'the app will not run at all', so, test it yourself and if it doesn't work then you can request us to add support for your distro via creating a github issue.
> ⚠️ Sandboxed Browsers may not work properly (eg: Flatpak, Snaps) (have issue with: Browser NativeMessaging API [read here](https://github.com/flatpak/xdg-desktop-portal/issues/655)) (But, still try it yourself to see if it works)
1. For linux users Pre-Requirements are mostly fulfilled as 'Python' is pre installed in most linux distros and 'FFmpeg', 'Node.js' are auto installed as a dependency while installing the .deb / .rpm package. You just need to install 'PytubePP' manually by clicking the blue 'install' button opening pytubepp-helper. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper.
> Always make sure your system packages are up-to-date (you may face issues otherwise, the app may not open at all) > 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/) > 'AppIndicator' feature must be enabled for seemless experiance with pytubepp-helper. If your distro doesn't support this by default (eg: fedora) then you need to enable it for your GNOME desktop environment manually, using a GNOME shell extension: [AppIndicator and KStatusNotifierItem Support](https://extensions.gnome.org/extension/615/appindicator-support/)
3. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp) 2. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
4. PRO TIPS: 3. Pro Tips:
- Make sure PytubePP Helper is always running in the background (Appindicator) otherwise PytubePP Extension will not work properly. - Make sure PytubePP Helper is always running in the background (Appindicator) otherwise PytubePP Extension will not work properly.
- Always open PytubePP Helper from Appindicator if it's already running. if you open PytubePP Helper from programs menu or shotcut when PytubePP Helper is already running in Appindicator then two instances of PytubePP Helper will run on the same time which may cause the app to malfunction! - PytubePP Helper by default always autostarts itself when Linux Distro starts. Make sure autostart is not disabled for PytubePP Helper in your distro's Startup Manager / Applications
- PytubePP Helper by default always autostarts itself when Linux Distro starts. Make sure autosart is not disabled for PytubePP Helper in your distro's Startup Manager / Applications
### ❔ How It Works * **🍎 MAC OS:**
1. If you don't have any Pre-Requirements installed first install [Homebrew](https://brew.sh)
2. Python mostly comes pre-installed in MacOS, But on the case if you are running Python version older than 3.8 upgrade it to a newer version using Homebrew command: `brew upgrade python`
3. Now, open PytubePP Helper app and click on the (blue) install button on the right side of 'FFmpeg' to install it. Also, install 'Node.js' and 'PytubePP' following the same step.
4. Then, click on the 'Register' botton on the top right corner to register 'PytubePP Helper' in your system and also add it to your system's autostart entry. If you see a MacOS notification saying 'pytubepp-helper' is added as a startup app then it's done.
5. Now click on the 'Refresh' button and you will see the 'Ready' message. Then close PytubePP Helper.
5. You can now add the [PytubePP Extension](https://github.com/neosubhamoy/pytubepp-extension) in your browser and it should work properly with [PytubePP](https://github.com/neosubhamoy/pytubepp)
6. Pro Tips:
- Make sure PytubePP Helper is always running in the background (top bar) otherwise PytubePP Extension will not work properly.
- Always allow all the MacOS security popups if it's from 'pytubepp-helper' otherwise it will not function properly.
- Don't quit 'pytubepp-helper' from the dock otherwise it will stop working (always use the close button to just hide the app window not fully quit it)
- PytubePP Helper by default always autostarts itself when MacOS starts. Make sure autostart is not disabled for PytubePP Helper in Settings (General > Login Apps)
### 🤔 How It Works
- PytubePP Helper is an intermediate communicator between PytubePP Extension and Pytube Post Processor CLI interface. It is used as a bridge to estblish communication between the System Shell / CMD and Browser Extension, as a Browser Extension can not directly talk (execute commands) with System Shell / CMD for security reasons. Browser Extensions are isolated from the system too, the only way they can communicate with the system (native apps only) is nativeMessaging API provided by Chrome (other Browsers provides it too). So, PytubePP Helper uses that API to communicate with the Browser Extension and recives it's requests and processes the data from PytubePP CLI then genrates a response and sends it to the Browser Extension. For further understanding view the system design diagram of PytubePP Helper app below: - PytubePP Helper is an intermediate communicator between PytubePP Extension and Pytube Post Processor CLI interface. It is used as a bridge to estblish communication between the System Shell / CMD and Browser Extension, as a Browser Extension can not directly talk (execute commands) with System Shell / CMD for security reasons. Browser Extensions are isolated from the system too, the only way they can communicate with the system (native apps only) is nativeMessaging API provided by Chrome (other Browsers provides it too). So, PytubePP Helper uses that API to communicate with the Browser Extension and recives it's requests and processes the data from PytubePP CLI then genrates a response and sends it to the Browser Extension. For further understanding view the system design diagram of PytubePP Helper app below:
@@ -86,7 +107,6 @@ A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Proces
Want to be part of this? Feel free to contribute...!! Pull Requests are always welcome...!! (^_^) Follow these simple steps to start building: Want to be part of this? Feel free to contribute...!! Pull Requests are always welcome...!! (^_^) Follow these simple steps to start building:
* It is highly reccomended to use the same OS for which platform you want to build (eg: 'linux distro' for linux binaries, 'windows' for windows binaries)
* Make sure to install Rust, Node.js and Git before proceeding. * Make sure to install Rust, Node.js and Git before proceeding.
* Install tauri [Prerequisites](https://tauri.app/v1/guides/getting-started/prerequisites) for your OS / platform * Install tauri [Prerequisites](https://tauri.app/v1/guides/getting-started/prerequisites) for your OS / platform
1. Fork this repo in your github account. 1. Fork this repo in your github account.
@@ -96,12 +116,7 @@ Want to be part of this? Feel free to contribute...!! Pull Requests are always w
```code ```code
npm install npm install
``` ```
4. Select the development platform directory (for which OS / platform you want to build / contribute now) (source code for each platform is separated) (eg: linux) 4. Run development / build process
```
cd pytubepp-helper
cd linux
```
5. Run development / build process
```code ```code
npm run tauri dev npm run tauri dev
``` ```
@@ -115,3 +130,5 @@ npm run tauri build
### 📝 License ### 📝 License
PytubePP Helper is Licensed under the [MIT license](https://github.com/neosubhamoy/pytubepp-helper/blob/main/LICENSE). Anyone can view, modify, use (personal and commercial) or distribute it's sources without any attribution and extra permissions. PytubePP Helper is Licensed under the [MIT license](https://github.com/neosubhamoy/pytubepp-helper/blob/main/LICENSE). Anyone can view, modify, use (personal and commercial) or distribute it's sources without any attribution and extra permissions.
⚖️ NOTE: YouTube is a trademark of Google LLC. Use of this trademark is subject to Google Permissions. Downloading and using Copyrighted YouTube Content for Commercial pourposes are not allowed by YouTube Terms without proper Permissions from the Creator. We don't promote this kinds of activity, You should use the downloaded contents wisely and at your own responsibility.

View File

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 118 KiB

View File

@@ -0,0 +1,22 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const msghostSrc = path.join(__dirname, 'src-tauri', 'target', 'aarch64-apple-darwin', 'release', 'pytubepp-helper-msghost');
const msghostDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost');
const autostartPlistSrc = path.join(__dirname, 'src-tauri', 'autostart', 'pytubepp-helper-autostart.plist');
const autostartPlistDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-autostart.plist');
const msghostManifestMacChromeSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'chrome', 'com.neosubhamoy.pytubepp.helper.json');
const msghostManifestMacChromeDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.json');
const msghostManifestMacFirefoxSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'firefox', 'com.neosubhamoy.pytubepp.helper.json');
const msghostManifestMacFirefoxDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost-moz.json');
fs.copyFileSync(msghostSrc, msghostDest);
// fs.copyFileSync(autostartSrc, autostartDest);
fs.copyFileSync(autostartPlistSrc, autostartPlistDest);
fs.copyFileSync(msghostManifestMacChromeSrc, msghostManifestMacChromeDest);
fs.copyFileSync(msghostManifestMacFirefoxSrc, msghostManifestMacFirefoxDest);
console.log('Files copied successfully');

18
copyFiles.js Normal file
View File

@@ -0,0 +1,18 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const msghostSrc = path.join(__dirname, 'src-tauri', 'target', 'release', 'pytubepp-helper-msghost.exe');
const msghostDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.exe');
const msghostManifestWinChromeSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'windows', 'chrome', 'com.neosubhamoy.pytubepp.helper.json');
const msghostManifestWinChromeDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.json');
const msghostManifestWinFirefoxSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'windows', 'firefox', 'com.neosubhamoy.pytubepp.helper.json');
const msghostManifestWinFirefoxDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost-moz.json');
fs.copyFileSync(msghostSrc, msghostDest);
fs.copyFileSync(msghostManifestWinChromeSrc, msghostManifestWinChromeDest);
fs.copyFileSync(msghostManifestWinFirefoxSrc, msghostManifestWinFirefoxDest);
console.log('Files copied successfully');

View File

@@ -0,0 +1,21 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const msghostSrc = path.join(__dirname, 'src-tauri', 'target', 'x86_64-apple-darwin', 'release', 'pytubepp-helper-msghost');
const msghostDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost');
const autostartPlistSrc = path.join(__dirname, 'src-tauri', 'autostart', 'pytubepp-helper-autostart.plist');
const autostartPlistDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-autostart.plist');
const msghostManifestMacChromeSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'chrome', 'com.neosubhamoy.pytubepp.helper.json');
const msghostManifestMacChromeDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost.json');
const msghostManifestMacFirefoxSrc = path.join(__dirname, 'src-tauri', 'msghost-manifest', 'macos', 'firefox', 'com.neosubhamoy.pytubepp.helper.json');
const msghostManifestMacFirefoxDest = path.join(__dirname, 'src-tauri', 'pytubepp-helper-msghost-moz.json');
fs.copyFileSync(msghostSrc, msghostDest);
fs.copyFileSync(autostartPlistSrc, autostartPlistDest);
fs.copyFileSync(msghostManifestMacChromeSrc, msghostManifestMacChromeDest);
fs.copyFileSync(msghostManifestMacFirefoxSrc, msghostManifestMacFirefoxDest);
console.log('Files copied successfully');

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + React + Typescript</title> <title>PytubePP Helper</title>
</head> </head>
<body> <body>

24
linux/.gitignore vendored
View File

@@ -1,24 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -1,7 +0,0 @@
# Tauri + React + Typescript
This template should help get you started developing with Tauri, React and Typescript in Vite.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

View File

@@ -1,20 +0,0 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}

View File

@@ -1,14 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + React + Typescript</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -1,36 +0,0 @@
{
"name": "pytubepp-helper",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-slot": "^1.1.0",
"@tauri-apps/api": "^1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"lucide-react": "^0.441.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@tauri-apps/cli": "^1",
"@types/node": "^22.5.5",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "^5.2.2",
"vite": "^5.3.1"
}
}

View File

@@ -1,6 +0,0 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +0,0 @@
[package]
name = "pytubepp-helper"
version = "0.1.0"
description = "A Helper App for PytubePP Extension/Addon to Communicate with Pytube Post Processor CLI"
authors = ["neosubhamoy <hey@neosubhamoy.com>"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1", features = [] }
[dependencies]
tauri = { version = "1", features = [ "shell-all", "window-show", "window-hide", "window-maximize", "process-exit", "process-relaunch", "window-unminimize", "window-unmaximize", "window-close", "system-tray", "window-start-dragging", "window-minimize"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1.39.2", features = ["full"] }
tokio-tungstenite = "*"
futures-util = "0.3.30"
[features]
# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"]
[workspace]
members = [
".",
"msghost",
"autostart"
]

View File

@@ -1 +0,0 @@
/target

View File

@@ -1,10 +0,0 @@
[package]
name = "pytubepp-helper-autostart"
version = "0.1.0"
description = "PytubePP Helper (Autostart)"
authors = ["neosubhamoy <hey@neosubhamoy.com>"]
edition = "2021"
[dependencies]
websocket = "0.27.1"
serde_json = "1.0"

View File

@@ -1,55 +0,0 @@
#![windows_subsystem = "windows"]
use std::process::Command;
use websocket::client::ClientBuilder;
use websocket::OwnedMessage;
use std::thread::sleep;
use std::time::Duration;
fn connect_with_retry(url: &str, max_attempts: u32) -> Result<websocket::sync::Client<std::net::TcpStream>, Box<dyn std::error::Error>> {
let mut attempts = 0;
loop {
match ClientBuilder::new(url).unwrap().connect_insecure() {
Ok(client) => {
eprintln!("Successfully connected to Tauri app :)");
return Ok(client);
}
Err(e) => {
attempts += 1;
if attempts >= max_attempts {
return Err(Box::new(e));
}
let wait_time = Duration::from_secs(2u64.pow(attempts));
eprintln!("Connection attempt {} failed. Retrying in {:?}...", attempts, wait_time);
sleep(wait_time);
}
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Launch the main application
let _ = Command::new("pytubepp-helper")
.spawn();
// Connect with the Tauri app
let websocket_url = "ws://localhost:3030";
eprintln!("Attempting to connect to {}", websocket_url);
let mut client = match connect_with_retry(websocket_url, 2) {
Ok(client) => client,
Err(e) => {
eprintln!("Failed to connect after multiple attempts: {:?}", e);
return Err(e);
}
};
// Send message to Tauri app
client.send_message(&OwnedMessage::Text(serde_json::json!({
"url": "",
"command": "autostart",
"argument": ""
}).to_string()))?;
Ok(())
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

View File

@@ -1 +0,0 @@
/target

View File

@@ -1,10 +0,0 @@
[package]
name = "pytubepp-helper-msghost"
version = "0.1.0"
description = "PytubePP Helper Native Messaging Host"
authors = ["neosubhamoy <hey@neosubhamoy.com>"]
edition = "2021"
[dependencies]
websocket = "0.27.1"
serde_json = "1.0"

View File

@@ -1,260 +0,0 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::{process::Command, sync::Arc, env};
use serde_json::Value;
use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu};
use tokio::{net::{TcpListener, TcpStream}, sync::{Mutex, oneshot}};
use tokio_tungstenite::accept_async;
use futures_util::{SinkExt, StreamExt};
struct ResponseChannel {
sender: Option<oneshot::Sender<String>>,
}
struct WebSocketState {
sender: Option<futures_util::stream::SplitSink<tokio_tungstenite::WebSocketStream<TcpStream>, tokio_tungstenite::tungstenite::Message>>,
response_channel: ResponseChannel,
}
#[tauri::command]
async fn send_to_extension(
message: String,
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
) -> Result<(), String> {
let mut state = state.lock().await;
if let Some(sender) = &mut state.sender {
sender.send(tokio_tungstenite::tungstenite::Message::Text(message)).await
.map_err(|e| format!("Failed to send message: {}", e))?;
Ok(())
} else {
Err("No active WebSocket connection".to_string())
}
}
#[tauri::command]
async fn receive_frontend_response(
response: String,
state: tauri::State<'_, Arc<Mutex<WebSocketState>>>,
) -> Result<(), String> {
let mut state = state.lock().await;
if let Some(sender) = state.response_channel.sender.take() {
sender.send(response).map_err(|e| format!("Failed to send response: {:?}", e))?;
}
Ok(())
}
#[tauri::command]
fn fetch_video_info(url: String) {
#[cfg(target_os = "windows")]
{
let command = format!("pytubepp \"{}\" -i", &url);
Command::new("cmd")
.args(["/k", command.as_str()])
.spawn()
.unwrap();
}
#[cfg(target_os = "linux")]
{
let command = format!("pytubepp \"{}\" -i", &url);
Command::new("gnome-terminal")
.args(["--", "bash", "-c", command.as_str()])
.spawn()
.unwrap();
}
#[cfg(target_os = "macos")]
{
let command = format!("pytubepp \"{}\" -i", &url);
Command::new("osascript")
.arg("-e")
.arg(format!(
"tell app \"Terminal\" to activate do script \"{}\"",
command
))
.spawn()
.unwrap();
}
}
#[tauri::command]
fn install_program(icommand: String) {
#[cfg(target_os = "windows")]
{
let command = format!("{}", &icommand);
Command::new("cmd")
.args(["/k", command.as_str()])
.spawn()
.unwrap();
}
#[cfg(target_os = "linux")]
{
let command = format!("{}", &icommand);
Command::new("gnome-terminal")
.args(["--", "bash", "-c", command.as_str()])
.spawn()
.unwrap();
}
#[cfg(target_os = "macos")]
{
let command = format!("{}", &icommand);
Command::new("osascript")
.arg("-e")
.arg(format!(
"tell app \"Terminal\" to activate do script \"{}\"",
command
))
.spawn()
.unwrap();
}
}
#[tauri::command]
fn download_stream(url: String, stream: String) {
#[cfg(target_os = "windows")]
{
let command = format!("pytubepp \"{}\" -s {}", &url, &stream);
Command::new("cmd")
.args(["/k", command.as_str()])
.spawn()
.unwrap();
}
#[cfg(target_os = "linux")]
{
let command = format!("pytubepp \"{}\" -s {}", &url, &stream);
Command::new("gnome-terminal")
.args(["--", "bash", "-c", command.as_str()])
.spawn()
.unwrap();
}
#[cfg(target_os = "macos")]
{
let command = format!("pytubepp \"{}\" -s {}", &url, &stream);
Command::new("osascript")
.arg("-e")
.arg(format!(
"tell app \"Terminal\" to activate do script \"{}\"",
command
))
.spawn()
.unwrap();
}
}
#[tokio::main]
async fn main() {
let websocket_state = Arc::new(Mutex::new(WebSocketState {
sender: None,
response_channel: ResponseChannel { sender: None },
}));
let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("show".to_string(), "Show"))
.add_item(CustomMenuItem::new("quit".to_string(), "Quit"));
let system_tray = SystemTray::new().with_menu(tray_menu).with_tooltip("PytubePP Helper");
tauri::Builder::default()
.system_tray(system_tray)
.on_system_tray_event(|app, event| match event {
SystemTrayEvent::LeftClick {
position: _,
size: _,
..
} => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"show" => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"quit" => {
app.exit(0);
}
_ => {}
},
_ => {}
})
.manage(websocket_state.clone())
.setup(move |app| {
let app_handle = app.handle();
let ws_state = websocket_state.clone();
tokio::spawn(async move {
let listener = TcpListener::bind("127.0.0.1:3030").await.unwrap();
println!("WebSocket server listening on ws://127.0.0.1:3030");
while let Ok((stream, _)) = listener.accept().await {
let app_handle = app_handle.clone();
let ws_state = ws_state.clone();
tokio::spawn(handle_connection(stream, app_handle, ws_state));
}
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
send_to_extension,
fetch_video_info,
install_program,
download_stream,
receive_frontend_response
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
async fn handle_connection(stream: TcpStream, app_handle: tauri::AppHandle, ws_state: Arc<Mutex<WebSocketState>>) {
let ws_stream = accept_async(stream).await.unwrap();
let (ws_sender, mut ws_receiver) = ws_stream.split();
// Store the sender in the shared state
{
let mut state = ws_state.lock().await;
state.sender = Some(ws_sender);
}
println!("New WebSocket connection established");
while let Some(msg) = ws_receiver.next().await {
if let Ok(msg) = msg {
if let Ok(text) = msg.to_text() {
println!("Received message: {}", text);
// Parse the JSON message
if let Ok(json_value) = serde_json::from_str::<Value>(text) {
// Create a new channel for this request
let (response_sender, response_receiver) = oneshot::channel();
{
let mut state = ws_state.lock().await;
state.response_channel.sender = Some(response_sender);
}
// Emit an event to the frontend
app_handle.emit_all("websocket-message", json_value).unwrap();
// Wait for the response from the frontend
let response = response_receiver.await
.unwrap_or_else(|e| format!("Error receiving response: {:?}", e));
// Send the response back through WebSocket
let mut state = ws_state.lock().await;
if let Some(sender) = &mut state.sender {
let _ = sender.send(tokio_tungstenite::tungstenite::Message::Text(response)).await;
}
}
}
}
}
println!("WebSocket connection closed");
// Remove the sender from the shared state when the connection closes
let mut state = ws_state.lock().await;
state.sender = None;
}

View File

@@ -1,133 +0,0 @@
{
"build": {
"beforeDevCommand": "npm run dev && cargo build --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --manifest-path=./src-tauri/autostart/Cargo.toml",
"beforeBuildCommand": "npm run build && cargo build --release --manifest-path=./src-tauri/msghost/Cargo.toml && cargo build --release --manifest-path=./src-tauri/autostart/Cargo.toml",
"devPath": "http://localhost:1420",
"distDir": "../dist"
},
"package": {
"productName": "pytubepp-helper",
"version": "0.2.0"
},
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": true,
"execute": true,
"sidecar": true,
"open": true,
"scope": [
{
"name": "detect-distro",
"cmd": "grep",
"args": ["^ID=", "/etc/os-release"]
},
{
"name": "is-apt-installed",
"cmd": "apt",
"args": ["--version"]
},
{
"name": "is-dnf-installed",
"cmd": "dnf",
"args": ["--version"]
},
{
"name": "is-python-installed",
"cmd": "python3",
"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": "pytubefix",
"args": [{ "validator": "\\S+"}, "--list"]
}
]
},
"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
}
},
"windows": [
{
"title": "PytubePP Helper",
"width": 500,
"height": 320
}
],
"security": {
"csp": null
},
"bundle": {
"active": true,
"targets": "all",
"identifier": "com.neosubhamoy.pytubepp.helper",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"deb": {
"depends": ["python3-pip", "ffmpeg"],
"files": {
"/etc/opt/chrome/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/chrome/com.neosubhamoy.pytubepp.helper.json",
"/etc/chromium/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/chrome/com.neosubhamoy.pytubepp.helper.json",
"/usr/lib/mozilla/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/firefox/com.neosubhamoy.pytubepp.helper.json",
"/usr/bin/pytubepp-helper-msghost": "./target/release/pytubepp-helper-msghost",
"/usr/bin/pytubepp-helper-autostart": "./target/release/pytubepp-helper-autostart",
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
}
},
"rpm": {
"epoch": 0,
"release": "1",
"license": "MIT",
"depends": ["python3-pip", "ffmpeg-free"],
"files": {
"/etc/opt/chrome/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/chrome/com.neosubhamoy.pytubepp.helper.json",
"/etc/chromium/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/chrome/com.neosubhamoy.pytubepp.helper.json",
"/usr/lib/mozilla/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/firefox/com.neosubhamoy.pytubepp.helper.json",
"/usr/bin/pytubepp-helper-msghost": "./target/release/pytubepp-helper-msghost",
"/usr/bin/pytubepp-helper-autostart": "./target/release/pytubepp-helper-autostart",
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
}
}
},
"systemTray": {
"iconPath": "icons/32x32.png",
"iconAsTemplate": true
}
}
}

View File

@@ -1,116 +0,0 @@
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafb);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}

View File

@@ -1,255 +0,0 @@
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 { 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, extractDistroId, detectDistro, detectDistroBase } from "./lib/utils";
import { CircleCheck, TriangleAlert, CircleAlert } from 'lucide-react';
function App() {
useEffect(() => {
const handleCloseRequested = (event: any) => {
event.preventDefault();
appWindow.hide();
};
appWindow.onCloseRequested(handleCloseRequested);
}, []);
const [distroId, setDistroId] = useState<string | null>(null)
const [distroBase, setDistroBase] = useState<string | null>(null)
const [installedPrograms, setInstalledPrograms] = useState<InstalledPrograms>({
apt: {
installed: false,
version: null,
},
dnf: {
installed: false,
version: null,
},
python: {
installed: false,
version: null,
},
pip: {
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') {
sendStreamInfo(event.payload.url);
} 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('receive_frontend_response', { response: 'Download started' });
} catch (error) {
console.error(error);
}
};
startDownload();
} else if (event.payload.command === 'autostart') {
const handleAppAutostart = async () => {
appWindow.hide();
await invoke('receive_frontend_response', { response: 'Appwindow Hidden' });
};
handleAppAutostart();
}
});
return () => {
unlisten.then(f => f());
};
}, []);
function checkAllPrograms() {
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('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('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();
detectDistro().then((result) => {
if(result) {
setDistroId(extractDistroId(result))
setDistroBase(detectDistroBase(extractDistroId(result)))
}
})
}
, []);
return (
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<div className="container">
<div className="topbar flex justify-between items-center mt-5 mx-3">
<h1 className="text-xl font-bold">PytubePP Helper</h1>
<Button size="sm" onClick={checkAllPrograms}>Refresh</Button>
</div>
{ distroId && distroBase && distroBase === 'debian' ?
<div className="programstats mt-5 mx-3">
<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.apt.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo apt install Python3.12 -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.pip.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'pip install pytubepp --break-system-packages'})}}>install</Button> : null}
</div>
{(!installedPrograms.apt.installed && (!installedPrograms.python.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.pip.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.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>
: distroId && distroBase && distroBase === 'rhel' ?
<div className="programstats mt-5 mx-3">
<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.dnf.installed ? <Button variant="link" className="text-blue-600 px-0" onClick={async () => { await invoke('install_program', {icommand: 'sudo dnf install python3.12 -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.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.dnf.installed && (!installedPrograms.python.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 debian packages. Please install it manually for your distro.
</AlertDescription>
</Alert>
: null}
{(!installedPrograms.pip.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.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>
:
<div className="programstats mt-5 mx-3">
<Alert className="mt-5" variant="destructive">
<CircleAlert className="h-5 w-5" />
<AlertTitle>Unsupported Distro</AlertTitle>
<AlertDescription>
Sorry, your linux distro is currently not supported. If you think this is just a mistake or you want to request us to add support for your 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>
</ThemeProvider>
);
}
export default App;

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -1,66 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 240 10% 3.9%;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--radius: 0.5rem
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
--card: 240 10% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 240 10% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 240 5.9% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 240 3.7% 15.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -1,147 +0,0 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
import { Command } from '@tauri-apps/api/shell';
import { Stream } from "@/types";
import { invoke } from "@tauri-apps/api";
export function extractXml(input: string): string[] {
const regex = /<Stream: [^>]+>/g;
const matches = input.match(regex);
return matches ? matches : [];
}
function parseAttributes(attributesString: string): Partial<Stream> {
const attributes: Partial<Stream> = {};
const regex = /(\w+)="([^"]*)"/g;
let match;
while ((match = regex.exec(attributesString)) !== null) {
const key = match[1];
const value = match[2];
if (['itag', 'mime_type', 'res', 'fps', 'vcodec'].includes(key)) {
attributes[key as keyof Partial<Stream>] = value;
}
}
return attributes;
}
export function convertXmlToJson(xmlStrings: string[]): Stream[] {
return xmlStrings
.map(xmlString => {
const attributesString = xmlString.replace('<Stream: ', '').replace('>', '');
return parseAttributes(attributesString);
})
.filter(stream => stream.res !== undefined) as Stream[];
}
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
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();
if (output.code === 0) {
return { installed: true, output: output.stdout };
} else {
return { installed: false, output: output.stdout };
}
} catch (error) {
console.error(error);
return { installed: false, output: null };
}
}
export async function detectDistro(): Promise<string | null> {
try{
const output = await new Command('detect-distro', ['^ID=', '/etc/os-release']).execute();
if (output.code === 0) {
return output.stdout;
} else {
return output.stdout;
}
} catch (error) {
console.error(error);
return null;
}
}
export function detectDistroBase(distro: string | null): string | null{
if(distro) {
if(['debian', 'ubuntu', 'pop', 'kali'].includes(distro)) {
return 'debian';
} else if (['rhel', 'fedora', 'centos', 'rocky'].includes(distro)) {
return 'rhel';
} else {
return 'other';
}
} else {
return null;
}
}
export function extractVersion(output: string): string | null {
const versionPatterns = [
/ffmpeg version (\d+\.\d+)/, // Pattern for ffmpeg
/Python (\d+\.\d+\.\d+)/, // Pattern for Python
/pytubefix (\d+\.\d+\.\d+)/, // Pattern for pytubefix
/pytubepp (\d+\.\d+\.\d+)/, // Pattern for pytubepp
/apt (\d+\.\d+\.\d+)/, // Pattern for apt
/(\d+\.\d+\.\d+)/, // Pattern for dnf
/pip (\d+\.\d+)/, // Pattern for pip
];
for (const pattern of versionPatterns) {
const match = output.match(pattern);
if (match) {
return match[1];
}
}
return null;
}
export function extractDistroId(input: string): string | null {
const regex = /ID=([a-zA-Z]+)/;
const match = input.match(regex);
return match ? match[1] : null;
}
export async function sendStreamInfo(url: string) {
const fetchData = async () => {
try {
const output = await new Command('fetch-video-info', [url, '--list']).execute();
if (output.code === 0) {
console.log(output.stdout);
const sendStreamData = async () => {
try {
const streamsstr = JSON.stringify(convertXmlToJson(extractXml(output.stdout)))
await invoke('receive_frontend_response', { response: streamsstr });
} catch (error) {
console.error(error);
}
};
sendStreamData();
} else {
console.log(output.stdout);
}
} catch (error) {
console.error(error);
}
};
fetchData();
}
export function compareVersions (v1: string, v2: string) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const part1 = parts1[i] || 0;
const part2 = parts2[i] || 0;
if (part1 > part2) return 1;
if (part1 < part2) return -1;
}
return 0;
};

View File

@@ -1,9 +0,0 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);

View File

@@ -1,63 +0,0 @@
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
theme: {
extend: {
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
},
colors: {
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
chart: {
'1': 'hsl(var(--chart-1))',
'2': 'hsl(var(--chart-2))',
'3': 'hsl(var(--chart-3))',
'4': 'hsl(var(--chart-4))',
'5': 'hsl(var(--chart-5))'
}
}
}
},
plugins: [require("tailwindcss-animate")],
}

View File

@@ -1,27 +0,0 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig(async () => ({
plugins: [react()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
watch: {
// 3. tell vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
}));

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{ {
"name": "pytubepp-helper", "name": "pytubepp-helper",
"private": true, "private": true,
"version": "0.1.0", "version": "0.7.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -10,20 +10,34 @@
"tauri": "tauri" "tauri": "tauri"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^3.10.0",
"@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-slot": "^1.1.0", "@radix-ui/react-label": "^2.1.1",
"@tauri-apps/api": "^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", "class-variance-authority": "^0.7.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"lucide-react": "^0.436.0", "lucide-react": "^0.436.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^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", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7" "tailwindcss-animate": "^1.0.7",
"zod": "^3.24.1"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^1", "@tauri-apps/cli": "^2.2.7",
"@types/node": "^22.2.0", "@types/node": "^22.2.0",
"@types/react": "^18.2.15", "@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7", "@types/react-dom": "^18.2.7",

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +1,45 @@
[package] [package]
name = "pytubepp-helper" name = "pytubepp-helper"
version = "0.1.0" version = "0.7.0"
description = "PytubePP Helper" description = "PytubePP Helper"
authors = ["neosubhamoy"] authors = ["neosubhamoy"]
edition = "2021" edition = "2021"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies] [build-dependencies]
tauri-build = { version = "1", features = [] } tauri-build = { version = "2", features = [] }
[dependencies] [dependencies]
tauri = { version = "1", features = [ "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 = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
tokio = { version = "1.39.2", features = ["full"] } tokio = { version = "1.39.2", features = ["full"] }
tokio-tungstenite = "*" tokio-tungstenite = "*"
futures-util = "0.3.30" 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] [features]
# This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!! # This feature is used for production builds or when a dev server is not specified, DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"] custom-protocol = ["tauri/custom-protocol"]
[lib]
name = "pytubepp_helper_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[workspace] [workspace]
members = [ members = [
".", ".",
"msghost", "msghost"
"autostart"
] ]

View File

@@ -2,7 +2,7 @@
Type=Application Type=Application
Name=pytubepp-helper Name=pytubepp-helper
Icon=pytubepp-helper Icon=pytubepp-helper
Comment=pytubepp-helper autostart script Comment=pytubepp-helper autostart
Exec=/usr/bin/pytubepp-helper-autostart Exec=/usr/bin/pytubepp-helper --hidden
StartupNotify=false StartupNotify=false
Terminal=false Terminal=false

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.neosubhamoy.pytubepp.helper</string>
<key>ProgramArguments</key>
<array>
<string>/Applications/pytubepp-helper.app/Contents/MacOS/pytubepp-helper</string>
<string>--hidden</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>

View 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"
]
}

View 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"
]
}

View File

Before

Width:  |  Height:  |  Size: 8.2 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

View File

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

View File

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

View 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

View File

@@ -10,7 +10,7 @@
<RegistryValue Type="string" Value="[INSTALLDIR]pytubepp-helper-msghost-moz.json" KeyPath="no" /> <RegistryValue Type="string" Value="[INSTALLDIR]pytubepp-helper-msghost-moz.json" KeyPath="no" />
</RegistryKey> </RegistryKey>
<RegistryKey Root="HKCU" Key="Software\Microsoft\Windows\CurrentVersion\Run"> <RegistryKey Root="HKCU" Key="Software\Microsoft\Windows\CurrentVersion\Run">
<RegistryValue Name="pytubepp-helper" Type="string" Value="[INSTALLDIR]pytubepp-helper-autostart.exe" KeyPath="no" /> <RegistryValue Name="pytubepp-helper" Type="string" Value="&quot;[INSTALLDIR]pytubepp-helper.exe&quot; --hidden" KeyPath="no" />
</RegistryKey> </RegistryKey>
</Component> </Component>
</DirectoryRef> </DirectoryRef>

View File

@@ -0,0 +1,7 @@
{
"name": "com.neosubhamoy.pytubepp.helper",
"description": "A helper app for pytubepp-extension to communicate with pytubepp-cli",
"path": "/Applications/pytubepp-helper.app/Contents/Resources/pytubepp-helper-msghost",
"type": "stdio",
"allowed_origins": ["chrome-extension://adebedkaedobamilbbobbajepnnkkfcg/", "chrome-extension://mmhhbpdhkogpcieblpdilflfoimajepp/", "chrome-extension://ebneapoekcjelholncnlpdohjbjabhbi/", "chrome-extension://cohjehldppmnbfogjdjpbjknhlhmfhjj/"]
}

View File

@@ -0,0 +1,7 @@
{
"name": "com.neosubhamoy.pytubepp.helper",
"description": "A helper app for pytubepp-extention to communicate with pytubepp-cli",
"path": "/Applications/pytubepp-helper.app/Contents/Resources/pytubepp-helper-msghost",
"type": "stdio",
"allowed_extensions": ["pytubepp-addon@neosubhamoy.com"]
}

View File

@@ -2,15 +2,13 @@
name = "pytubepp-helper-msghost" name = "pytubepp-helper-msghost"
version = "0.1.0" version = "0.1.0"
description = "PytubePP Helper Native Messaging Host" description = "PytubePP Helper Native Messaging Host"
authors = ["neosubhamoy"] authors = ["neosubhamoy <hey@neosubhamoy.com>"]
edition = "2021" edition = "2021"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
websocket = "0.27.1" websocket = "0.27.1"
directories = "5.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
[build-dependencies]
winresource = "0.1.17"

View 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()
}

View File

@@ -1,11 +1,21 @@
mod config;
use config::load_config;
use serde_json::Value;
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
use websocket::client::ClientBuilder;
use websocket::OwnedMessage;
use std::thread::sleep; use std::thread::sleep;
use std::time::Duration; 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; let mut attempts = 0;
loop { loop {
match ClientBuilder::new(url).unwrap().connect_insecure() { 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)); return Err(Box::new(e));
} }
let wait_time = Duration::from_secs(2u64.pow(attempts)); 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); sleep(wait_time);
} }
} }
@@ -55,7 +68,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(msg) => { Ok(msg) => {
eprintln!("Received message: {}", msg); eprintln!("Received message: {}", msg);
msg msg
}, }
Err(e) => { Err(e) => {
eprintln!("Error reading message: {:?}", e); eprintln!("Error reading message: {:?}", e);
return Err(e); return Err(e);
@@ -63,24 +76,30 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}; };
// Send immediate response to the extension // Send immediate response to the extension
write_stdout_message(&serde_json::json!({ write_stdout_message(
"status": "received", &serde_json::json!({
"message": "Message received by native host" "status": "received",
}).to_string())?; "message": "Message received by native host"
})
.to_string(),
)?;
let parsed: Value = serde_json::from_str(&input)?; 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); 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, Ok(client) => client,
Err(e) => { Err(e) => {
eprintln!("Failed to connect after multiple attempts: {:?}", e); eprintln!("Failed to connect after multiple attempts: {:?}", e);
write_stdout_message(&serde_json::json!({ write_stdout_message(
"status": "error", &serde_json::json!({
"message": "Failed to connect to Tauri app" "status": "error",
}).to_string())?; "message": "Failed to connect to Tauri app"
})
.to_string(),
)?;
return Err(e); return Err(e);
} }
}; };
@@ -93,10 +112,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Send Tauri app's response back to browser extension // Send Tauri app's response back to browser extension
if let OwnedMessage::Text(text) = message { if let OwnedMessage::Text(text) = message {
write_stdout_message(&serde_json::json!({ write_stdout_message(
"status": "success", &serde_json::json!({
"response": text "status": "success",
}).to_string())?; "response": text
})
.to_string(),
)?;
} }
Ok(()) Ok(())

51
src-tauri/src/config.rs Normal file
View 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
View 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;
}

6
src-tauri/src/main.rs Normal file
View File

@@ -0,0 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#[tokio::main]
async fn main() {
pytubepp_helper_lib::run().await;
}

49
src-tauri/tauri.conf.json Normal file
View File

@@ -0,0 +1,49 @@
{
"$schema": "https://schema.tauri.app/config/2",
"build": {
"beforeDevCommand": "npm run dev",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist",
"devUrl": "http://localhost:1422"
},
"bundle": {
"active": true,
"targets": "all",
"createUpdaterArtifacts": true,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"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
}
]
}
}

View File

@@ -0,0 +1,63 @@
{
"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",
"devUrl": "http://localhost:1422",
"frontendDist": "../dist"
},
"identifier": "com.neosubhamoy.pytubepp.helper",
"app": {
"windows": [
{
"title": "PytubePP Helper",
"width": 510,
"height": 345,
"useHttpsScheme": true
}
],
"security": {
"csp": null,
"capabilities": [
"main-capability",
"shell-scope"
]
}
},
"bundle": {
"active": true,
"targets": ["deb", "rpm"],
"createUpdaterArtifacts": true,
"licenseFile": "../LICENSE",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"linux": {
"deb": {
"depends": ["python3-pip", "nodejs", "ffmpeg", "gnome-terminal"],
"files": {
"/etc/opt/chrome/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
"/etc/chromium/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
"/usr/lib/mozilla/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/firefox/com.neosubhamoy.pytubepp.helper.json",
"/usr/bin/pytubepp-helper-msghost": "./target/release/pytubepp-helper-msghost",
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
}
},
"rpm": {
"epoch": 0,
"release": "1",
"depends": ["python3-pip", "nodejs", "ffmpeg", "gnome-terminal"],
"files": {
"/etc/opt/chrome/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
"/etc/chromium/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/chrome/com.neosubhamoy.pytubepp.helper.json",
"/usr/lib/mozilla/native-messaging-hosts/com.neosubhamoy.pytubepp.helper.json": "./msghost-manifest/linux/firefox/com.neosubhamoy.pytubepp.helper.json",
"/usr/bin/pytubepp-helper-msghost": "./target/release/pytubepp-helper-msghost",
"/etc/xdg/autostart/pytubepp-helper-autostart.desktop": "./autostart/pytubepp-helper-autostart.desktop"
}
}
}
}
}

View File

@@ -0,0 +1,72 @@
{
"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",
"devUrl": "http://localhost:1422",
"frontendDist": "../dist"
},
"identifier": "com.neosubhamoy.pytubepp.helper",
"app": {
"windows": [
{
"title": "PytubePP Helper",
"width": 515,
"height": 365,
"useHttpsScheme": true
}
],
"security": {
"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"],
"createUpdaterArtifacts": true,
"licenseFile": "../LICENSE",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"macOS": {
"minimumSystemVersion": "10.13",
"providerShortName": "neosubhamoy"
},
"resources": [
"pytubepp-helper-msghost.json",
"pytubepp-helper-msghost-moz.json",
"pytubepp-helper-msghost",
"pytubepp-helper-autostart.plist"
]
}
}

View File

@@ -0,0 +1,67 @@
{
"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",
"devUrl": "http://localhost:1422",
"frontendDist": "../dist"
},
"identifier": "com.neosubhamoy.pytubepp.helper",
"app": {
"windows": [
{
"title": "PytubePP Helper",
"width": 510,
"height": 345,
"useHttpsScheme": true
}
],
"security": {
"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"],
"createUpdaterArtifacts": true,
"licenseFile": "../LICENSE",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"windows": {
"wix": {
"fragmentPaths": ["installer/windows/wix-fragment.wxs"],
"componentRefs": ["PytubeppHelperFragmentRegistryEntries"]
},
"nsis": {
"installerHooks": "installer/windows/nsis-hooks.nsi"
}
},
"resources": [
"pytubepp-helper-msghost.json",
"pytubepp-helper-msghost-moz.json",
"pytubepp-helper-msghost.exe"
]
}
}

98
src/App.tsx Normal file
View File

@@ -0,0 +1,98 @@
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 { 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()
}
}
useEffect(() => {
const handleCloseRequested = (event: any) => {
event.preventDefault();
appWindow.hide();
};
appWindow.onCloseRequested(handleCloseRequested);
}, []);
useEffect(() => {
const unlisten = listen<WebSocketMessage>('websocket-message', (event) => {
if(event.payload.command === 'send-stream-info') {
sendStreamInfo(event.payload.url);
} else if(event.payload.command === 'download-stream') {
const startDownload = async () => {
try {
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);
}
};
startDownload();
} else if (event.payload.command === 'autostart') {
const handleAppAutostart = async () => {
appWindow.hide();
await invoke('receive_frontend_response', { response: 'Appwindow Hidden' });
};
handleAppAutostart();
}
});
return () => {
unlisten.then(f => f());
};
}, []);
useEffect(() => {
const checkForUpdates = async () => {
let permissionGranted = await isPermissionGranted();
if (!permissionGranted) {
const permission = await requestPermission();
permissionGranted = permission === 'granted';
}
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!` });
}
}
} catch (error) {
console.error(error);
}
};
if (!isAppUpdateChecked) {
checkForUpdates();
}
}, [])
return (
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<TooltipProvider delayDuration={1000}>
{children}
<Toaster />
</TooltipProvider>
</ThemeProvider>
);
}
export default App;

View 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 }

View File

@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
const buttonVariants = cva( 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: { variants: {
variant: { variant: {

View 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
View 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,
}

View 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 }

View 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 }

View 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>
);
};

View 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
View 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,
}

View 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>
)
}

View 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
View 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 }

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